text:
package com.gemstone.gemfire.cache.client;

import com.gemstone.gemfire.GemFireException;

/**
 * A generic exception indicating that a failure has happened while communicating
 * with a gemfire server. Subclasses of this exception provide more detail
 * on specific failures.
 * @author dsmith
 * @since 5.7
 */
public class ServerConnectivityException extends GemFireException {
private static final long serialVersionUID = -5205644901262051330L;

  /**
   * Create a new instance of ServerConnectivityException without a detail message or cause.
   */
  public ServerConnectivityException() {
  }

  /**
   *
   * Create a new instance of ServerConnectivityException with a detail message
   * @param message the detail message
   */
  public ServerConnectivityException(String message) {
    super(message);
  }

  /**
   * Create a new instance of ServerConnectivityException with a detail message and cause
   * @param message the detail message
   * @param cause the cause
   */
  public ServerConnectivityException(String message, Throwable cause) {
    super(message, cause);
  }

  /**
   * Create a new instance of ServerConnectivityException with a cause
   * @param cause the cause
   */
  public ServerConnectivityException(Throwable cause) {
    super(cause);
  }

}


text:
<?xml version='1.0' encoding='UTF-8'?>
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
  <!--General: Names-->
  <!--General: Permissions-->
  <!--General: Actions-->
  <!--Views-->
  <!--Views: Setup-->
  <string name="menu_about">Maererano</string>
  <!--Views: About: Welcome-->
  <!--Views: About: OTR-->
  <!--Views: About: Security-->
  <!--Views: Account list-->
  <!--Views: Setup: Account-->
  <string name="label_password">Svombunuro:</string>
  <string name="sign_in">Pinda</string>
  <string name="account_setup_password">svombunuro</string>
  <string name="account_setup_pers_now_title">Pinda</string>
  <!--Views: Settings: Account-->
  <!--Views: Contact list-->
  <!--Views: Chat: Single-->
  <!--Views: Chat: Group-->
  <!--Security: OTR-->
  <string name="menu_sign_in">Pinda</string>
  <!--Security: OTR: Keyring-->
  <!--Security: OTR: Verification-->
  <!--Security: OTR: Verification: QA-->
  <!--Views: VoIP-->
  <!--Views: Settings: General-->
  <!--Actions: Settings: General: Security and Privacy-->
  <!--Actions: Settings: General: User Interface-->
  <!--Actions: Settings: General: Other Tuning-->
  <!--Actions: Settings: General: Notifications-->
  <string name="notification_vibrate_title">Bvunda</string>
  <string name="notification_sound_title">Mand</string>
  <!--Actions: Settings: General: Developer-->
  <!--Alerts: Dialogs-->
  <!--Alerts: Notifications-->
  <!--Alerts: Exceptions-->
  <!--added 2011/09/01-->
  <!--Other-->
  <!--Other: Slide Menu-->
  <string name="menu_settings">zvamada</string>
  <string name="menu_sign_out">Buda</string>
  <!--Other: Provider-->
  <!--Other: Development Strings [Do not localize!]-->
  <!--Other: Presence States-->
  <!--Other: Smileys-->
  <!--[Do not localize!]-->
</resources>

redpajama_set_name: RedPajamaGithub


