text:
using SensusUI.UiProperties;
using System;
using System.Linq;

namespace SensusService.Probes
{
    public abstract class ListeningProbe : Probe
    {
        private float _maxDataStoresPerSecond;
        private bool _keepDeviceAwake;
        private bool _deviceAwake;

        private readonly object _locker = new object();

        [EntryFloatUiProperty("Max Data / Second:", true, int.MaxValue)]
        public float MaxDataStoresPerSecond
        {
            get { return _maxDataStoresPerSecond; }
            set { _maxDataStoresPerSecond = value; }
        }

        [OnOffUiProperty("Keep Device Awake:", true, int.MaxValue - 1)]
        public bool KeepDeviceAwake
        {
            get
            {
                return _keepDeviceAwake;
            }
            set
            {
                _keepDeviceAwake = value;
            }
        }

        protected override float RawParticipation
        {
            get
            {
                #if __ANDROID__
                // compute participation using successful health test times of the probe
                long dayMS = 60000 * 60 * 24;
                long participationHorizonMS = Protocol.ParticipationHorizonDays * dayMS;
                float fullParticipationHealthTests = participationHorizonMS / (float)SensusServiceHelper.HEALTH_TEST_DELAY_MS;

                // lock collection because it might be concurrently modified by the test health method running in another thread.
                lock (SuccessfulHealthTestTimes)
                    return SuccessfulHealthTestTimes.Count(healthTestTime => healthTestTime >= Protocol.ParticipationHorizon) / fullParticipationHealthTests;
                #elif __IOS__
                // on ios, we cannot rely on the health test times to tell us how long the probe has been running. this is
                // because, unlike in android, ios does not let local notifications return to the app when the app is in the
                // background. instead, the ios user must open a notification or directly open the app in order for the health
                // test to run. so the best we can do is keep track of when the probe was started and stopped and compute participation
                // based on how much of the participation horizon has been covered by the probe. it is possible that the probe
                // is in this running state but is somehow faulty and failing the health tests. thus, the approach is not
                // perfect, but it's the best we can do on ios.
                double runningSeconds;

                lock (StartStopTimes)
                {
                    if (StartStopTimes.Count == 0)
                        return 0;

                    runningSeconds = StartStopTimes.Select((startStopTime, index) =>
                        {
                            DateTime? startTime = null;
                            DateTime? stopTime = null;

                            // if this is the final element and it's a start time, then the probe is currently running and we should calculate
                            // how much time has elapsed since the probe was started.
                            if (index == StartStopTimes.Count - 1 && startStopTime.Item1)
                            {
                                // if the current start time came before the participation horizon, use the horizon as the start time.
                                if (startStopTime.Item2 < Protocol.ParticipationHorizon)
                                    startTime = Protocol.ParticipationHorizon;
                                else
                                    startTime = startStopTime.Item2;

                                // the probe is currently running, so use the current time as the stop time.
                                stopTime = DateTime.Now;
                            }
                            // otherwise, we only need to consider stop times after the participation horizon.
                            else if (!startStopTime.Item1 && startStopTime.Item2 > Protocol.ParticipationHorizon)
                            {
                                stopTime = startStopTime.Item2;

                                // if the previous element is a start time, use it.
                                if (index > 0 && StartStopTimes[index - 1].Item1)
                                    startTime = StartStopTimes[index - 1].Item2;

                                // if we don't have a previous element that's a start time, or we do but the start time was before the participation horizon, then
                                // use the participation horizon as the start time.
                                if (startTime == null || startTime.Value < Protocol.ParticipationHorizon)
                                    startTime = Protocol.ParticipationHorizon;
                            }

                            // if we've got a start and stop time, return the total number of seconds covered.
                            if (startTime != null && stopTime != null)
                                return (stopTime.Value - startTime.Value).TotalSeconds;
                            else
                                return 0;

                        }).Sum();
                }

                double participationHorizonSeconds = TimeSpan.FromDays(Protocol.ParticipationHorizonDays).TotalSeconds;
                return (float)(runningSeconds / participationHorizonSeconds);
                #else
                #error "Unrecognized platform."
                #endif
            }
        }

        public override string CollectionDescription
        {
            get
            {
                return DisplayName + ":  When it changes.";
            }
        }

        protected ListeningProbe()
        {
            _maxDataStoresPerSecond = 1;
            _keepDeviceAwake = true;
            _deviceAwake = false;
        }

        protected sealed override void InternalStart()
        {
            lock (_locker)
            {
                // only keep device awake if we're not already running. calls to LetDeviceSleep must match these exactly.
                if (!Running && _keepDeviceAwake)
                {
                    SensusServiceHelper.Get().KeepDeviceAwake();
                    _deviceAwake = true;
                }

                base.InternalStart();

                StartListening();
            }
        }

        protected abstract void StartListening();

        public sealed override void Stop()
        {
            lock (_locker)
            {
                base.Stop();

                StopListening();

                if (_deviceAwake)
                {
                    SensusServiceHelper.Get().LetDeviceSleep();
                    _deviceAwake = false;
                }
            }
        }

        protected abstract void StopListening();

        public sealed override void StoreDatum(Datum datum)
        {
            float storesPerSecond = 1 / (float)(DateTimeOffset.UtcNow - MostRecentStoreTimestamp).TotalSeconds;
            if (storesPerSecond <= _maxDataStoresPerSecond)
                base.StoreDatum(datum);
        }

        public override void ResetForSharing()
        {
            base.ResetForSharing();

            _deviceAwake = false;
        }
    }
}


text:
<!DOCTYPE html>

   <meta charset="utf-8"></meta>
   <title>2020-CH-07-trade</title>

Byteshandel

							 Varje bäver erbjuder dig ett byte: Om du ger bävern det föremål som visas på skylten så får du i gengäld föremålet som den håller i handen.

Hitta en serie byten som låter dig börja med startobjektet och sluta med målobjektet.

Placera bävrar i de grå rutorna, i den ordning du vill utföra bytena.

Innan du börjar byteshandla så ska du välja den grupp bävrar som du kommer att kunna byta med. Dra så få bävrar som möjligt till det stora grå fältet, så att du oavsett startobjekt kan byta till dig slutobjektet.

Lösning

Det är datavetenskap!

redpajama_set_name: RedPajamaGithub


text:
def swi_product_dict(csvfile,fieldnames):
    import csv

    csvfile = open(csvfile,'rbU')
    reader = csv.DictReader(csvfile,fieldnames,delimiter=',')

    completedict = {}
    for line in reader:
        tmpdict = {}
        pipedict = {}
        dkey = line['SWI_SKU']
        tmpdict['SWI_SKU'] = line['SWI_SKU']
        tmpdict['BO_VARIANCE_ID'] = line['BO_VARIANCE_ID']
        tmpdict['STYLE'] = line['STYLE']
        tmpdict['STORE'] = line['STORE']
        tmpdict['CATEGORY'] = line['CATEGORY']
        tmpdict['SUBCATEGORY'] = line['SUBCATEGORY']
        tmpdict['BRAND_NAME'] = line['BRAND_NAME']
        tmpdict['TITLE'] = line['TITLE']
        tmpdict['QOH'] = line['QOH']
        tmpdict['WEIGHT'] = line['WEIGHT']
        tmpdict['PRODUCT_DESCRIPTION'] = line['PRODUCT_DESCRIPTION']
        tmpdict['MSRP'] = line['MSRP']
        tmpdict['SELL_PRICE'] = line['SELL_PRICE']
        tmpdict['YOUR_COST'] = line['YOUR_COST']
        tmpdict['IMAGE'] = line['IMAGE']
        pipelist = line['FEATURES_PIPED']
        pipelist = pipelist.split('|')

        while len(pipelist) > 0:
            try:
                #print len(pipelist)
                value = pipelist.pop()
                key = pipelist.pop()
                pipedict[key] = value
            except IndexError:
                len(pipelist)

        tmpdict['FEATURES_PIPED'] = pipedict
        completedict[dkey] = tmpdict
    csvfile.close()
    return completedict