text:
module.exports = function (locationUpdated){
  navigator.geolocation.getCurrentPosition(
    (position) => locationUpdated(position),
    (error) => alert(error.message),
    {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
 );
};


text:
package org.slieb.closure.soyoptimizer.callback;

import com.google.javascript.jscomp.NodeTraversal;
import com.google.javascript.rhino.Node;
import org.slieb.closure.soyoptimizer.DelegateReference;
import org.slieb.closure.soyoptimizer.DelegateRegistration;
import org.slieb.closure.soyoptimizer.SoyDelegateNodeHelper;
import org.slieb.closure.soyoptimizer.node.DelegateRegistrationCall;

import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import static java.util.stream.Collectors.toSet;

public class DelegateTemplateRegistrationsScanner extends NodeTraversal.AbstractShallowCallback {

    private final Set<DelegateRegistration> registrations;

    public DelegateTemplateRegistrationsScanner() {registrations = Collections.newSetFromMap(new ConcurrentHashMap<>());}

    @Override
    public void visit(final NodeTraversal t,
                      final Node n,
                      final Node parent) {
        if (SoyDelegateNodeHelper.isRegisterDelegateFunction(n)) {
            registrations.add(new DelegateRegistrationCall(n).toRegistration());
        }
    }

    public Map<DelegateReference, Double> getRegistrationsPriorityMap() {
        final Map<DelegateReference, Double> priorityMap = new ConcurrentHashMap<>();
        registrations.stream().forEach(registration -> {
            final DelegateReference templateReference = registration.getReference();
            final Double priority = registration.getPriority();
            if (!priorityMap.containsKey(templateReference) || priorityMap.get(templateReference) < priority) {
                priorityMap.put(templateReference, priority);
            }
        });
        return priorityMap;
    }

    public Set<DelegateRegistration> getOverriddenRegistrations() {
        final Map<DelegateReference, Double> priorityMap = getRegistrationsPriorityMap();
        return registrations.stream().filter(r -> priorityMap.get(r.getReference()) > r.getPriority()).collect(toSet());
    }
}


text:
// Avoid `console` errors in browsers that lack a console.
'use strict';
(function(window) {
    var method;
    var noop = function () {};
    var methods = [
        'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
        'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
        'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
        'timeline', 'timelineEnd', 'timeStamp', 'trace', 'warn'
    ];
    var length = methods.length;
    var console = (window.console = window.console || {});

    while (length--) {
        method = methods[length];

        // Only stub undefined methods.
        if (!console[method]) {
            console[method] = noop;
        }
    }

    var docElem = window.document.documentElement,
        transEndEventNames = {
            'WebkitTransition': 'webkitTransitionEnd',
            'MozTransition': 'transitionend',
            'OTransition': 'oTransitionEnd',
            'msTransition': 'MSTransitionEnd',
            'transition': 'transitionend'
        },
        transEndEventName = transEndEventNames[ Modernizr.prefixed( 'transition' ) ],
        support = {
            transitions : Modernizr.csstransitions,
            support3d : Modernizr.csstransforms3d
        };

    function setTransform( el, transformStr ) {
        el.style.WebkitTransform = transformStr;
        el.style.msTransform = transformStr;
        el.style.transform = transformStr;
    }

    // from http://responsejs.com/labs/dimensions/
    function getViewportW() {
        var client = docElem['clientWidth'],
            inner = window['innerWidth'];

        if( client < inner )
            return inner;
        else
            return client;
    }

    function extend( a, b ) {
        for( var key in b ) {
            if( b.hasOwnProperty( key ) ) {
                a[key] = b[key];
            }
        }
        return a;
    }

    function CBPGridGallery( el, options ) {
        this.el = el;
        this.options = extend( {}, this.options );
            extend( this.options, options );
            this._init();
    }

    CBPGridGallery.prototype.options = {
    };

    CBPGridGallery.prototype._init = function() {
        // main grid
        this.grid = this.el.querySelector( 'section.grid-wrap > ul.grid' );
        // main grid items
        this.gridItems = [].slice.call( this.grid.querySelectorAll( 'li:not(.grid-sizer)' ) );
        // items total
        this.itemsCount = this.gridItems.length;
        // slideshow grid
        this.slideshow = this.el.querySelector( 'section.slideshow > ul' );
        // slideshow grid items
        this.slideshowItems = [].slice.call( this.slideshow.children );
        // index of current slideshow item
        this.current = -1;
        // slideshow control buttons
        this.ctrlPrev = this.el.querySelector( 'section.slideshow > nav > span.nav-prev' );
        this.ctrlNext = this.el.querySelector( 'section.slideshow > nav > span.nav-next' );
        this.ctrlClose = this.el.querySelector( 'section.slideshow > nav > span.nav-close' );
        // init masonry grid
        if(this.options.isSHowThumb){
            this._initMasonry();
        }
        // init events
        this._initEvents();
    };

    CBPGridGallery.prototype._initMasonry = function() {
        var grid = this.grid;
        imagesLoaded( grid, function() {
            var pckry = new Packery( grid, {
                itemSelector: 'li',
                gutter: 10,
                percentPosition: true
            });
        });
    };

    CBPGridGallery.prototype._initEvents = function() {
        var self = this;

        // open the slideshow when clicking on the main grid items
        this.gridItems.forEach( function( item, idx ) {
            item.addEventListener( 'click', function() {
                self._openSlideshow( idx );
            } );
        } );

        // slideshow controls
        this.ctrlPrev.addEventListener( 'click', function() { self._navigate( 'prev' ); } );
        this.ctrlNext.addEventListener( 'click', function() { self._navigate( 'next' ); } );
        this.ctrlClose.addEventListener( 'click', function() { self._closeSlideshow(); } );

        $(this.el.children[1]).on('swiperight', function(){
            self._navigate( 'prev' );
        });

        $(this.el.children[1]).on('swipeleft', function(){
            self._navigate( 'next' );
        });

        // window resize
        window.addEventListener( 'resize', function() { self._resizeHandler(); } );

        // keyboard navigation events
        document.addEventListener( 'keydown', function( ev ) {
            if ( self.isSlideshowVisible ) {
                var keyCode = ev.keyCode || ev.which;

                switch (keyCode) {
                    case 37:
                        self._navigate( 'prev' );
                        break;
                    case 39:
                        self._navigate( 'next' );
                        break;
                    case 27:
                        self._closeSlideshow();
                        break;
                }
            }
        } );

        // trick to prevent scrolling when slideshow is visible
        window.addEventListener( 'scroll', function() {
            if ( self.isSlideshowVisible ) {
                window.scrollTo( self.scrollPosition ? self.scrollPosition.x : 0, self.scrollPosition ? self.scrollPosition.y : 0 );
            }
            else {
                self.scrollPosition = { x : window.pageXOffset || docElem.scrollLeft, y : window.pageYOffset || docElem.scrollTop };
            }
        });
    };

    CBPGridGallery.prototype._openSlideshow = function( pos ) {
        this.isSlideshowVisible = true;
        this.current = pos;

        $(this.el).addClass('slideshow-open');

        /* position slideshow items */

        // set viewport items (current, next and previous)
        this._setViewportItems();

        // add class "current" and "show" to currentItem
        $(this.currentItem).addClass('current');
        $(this.currentItem).addClass('show');

        // add class show to next and previous items
        // position previous item on the left side and the next item on the right side
        if( this.prevItem ) {
            $(this.prevItem).addClass('show');
            var translateVal = Number( -1 * ( getViewportW() / 2 + this.prevItem.offsetWidth / 2 ) );
            setTransform( this.prevItem, support.support3d ? 'translate3d(' + translateVal + 'px, 0, -150px)' : 'translate(' + translateVal + 'px)' );
        }
        if( this.nextItem ) {
            $(this.nextItem).addClass('show');
            var translateVal = Number( getViewportW() / 2 + this.nextItem.offsetWidth / 2 );
            setTransform( this.nextItem, support.support3d ? 'translate3d(' + translateVal + 'px, 0, -150px)' : 'translate(' + translateVal + 'px)' );
        }
    };

    CBPGridGallery.prototype._navigate = function( dir ) {
        if( this.isAnimating ) return;
        if( dir === 'next' && this.current === this.itemsCount - 1 ||  dir === 'prev' && this.current === 0  ) {
            this._closeSlideshow();
            return;
        }

        this.isAnimating = true;

        // reset viewport items
        this._setViewportItems();

        var self = this,
            itemWidth = this.currentItem.offsetWidth,
            // positions for the centered/current item, both the side items and the incoming ones
            transformLeftStr = support.support3d ? 'translate3d(-' + Number( getViewportW() / 2 + itemWidth / 2 ) + 'px, 0, -150px)' : 'translate(-' + Number( getViewportW() / 2 + itemWidth / 2 ) + 'px)',
            transformRightStr = support.support3d ? 'translate3d(' + Number( getViewportW() / 2 + itemWidth / 2 ) + 'px, 0, -150px)' : 'translate(' + Number( getViewportW() / 2 + itemWidth / 2 ) + 'px)',
            transformCenterStr = '', transformOutStr, transformIncomingStr,
            // incoming item
            incomingItem;

        if( dir === 'next' ) {
            transformOutStr = support.support3d ? 'translate3d( -' + Number( (getViewportW() * 2) / 2 + itemWidth / 2 ) + 'px, 0, -150px )' : 'translate(-' + Number( (getViewportW() * 2) / 2 + itemWidth / 2 ) + 'px)';
            transformIncomingStr = support.support3d ? 'translate3d( ' + Number( (getViewportW() * 2) / 2 + itemWidth / 2 ) + 'px, 0, -150px )' : 'translate(' + Number( (getViewportW() * 2) / 2 + itemWidth / 2 ) + 'px)';
        }
        else {
            transformOutStr = support.support3d ? 'translate3d( ' + Number( (getViewportW() * 2) / 2 + itemWidth / 2 ) + 'px, 0, -150px )' : 'translate(' + Number( (getViewportW() * 2) / 2 + itemWidth / 2 ) + 'px)';
            transformIncomingStr = support.support3d ? 'translate3d( -' + Number( (getViewportW() * 2) / 2 + itemWidth / 2 ) + 'px, 0, -150px )' : 'translate(-' + Number( (getViewportW() * 2) / 2 + itemWidth / 2 ) + 'px)';
        }

        // remove class animatable from the slideshow grid (if it has already)
        $(self.slideshow).removeClass('animatable');

        if( dir === 'next' && this.current < this.itemsCount - 2 || dir === 'prev' && this.current > 1 ) {
            // we have an incoming item!
            incomingItem = this.slideshowItems[ dir === 'next' ? this.current + 2 : this.current - 2 ];
            setTransform( incomingItem, transformIncomingStr );
            $(incomingItem).addClass('show');
        }

        var slide = function() {
            // add class animatable to the slideshow grid
            $(self.slideshow).addClass('animatable');

            // overlays:
            $(self.currentItem).removeClass('current');
            var nextCurrent = dir === 'next' ? self.nextItem : self.prevItem;
            $(nextCurrent).addClass('current');

            setTransform( self.currentItem, dir === 'next' ? transformLeftStr : transformRightStr );

            if( self.nextItem ) {
                setTransform( self.nextItem, dir === 'next' ? transformCenterStr : transformOutStr );
            }

            if( self.prevItem ) {
                setTransform( self.prevItem, dir === 'next' ? transformOutStr : transformCenterStr );
            }

            if( incomingItem ) {
                setTransform( incomingItem, dir === 'next' ? transformRightStr : transformLeftStr );
            }

            var onEndTransitionFn = function( ev ) {
                if( support.transitions ) {
                    if( ev.propertyName.indexOf( 'transform' ) === -1 ) return false;
                    this.removeEventListener( transEndEventName, onEndTransitionFn );
                }

                if( self.prevItem && dir === 'next' ) {
                    $(self.prevItem).addClass('show');
                }
                else if( self.nextItem && dir === 'prev' ) {
                    $(self.nextItem).removeClass('show');
                }

                if( dir === 'next' ) {
                    self.prevItem = self.currentItem;
                    self.currentItem = self.nextItem;
                    if( incomingItem ) {
                        self.nextItem = incomingItem;
                    }
                }
                else {
                    self.nextItem = self.currentItem;
                    self.currentItem = self.prevItem;
                    if( incomingItem ) {
                        self.prevItem = incomingItem;
                    }
                }

                self.current = dir === 'next' ? self.current + 1 : self.current - 1;
                self.isAnimating = false;
            };

            if( support.transitions ) {
                self.currentItem.addEventListener( transEndEventName, onEndTransitionFn );
            }
            else {
                onEndTransitionFn();
            }
        };

        setTimeout( slide, 25 );
    }

    CBPGridGallery.prototype._closeSlideshow = function( pos ) {
        // remove class slideshow-open from the grid gallery elem
        $(this.el).removeClass('slideshow-open');
        // remove class animatable from the slideshow grid
        $(this.slideshow).removeClass('animatable');

        var self = this,
            onEndTransitionFn = function( ev ) {
                if( support.transitions ) {
                    if( ev.target.tagName.toLowerCase() !== 'ul' ) return;
                    this.removeEventListener( transEndEventName, onEndTransitionFn );
                }
                // remove classes show and current from the slideshow items
                $(self.currentItem).removeClass('current');

                self.slideshowItems.forEach( function(item){
                    $(item).removeClass('show');
                });

                // also reset any transforms for all the items
                self.slideshowItems.forEach( function( item ) { setTransform( item, '' ); } );

                self.isSlideshowVisible = false;
            };

        if( support.transitions ) {
            this.el.addEventListener( transEndEventName, onEndTransitionFn );
        }
        else {
            onEndTransitionFn();
        }
    };

    CBPGridGallery.prototype._setViewportItems = function() {
        this.currentItem = null;
        this.prevItem = null;
        this.nextItem = null;

        if( this.current > 0 ) {
            this.prevItem = this.slideshowItems[ this.current - 1 ];
        }
        if( this.current < this.itemsCount - 1 ) {
            this.nextItem = this.slideshowItems[ this.current + 1 ];
        }
        this.currentItem = this.slideshowItems[ this.current ];
    }

    // taken from https://github.com/desandro/vanilla-masonry/blob/master/masonry.js by David DeSandro
    // original debounce by John Hann
    // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
    CBPGridGallery.prototype._resizeHandler = function() {
        var self = this;
        function delayed() {
            self._resize();
            self._resizeTimeout = null;
        }
        if ( this._resizeTimeout ) {
            clearTimeout( this._resizeTimeout );
        }
        this._resizeTimeout = setTimeout( delayed, 50 );
    }

    CBPGridGallery.prototype._resize = function() {
        if ( this.isSlideshowVisible ) {
            // update width value
            if( this.prevItem ) {
                var translateVal = Number( -1 * ( getViewportW() / 2 + this.prevItem.offsetWidth / 2 ) );
                setTransform( this.prevItem, support.support3d ? 'translate3d(' + translateVal + 'px, 0, -150px)' : 'translate(' + translateVal + 'px)' );
            }
            if( this.nextItem ) {
                var translateVal = Number( getViewportW() / 2 + this.nextItem.offsetWidth / 2 );
                setTransform( this.nextItem, support.support3d ? 'translate3d(' + translateVal + 'px, 0, -150px)' : 'translate(' + translateVal + 'px)' );
            }
        }
    }

    // add to global namespace
    window.CBPGridGallery = CBPGridGallery;
}(window));


text:
package play.learn.tomcat;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServlet;

/**
 * this is better than before, got start and stop
 *
 */
@javax.servlet.annotation.WebServlet(
		// servlet name
		name = "complex",
		// servlet url pattern
		value = {"/complex"},
		// async support needed
		asyncSupported = true,
		// servlet init params
		initParams = {
				@WebInitParam(name = "threadpoolsize", value= "3")
		}
)
public class IngressServletV1 extends HttpServlet {

	public static final AtomicInteger counter = new AtomicInteger(0);
	public static final int CALLBACK_TIMEOUT = 60000;
	public static final int MAX_SIMULATED_TASK_LENGTH_MS = 5000;

	/** executor svc */
	private ExecutorService exec;

	@Override
	public void init() throws ServletException {
		// TODO maybe should be 1.5 times of the tomcat max thread pool.
		int size = Integer.parseInt(getInitParameter("threadpoolsize"));
		exec = Executors.newFixedThreadPool(size);
	}

	@Override
	public void destroy() {
		exec.shutdown();
	}

	/**
	 * Spawn the task on the provided {@link #exec} object.
	 * This limits the max number of threads in the pool that can be spawned and puts
	 * a ceiling on the max number of threads that can be used to the init param
	 * "threadpoolsize".
	 */
	@Override
	public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
		// create the async context, otherwise getAsyncContext() will be null
		final AsyncContext ctx = req.startAsync();

		// set the timeout
		ctx.setTimeout(CALLBACK_TIMEOUT);

		// attach listener to response to lifecycle events of this asynccontext
		ctx.addListener(new AsyncListener() {

			// timeout has occured in async task... handle it!!
			@Override
			public void onTimeout(AsyncEvent event) throws IOException {
				log("onTiemout called");
				log(event.toString());
				ctx.getResponse().getWriter().write("timeout!!");
				ctx.complete();
			}

			// async context has started, nothing to do
			@Override
			public void onStartAsync(AsyncEvent arg0) throws IOException {
			}

			// this never get called - error has occured in async task... handle it
			@Override
			public void onError(AsyncEvent event) throws IOException {
				log("onError called");
				log(event.toString());
				ctx.getResponse().getWriter().write("ERROR!!");
				ctx.complete();
			}

			// complete() has already been called on the async context, nothing to do
			@Override
			public void onComplete(AsyncEvent event) throws IOException { }
		});

		// simulate error only - this does not cause onError - causes network erro on client side
		if (counter.addAndGet(1) < 5) {
			throw new IndexOutOfBoundsException("Simulated error");
		} else {
			// spawn some task to be run in executor
			enqueLongRunningTask(ctx);
		}
	}

	/**
	 * if something goes wrong in the task, it simply causes timeout condition that causes
	 * the async context listener to be invoked (after the fact)
	 *
	 * if the {@link AsyncContext@getResponse()} is null, that means this context has
	 * already timedout (and context listener has been invoked).
	 */
	private void enqueLongRunningTask(final AsyncContext ctx) {
		exec.execute(new Runnable() {

			@Override
			public void run() {

				try {

				// simulate random delay
				int delay = new Random().nextInt(MAX_SIMULATED_TASK_LENGTH_MS);
				Thread.currentThread().sleep(delay);

				// response is null if the context has already timedout
				// (at this point the app server has called the listener already)
				ServletResponse response = ctx.getResponse();
				if (response != null) {
					response.getWriter().write(MessageFormat.format("processing task in id {0} delay : {1}", Thread.currentThread().getId(), delay));
					ctx.complete();
				} else {
					throw new IllegalStateException("Response object from context is null!");
				}

				} catch (Exception e) {
					log("Problem processing task", e);
					e.printStackTrace();
				}
			}
		});
	}

}