def url_download_file_http(url):
    from time import time
    import os, urllib
    try:
        downloaddir = os.path.join(os.path.expanduser('~'), 'script_downloads')
        #downloaddir = os.path.join('/Users/johnb', 'script_dowloads')
        if not downloaddir:
            os.mkdir(downloaddir)
        filename = url.split('/')[-1]
        filepath =  os.path.join(downloaddir, filename)
        url_start = time()
        downloadfile = urllib.urlretrieve(url, filepath)
        url_end = time()
        #filepath.close()
        print "File: %s\vDownload Time -> %s"  % (filename,url_end - url_start)
    except OSError:
        print "OS Error {0}".format(filepath)
    except IOError:
        print "IO Error {0}".format(filepath)
    except AttributeError:
        print "Attribute Error - Type doesnt have a property requested {0}".format(filepath)

def url_download_file_requests(url):
    r = requests.get(url)

import os,sys
en = os.environ
print en['PYTHONSTARTUP']
#csvfile = os.path.join(os.path.abspath(os.curdir),'BlueFly.csv')
csvfile = '/Users/johnb/Dropbox/Apps/PythonistaAppOnly/BlueFly.csv'
missingcsv = '/Users/johnb/Dropbox/Apps/PythonistaAppOnly/mistswis/missingswiwatch.csv'
#csvfile = os.path.join(os.path.abspath(os.curdir),'datafeedSAMPLE2.csv')
fieldnamelist = ["SWI_SKU","BO_VARIANCE_ID","STYLE","STORE","CATEGORY","SUBCATEGORY","BRAND_NAME","TITLE","QOH","WEIGHT","PRODUCT_DESCRIPTION","MSRP","SELL_PRICE","YOUR_COST","IMAGE","FEATURES_PIPED"]

## Make Dict of Csvfile
swidict = swi_product_dict(csvfile,fieldnamelist)

## IterItems Pulling Image + Download
#from PYTHON_FUNCTION_MASTER import url_download_file_http
count = len(swidict)
for k,v in swidict.iteritems():
    import urllib,csv
    #print found[1]['IMAGE']
    swi_image = v['IMAGE']
    swi_sku = v['SWI_SKU']
#    with open(missingcsv, 'rbU') as f:
    reader = csv.reader(open(missingcsv, 'rbU'),dialect=csv)
    for row in reader:
        print row[1]

    url_download_file_http(swi_image)
    count -= 1
    print "Downloads Remaining: {0}".format(count)
#print swidict


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN""http://www.w3.org/TR/REC-html40/frameset.dtd">

<TITLE>
Xerces2 Implementation: Class  NamedNodeMapImpl
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Serialized
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  SUMMARY:  INNER | FIELD | CONSTR | METHOD

DETAIL:  FIELD | CONSTR | METHOD

org.apache.xerces.impl.xs.opti

Class  NamedNodeMapImpl

java.lang.Object
  |
  +--org.apache.xerces.impl.xs.opti.NamedNodeMapImpl

All Implemented Interfaces:
org.w3c.dom.NamedNodeMap

public class NamedNodeMapImpl
extends java.lang.Object
implements org.w3c.dom.NamedNodeMap

INTERNAL:

Usage of this class is not supported. It may be altered or removed at any time.

Version:
$Id: NamedNodeMapImpl.java 699892 2008-09-28 21:08:27Z mrglavas $

Author:
Rahul Srivastava, Sun Microsystems Inc.

Constructor Summary

NamedNodeMapImpl(org.w3c.dom.Attr[] attrs)

Method Summary

 int
getLength()

          The number of nodes in this map.

 org.w3c.dom.Node
getNamedItem(java.lang.String name)

          Retrieves a node specified by name.

 org.w3c.dom.Node
getNamedItemNS(java.lang.String namespaceURI,
               java.lang.String localName)

          Retrieves a node specified by local name and namespace URI.

 org.w3c.dom.Node
item(int index)

          Returns the indexth item in the map.

 org.w3c.dom.Node
removeNamedItem(java.lang.String name)

          Removes a node specified by name.

 org.w3c.dom.Node
removeNamedItemNS(java.lang.String namespaceURI,
                  java.lang.String localName)

          Removes a node specified by local name and namespace URI.

 org.w3c.dom.Node
setNamedItem(org.w3c.dom.Node arg)

          Adds a node using its nodeName attribute.

 org.w3c.dom.Node
setNamedItemNS(org.w3c.dom.Node arg)

          Adds a node using its namespaceURI and
 localName.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

NamedNodeMapImpl

public NamedNodeMapImpl(org.w3c.dom.Attr[] attrs)

Method Detail

getNamedItem

public org.w3c.dom.Node getNamedItem(java.lang.String name)

Description copied from interface: org.w3c.dom.NamedNodeMap

Retrieves a node specified by name.

Specified by:
getNamedItem in interface org.w3c.dom.NamedNodeMap

Following copied from interface: org.w3c.dom.NamedNodeMap

Parameters:
name - The nodeName of a node to retrieve.
Returns:
A Node (of any type) with the specified
   nodeName, or null if it does not identify
   any node in this map.

item

public org.w3c.dom.Node item(int index)

Description copied from interface: org.w3c.dom.NamedNodeMap

Returns the indexth item in the map. If index
 is greater than or equal to the number of nodes in this map, this
 returns null.

Specified by:
item in interface org.w3c.dom.NamedNodeMap

Following copied from interface: org.w3c.dom.NamedNodeMap

Parameters:
index - Index into this map.
Returns:
The node at the indexth position in the map, or
   null if that is not a valid index.

getLength

public int getLength()

Description copied from interface: org.w3c.dom.NamedNodeMap

The number of nodes in this map. The range of valid child node indices
 is 0 to length-1 inclusive.

Specified by:
getLength in interface org.w3c.dom.NamedNodeMap

getNamedItemNS

public org.w3c.dom.Node getNamedItemNS(java.lang.String namespaceURI,
                                       java.lang.String localName)

Description copied from interface: org.w3c.dom.NamedNodeMap

Retrieves a node specified by local name and namespace URI.

Per [XML Namespaces]
 , applications must use the value null as the namespaceURI parameter
 for methods if they wish to have no namespace.

Specified by:
getNamedItemNS in interface org.w3c.dom.NamedNodeMap

Following copied from interface: org.w3c.dom.NamedNodeMap

Parameters:
namespaceURI - The namespace URI of the node to retrieve.
localName - The local name of the node to retrieve.
Returns:
A Node (of any type) with the specified local
   name and namespace URI, or null if they do not
   identify any node in this map.
Throws:
org.w3c.dom.DOMException - NOT_SUPPORTED_ERR: May be raised if the implementation does not
   support the feature "XML" and the language exposed through the
   Document does not support XML Namespaces (such as [HTML 4.01]).

setNamedItemNS

public org.w3c.dom.Node setNamedItemNS(org.w3c.dom.Node arg)
                                throws org.w3c.dom.DOMException

Description copied from interface: org.w3c.dom.NamedNodeMap

Adds a node using its namespaceURI and
 localName. If a node with that namespace URI and that
 local name is already present in this map, it is replaced by the new
 one. Replacing a node by itself has no effect.

Per [XML Namespaces]
 , applications must use the value null as the namespaceURI parameter
 for methods if they wish to have no namespace.

Specified by:
setNamedItemNS in interface org.w3c.dom.NamedNodeMap

Following copied from interface: org.w3c.dom.NamedNodeMap

Parameters:
arg - A node to store in this map. The node will later be
   accessible using the value of its namespaceURI and
   localName attributes.
Returns:
If the new Node replaces an existing node the
   replaced Node is returned, otherwise null
   is returned.
Throws:
org.w3c.dom.DOMException - WRONG_DOCUMENT_ERR: Raised if arg was created from a
   different document than the one that created this map.

NO_MODIFICATION_ALLOWED_ERR: Raised if this map is readonly.

INUSE_ATTRIBUTE_ERR: Raised if arg is an
   Attr that is already an attribute of another
   Element object. The DOM user must explicitly clone
   Attr nodes to re-use them in other elements.

HIERARCHY_REQUEST_ERR: Raised if an attempt is made to add a node
   doesn't belong in this NamedNodeMap. Examples would include trying
   to insert something other than an Attr node into an Element's map
   of attributes, or a non-Entity node into the DocumentType's map of
   Entities.

NOT_SUPPORTED_ERR: May be raised if the implementation does not
   support the feature "XML" and the language exposed through the
   Document does not support XML Namespaces (such as [HTML 4.01]).

setNamedItem

public org.w3c.dom.Node setNamedItem(org.w3c.dom.Node arg)
                              throws org.w3c.dom.DOMException

Description copied from interface: org.w3c.dom.NamedNodeMap

Adds a node using its nodeName attribute. If a node with
 that name is already present in this map, it is replaced by the new
 one. Replacing a node by itself has no effect.

As the nodeName attribute is used to derive the name
 which the node must be stored under, multiple nodes of certain types
 (those that have a "special" string value) cannot be stored as the
 names would clash. This is seen as preferable to allowing nodes to be
 aliased.

Specified by:
setNamedItem in interface org.w3c.dom.NamedNodeMap

Following copied from interface: org.w3c.dom.NamedNodeMap

Parameters:
arg - A node to store in this map. The node will later be
   accessible using the value of its nodeName attribute.
Returns:
If the new Node replaces an existing node the
   replaced Node is returned, otherwise null
   is returned.
Throws:
org.w3c.dom.DOMException - WRONG_DOCUMENT_ERR: Raised if arg was created from a
   different document than the one that created this map.

NO_MODIFICATION_ALLOWED_ERR: Raised if this map is readonly.

INUSE_ATTRIBUTE_ERR: Raised if arg is an
   Attr that is already an attribute of another
   Element object. The DOM user must explicitly clone
   Attr nodes to re-use them in other elements.

HIERARCHY_REQUEST_ERR: Raised if an attempt is made to add a node
   doesn't belong in this NamedNodeMap. Examples would include trying
   to insert something other than an Attr node into an Element's map
   of attributes, or a non-Entity node into the DocumentType's map of
   Entities.

removeNamedItem

public org.w3c.dom.Node removeNamedItem(java.lang.String name)
                                 throws org.w3c.dom.DOMException

Description copied from interface: org.w3c.dom.NamedNodeMap

Removes a node specified by name. When this map contains the attributes
 attached to an element, if the removed attribute is known to have a
 default value, an attribute immediately appears containing the
 default value as well as the corresponding namespace URI, local name,
 and prefix when applicable.

Specified by:
removeNamedItem in interface org.w3c.dom.NamedNodeMap

Following copied from interface: org.w3c.dom.NamedNodeMap

Parameters:
name - The nodeName of the node to remove.
Returns:
The node removed from this map if a node with such a name
   exists.
Throws:
org.w3c.dom.DOMException - NOT_FOUND_ERR: Raised if there is no node named name in
   this map.

NO_MODIFICATION_ALLOWED_ERR: Raised if this map is readonly.

removeNamedItemNS

public org.w3c.dom.Node removeNamedItemNS(java.lang.String namespaceURI,
                                          java.lang.String localName)
                                   throws org.w3c.dom.DOMException

Description copied from interface: org.w3c.dom.NamedNodeMap

Removes a node specified by local name and namespace URI. A removed
 attribute may be known to have a default value when this map contains
 the attributes attached to an element, as returned by the attributes
 attribute of the Node interface. If so, an attribute
 immediately appears containing the default value as well as the
 corresponding namespace URI, local name, and prefix when applicable.

Per [XML Namespaces]
 , applications must use the value null as the namespaceURI parameter
 for methods if they wish to have no namespace.

Specified by:
removeNamedItemNS in interface org.w3c.dom.NamedNodeMap

Following copied from interface: org.w3c.dom.NamedNodeMap

Parameters:
namespaceURI - The namespace URI of the node to remove.
localName - The local name of the node to remove.
Returns:
The node removed from this map if a node with such a local
   name and namespace URI exists.
Throws:
org.w3c.dom.DOMException - NOT_FOUND_ERR: Raised if there is no node with the specified
   namespaceURI and localName in this map.

NO_MODIFICATION_ALLOWED_ERR: Raised if this map is readonly.

NOT_SUPPORTED_ERR: May be raised if the implementation does not
   support the feature "XML" and the language exposed through the
   Document does not support XML Namespaces (such as [HTML 4.01]).

      Overview
      Package
    Class
      Tree
      Serialized
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  SUMMARY:  INNER | FIELD | CONSTR | METHOD

DETAIL:  FIELD | CONSTR | METHOD

Copyright © 1999-2010 The Apache Software Foundation. All Rights Reserved.


text:
//////////////////////////////////////////////////////////////////////
// Class copied from Algorithmia.
//////////////////////////////////////////////////////////////////////
// Algorithmia is (c) 2018 Solutions Design. All rights reserved.
// https://github.com/SolutionsDesign/Algorithmia
//////////////////////////////////////////////////////////////////////
// COPYRIGHTS:
// Copyright (c) 2018 Solutions Design. All rights reserved.
//
// The Algorithmia library sourcecode and its accompanying tools, tests and support code
// are released under the following license: (BSD2)
// ----------------------------------------------------------------------
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1) Redistributions of source code must retain the above copyright notice, this list of
//    conditions and the following disclaimer.
// 2) Redistributions in binary form must reproduce the above copyright notice, this list of
//    conditions and the following disclaimer in the documentation and/or other materials
//    provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY SOLUTIONS DESIGN ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SOLUTIONS DESIGN OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The views and conclusions contained in the software and documentation are those of the authors
// and should not be interpreted as representing official policies, either expressed or implied,
// of Solutions Design.
//
//////////////////////////////////////////////////////////////////////
// Contributers to the code:
//		- Frans Bouma [FB]
//////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IGCSClient.Classes
{
	/// <summary>
	/// A generic container event args which is useful if you want to raise an event and pass a single value along to the subscribers.
	/// </summary>
	/// <typeparam name="TValue">The type of the value contained in the event args.</typeparam>
	public class ContainerEventArgs<TValue> : EventArgs
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="ContainerEventArgs<TValue>"/> class.
		/// </summary>
		/// <param name="value">The value.</param>
		public ContainerEventArgs(TValue value)
		{
			this.Value = value;
		}

		#region Class Property Declarations
		/// <summary>
		/// Gets or sets the value contained in the event args
		/// </summary>
		public TValue Value { get; set; }
		#endregion
	}
}


text:
package com.netflix.hystrix.contrib.metrics.controller;

import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.fail;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.ServiceUnavailableException;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Response;