text:
@interface FBSDKIntegrityManager : NSObject

+ (void)enable;
+ (nullable NSDictionary<NSString *, id> *)processParameters:(nullable NSDictionary<NSString *, id> *)parameters;

@end

#endif


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
	<meta name="author" content="PortaPlanter" />
    <meta name="description" content="PortaPlanter™ makes products that help you have healthier, more manageable, and more environmentally beneficial plants and planters.">
    <link rel="favicon" href="/image/firehorse_icon_v2_w68.png">

      <title>Another markdown full cheatsheet demo</title>

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha256-MfvZlkHCEqatNoGiOXveE8FIwMzZg4W85qfrfIFBfYc= sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ=="
    crossorigin="anonymous">

    <link href="/static/css/main.css" rel="stylesheet">
	<link href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:200,400,200bold,400old" rel="stylesheet" type="text/css">
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
	<link href="/static/css/bootstrap.icon-large.min.css" rel="stylesheet">

		  Another markdown full cheatsheet demo

		May 27, 2013

			 News

			 Tags

			 Blog

			 Post

This is Markdown Cheatsheet Demo for Sustain, this Jekyll theme. Please check the raw content of this file for the markdown usage.

Typography Elements in One

Let’s start with a informative paragraph. This text is bolded. But not this one! How about italic text? Cool right? Ok, let’s combine them together. Yeah, that’s right! I have code to highlight, so ThisIsMyCode(). What a nice! Good people will hyperlink away, so here we go or http://www.example.com.