import org.apache.commons.configuration.SystemConfiguration;
import org.glassfish.jersey.media.sse.EventInput;
import org.glassfish.jersey.media.sse.InboundEvent;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.TestProperties;
import org.junit.Assert;
import org.junit.Test;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.contrib.metrics.HystrixStreamFeature;

/**
 * @author justinjose28
 *
 */
@Path("/hystrix")
public class HystricsMetricsControllerTest extends JerseyTest {
	protected static final AtomicInteger requestCount = new AtomicInteger(0);

	@POST
	@Path("/command")
	@Consumes(APPLICATION_JSON)
	public void command() throws Exception {
		TestHystrixCommand command = new TestHystrixCommand();
		command.execute();
	}

	@Override
	protected Application configure() {
		int port = 0;
		try {
			final ServerSocket socket = new ServerSocket(0);
			port = socket.getLocalPort();
			socket.close();
		} catch (IOException e1) {
			throw new RuntimeException("Failed to find port to start test server");
		}
		set(TestProperties.CONTAINER_PORT, port);
		try {
			SystemConfiguration.setSystemProperties("test.properties");
		} catch (Exception e) {
			throw new RuntimeException("Failed to load config file");
		}
		return new ResourceConfig(HystricsMetricsControllerTest.class, HystrixStreamFeature.class);
	}

	protected String getPath() {
		return "hystrix.stream";
	}

	protected boolean isStreamValid(String data) {
		return data.contains("\"type\":\"HystrixThreadPool\"") && data.contains("\"currentCompletedTaskCount\":" + requestCount.get());
	}

	@Test
	public void testInfiniteStream() throws Exception {
		executeHystrixCommand(); // Execute a Hystrix command so that metrics are initialized.
		EventInput stream = getStream(); // Invoke Stream API which returns a steady stream output.
		try {
			validateStream(stream, 1000); // Validate the stream.
			System.out.println("Validated Stream Output 1");
			executeHystrixCommand(); // Execute Hystrix Command again so that request count is updated.
			validateStream(stream, 1000); // Stream should show updated request count
			System.out.println("Validated Stream Output 2");
		} finally {
			if (stream != null) {
				stream.close();
			}
		}
	}

	@Test
	public void testConcurrency() throws Exception {
		executeHystrixCommand(); // Execute a Hystrix command so that metrics are initialized.
		List<EventInput> streamList = new ArrayList<EventInput>();
		try {
			// Fire 3 requests, validate their responses and hold these connections.
			for (int i = 0; i < 3; i++) {
				EventInput stream = getStream();
				System.out.println("Received Response for Request#" + (i + 1));
				streamList.add(stream);
				validateStream(stream, 1000);
				System.out.println("Validated Response#" + (i + 1));
			}

			// Fourth request should fail since max configured connection is 3.
			try {
				streamList.add(getStreamFailFast());
				Assert.fail("Expected 'ServiceUnavailableException' but, request went through.");
			} catch (ServiceUnavailableException e) {
				System.out.println("Got ServiceUnavailableException as expected.");
			}

			// Close one of the connections
			streamList.get(0).close();
			streamList.remove(0);

			// Try again after closing one of the connections. This request should go through.
			EventInput eventInput = getStream();
			streamList.add(eventInput);
			validateStream(eventInput, 1000);
		} finally {
			for (EventInput stream : streamList) {
				if (stream != null) {
					stream.close();
				}
			}
		}

	}

	private void executeHystrixCommand() throws Exception {
		Response response = target("hystrix/command").request().post(null);
		assertEquals(204, response.getStatus());
		System.out.println("Hystrix Command ran successfully.");
		requestCount.incrementAndGet();
	}

	private EventInput getStream() throws Exception {
		long timeElapsed = System.currentTimeMillis();
		while (System.currentTimeMillis() - timeElapsed < 3000) {
			try {
				return getStreamFailFast();
			} catch (Exception e) {

			}
		}
		fail("Not able to connect to Stream end point");
		return null;
	}

	private EventInput getStreamFailFast() throws Exception {
		return target(getPath()).request().get(EventInput.class);
	}

	private void validateStream(EventInput eventInput, long waitTime) {
		long timeElapsed = System.currentTimeMillis();
		while (!eventInput.isClosed() && System.currentTimeMillis() - timeElapsed < waitTime) {
			final InboundEvent inboundEvent = eventInput.read();
			if (inboundEvent == null) {
				Assert.fail("Failed while verifying stream. Looks like connection has been closed.");
				break;
			}
			String data = inboundEvent.readData(String.class);
			System.out.println(data);
			if (isStreamValid(data)) {
				return;
			}
		}
		Assert.fail("Failed while verifying stream");
	}

	public static class TestHystrixCommand extends HystrixCommand<Void> {

		protected TestHystrixCommand() {
			super(HystrixCommandGroupKey.Factory.asKey("test"));
		}

		@Override
		protected Void run() throws Exception {
			return null;
		}

	}

}


text:
"""
Useful additional string functions.
"""

from __future__ import absolute_import, division

__author__ = "Shyue Ping Ong"
__copyright__ = "Copyright 2012, The Materials Project"
__version__ = "0.1"
__maintainer__ = "Shyue Ping Ong"
__email__ = "ongsp@ucsd.edu"
__date__ = "2/28/14"

import sys

def remove_non_ascii(s):
    """
    Remove non-ascii characters in a file. Needed when support for non-ASCII
    is not available.

    Args:
        s (str): Input string

    Returns:
        String with all non-ascii characters removed.
    """
    return "".join(i for i in s if ord(i) < 128)

def unicode2str(s):
    """
    Forces a unicode to a string in Python 2, but transparently handles
    Python 3.

    Args:
        s (str/unicode): Input string / unicode.

    Returns:
        str in Python 2. Unchanged otherwise.
    """
    return s.encode('utf-8') if sys.version_info.major < 3 else s

def str2unicode(s):
    """
    Converts strings to unicode in python 2. Ignores Python 3 strings.

    Args:
        s (str/unicode): Input string / unicode.

    Returns:
        Unicode.
    """
    return unicode(s) if sys.version_info.major < 3 else s

def is_string(s):
    """True if s behaves like a string (duck typing test)."""
    try:
        s + " "
        return True

    except TypeError:
        return False

def list_strings(arg):
    """
    Always return a list of strings, given a string or list of strings as
    input.

    :Examples:

    >>> list_strings('A single string')
    ['A single string']

    >>> list_strings(['A single string in a list'])
    ['A single string in a list']

    >>> list_strings(['A','list','of','strings'])
    ['A', 'list', 'of', 'strings']
    """
    if is_string(arg):
        return [arg]
    else:
        return arg

def marquee(text="", width=78, mark='*'):
    """
    Return the input string centered in a 'marquee'.

    Args:
        text (str): Input string
        width (int): Width of final output string.
        mark (str): Character used to fill string.

    :Examples:

    >>> marquee('A test', width=40)
    '**************** A test ****************'

    >>> marquee('A test', width=40, mark='-')
    '---------------- A test ----------------'

    marquee('A test',40, ' ')
    '                 A test                 '
    """
    if not text:
        return (mark*width)[:width]

    nmark = (width-len(text)-2)//len(mark)//2
    if nmark < 0:
        nmark = 0

    marks = mark * nmark
    return '%s %s %s' % (marks, text, marks)

def boxed(msg, ch="=", pad=5):
    """
    Returns a string in a box

    Args:
        msg: Input string.
        ch: Character used to form the box.
        pad: Number of characters ch added before and after msg.

    >>> print(boxed("hello", ch="*", pad=2))
    ***********
    ** hello **
    ***********
    """
    if pad > 0:
        msg = pad * ch + " " + msg.strip() + " " + pad * ch

    return "\n".join([len(msg) * ch,
                      msg,
                      len(msg) * ch,
                     ])

def make_banner(s, width=78, mark="*"):
    banner = marquee(s, width=width, mark=mark)
    return "\n" + len(banner) * mark + "\n" + banner + "\n" + len(banner) * mark

def indent(lines, amount, ch=' '):
    """Indent the lines in a string by padding each one with proper number of pad characters"""
    padding = amount * ch
    return padding + ('\n' + padding).join(lines.split('\n'))


text:
package estivate.core.eval.lang;

import java.util.ArrayList;
import java.util.List;

import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import estivate.core.ast.ReduceAST;
import estivate.core.ast.lang.SimpleValueAST;
import estivate.core.ast.lang.ValReduceAST;
import estivate.core.eval.EstivateEvaluator.EvalContext;
import estivate.core.eval.EstivateEvaluator.ReduceEvaluator;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ValReduceEvaluator implements ReduceEvaluator {

	public static final ValReduceEvaluator INSTANCE = new ValReduceEvaluator();

	public void evalReduce(EvalContext context, ReduceAST reduce,
			SimpleValueAST simpleValueAST) {

		if(reduce instanceof ValReduceAST){

			Elements elements = context.getQueryResult();

			Object reduceValue;

			if (simpleValueAST.isValueList()) {
				List<String> list = new ArrayList<String>();

				for (Element element : elements) {
					list.add(element.val());
				}

				reduceValue = list;
			} else {
				if (elements.size() > 1) {
					log.warn(
							"'{}' Val concats elements. Consider fixing the Query expression to get only one element.",
							context.getMemberName());
				}

				StringBuilder sb = new StringBuilder(50);
				for (Element element : elements) {
					if (sb.length() != 0)
						sb.append(" ");
					sb.append(element.val());
				}

				reduceValue = sb.toString();
			}

			context.getValue().put(simpleValueAST, reduceValue);
		}
	}

}


text: module.exports = 'string exported from module 3';


text:
package controllers

import neo4j.models.user.{UserRole, User}
import scala.Boolean

object PlaySession extends BaseController {
  def AUTH_SESSION: String = "EMAIL"

  def getUser(implicit request: play.api.mvc.RequestHeader): User = {
    val token = request.session.get(AUTH_SESSION)
    if (token == None || token.get == null) {
      null
    } else {
      User.getUserByEMail(token.get)
    }
  }

  def isLoggedIn(implicit request: play.api.mvc.RequestHeader): Boolean = {
    getUser != null
  }

  def isAdmin(implicit request: play.api.mvc.RequestHeader): Boolean = hasMinRole(UserRole.ADMIN)

  def hasMinRole(role: UserRole)(implicit request: play.api.mvc.RequestHeader): Boolean = getUser.hasMinRole(role)

}


text:
namespace Chimera {

Div::Div(Document& document)
    : Element("div", document)
    { }

Div::~Div() { }

bool Div::handleEvent(Event* event) {
    if (event->type == EventType::Scroll) {
        auto mouseScrollEvent = dynamic_cast<MouseScrollEvent*>(event);

        if (rect.contains(float(mouseScrollEvent->x), float(mouseScrollEvent->y))) {
            int internalHeight = 0;
            for (auto& child : mChildren) {
                internalHeight += int(child->rect.height);
            }

            if (rect.height < internalHeight) {
                scroll.y += mouseScrollEvent->direction * 5;
                return false;
            }
        }
    }

    return true;
}

void Div::render(DrawData* data) {
    style.update(this, mDocument->animationController);

    float textWidth = data->measureText(textContent, style.fontFamily, style.fontSize);

    // Layout
    layout.calculateDimensions(mChildren);

    if (textWidth > layout.intrinsicWidth)
    {
        layout.intrinsicWidth = int(textWidth);
    }

    if (layout.intrinsicHeight < style.fontSize && textContent != "")
    {
        layout.intrinsicHeight = style.fontSize + 10;
    }

    layout.layout();

    // Rendering
    scissor.x = layout.rect.x;
    scissor.y = layout.rect.y;
    scissor.width = layout.rect.width;
    scissor.height = layout.rect.height;

    if (dirty > 0)
    {
        if (style.backgroundImage != "") {
            if (mBackgroundImage == nullptr) {
                mBackgroundImage = mDocument->loadImage(style.backgroundImage,
                    style.width, style.height);
            }

            data->addImage(layout.rect, mBackgroundImage->textureId);
        } else {
            data->addRectFilled(layout.rect, style.backgroundColor);
        }

    #define CHIMERA_DEBUG_RENDER 0
    #if CHIMERA_DEBUG_RENDER
        if (style.backgroundColor.a == 0)
        {
            style.backgroundColor = Color::fromRGBA(rand() % 255, rand() % 255, rand() % 255, 1);
        }
    #endif

        if (textContent != "") {
            Rect position{
                layout.rect.x + style.padding.left,
                layout.rect.y + style.padding.top,
                layout.rect.width,
                layout.rect.height
            };

            if (style.textAlign == Align::Center) {
                position.x = layout.rect.x + (layout.rect.width / 2) - (textWidth / 2);
            }

            auto newColor = style.color;
            newColor.a *= style.opacity;
            data->addText(position, textContent, style.fontFamily, style.fontSize, scissor, newColor);

            if (style.textDecoration == TextDecoration::Underline) {
                Rect decorationRect{position.x, position.y + style.fontSize, textWidth, 2};
                data->addRectFilled(decorationRect, style.color, scissor);
            }
        }

        // dirty--;
    }

    // Render scrollbars
    // if (rect.height < internalHeight) {
    //     Rect scrollbar{
    //         rect.x + rect.width,
    //         rect.y - scroll.y,
    //         20,
    //         50
    //     };
    //     //data->addRectFilled(scrollbar, Color::fromRGBA(150, 150, 150, 0.7), scrollbar);
    // }

    // Updating and propagation
    layout.updateChildren(mChildren);

    float previousAlpha = data->globalAlpha;
    data->globalAlpha *= style.opacity;

    for (auto& element : mChildren)
    {
        element->render(data);
    }

    data->globalAlpha = previousAlpha;
}

}  // namespace Chimera


text:
package com.salesfront.commons.shared.model.v20150831.custom;

import com.salesfront.commons.shared.model.Model;

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

/**
 * Created by ahtremblay on 2016-07-04.
 */
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder={"button"})
public class Layout implements Model {
    private static final long serialVersionUID = 4421991364363260542L;

    private List<LayoutButton> button = new ArrayList<>();

    public List<LayoutButton> getButton() {
        return button;
    }

    public void setButton(List<LayoutButton> button) {
        this.button = button;
    }
}


text:
package com.tasomaniac.android.pomodoro.receiver;

import android.content.Context;
import android.content.Intent;

import com.tasomaniac.android.pomodoro.service.PomodoroNotificationService;
import com.tasomaniac.android.pomodoro.shared.receiver.BaseNotificationReceiver;

/**
 * Created by Said Tahsin Dane on 02/04/15.
 */
public class PomodoroNotificationReceiver extends BaseNotificationReceiver {

    public PomodoroNotificationReceiver() {
    }

    @Override
    public Intent getNotificationServiceIntent(Context context) {
        return new Intent(context, PomodoroNotificationService.class);
    }
}


text:
Angular IE7 Support Module
==========================

Since angular 1.2 it dropped support for IE7, and for good reason. However, poor little sods like me have to keep supporting my apps in IE7. While I keep working on my project I'm finding ways to get around IE7 annoyances and as I do I'll put them in to this module.