Headings H1 to H6

H1 Heading

H2 Heading

H3 Heading

H4 Heading

H5 Heading

H6 Heading

Footnote

Let’s say you have text that you want to refer with a footnote, you can do that too! This is an example for the footnote number one ^1. You can even add more footnotes, with link! ^2

Blockquote

Start by doing what’s necessary; then do what’s possible; and suddenly you are doing the impossible. –Francis of Assisi

NOTE: This theme does NOT support nested blockquotes.

List Items

First order list item

Second item

Unordered list can use asterisks

Or minuses

Or pluses

Code Blocks

var s = "JavaScript syntax highlighting";
alert(s);

s = "Python syntax highlighting"
print s

No language indicated, so no syntax highlighting.
But let's throw in a <b>tag</b>.

Table

Table 1: With Alignment

 Tables
 Are
 Cool

 col 3 is
 right-aligned
 $1600

 col 2 is
 centered
   $12

 zebra stripes
 are neat
    $1

Table 2: With Typography Elements

Markdown
 Less
 Pretty

Still
 renders
 nicely

1
 2
 3

Horizontal Line

The HTML <hr> element is for creating a “thematic break” between paragraph-level elements. In markdown, you can create a <hr> with any of the following:

___: three consecutive underscores

---: three consecutive dashes

***: three consecutive asterisks

renders to:

Media

YouTube Embedded Iframe

Image

Related Posts

								 June  5, 2013

								 A Full and Comprehensive Style Test

								 April  2, 2013

								 Now some lorem ipsum

								 March 15, 2013

								 Continued...

        Please enable JavaScript to view the comments powered by Disqus.
        blog comments powered by Disqus

PortaPlanter © 2015, All rights reserved.


text:
require 'spec_helper'

describe 'API' do
  describe 'SweepsController#trigger' do
    let(:project) { create(:project, :with_viewport, :with_url) }
    let(:params) do
      {
        title: 'Deploy',
        description: 'Release Notes: noop',
      }
    end

    subject do
      post trigger_project_sweeps_path(project), params.to_json,
           'Content-Type' => 'application/json',
           'Accept'       => 'application/json'
    end

    context 'with valid params' do
      it 'adds a snapshot' do
        expect { subject }.to change { Snapshot.count }.by(1)
      end

      it 'sends back a json with a URL leading to the sweep' do
        subject
        response.body.should include project_sweep_url(project, Sweep.last)
        JSON.parse(response.body)['url']
          .should == project_sweep_url(project, Sweep.last)
      end

      it 'adds a sweep' do
        expect { subject }.to change { Sweep.count }.by(1)
      end
    end

    context 'with invalid params' do
      before { params.delete(:title) }

      it 'sends back a json with errors' do
        subject
        JSON.parse(response.body)['errors'].should_not be_nil
      end

      it 'has a 400 response code' do
        subject
        response.status.should == 400
      end
    end
  end