**Before using this module, make sure you have followed the [appropriate guidelines by angular](https://docs.angularjs.org/guide/ie).**

This module currently fixes:

1. The SCE (Strict Contextual Escaping) problem (simply by turning it off).
2. The `$anmiate.[add|remove]Class` problems which also affect `ng-show ng-hide ng-class`.

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

1. Either download directly from here or fetch with bower `bower install angular-ie7-support`.
2. Include a version of jQuery that supports IE7. You may include this conditionally just for IE7.
3. Make sure you have **only** given your app the ID `ng-app` (`<html id="ng-app" ng-app="my-app">`) when in IE7 by using conditional HTML comments.
4. Include this module in to your app `angular.module('my-app', ['ie7-support'])`.

Tests
-----

1. Install Karma: `[sudo] npm i -g karma-cli`
2. Install Bower: `[sudo] npm i -g bower`
3. Install components: `npm i`
4. Run a single test: `npm test`
5. Or watch your files and run the tests when they change: `npm run watch-test`


text: {{ tab.title }}


text:
<?php

namespace Biz\Thread\Firewall;

use Topxia\Service\Common\ServiceKernel;

class ClassroomThreadFirewall extends AbstractThreadFirewall
{
    public function accessThreadRead($thread)
    {
        return $this->getClassroomService()->canLookClassroom($thread['targetId']);
    }

    public function accessThreadCreate($thread)
    {
        $user = $this->getCurrentUser();
        $member = $this->getClassroomService()->getClassroomMember($thread['targetId'], $user['id']);

        $classroom = $this->getClassroomService()->getClassroom($thread['targetId']);

        if (!empty($member['levelId'])
            && empty($classroom['vipLevelId'])) {
            return false;
        }

        if ($this->isVipPluginEnabled()
            && $this->getSettingService()->get('vip.enabled', 0)
            && !empty($member['levelId'])
            && $this->getVipService()->checkUserInMemberLevel($user['id'], $classroom['vipLevelId']) != 'ok') {
            return false;
        }

        return $this->getClassroomService()->canLookClassroom($thread['targetId']);
    }

    public function accessThreadDelete($thread)
    {
        return $this->hasManagePermission($thread, true);
    }

    public function accessThreadUpdate($thread)
    {
        return $this->hasManagePermission($thread, true);
    }

    public function accessThreadSticky($thread)
    {
        return $this->hasManagePermission($thread, false);
    }

    public function accessThreadNice($thread)
    {
        return $this->hasManagePermission($thread, false);
    }

    public function accessThreadSolved($thread)
    {
        return $this->hasManagePermission($thread, false);
    }

    public function accessPostCreate($post)
    {
        return $this->getClassroomService()->canLookClassroom($post['targetId']);
    }

    public function accessPostUpdate($post)
    {
        return $this->hasManagePermission($post, true);
    }

    public function accessPostDelete($post)
    {
        return $this->hasManagePermission($post, true);
    }

    public function accessPostVote($post)
    {
        return $this->getClassroomService()->canLookClassroom($post['targetId']);
    }

    public function accessPostAdopted($post)
    {
        $result = $this->getClassroomService()->canLookClassroom($post['targetId']);

        return $result;
    }

    public function accessEventCreate($resource)
    {
        return $this->getClassroomService()->canCreateThreadEvent($resource);
    }

    public function accessMemberDelete($member)
    {
        if ($this->getClassroomService()->canManageClassroom($member['targetId'])) {
            return true;
        }

        $user = $this->getCurrentUser();

        if ($member['userId'] == $user['id']) {
            return true;
        }

        return false;
    }

    protected function hasManagePermission($resource, $ownerCanManage = false)
    {
        if ($this->getClassroomService()->canManageClassroom($resource['targetId'], 'admin_course_thread')) {
            return true;
        }

        $user = $this->getCurrentUser();

        if ($ownerCanManage && $resource['userId'] == $user['id']) {
            return true;
        }

        return false;
    }

    protected function getClassroomService()
    {
        return ServiceKernel::instance()->createService('Classroom:ClassroomService');
    }

    protected function getVipService()
    {
        return ServiceKernel::instance()->createService('VipPlugin:Vip:VipService');
    }

    protected function getKernel()
    {
        return ServiceKernel::instance();
    }

    protected function isVipPluginEnabled()
    {
        $setting = $this->getSettingService()->get('vip');

        return $this->isPluginInstalled('Vip') && !empty($setting['enabled']);
    }

    protected function isPluginInstalled($code)
    {
        $app = ServiceKernel::instance()->createService('CloudPlatform:AppService')->getAppByCode($code);

        return !empty($app);
    }

    protected function getSettingService()
    {
        return ServiceKernel::instance()->createService('System:SettingService');
    }

    public function getCurrentUser()
    {
        return $this->getKernel()->getCurrentUser();
    }
}


text:
import threading
import os

import sublime
import sublime_plugin

from .. import text
from ..show_quick_panel import show_quick_panel
from ..package_manager import PackageManager
from .existing_packages_command import ExistingPackagesCommand

class ListPackagesCommand(sublime_plugin.WindowCommand):

    """
    A command that shows a list of all installed packages in the quick panel
    """

    def run(self):
        ListPackagesThread(self.window).start()

class ListPackagesThread(threading.Thread, ExistingPackagesCommand):

    """
    A thread to prevent the listing of existing packages from freezing the UI
    """

    def __init__(self, window, filter_function=None):
        """
        :param window:
            An instance of :class:`sublime.Window` that represents the Sublime
            Text window to show the list of installed packages in.

        :param filter_function:
            A callable to filter packages for display. This function gets
            called for each package in the list with a three-element list
            as returned by :meth:`ExistingPackagesCommand.make_package_list`:
              0 - package name
              1 - package description
              2 - [action] installed version; package url
            If the function returns a true value, the package is listed,
            otherwise it is discarded. If `None`, no filtering is performed.
        """

        self.window = window
        self.filter_function = filter_function
        self.manager = PackageManager()
        threading.Thread.__init__(self)

    def run(self):
        self.package_list = self.make_package_list()
        if self.filter_function:
            self.package_list = list(filter(self.filter_function, self.package_list))

        def show_panel():
            if not self.package_list:
                sublime.message_dialog(text.format(
                    u'''
                    Package Control

                    There are no packages to list
                    '''
                ))
                return
            show_quick_panel(self.window, self.package_list, self.on_done)
        sublime.set_timeout(show_panel, 10)

    def on_done(self, picked):
        """
        Quick panel user selection handler - opens the homepage for any
        selected package in the user's browser

        :param picked:
            An integer of the 0-based package name index from the presented
            list. -1 means the user cancelled.
        """

        if picked == -1:
            return
        package_name = self.package_list[picked][0]

        def open_dir():
            package_dir = self.manager.get_package_dir(package_name)
            if not os.path.exists(package_dir):
                package_dir = self.manager.settings['installed_packages_path']
            self.window.run_command('open_dir', {"dir": package_dir})
        sublime.set_timeout(open_dir, 10)


text:
wikitree-tools
==============

Collection of tools for working with WikiTree


text:
package com.taobao.weex.ui.component;

import com.taobao.weappplus_sdk.BuildConfig;
import com.taobao.weex.WXSDKInstanceTest;
import com.taobao.weex.common.Component;
import com.taobao.weex.common.Constants;
import com.taobao.weex.dom.TestDomObject;
import com.taobao.weex.ui.SimpleComponentHolder;
import com.taobao.weex.ui.view.WXEditText;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

import static com.taobao.weex.common.Constants.Name.*;
import static com.taobao.weex.common.Constants.Value.*;

/**
 * Created by sospartan on 8/3/16.
 */
@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 19)
@PowerMockIgnore( {"org.mockito.*", "org.robolectric.*", "android.*"})
@PrepareForTest
public class EditComponentTest {
  static final String[] PROPS = {
      TEXT_ALIGN,
      FONT_SIZE,
      COLOR,
      TYPE,
      VALUE,
      PLACE_HOLDER,
      PLACEHOLDER_COLOR,
      AUTOFOCUS,
      LINES,
      SINGLELINE,
      MAX_LENGTH,
      ROWS};
  static final Object[][] TEST_VALUES = {
      {null,CENTER, Constants.Name.LEFT, Constants.Name.RIGHT,"kdkdkdk"},
      {null,12,Integer.MAX_VALUE,0,-2},
      {"red","#000","#ffffff","rgb(12,23,45)"},
      {"DKDK",
          TEXT,
          PASSWORD,
          TEL,
          EMAIL,
          URL,
          DATE,
          TIME,
          DATETIME},
      {null,123,"dkdkdkdk"},
      {null,123,"dkdkdkdk"},
      {"red","#000","#ffffff","rgb(12,23,45)"},
      {null,true,"true","false",false,"test"},
      {null,34,Integer.MAX_VALUE,-1,"test"},
      {null,true,"true","false",false,"test"},
      {null,34,Integer.MAX_VALUE,-1,"test"},
      {null,34,Integer.MAX_VALUE,-1,"test"},
      };