end


text:
package com.bplow.deep.base.jackson;

import java.io.IOException;
import java.io.InputStream;

import org.junit.Test;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ReadVistorData {

    @Test
    public void read() throws JsonParseException, JsonMappingException, IOException {
        InputStream in = this.getClass().getResourceAsStream("/vistor-json.txt");

        /*ObjectMapper mapper = new ObjectMapper();
        mapper.enableDefaultTyping();
        Message massage = mapper.readValue(in, Message.class);*/

        Message massage = JSON.parseObject(in, Message.class);

        System.out.println(massage.getMessage());
    }

}


text:
        {{field.label}}
        <input [formControlName]="field.key" [id]="field.key" [placeholder]="field.placeholder" [required]="field.required" class="ms-TextField-field"
            [type]="field.type">

{{field.label}} is required

            {{field.label}}

            <input class="ms-TextField-field" type="date" [formControlName]="field.key" [id]="field.key" [placeholder]="field.placeholder"
                [required]="field.required">

{{field.label}} is required

        Go to today

                Jan
                Feb
                Mar
                Apr
                May
                Jun
                Jul
                Aug
                Sep
                Oct
                Nov
                Dec

            {{field.label}}

            <select class="ms-Dropdown-select" [id]="field.key" [formControlName]="field.key">
            <option *ngFor="let opt of field.options" [value]="opt.key" [attr.selected]="opt.selected">{{opt.value}}</option>
        </select>

{{field.label}} is required

        <input type="checkbox" class="ms-CheckBox-input" [id]="field.key" [formControlName]="field.key">

            {{field.label}}

            {{field.label}}

                <input tabindex="-1" [value]="opt.key" type="radio" class="ms-RadioButton-input">

                        {{opt.value}}

        {{field.label}}
        <input type="checkbox" [id]="field.key" [formControlName]="field.key" class="ms-Toggle-input" />

            Off
            On


text:
// Copyright (c) 2016-2017 Vadim Macagon
// MIT License, see LICENSE file for full terms.

import { IWidget, WidgetPath } from './widgets';

export const enum PatchOperation {
  ReplaceWidget = 0,
  ReplaceValue,
  SpliceWidgetArray,
  SpliceValueArray
}

export interface IReplaceValue {
  op: PatchOperation.ReplaceValue;
  path: WidgetPath;
  value: any;
}

export interface IReplaceWidget {
  op: PatchOperation.ReplaceWidget;
  path: WidgetPath;
  value: IWidget;
}

export interface ISpliceValueArray {
  op: PatchOperation.SpliceValueArray;
  path: WidgetPath;
  start: number;
  deleteCount?: number;
  added: any[];
}

export interface ISpliceWidgetArray {
  op: PatchOperation.SpliceWidgetArray;
  path: WidgetPath;
  start: number;
  deleteCount?: number;
  added?: IWidget[];
}

/**
 * A widget patch is an ordered list of changes to be applied to a generic widget description.
 */
export type WidgetChange = IReplaceWidget | IReplaceValue | ISpliceWidgetArray | ISpliceValueArray;
export type WidgetPatch = WidgetChange[];

/**
 * Modifies an object by applying a patch operation to it.
 *
 * @param obj Object to modify.
 * @param change Operation to apply.
 * @param createWidget Function that converts generic widget descriptions to application specific
 *                     objects representing concrete widgets.
 */
export function applyWidgetPatchOpToObject<T>(
  obj: T, change: WidgetChange, createWidget: (widget: IWidget) => T
): void {
  let target: any = obj;
  for (let i = 0; i < change.path.length - 1; ++i) {
    target = target[change.path[i]];
      // TODO: if target is undefined throw an error
  }
  const key = change.path[change.path.length - 1];

  switch (change.op) {
    case PatchOperation.ReplaceWidget:
      target[key] = createWidget(change.value);
      break;
    case PatchOperation.ReplaceValue:
      target[key] = change.value;
      break;
    case PatchOperation.SpliceWidgetArray:
      if (change.added) {
        const added = change.added.map(widget => createWidget(widget));
        target[key].splice(change.start, change.deleteCount, ...added);
      } else {
        target[key].splice(change.start, change.deleteCount);
      }
      break;
    case PatchOperation.SpliceValueArray:
      if (change.added) {
        target[key].splice(change.start, change.deleteCount, ...change.added);
      } else {
        target[key].splice(change.start, change.deleteCount);
      }
      break;
  }
}


text:
require 'test_helper'

class LayerPusherTest < ActiveSupport::TestCase
  test "truth" do
    assert_kind_of Module, LayerPusher
  end
end


text:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-returns',
  templateUrl: './returns.component.html',
  styleUrls: ['./returns.component.css']
})
export class ReturnsComponent implements OnInit {
  constructor() {}

  ngOnInit() {}
}


text:
<?php

namespace Oro\Bundle\CalendarBundle\Tests\Behat\Element;

use Behat\Gherkin\Node\TableNode;
use Oro\Bundle\FormBundle\Tests\Behat\Element\OroForm;
use Oro\Bundle\TestFrameworkBundle\Behat\Element\Element;

class EventForm extends OroForm
{
    const REPEATS_DROP_DOWN = 'Repeats';
    const COLOR_FIELD_NAME = 'Color';

    /**
     * Set repeating type drop down
     * Like: Daily/Weekly/Monthly/Yearly
     *
     * @param string $type
     */
    public function setRecurrenceType($type)
    {
        $this->fillField(self::REPEATS_DROP_DOWN, $type);
    }

    /**
     * Set recurrence parameters from TableNode
     */
    public function fill(TableNode $table)
    {
        foreach ($table->getRows() as list($label, $value)) {
            if ($label == self::REPEATS_DROP_DOWN) {
                $this->fillField('Repeat', true);
                $this->setRecurrenceType($value);
            }

            if ($label == self::COLOR_FIELD_NAME) {
                $this->elementFactory->wrapElement('Simple Color Picker Field', $this)->setValue($value);
                continue;
            }

            $locator = isset($this->options['mapping'][$label]) ? $this->options['mapping'][$label] : $label;
            $value = self::normalizeValue($value);

            $field = $this->findField($locator);
            self::assertNotNull($field, "Element $label not found");
            $field->setValue($value);
        }
    }

    /**
     * @param string $name
     * @return \Behat\Mink\Element\NodeElement|Element|null
     */
    public function findField($name)
    {
        if ($this->elementFactory->hasElement($name)) {
            return $this->elementFactory->createElement($name);
        } else {
            return parent::findField($name);
        }
    }
}


text:
const Collaborators = require('../../../../server/models/collaborators.model');

const collaboratorsQueryResolvers = {
  async collaborators() {
    return await Collaborators.find();
  },
  async collaborator(root, {
    _id
  }) {
    return await Collaborators.findById(_id);
  },
  async collaboratorByName(root, {
    name
  }) {
    return await Collaborators.findByName(name);
  }
};

module.exports = collaboratorsQueryResolvers;


text:
package com.kc.shiptransport.mvp.hserectification;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.kc.shiptransport.R;
import com.kc.shiptransport.data.bean.hse.HseDefectListBean;
import com.kc.shiptransport.db.hse.HseDefectDeadline;
import com.kc.shiptransport.db.hse.HseDefectType;
import com.kc.shiptransport.interfaze.OnDailogCancleClickListener;
import com.kc.shiptransport.mvp.BaseFragment;
import com.kc.shiptransport.mvp.hserectificationlist.HseRectificationListActivity;
import com.kc.shiptransport.mvp.hserectificationupdate.HseRectificationUpdateActivity;
import com.kc.shiptransport.util.CalendarUtil;
import com.kc.shiptransport.util.PopwindowUtil;
import com.kc.shiptransport.util.SettingUtil;
import com.kc.shiptransport.util.ToastUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.litepal.crud.DataSupport;

import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * @author 邱永恒
 * @time 2017/11/28  10:11
 * @desc ${TODD}
 */

public class HseRectificationFragment extends BaseFragment<HseRectificationActivity> implements HseRectificationContract.View, View.OnClickListener {
    private static int pageSize = 20;
    private static int pageCount = 1;

    @BindView(R.id.select_1)
    TextView select1;
    @BindView(R.id.select_2)
    TextView select2;
    @BindView(R.id.select_3)
    TextView select3;
    @BindView(R.id.select_4)
    TextView select4;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    Unbinder unbinder;
    private HseRectificationContract.Presenter presenter;
    private CommonAdapter<HseDefectListBean> adapter;
    private int deletePosition;
    private List<HseDefectType> defectTypeList;
    private List<HseDefectDeadline> defectDeadlineList;
    private String[] defectStatusList;
    private int defectTypeID;
    private int rectificationDeadline;
    private int isSubmitted = 0; // 默认0, 显示未处理
    private String startDate;
    private String endDate;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        initViews(rootView);
        initListener();

        presenter.subscribe(); // 同步基本数据
        return rootView;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_hse_rectification, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_rectification:
                // 跳转到已整改列表
                HseRectificationListActivity.startActivity(getContext());
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void initViews(View view) {
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        refreshLayout.setEnableHeaderTranslationContent(false);
        select1.setText("提交时间");
        select2.setText("缺陷类别");
        select3.setText("整改期限");
        select4.setVisibility(View.GONE);
    }