  AbstractEditComponent component;

  public static WXInput create() throws IllegalAccessException, InstantiationException, InvocationTargetException {
    return (WXInput) new SimpleComponentHolder(WXInput.class).createInstance(WXSDKInstanceTest.createInstance(), new TestDomObject(), WXDivTest.create(), false);
  }

  public static Textarea createTextarea() throws IllegalAccessException, InstantiationException, InvocationTargetException {
    return (Textarea) new SimpleComponentHolder(Textarea.class).createInstance(WXSDKInstanceTest.createInstance(), new TestDomObject(), WXDivTest.create(), false);
  }

  @Before
  public void setUp() throws Exception {
    component = create();
    ComponentTest.create(component);
  }

  @After
  public void tearDown() throws Exception {
    ComponentTest.destory(component);
  }

  @Test
  public void testEvent() throws Exception {
    WXEditText view = component.getHostView();
    view.performClick();
    view.setText("");
    view.requestFocus();
    view.setText("hello");
    view.clearFocus();
    view.setText(null);
  }

  @Test
  public void testSetProperty() throws Exception {

    ComponentTest.setProperty(component,PROPS,TEST_VALUES);
  }

}


text:
namespace EventSystem.Web.Models
{
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using EventSystem.Web.Attributes;
    using Resources;
    public class ExternalLoginConfirmationViewModel
    {
        [Required]
        [ResourcesDisplayName("Email", NameResourceType = typeof(Global))]
        public string Email { get; set; }
    }

    public class ExternalLoginListViewModel
    {
        public string ReturnUrl { get; set; }
    }

    public class SendCodeViewModel
    {
        public string SelectedProvider { get; set; }
        public ICollection<System.Web.Mvc.SelectListItem> Providers { get; set; }
        public string ReturnUrl { get; set; }
        public bool RememberMe { get; set; }
    }

    public class VerifyCodeViewModel
    {
        [Required]
        public string Provider { get; set; }

        [Required]
        [Display(Name = "Code")]
        public string Code { get; set; }
        public string ReturnUrl { get; set; }

        [Display(Name = "Remember this browser?")]
        public bool RememberBrowser { get; set; }

        public bool RememberMe { get; set; }
    }

    public class ForgotViewModel
    {
        [Required]
        [ResourcesDisplayName("Email", NameResourceType = typeof(Global))]
        public string Email { get; set; }
    }

    public class LoginViewModel
    {
        [Required(ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "RequiredEmail")]
        [ResourcesDisplayName("Email", NameResourceType = typeof(Global))]
        [EmailAddress]
        public string Email { get; set; }

        [Required(ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "RequiredPassword")]
        [DataType(DataType.Password)]
        [ResourcesDisplayName("Password", NameResourceType = typeof(Global))]
        public string Password { get; set; }

        [ResourcesDisplayName("RememberMe", NameResourceType = typeof(Global))]
        public bool RememberMe { get; set; }
    }

    public class RegisterViewModel
    {

        [Required(ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "RequiredFirstName")]
        [ResourcesDisplayName("FirstName", NameResourceType = typeof(Global))]
        public string FirstName { get; set; }

        [Required(ErrorMessageResourceType = typeof(Resources.Global), ErrorMessageResourceName = "RequiredLastName")]
        [ResourcesDisplayName("LastName", NameResourceType = typeof(Global))]
        public string LastName { get; set; }

        [Required(ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "RequiredEmail")]
        [EmailAddress(ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "RequiredEmail")]
        [ResourcesDisplayName("Email", NameResourceType = typeof(Global))]
        public string Email { get; set; }