    @Override
    public void initListener() {
        select1.setOnClickListener(this);
        select2.setOnClickListener(this);
        select3.setOnClickListener(this);
        select4.setOnClickListener(this);

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh(30000, false);
                refresh(false, false);
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadmore(30000, false);
                refresh(false, true);
            }
        });
    }

    @Override
    public void setPresenter(HseRectificationContract.Presenter presenter) {
        this.presenter = presenter;
    }

    @Override
    public void showLoading(boolean isShow) {
        if (isShow) {
            activity.showProgressDailog("请稍等", "请稍等...", new OnDailogCancleClickListener() {
                @Override
                public void onCancel(ProgressDialog dialog) {
                    presenter.unsubscribe();
                }
            });
        } else {
            activity.hideProgressDailog();
        }
    }

    @Override
    public void showError(String msg) {
        ToastUtil.tip(getContext(), msg);
    }

    @Override
    public int setView() {
        return R.layout.fragment_hse_list;
    }

    @Override
    public int setTitle() {
        return R.string.title_hse_retification;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (refreshLayout != null && refreshLayout.isRefreshing()) {
            refreshLayout.finishRefresh();
        }
        if (presenter != null) {
            presenter.unsubscribe();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.select_1: // 提交时间
                PopwindowUtil.showPopwindow(getContext(), getResources().getStringArray(R.array.select_hse_check_time), select1, false, new PopwindowUtil.InitHolder<String>() {
                    @Override
                    public void initHolder(ViewHolder holder, final String s, final int position) {
                        holder.setText(R.id.tv_spinner, s)
                                .setOnClickListener(R.id.tv_spinner, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        select1.setText(s);
                                        switch (position) {
                                            case 0:
                                                startDate = CalendarUtil.getOffsetDate(CalendarUtil.YYYY_MM_DD, Calendar.DATE, -30);
                                                endDate = CalendarUtil.getOffsetDate(CalendarUtil.YYYY_MM_DD, Calendar.DATE, 1);
                                                break;
                                            case 1:
                                                PopwindowUtil.recyclerView.setVisibility(View.GONE);
                                                PopwindowUtil.ll.setVisibility(View.VISIBLE);
                                                break;
                                        }

                                        if (position != 1) {
                                            refresh(true, false);
                                            PopwindowUtil.hidePopwindow();
                                        }
                                    }
                                });
                    }
                }, new PopwindowUtil.OnPopOKClickListener() {
                    @Override
                    public void onOkClick(String startTime, String endTime) {
                        startDate = startTime;
                        endDate = endTime;
                        refresh(true, false);
                    }
                }, null);
                break;
            case R.id.select_2: // 缺陷类别
                PopwindowUtil.showPopwindow(getContext(), defectTypeList, select1, false, new PopwindowUtil.InitHolder<HseDefectType>() {
                    @Override
                    public void initHolder(ViewHolder holder, final HseDefectType hseDefectType, int position) {
                        holder.setText(R.id.tv_spinner, hseDefectType.getName())
                                .setOnClickListener(R.id.tv_spinner, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        select2.setText(hseDefectType.getName());
                                        defectTypeID = hseDefectType.getItemID(); // 缺陷id
                                        refresh(true, false);
                                        PopwindowUtil.hidePopwindow();
                                    }
                                });
                    }
                }, null, new PopwindowUtil.OnHeadClickListener() {
                    @Override
                    public void onHeadClick(View view, RecyclerView.ViewHolder holder, int position) {
                        select1.setText("全部缺陷类型");
                        defectTypeID = 0;
                        refresh(true, false);
                    }
                });
                break;
            case R.id.select_3: // 整改期限
                PopwindowUtil.showPopwindow(getContext(), defectDeadlineList, select3, false, new PopwindowUtil.InitHolder<HseDefectDeadline>() {
                    @Override
                    public void initHolder(ViewHolder holder, final HseDefectDeadline hseDefectDeadline, int position) {
                        holder.setText(R.id.tv_spinner, hseDefectDeadline.getRectificationDeadlineName())
                                .setOnClickListener(R.id.tv_spinner, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        select3.setText(hseDefectDeadline.getRectificationDeadlineName());
                                        rectificationDeadline = hseDefectDeadline.getRectificationDeadlineID();
                                        PopwindowUtil.hidePopwindow();
                                        refresh(true, false);
                                    }
                                });
                    }
                }, null, new PopwindowUtil.OnHeadClickListener() {
                    @Override
                    public void onHeadClick(View view, RecyclerView.ViewHolder holder, int position) {
                        select3.setText("全部整改期限");
                        rectificationDeadline = 0;
                        refresh(true, false);
                    }
                });
                break;
            case R.id.select_4: // 处理状态
                PopwindowUtil.showPopwindow(getContext(), defectStatusList, select4, false, new PopwindowUtil.InitHolder<String>() {
                    @Override
                    public void initHolder(ViewHolder holder, final String s, final int position) {
                        holder.setText(R.id.tv_spinner, s)
                                .setOnClickListener(R.id.tv_spinner, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        select4.setText(s);
                                        isSubmitted = position - 1;
                                        refresh(true, false);
                                        PopwindowUtil.hidePopwindow();
                                    }
                                });
                    }
                }, null, new PopwindowUtil.OnHeadClickListener() {
                    @Override
                    public void onHeadClick(View view, RecyclerView.ViewHolder holder, int position) {
                        select4.setText("全部状态");
                        isSubmitted = 100;
                        refresh(true, false);
                    }
                });
                break;
        }
    }

    /**
     * 查询条件:
     * 1. 当前船舶账号
     * 2. 提交时间
     * 3. 缺陷类别
     * 4. 整改期限
     *
     * @param isShow
     */
    private void refresh(boolean isShow, boolean isLoadmore) {
        if (isLoadmore) {
            presenter.getDefects(pageSize,
                    ++pageCount,
                    new HseDefectListBean(0,
                            0,
                            0,
                            creator,
                            null,
                            defectTypeID,
                            null,
                            null,
                            rectificationDeadline,
                            null,
                            null,
                            null,
                            null,
                            null,
                            isSubmitted,
                            null,
                            null,
                            0,
                            null),
                    startDate,
                    endDate,
                    isShow);
        } else {
            pageCount = 1;
            presenter.getDefects(pageSize,
                    pageCount,
                    new HseDefectListBean(0,
                            0,
                            0,
                            creator,
                            null,
                            defectTypeID,
                            null,
                            null,
                            rectificationDeadline,
                            null,
                            null,
                            null,
                            null,
                            null,
                            isSubmitted,
                            null,
                            null,
                            0,
                            null),
                    startDate,
                    endDate,
                    isShow);
        }
    }

    @Override
    public void showDefects(List<HseDefectListBean> list, boolean isFirst) {
        if (list == null || list.isEmpty()) {
            // 不能加载更多
            refreshLayout.finishLoadmore();
            refreshLayout.setLoadmoreFinished(true);
        }
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadmore();
        if (adapter == null) {
            adapter = new CommonAdapter<HseDefectListBean>(getContext(), R.layout.item_hse_rectification, list) {
                @Override
                protected void convert(ViewHolder holder, final HseDefectListBean bean, final int position) {
                    holder.setText(R.id.tv_defect_date, bean.getSystemDate())
                            .setText(R.id.tv_defect_type, bean.getDefectTypeName())
                            .setText(R.id.tv_defect_project, bean.getDefectItem())
                            .setText(R.id.tv_defect_deadline, bean.getRectificationDeadlineName())
                            .setText(R.id.tv_defect_status, bean.getIsSubmitted() == 1 ? "已处理" : "未处理")
                            .setText(R.id.tv_remark, bean.getRemark())
                            .setText(R.id.tv_deadline_date, bean.getDeadlineTime())
                            .setVisible(R.id.btn_delete, bean.getRectificationRecordID() != 0) // 如果没有提交过整改数据, 不显示删除
                            .setOnClickListener(R.id.btn_detail, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    // 查看详情
                                    Bundle bundle = new Bundle();
                                    bundle.putSerializable(HseRectificationUpdateActivity.DATA, bean);
                                    bundle.putInt(HseRectificationUpdateActivity.TYPE, SettingUtil.TYPE_HSE_RECTIFICATION_DEFECT_DETAIL);
                                    HseRectificationUpdateActivity.startActivity(getContext(), bundle);
                                }
                            })
                            .setOnClickListener(R.id.btn_rectification, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    // TODO: 整改
                                    Bundle bundle = new Bundle();
                                    bundle.putSerializable(HseRectificationUpdateActivity.DATA, bean);
                                    bundle.putInt(HseRectificationUpdateActivity.TYPE, SettingUtil.TYPE_HSE_RECTIFICATION_ADD);
                                    HseRectificationUpdateActivity.startActivity(getContext(), bundle);
                                }
                            })
                            .setOnClickListener(R.id.btn_delete, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    activity.showDailog("删除HSE整改", "是否删除整改记录?", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            deletePosition = position;
                                            if (bean.getRectificationRecordID() == 0) {
                                                ToastUtil.tip(getContext(), "此缺陷还未整改, 不能删除");
                                            } else {
                                                presenter.deleteForItem(bean.getRectificationRecordID());
                                            }
                                        }
                                    });
                                }
                            });
                }
            };
        } else {
            if (isFirst) {
                adapter.clear();
            }
            adapter.loadmore(list);
        }
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void showDeleteResult(boolean isSuccess) {
        if (isSuccess) {
            ToastUtil.tip(getContext(), "删除成功");
//            adapter.removeItem(deletePosition); // 不删除记录
            adapter.getDatas().get(deletePosition).setRectificationRecordID(0);
            adapter.notifyItemChanged(deletePosition);
        } else {
            ToastUtil.tip(getContext(), "删除失败, 请重试");
        }
    }

    @Override
    public void showSyncResult(boolean isSuccess) {
        if (isSuccess) {
            // 缺陷类别
            defectTypeList = DataSupport.findAll(HseDefectType.class);
            // 整改期限
            defectDeadlineList = DataSupport.findAll(HseDefectDeadline.class);
            // 处理状态
            defectStatusList = getResources().getStringArray(R.array.select_hse_defect_status);

        } else {
            ToastUtil.tip(getContext(), "同步数据失败, 请重试");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        refreshLayout.autoRefresh();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="4dp"
        android:indeterminate="true"
        android:visibility="gone" />

    <ImageButton
        android:id="@+id/username_image"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_gravity="center_horizontal"
        android:layout_margin="8dp"
        android:background="@drawable/ic_user_profile"
        android:contentDescription="@string/auth"
        android:scaleType="fitCenter"  />

    <TextView
        android:id="@+id/username"
        style="@style/text_gray_big"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:gravity="center_horizontal" />

    <TextView
        android:id="@+id/username_snippet"
        style="@style/text_gray_big"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:gravity="center_horizontal" />

    <GridView
        android:id="@+id/fragment_user_comments__list"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
        android:background="@color/light_light_gray"
        android:divider="@android:color/transparent"
        android:dividerHeight="8dp"
        android:numColumns="2"
        android:paddingTop="8dp"
        android:horizontalSpacing="8dp"
        android:verticalSpacing="8dp" >
    </GridView>

</LinearLayout>


text:
import React, { Component } from 'react';
import styles from './../assets/graph_picker.css'
import Select from 'react-select';
import {graphColors} from './../assets/colors.js'
import './../assets/react-select.css';
import tinycolor from 'tinycolor2';

class GraphPicker extends Component {

  constructor(props) {
    super(props)

    const metrics = [
      'timeWasted',
      'averageRenderTime',
      'totalLifeCycleTime',
      'totalRenderTime',
      'totalTime',
    ]

    this.displayNameMetrics = {
      'timeWasted': 'Time Wasted',
      'averageRenderTime': 'Avg. Render Time',
      'totalLifeCycleTime': 'Total Lifecycle Time',
      'totalRenderTime': 'Total Render Time',
      'totalTime': 'Total Time',
    }

    this.disabled = false //this.props.disabled;

    this.componentOptions = this.loadComponentOptions(this.props.allComponents);
    this.metricOptions = this.loadOptions(metrics);
    this.renderButtonsActive = false;
    this.hasCurrentTimeWasted = false;

    this.state = {
      selectComponentValue: undefined,
      selectMetricValue: 'timeWasted',
      selectGraphValue: undefined,
      selectColorValue: undefined,
      showColorOptions: true
    }
    this.colorButtons = graphColors.map(color =>
      <button
        className={styles.colorButton}
        style=
          {{background: color}}
        onClick={
          () => {this.updateColorValue(color)}
        }
      />
    )

  }

  componentWillReceiveProps(props) {
    if (this.props.allComponents){
      this.componentOptions = this.loadComponentOptions(this.props.allComponents)
    }
    this.forceUpdate();
  }

  updateComponentValue(newValue) {
    this.setState({
      selectComponentValue: newValue
    });
  }

  updateMetricValue(newValue) {
    this.setState({
      selectMetricValue: newValue
    });
  }

  updateGraphValue(newValue){
    this.setState({
      selectGraphValue: newValue
    });
  }

  updateColorValue(newValue) {
    this.setState(
      {selectColorValue: newValue}
    );
  }

  toggleColorPanel = () => {
    this.setState(
      {showColorOptions: !this.state.showColorOptions}
    )
  }

  loadOptions(options) {
    let arr = []

    options.forEach(option => {
      if (option.name) {
        option = option.name;
      }

      let labelName = options[0] === 'timeWasted' ? this.displayNameMetrics[option] : option

      arr.push({ value: option, label: labelName})
    })
    return arr;
  }

  loadComponentOptions(options) {
    const arr = [];
    const sorted = options.sort( (a,b) => {
      return a.getMetricTotal(this.state.selectMetricValue)  {
      let wastedColor = 'grey';
      if (this.state.selectMetricValue === 'timeWasted'){
        if (option.getMetricTotal('timeWasted') != 0) {
          if (option.getLastValue('timeWasted')){
            this.hasCurrentTimeWasted = true;
            wastedColor = '#ff5757';
          }else {
            this.hasCurrentTimeWasted = false;
            wastedColor = '#57ff9e'
          }
        }
      }
      arr.push(
        {
        value: option.name, label: option.name, style: {background:wastedColor, color:'white'}
        })
      }
    )
    return arr;
  }

  handleClick = (whichGraph) => {
    this.props.allComponents.forEach(component => {
      if (component.name === this.state.selectComponentValue) {
        component.toggleActiveMetric('RENDER', this.state.selectMetricValue, whichGraph, this.state.selectGraphValue, this.state.selectColorValue);
        if (whichGraph === 1) {
          this.props.twoGraphToggler(true);
        }
        this.props.updateGraph();
      }
    })
  }

getBackgroundColor = (hex) => {
  let thisColor = new tinycolor(hex);
  if (thisColor.getBrightness() < 160) return 'black';
  else return 'white';
}

canRenderToGraph = () => {
  return this.state.selectComponentValue && this.state.selectGraphValue && this.state.selectColorValue
}

  render() {
    return (

          <Select
            placeholder='Performance Metric'
            autofocus={false}
            options={this.metricOptions}
            simpleValue
            clearable={true}
            name="selected-state"
            disabled={false}
            value={this.state.selectMetricValue}
            onChange={this.updateMetricValue.bind(this)}
            searchable={true}
            style={{
              zIndex:'999999'
            }}
          />

          <Select
            placeholder={
              this.state.selectMetricValue
              ? `Component (sorted by ${this.state.selectMetricValue})`
              : `Component`
            }
            autofocus={false}
            simpleValue
            options={this.componentOptions}
            clearable={true}
            name="selected-state"
            disabled={false}
            value={this.state.selectComponentValue}
            onChange={this.updateComponentValue.bind(this)}
            searchable={true}

          />

          <button
            className={
              this.state.selectGraphValue === 'line' ? styles.graphButtonSelected : styles.graphButton
              }
            >
             this.updateGraphValue('line') }
            />
          </button>

          <button
            className={styles.colorOptionButton}
            onClick={this.toggleColorPanel}
            style={{background: this.state.selectColorValue}}
          >

          </button>
          <button
            className={
              this.state.selectGraphValue === 'area' ? styles.graphButtonSelected : styles.graphButton
              }
            >
             this.updateGraphValue('area') }
            />
          </button>

          <button
            className={
              this.state.selectGraphValue === 'bar' ? styles.graphButtonSelected : styles.graphButton
              }
            >
             this.updateGraphValue('bar') }
            />
          </button>

          {this.colorButtons}

          <button
            className= {
              this.canRenderToGraph() ? styles.renderButtonActive : styles.renderButtonInactive
            }
            onClick={
              () => this.canRenderToGraph() && this.handleClick(0)
            }
          >
            Graph I
          </button>
          {(this.props.componentsActiveOnGraphs.length > 0) && (
            <button
              className= {
                this.canRenderToGraph() ? styles.renderButtonActive : styles.renderButtonInactive
              }
              onClick={
                () => this.handleClick(1)}
            >
              Graph II
            </button>
          )
          }

    );
  }
}

export default GraphPicker;