        [Required(ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "RequiredPassword")]
        [StringLength(100, ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "RequiredPassword", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [ResourcesDisplayName("Password", NameResourceType = typeof(Global))]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [ResourcesDisplayName("ConfirmPassword", NameResourceType = typeof(Global))]
        [Compare("Password", ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "PasswordMismatch")]
        public string ConfirmPassword { get; set; }
    }

    public class ResetPasswordViewModel
    {
        [Required(ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "RequiredEmail")]
        [EmailAddress(ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "RequiredEmail")]
        [ResourcesDisplayName("Email", NameResourceType = typeof(Global))]
        public string Email { get; set; }

        [Required(ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "RequiredPassword")]
        [StringLength(100, ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "RequiredPassword", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [ResourcesDisplayName("Password", NameResourceType = typeof(Global))]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [ResourcesDisplayName("ConfirmPassword", NameResourceType = typeof(Global))]
        [Compare("Password", ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "PasswordMismatch")]
        public string ConfirmPassword { get; set; }

        public string Code { get; set; }
    }

    public class ForgotPasswordViewModel
    {
        [Required(ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "RequiredEmail")]
        [EmailAddress(ErrorMessageResourceType = typeof(Global), ErrorMessageResourceName = "RequiredEmail")]
        [ResourcesDisplayName("Email", NameResourceType = typeof(Global))]
        public string Email { get; set; }
    }
}


text:
import test                         from 'ava';
import snapshot                     from '../../helpers/snapshot';
import Vue                          from 'vue/dist/vue.common.js';
import datepicker                   from '../../../src/lib/components/datepicker/index.vue';
import commonTest                   from '../../common/unit';

const testOptions = {
    test,
    Vue,
    snapshot,
    component : window.morning._origin.Form.extend(datepicker),
    name : 'datepicker',
    formValue1 : '2018-03-23',
    formValue2 : '2017-02-12',
    formValueInvalid1 : undefined,
    formValueInvalid2 : undefined,
    attrs : ``,
    uiid : 7,
    // cause : ui-calendar will highlight today.
    // but ui-datepicker no config can disabled this config.for test eveyday snapshot is different.
    delVmEl : true,
    _baseTestHookCustomMount : async vm => {

        // fixed date
        vm.date = +new Date(testOptions.formValue1);

        await new Promise(resolve => {

            vm.Vue.nextTick(() => {

                vm.$mount();

            });

            resolve();

        });

        return vm;

    },
    // this component allow emit event more than once.
    _formValueChangeSkipInvalidValueEmitTest : true,
    _formValueChangeSkipValueFilterEmitTest : true
};

commonTest.componentBase(testOptions);
commonTest.formBase(testOptions);
commonTest.formValueChange(testOptions);


text:
require_dependency "#{Rails.root}/lib/course_revision_updater"
require_dependency "#{Rails.root}/lib/article_status_manager"
require_dependency "#{Rails.root}/lib/importers/course_upload_importer"
require_dependency "#{Rails.root}/lib/data_cycle/update_logger"
require_dependency "#{Rails.root}/lib/analytics/histogram_plotter"
require_dependency "#{Rails.root}/lib/importers/revision_score_importer"
require_dependency "#{Rails.root}/lib/importers/average_views_importer"
require_dependency "#{Rails.root}/lib/errors/update_service_error_helper"
require_dependency "#{Rails.root}/lib/data_cycle/course_queue_sorting"

#= Pulls in new revisions for a single course and updates the corresponding records
class UpdateCourseStats
  include UpdateServiceErrorHelper
  include CourseQueueSorting

  def initialize(course, full: false)
    @course = course
    # If the upate was explicitly requested by a user,
    # it could be because the dates or other paramters were just changed.
    # In that case, do a full update rather than just fetching the most
    # recent revisions.
    @full_update = full || @course.needs_update

    @start_time = Time.zone.now
    fetch_data
    update_categories
    update_article_status if should_update_article_status?
    update_average_pageviews
    update_caches
    import_summaries_and_update_wikidata_stats if wikidata
    # This needs to happen after `update_caches` because it relies on ArticlesCourses#new_article
    # to calculate new article stats for each namespace.
    update_wiki_namespace_stats
    @course.update(needs_update: false)
    @end_time = Time.zone.now
    UpdateLogger.update_course(@course, 'start_time' => @start_time.to_datetime,
                                        'end_time' => @end_time.to_datetime,
                                        'sentry_tag_uuid' => sentry_tag_uuid,
                                        'error_count' => error_count)
  end

  private

  def fetch_data
    log_update_progress :start
    CourseRevisionUpdater.import_revisions(@course, all_time: @full_update, update_service: self)
    log_update_progress :revisions_imported

    RevisionScoreImporter.update_revision_scores_for_course(@course, update_service: self)
    log_update_progress :revision_scores_imported

    CourseUploadImporter.new(@course, update_service: self).run
    log_update_progress :uploads_imported
  end

  def update_categories
    Category.refresh_categories_for(@course)
    log_update_progress :categories_updated
  end

  def update_article_status
    ArticleStatusManager.update_article_status_for_course(@course)
    log_update_progress :article_status_updated
  end

  def update_average_pageviews
    AverageViewsImporter.update_outdated_average_views(@course.articles)
    log_update_progress :average_pageviews_updated
  end

  def update_caches
    ArticlesCourses.update_all_caches(@course.articles_courses)
    log_update_progress :articles_courses_updated
    CoursesUsers.update_all_caches(@course.courses_users)
    log_update_progress :courses_users_updated
    @course.update_cache
    HistogramPlotter.delete_csv(course: @course) # clear cached structural completeness data
    log_update_progress :course_cache_updated
  end

  def import_summaries_and_update_wikidata_stats
    UpdateWikidataStatsWorker.new.perform(@course)
    log_update_progress :wikidata_stats_updated
  end

  def update_wiki_namespace_stats
    # Update each of the tracked namespaces
    @course.course_wiki_namespaces.each do |course_wiki_ns|
      wiki = course_wiki_ns.courses_wikis.wiki
      namespace = course_wiki_ns.namespace
      UpdateWikiNamespaceStats.new(@course, wiki, namespace)
    end
    # Remove stats data for any namespaces that were previously
    # tracked but are no longer tracked.
    UpdateWikiNamespaceStats.clear_untracked_namespace_data(@course)
  end

  def wikidata
    @course.wikis.find { |wiki| wiki.project == 'wikidata' }
  end

  def log_update_progress(step)
    return unless debug?
    @sentry_logs ||= {}
    @sentry_logs[step] = Time.zone.now
    Sentry.capture_message "#{@course.title} update: #{step}",
                           level: 'warning',
                           extra: { logs: @sentry_logs }
  end

  TEN_MINUTES = 600
  def should_update_article_status?
    return true if Features.wiki_ed?
    # To cut down on overwhelming the system
    # for courses with huge numbers of articles
    # to check, we skip this on Programs & Events Dashboard
    # for slow-updating courses.
    # This means we miss cases of article deletion
    # and namespace changes unless the article
    longest_update_time(@course).to_i < TEN_MINUTES
  end

  def debug?
    @course.flags[:debug_updates]
  end
end


text:
'use strict';

// MODULES //

var Writable = require( 'readable-stream' ).Writable,
	copy = require( 'utils-copy' ),
	parse = require( 'utils-json-parse' ),
	validate = require( './validate.js' ),
	post = require( './post.js' );

// VARIABLES //

var DEFAULTS = require( './defaults.json' );

// STREAM //

/**
* FUNCTION: Stream( options )
*	Writable stream constructor.
*
* @constructor
* @param {Object} options - stream options
* @param {String} options.key - API key
* @param {String} options.id - widget id
* @param {Boolean} [options.objectMode=false] - specifies whether stream should operate in object mode
* @param {Boolean} [options.decodeStrings=true] - specifies whether written strings should be decoded into Buffer objects
* @param {Number} [options.highWaterMark=16] - specifies the Buffer level for when `write()` starts returning `false`
* @returns {Stream} Writable stream
*/
function Stream( options ) {
	var opts,
		err;

	if ( !arguments.length ) {
		throw new Error( 'insufficient input arguments. Must provide stream options.' );
	}
	if ( !( this instanceof Stream ) ) {
		return new Stream( options );
	}
	opts = copy( DEFAULTS );
	err = validate( opts, options );
	if ( err ) {
		throw err;
	}
	Writable.call( this, opts );
	this._objectMode = opts.objectMode;
	this._post = post( opts );
	this._destroyed = false;
	return this;
} // end FUNCTION Stream()

/**
* Create a prototype which inherits from the parent prototype.
*/
Stream.prototype = Object.create( Writable.prototype );

/**
* Set the constructor.
*/
Stream.prototype.constructor = Stream;

/**
* METHOD: _write( chunk, encoding, clbk )
*	Implements the `_write` method to send data to Geckoboard.
*
* @private
* @param {Buffer|String} chunk - streamed chunk
* @param {String} encoding - Buffer encoding
* @param {Function} clbk - callback to invoke once finished processing streamed chunk
*/
Stream.prototype._write = function _write( chunk, encoding, clbk ) {
	if ( !this._objectMode ) {
		if ( encoding === 'buffer' ) {
			chunk = chunk.toString();
		}
		chunk = parse( chunk );
		if ( chunk instanceof Error ) {
			return clbk( chunk );
		}
	}
	this._post( chunk, clbk );
}; // end METHOD _write()

/**
* METHOD: destroy( [error] )
*	Gracefully destroys a stream, providing backwards compatibility.
*
* @param {Object} [error] - optional error message
* @returns {Stream} Stream instance
*/
Stream.prototype.destroy = function destroy( error ) {
	if ( this._destroyed ) {
		return;
	}
	var self = this;
	this._destroyed = true;
	process.nextTick( close );

	return this;

	/**
	* FUNCTION: close()
	*	Emits a `close` event.
	*
	* @private
	*/
	function close() {
		if ( error ) {
			self.emit( 'error', error );
		}
		self.emit( 'close' );
	}
}; // end METHOD destroy()

// EXPORTS //

module.exports = Stream;