text:
//  ---------------------------------------------------------------------------------
//  Copyright (c) Microsoft Open Technologies, Inc.  All rights reserved.
//
//  The MIT License (MIT)
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//  ---------------------------------------------------------------------------------

namespace Microsoft.ConnectTheDots.Test
{
    using System;
    using System.Threading;
    using System.Net;
    using System.Diagnostics;
    using Microsoft.ConnectTheDots.Common;

    //--//

    public class WebServiceTest : ITest
    {
        public const int TEST_ITERATIONS = 100;
        public const int MAX_TEST_MESSAGES = 1000;

        //--//

        private const int MINUTES_TO_MILLISECONDS  = 60 * 1000;
        private const int STOP_TIMEOUT_MS          = 5000;                        // ms
        private const int MIN_WAIT_BEETWEEN_BURSTS = 5 * MINUTES_TO_MILLISECONDS; // 5 minutes in milliseconds

        //--//

        private readonly ILogger _logger;
        private readonly Random  _rand;
        private          string  _url;
        private          int     _totalMessagesSent;
        private          int     _totalMessagesToSend;

        //--//

        public WebServiceTest( string url, ILogger logger )
        {
            if( logger == null )
            {
                throw new ArgumentException( "Cannot run tests without logging" );
            }

            _logger = logger;

            _url = url;
            _rand = new Random( );
            _totalMessagesSent = 0;
            _totalMessagesToSend = 0;
        }

        public void Run( )
        {
            try
            {
                // Send a flurry of messages, repeat a few times
                for( int iteration = 0; iteration < TEST_ITERATIONS; ++iteration )
                {
                    int count = _rand.Next( MAX_TEST_MESSAGES );

                    while( --count >= 0 )
                    {
                        HttpWebRequest request = ( HttpWebRequest )WebRequest.Create( _url );
                        request.Method = "GET";

                        using( HttpWebResponse response = ( HttpWebResponse )request.GetResponse( ) )
                        {
                            if( response.StatusCode != HttpStatusCode.OK )
                            {
                                SignalError( response.StatusCode );
                            }
                            else
                            {
                                _totalMessagesSent++;
                            }
                        }
                    }

                    // sleep 5 to 10 minutes
                    int sleepMS = MIN_WAIT_BEETWEEN_BURSTS + _rand.Next( MIN_WAIT_BEETWEEN_BURSTS );

                    Console.WriteLine( String.Format( "Sent {0} messages, sleeping now for {1} minutes", _totalMessagesSent, sleepMS / MINUTES_TO_MILLISECONDS ) );

                    Thread.Sleep( sleepMS );
                }
            }
            catch( Exception ex )
            {
                _logger.LogError( "exception caught: " + ex.StackTrace );
            }
        }

        public void Completed( )
        {
            throw new NotImplementedException( );
        }

        public int TotalMessagesSent
        {
            get
            {
                return _totalMessagesSent;
            }
        }

        public int TotalMessagesToSend
        {
            get
            {
                return _totalMessagesToSend;
            }
        }

        protected void SignalError( HttpStatusCode code )
        {
            _logger.LogError( "Response yielded error: " + code.ToString( ) );

            Debug.Assert( false );
        }

    }
}


text:
var DrillbitTest =
{
	currentTest:null,
	results:[],
	tests:[],
	success:0,
	failed:0,
	totalAssertions:0,
	testAssertions:0,
	autoRun: true,
	completed: false,

	fireEvent: function(name, event) {
		var osname = Ti.Platform.osname;
		var isIOS = osname == "iphone" || osname == "ipad";

		event.name = name;
		event.platform = isIOS ? "iphone" : "android";
		event.suite = DrillbitTest.NAME;

		if (isIOS) {
			// The console log has a character limit, so we use http to communicate events
			var httpClient = Ti.Network.createHTTPClient();
			var url = "http://localhost:9999";
			httpClient.open("POST", "http://localhost:9999");
			httpClient.send(JSON.stringify(event));
		} else {
			Ti.API.debug("DRILLBIT_EVENT: " + JSON.stringify(event));
		}
	},

	runningTest: function(suite, name)
	{
		this.fireEvent('test', {test: name});
		appendMessage("> running test " + name + " in suite " + suite);
	},

	assertion: function(subject)
	{
		DrillbitTest.totalAssertions++;
		DrillbitTest.testAssertions++;
	},

	testPassed: function(name, lineNumber)
	{
		this.success++;
		this.results.push({
			name:name,
			passed:true,
			message: "Success",
			lineNumber: lineNumber
		});
		this.fireEvent('testStatus', {test: name, lineNumber: lineNumber, passed: true, error: null, assertions: DrillbitTest.testAssertions});
		appendMessage('>> test ' + name + ' passed', 'pass');
		if (DrillbitTest.autoRun) {
			DrillbitTest.runNextTest();
		}
	},

	testFailed: function(name, e)
	{
		this.failed++;
		this.results.push({
			name:name,
			passed:false,
			lineNumber:e.line,
			message: e.message || String(e)
		});

		var errorMessage = String(e).replace("\n","\\n");
		this.fireEvent('testStatus', {test: name, lineNumber: e.line, passed: false, error: errorMessage, assertions: DrillbitTest.testAssertions});

		appendMessage('>> test ' + name + ' failed: line ' + e.line + ", error: " + errorMessage, 'fail');
		if (DrillbitTest.autoRun) {
			DrillbitTest.runNextTest();
		}
	},

	complete: function() {
		this.completed = true;
		try {
			var results = this.getResults();
			results.suite = DrillbitTest.NAME;

			var coverage = null;
			var resultsInfo = { suite: DrillbitTest.NAME };
			var eventName = "complete";
			if (Ti.Platform.osname == "android") {
				// TODO just return this as an object
				// TODO re-enable coverage Ti.dumpCoverage();
				var resultsFile = Ti.Filesystem.getFile("appdata://results.json");
				resultsFile.write(JSON.stringify(results));
				eventName = "completeAndroid";
				resultsInfo.resultsPath = resultsFile.getNativePath();
				// TODO re-enable coverage resultsInfo.coveragePath = Ti.Filesystem.getFile("appdata://coverage.json").getNativePath();
			} else {
				coverage = Ti.dumpCoverage();
				resultsInfo.results = results;
				resultsInfo.coverage = coverage;
			}

			this.fireEvent(eventName, resultsInfo);
			if (Ti.Platform.osname == "android") {
				if ("instrumentation" in DrillbitTest) {
					DrillbitTest.instrumentation.finish(Ti.Android.RESULT_OK);
				} else {
					Titanium.API.debug('Instrumentation not defined, skipping automated finish');
				}
			}
		} catch (e) {
			Titanium.API.error("Exception on completion: "+e);
		}
	},

	getResults: function()
	{
		return {
			'results':this.results,
			'count':this.results.length,
			'success':this.success,
			'failed':this.failed,
			'assertions':this.assertions
		};
	},

	onComplete: function() {
		this.complete();
	},

	runNextTest: function() {
		this.testAssertions = 0;
		if (this.tests.length == 0) {
			this.onComplete();
		} else {
			var t = this.tests.shift();
			t();
		}
	}
};

DrillbitTest.gscope = {};
DrillbitTest.currentSubject = null;

function valueOf(obj)
{
	var subject = new DrillbitTest.Subject(obj);
	DrillbitTest.currentSubject = subject;
	return subject;
}

function fail(message, lineNumber)
{
	throw new DrillbitTest.Error(message, lineNumber);
}

DrillbitTest.Error = function(message,line)
{
	this.message = message;
	this.line = line;
};

DrillbitTest.Error.prototype.toString = function()
{
	return this.message;
};

DrillbitTest.Subject = function(target) {
	this.target = target;
	this.lineNumber = 0;
};

DrillbitTest.Subject.prototype.toString = function()
{
	return 'Subject[target='+this.target+',line='+this.lineNumber+']';
};

DrillbitTest.Scope = function(name) {
	this._testName = name;
	this._completed = false;
	// copy in the global scope
	for (var p in DrillbitTest.gscope)
	{
		this[p] = DrillbitTest.gscope[p];
	}
}

DrillbitTest.Scope.prototype.passed = function()
{
	if (!this._completed)
	{
		this._completed = true;
		if (DrillbitTest.currentSubject)
		{
			var lineNumber = 0;
			if ("lineNumber" in DrillbitTest.currentSubject) {
				lineNumber = DrillbitTest.currentSubject.lineNumber;
			}
			DrillbitTest.testPassed(this._testName, lineNumber);

		}
		else
		{
			DrillbitTest.testPassed(this._testName,-1);
		}
		DrillbitTest.currentSubject = null;
	}
}

DrillbitTest.Scope.prototype.failed = function(ex)
{
	if (!this._completed)
	{
		this._completed = true;
		DrillbitTest.testFailed(this._testName,ex);
		DrillbitTest.currentSubject = null;
	}
}

DrillbitTest.Subject.prototype.shouldBe = function(expected,lineNumber)
{
	this.lineNumber = lineNumber;
	DrillbitTest.assertion(this);
	if (this.target != expected)
	{
		throw new DrillbitTest.Error('should be: "'+expected+'", was: "'+this.target+'"',lineNumber);
	}
};
DrillbitTest.Subject.prototype.shouldBeEqual = DrillbitTest.Subject.prototype.shouldBe;

DrillbitTest.Subject.prototype.shouldNotBe = function(expected,lineNumber)
{
	this.lineNumber = lineNumber;
	DrillbitTest.assertion(this);
	if (this.target == expected)
	{
		throw new DrillbitTest.Error('should not be: '+expected+', was: '+this.target,lineNumber);
	}
};
DrillbitTest.Subject.prototype.shouldNotBeEqual = DrillbitTest.Subject.prototype.shouldNotBe;

DrillbitTest.Subject.prototype.shouldNotBeNull = function(expected,lineNumber)
{
	this.lineNumber = lineNumber;
	DrillbitTest.assertion(this);
	if (this.target === null)
	{
		throw new DrillbitTest.Error('should not be null, was: '+this.target,lineNumber);
	}
};

DrillbitTest.Subject.prototype.shouldNotBeUndefined = function(expected,lineNumber)
{
	this.lineNumber = lineNumber;
	DrillbitTest.assertion(this);
	if (this.target === undefined)
	{
		throw new DrillbitTest.Error('should not be undefined, was: '+this.target,lineNumber);
	}
};

DrillbitTest.Subject.prototype.shouldBeExactly = function(expected,lineNumber)
{
	this.lineNumber = lineNumber;
	DrillbitTest.assertion(this);
	if (this.target !== expected)
	{
		throw new DrillbitTest.Error('should be exactly: '+expected+', was: '+this.target,lineNumber);
	}
};

DrillbitTest.Subject.prototype.shouldNotBeExactly = function(expected,lineNumber)
{
	this.lineNumber = lineNumber;
	DrillbitTest.assertion(this);
	if (this.target === expected)
	{
		throw new DrillbitTest.Error('should not be exactly: '+expected+', was: '+this.target,lineNumber);
	}
};

DrillbitTest.Subject.prototype.shouldBeNull = function(expected,lineNumber)
{
	this.lineNumber = lineNumber;
	DrillbitTest.assertion(this);
	if (this.target !== null)
	{
		throw new DrillbitTest.Error('should be null, was: '+this.target,lineNumber);
	}
};

DrillbitTest.Subject.prototype.shouldBeString = function(expected,lineNumber)
{
	this.lineNumber = lineNumber;
	DrillbitTest.assertion(this);
	if (typeof this.target !== 'string')
	{
		throw new DrillbitTest.Error('should be string, was: '+typeof(this.target),lineNumber);
	}
};

DrillbitTest.Subject.prototype.shouldBeUndefined = function(expected,lineNumber)
{
	this.lineNumber = lineNumber;
	DrillbitTest.assertion(this);
	if (this.target !== undefined)
	{
		throw new DrillbitTest.Error('should be undefined, was: '+this.target,lineNumber);
	}
};

DrillbitTest.Subject.prototype.shouldBeFunction = function(expected,lineNumber)
{
	this.lineNumber = lineNumber;
	DrillbitTest.assertion(this);
	if ((typeof(this.target) != 'function') && !(this.target instanceof Function))
	{
		throw new DrillbitTest.Error('should be a function, was: '+typeof(this.target),lineNumber);
	}
};

DrillbitTest.Subject.prototype.shouldBeObject = function(expected,lineNumber)
{
	this.lineNumber = lineNumber;
	DrillbitTest.assertion(this);
	if ((typeof(this.target) != 'object') && !(this.target instanceof Object))
	{
		throw new DrillbitTest.Error('should be a object, was: ' + this.target,lineNumber);
	}
};

DrillbitTest.Subject.prototype.shouldBeNumber = function(expected,lineNumber)
{
	this.lineNumber = lineNumber;
	DrillbitTest.assertion(this);
	if (typeof(this.target) != 'number')
	{
		throw new DrillbitTest.Error('should be a number, was: '+typeof(this.target),lineNumber);
	}
};

DrillbitTest.Subject.prototype.shouldBeBoolean = function(expected,lineNumber)
{
	this.lineNumber = lineNumber;
	DrillbitTest.assertion(this);
	if (typeof(this.target) != 'boolean')
	{
		throw new DrillbitTest.Error('should be a boolean, was: '+typeof(this.target),lineNumber);
	}
};

DrillbitTest.Subject.prototype.shouldBeTrue = function(expected,lineNumber)
{
	this.lineNumber = lineNumber;
	DrillbitTest.assertion(this);
	if (this.target!==true)
	{
		throw new DrillbitTest.Error('should be true, was: '+this.target,lineNumber);
	}
};

DrillbitTest.Subject.prototype.shouldBeFalse = function(expected,lineNumber)
{
	this.lineNumber = lineNumber;
	DrillbitTest.assertion(this);
	if (this.target!==false)
	{
		throw new DrillbitTest.Error('should be false, was: '+this.target,lineNumber);
	}
};

DrillbitTest.Subject.prototype.shouldBeZero = function(expected,lineNumber)
{
	this.lineNumber = lineNumber;
	DrillbitTest.assertion(this);
	if (this.target!==0)
	{
		throw new DrillbitTest.Error('should be 0 (zero), was: '+this.target+' ('+typeof(this.target)+')',lineNumber);
	}
};

DrillbitTest.Subject.prototype.shouldBeArray = function(expected,lineNumber)
{
	this.lineNumber = lineNumber;
	DrillbitTest.assertion(this);
	// better way to check? we need to support our duck-typing too..
	if (this.target.constructor != Array)
	{
		throw new DrillbitTest.Error('should be an array, was: '+this.target,lineNumber);
	}
};

DrillbitTest.Subject.prototype.shouldContain = function(expected,lineNumber)
{
	this.lineNumber = lineNumber;
	DrillbitTest.assertion(this);
	if (this.target.indexOf(expected)==-1)
	{
		throw new DrillbitTest.Error('should contain: '+expected+', was: '+this.target,lineNumber);
	}
};

DrillbitTest.Subject.prototype.shouldBeOneOf = function(expected,lineNumber)
{
	this.lineNumber = lineNumber;
	DrillbitTest.assertion(this);
	if (expected.indexOf(this.target)==-1)
	{
		throw new DrillbitTest.Error('should contain one of: ['+expected.join(",")+'] was: '+this.target,lineNumber);
	}
};

DrillbitTest.Subject.prototype.shouldMatchArray = function(expected,lineNumber)
{
	this.lineNumber = lineNumber;
	DrillbitTest.assertion(this);
	if (this.target.length && expected.length && this.target.length == expected.length) {
		for (var i = 0; i < expected.length; i++) {
			if (expected[i] != this.target[i]) {
				throw new DrillbitTest.Error('element ' + i + ' should be: '+expected[i]+' was: '+this.target[i],lineNumber);
			}
		}
	}
	else {
		throw new DrillbitTest.Error('array lengths differ, expected: '+expected+', was: '+this.target,lineNumber);
	}
};

DrillbitTest.Subject.prototype.shouldBeGreaterThan = function(expected, lineNumber)
{
	this.lineNumber = lineNumber;
	DrillbitTest.assertion(this);
	if (this.target <= expected)
	{
		throw new DrillbitTest.Error('should be greater than, was ' + this.target + ' <= ' + expected,lineNumber);
	}
};

DrillbitTest.Subject.prototype.shouldBeLessThan = function(expected, lineNumber)
{
	this.lineNumber = lineNumber;
	DrillbitTest.assertion(this);
	if (this.target >= expected)
	{
		throw new DrillbitTest.Error('should be less than, was ' + this.target + ' >= ' + expected,lineNumber);
	}
};

DrillbitTest.Subject.prototype.shouldBeGreaterThanEqual = function(expected, lineNumber)
{
	this.lineNumber = lineNumber;
	DrillbitTest.assertion(this);
	if (this.target < expected)
	{
		throw new DrillbitTest.Error('should be greater than equal, was ' + this.target + ' < ' + expected,lineNumber);
	}
};

DrillbitTest.Subject.prototype.shouldBeLessThanEqual = function(expected, lineNumber)
{
	this.lineNumber = lineNumber;
	DrillbitTest.assertion(this);
	if (this.target > expected)
	{
		throw new DrillbitTest.Error('should be greater than, was ' + this.target + ' > ' + expected,lineNumber);
	}
};

DrillbitTest.Subject.prototype.shouldThrowException = function(expected,lineNumber)
{
	this.lineNumber = lineNumber;
	DrillbitTest.assertion(this);
	if (typeof(this.target) == 'function')
	{
		try {
			this.target();
		} catch (e) { return; }
		throw new DrillbitTest.Error("should throw exception, but didn't",lineNumber);
	}
	else throw new DrillbitTest.Error("should throw exception, but target isn't a function",lineNumber);
};

DrillbitTest.Subject.prototype.shouldNotThrowException = function(expected,lineNumber)
{
	this.lineNumber = lineNumber;
	DrillbitTest.assertion(this);
	if (typeof(this.target) == 'function')
	{
		try {
			this.target();
		} catch (e) {
			throw new DrillbitTest.Error("should not throw exception, but did",lineNumber);
		}
	}
	else throw new DrillbitTest.Error("should not throw exception, but target isn't a function",lineNumber);
};

function AsyncTest(args) {
	this.startFn = args.start;
	this.timeout = args.timeout || null;
	this.timeoutError = args.timeoutError || null;
	this.onTimeoutFn = args.onTimeout || null;
	this.timer = null;
	this.sequence = [];
};

AsyncTest.prototype.async = function(fn) {
	var self = this;
	return function() {
		try {
			fn.apply(self,arguments);
			if (self.sequence.length > 0) {
				self.sequence.shift().call(self);
			} else {
				if (self.timer != null) {
					clearTimeout(self.timer);
				}
				self.callback.passed();
			}
		} catch (e) {
			self.callback.failed(e);
		}
	};
};

AsyncTest.prototype.start = function(callback) {
	this.callback = callback;
	try {
		this.result = this.startFn.apply(this, [callback]);
		if (this.timeout != null) {
			var self = this;
			this.timer = setTimeout(function() {
				if (self.onTimeoutFn != null) {
					try {
						this.onTimeoutFn.apply(this, [this.result]);
						callback.passed();
					} catch (e) {
						callback.failed(e);
					}
				} else {
					var message = self.timeoutError || "Error: Timed out (" + self.timeout + "ms)";
					callback.failed(message);
				}
			}, this.timeout);
		}
		if (this.sequence.length > 0) {
			this.sequence.shift().call(this);
		}
	} catch (e) {
		callback.failed(e);
		return;
	}
};

AsyncTest.prototype.failed = function(e) {
	if (this.timer != null) {
		clearTimeout(this.timer);
	}
	this.callback.failed(e);
};

function asyncTest(args) {
	args = typeof(args) == 'function' ? {start: args} : args;
	return new AsyncTest(args);
};

redpajama_set_name: RedPajamaGithub


text:
namespace CSharpOptions
{
    public static class Option
    {
        public static Option<T> Create<T>(T value)
        {
            if (value == null) return default(None<T>);
            return new Some<T>(value);
        }

        public static Option<T> None<T>()
        {
            return default(None<T>);
        }

        public static Option<T> Of<T>(T value)
        {
            return value == null ? None<T>() : new Some<T>(value);
        }

        public static Option<T> Of<T>(T? value) where T : struct
        {
            return !value.HasValue ? None<T>() : new Some<T>(value.Value);
        }

        public static Option<T> ToOption<T>(this T value)
        {
            return Of(value);
        }

        public static Option<T> ToOption<T>(this T? value) where T : struct
        {
            return Of(value);
        }
    }
}


text:
* [Description](#description)
* [Data Types](#types)
* [Function Index](#index)
* [Function Details](#functions)

Erbi statement handle functions: perform queries, fetch rows, etc.
Copyright (c) 2013 Voalte Inc. <jburroughs@voalte.com>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

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

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

## Data Types ##

### stmt_private() ###

__abstract datatype__: `stmt_private()`

## Function Index ##

bind_params/2	Bind given parameters to this statement.

execute/1	Begin execution of this statement.

execute/2

fetchall_dict/1

fetchall_list/1
Fetch all remaining records and return a list.

fetchall_proplist/1

fetchrow_dict/1

fetchrow_list/1	Fetch a single record from the result set.

fetchrow_proplist/1

finish/1	Complete processing with this statement.

## Function Details ##

### bind_params/2 ###

bind_params(Statement::erbi_statement(), Params::erbi_bind_values()) -> ok | {error, any()}

Bind given parameters to this statement.
May be supplied as a positional list, or by name (contingent on driver support).
- Statement  - erbi statement handle
- BindValues - List of parameter values

### execute/1 ###

execute(Statement::erbi_statement()) -> ok | {error, any()}

Begin execution of this statement

### execute/2 ###

execute(Statement::erbi_statement(), Params::erbi_bind_values()) -> ok | {error, any()}

### fetchall_dict/1 ###

fetchall_dict(Statement::erbi_statement()) -> {ok, [dict()]} | {error, any()}

### fetchall_list/1 ###

fetchall_list(Statement::erbi_statement()) -> {ok, [[any()]]} | {error, any()}

Fetch all remaining records and return a list.

### fetchall_proplist/1 ###

fetchall_proplist(Statement::erbi_statement()) -> {ok, [[{atom(), any()}]]} | {error, any()}

### fetchrow_dict/1 ###

fetchrow_dict(Statement::erbi_statement()) -> {ok, dict()} | exhausted | {error, any()}

### fetchrow_list/1 ###

fetchrow_list(Statement::erbi_statement()) -> {ok, [any()]} | exhausted | {error, any()}

Fetch a single record from the result set.

### fetchrow_proplist/1 ###

fetchrow_proplist(Statement::erbi_statement()) -> {ok, [{atom(), any()}]} | exhausted | {error, any()}

### finish/1 ###

finish(Statement::erbi_statement()) -> ok | {error, any()}

Complete processing with this statement.
Closes associated cursor.


text:
from __future__ import unicode_literals
import webnotes
from webnotes.widgets.reportview import execute as runreport
from webnotes.utils import getdate

def execute(filters=None):
	priority_map = {"High": 3, "Medium": 2, "Low": 1}

	todo_list = runreport(doctype="ToDo", fields=["name", "date", "description",
		"priority", "reference_type", "reference_name", "assigned_by", "owner"],
		filters=[["ToDo", "checked", "!=", 1]])

	todo_list.sort(key=lambda todo: (priority_map.get(todo.priority, 0),
		todo.date and getdate(todo.date) or getdate("1900-01-01")), reverse=True)

	columns = ["ID:Link/ToDo:90", "Priority::60", "Date:Date", "Description::150",
		"Assigned To/Owner:Link/Profile:120", "Assigned By:Link/Profile:120", "Reference::200"]

	result = []
	for todo in todo_list:
		if todo.reference_type:
			todo.reference = """%s: %s""" % \
				(todo.reference_type, todo.reference_name, todo.reference_type, todo.reference_name)
		else:
			todo.reference = None
		result.append([todo.name, todo.priority, todo.date, todo.description,
			todo.owner, todo.assigned_by, todo.reference])

	return columns, result


text:
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using Microsoft.WindowsAzure.Storage.Blob;

namespace AccidentalFish.ApplicationSupport.Azure.Blobs
{
    internal class BlobMultipartStreamProvider : MultipartStreamProvider
    {
        private readonly Func<ContentDispositionHeaderValue, string> _getBlobName;
        private readonly CloudBlobContainer _blobContainer;

        public BlobMultipartStreamProvider(CloudBlobContainer blobContainer)
        {
            _getBlobName = null;
            _blobContainer = blobContainer;
        }

        public BlobMultipartStreamProvider(CloudBlobContainer blobContainer,
            Func<ContentDispositionHeaderValue, string> getBlobName) : this(blobContainer)
        {
            _getBlobName = getBlobName;
        }

        public override Stream GetStream(HttpContent parent, HttpContentHeaders headers)
        {
            Stream stream = null;
            ContentDispositionHeaderValue contentDisposition = headers.ContentDisposition;
            if (contentDisposition != null)
            {
                string blobFilename = null;
                if (_getBlobName != null)
                {
                    blobFilename = _getBlobName(contentDisposition);
                }
                else if (!String.IsNullOrWhiteSpace(contentDisposition.FileName))
                {
                    blobFilename = contentDisposition.FileName;
                }

                if (!String.IsNullOrWhiteSpace(blobFilename))
                {
                    CloudBlockBlob blob = _blobContainer.GetBlockBlobReference(blobFilename);
                    stream = blob.OpenWrite();
                }
            }
            return stream;
        }
    }
}


text:
package plans

type Action rune

const (
	NoOp             Action = 0
	Create           Action = '+'
	Read             Action = '←'
	Update           Action = '~'
	DeleteThenCreate Action = '∓'
	CreateThenDelete Action = '±'
	Delete           Action = '-'
)

//go:generate stringer -type Action

// IsReplace returns true if the action is one of the two actions that
// represents replacing an existing object with a new object:
// DeleteThenCreate or CreateThenDelete.
func (a Action) IsReplace() bool {
	return a == DeleteThenCreate || a == CreateThenDelete
}


text:
///<reference path="../IModel.ts"/>

module TS.MVP.Table {
    export interface ITablePresenterModel extends IModel {
        getRowCount(): number;

        getColumnCount(): number;

        getRowHeaderDepth(): number;

        getColumnHeaderDepth(): number;

        getRowHeader(row: number, depth:number): TableHeader;

        getColumnHeader(column: number, depth:number): TableHeader;

        getCell(row: number, column: number): IPresenter;
    }

}


text:
layout: post

title: "Coveo for Sitecore V4 Cloud - The Road to Production"
tags: [Sitecore, Cloud, Coveo for Sitecore, Environment]

author:
  name: Simon Langevin
  bio:  Coveo for Sitecore Solution Architect
  image: slangevin.png
---
Coveo for Sitecore 4.0 was released this spring and allowed Coveo for Sitecore users to move their index to the cloud, reducing maintenance effort and opening the way for the advanced cloud features, such as Coveo Machine Learning and the query pipelines.
Integrating Coveo for Sitecore to your Sitecore solution is now easier than ever. You can download the package directly on [the Coveo website](https://www.coveo.com/en/solutions/coveo-for-sitecore/download) and follow the installation wizard in Sitecore.
This is great to try the product with a trial organization, but how do you manage a paid license?
I received several questions in the past few months about environment setup and license management. In this blog post, I will try to clarify a few things.
<!-- more -->

## What kind of organization do I get when I purchase Coveo for Sitecore?

All Coveo for Sitecore cloud plans offer a Production and Sandbox cloud organization. The owner of the organization is the recipient of the license.
The Coveo license team rarely accepts changing the owner for you due to legal and security concerns. This means that you, or your client, need to manage access to the organizations.
Inviting members is a straightforward approach documented [here](https://developers.coveo.com/x/AocdAg).
Once a member is assigned as an Administrator, he or she can manage the invites in the future.

## What about integrators?

Out of the box, Coveo Cloud has two groups: Administrators and Users. Users have very limited privileges, which are not sufficient for a Coveo for Sitecore developers.
You can add integrators to the Administrator group, but they will then have the same powers as you, including the ability to invite members and to give them administrator privileges.
This might not be the best solution for integrators hired from an external agency. The Coveo documentation team wrote a help page to [create a group with restricted privileges](https://developers.coveo.com/x/14AkAg).
This page can help you create a group with access to everything except groups and members control. The decision to remove other privileges mostly depend on your security policy.
For example, you might want to give read access to the Usage Analytics or Index Content on the sandbox organization, but remove that privilege in production.

## Where do I code? Where do I test?

As a best practice, I would tend to limit my sandbox organization for testing only. For development, you can either purchase an additional organization, or use trial organizations.
This is also a good strategy when multiple developers are coding on different copies of your instance. Each of them can have their own organization to code and test against.
The trial organizations are only valid for one month, but creating a new one is very easy. Simply go to the Sitecore Control Panel and choose Configuration in the Coveo Search Menu. From there, you can use the Coveo Cloud Organization feature to connect to Coveo Cloud. Once you are redirected back to Sitecore, you will be given the option to create a new organization. This new org will not be configured, but rebuilding your indexes will do the trick.

![Coveo for Sitecore Cloud Configuration](/images/CoveoForSitecoreV4Cloud/NewOrg.PNG)

The only limitation with this approach is when it comes to external content. You will lose the configuration of external sources every month, but be aware that you can access the JSON of your source from the Cloud Administration Console. Keeping this JSON and copying it in another organization will re-create the source.

![Coveo Source JSON](/images/CoveoForSitecoreV4Cloud/EditJSON.PNG)

In summary, it would look like the following

![Coveo for Sitecore Cloud Environment](/images/CoveoForSitecoreV4Cloud/CloudEnv.PNG)

The diagram above is in a scenario where each developer has access to a unique Sitecore and database farm. If all the developers are sharing the same Sitecore, then a single Coveo organization will be sufficient.
In this case, Coveo for Sitecore needs to be configured according to [the Scaling Guide](https://developers.coveo.com/display/SitecoreV4/Coveo+for+Sitecore+Scaling+Guide).
I hope this answers a few questions about how to get started with Coveo for Sitecore cloud.

If you have any questions, do not hesitate to post on [Sitecore Stack Exchange](http://sitecore.stackexchange.com/).


text:
<!DOCTYPE html>

  <title>CSS Reftest Reference</title>
  <link rel="author" title="Daniel Holbert" href="mailto:dholbert@mozilla.com">
  <meta charset="utf-8">

  a a
b b
x x


text:
package org.rdv.viz.spectrum;

/**
 * An enum of window functions.
 *
 * @author Jason P. Hanley
 */
public enum WindowFunction {
  Bartlett,
  Blackman,
  Hamming,
  Hann,
  Rectangular
}


text:
var Class = require('../core/class');
var Path = require('../core/path');
var Transform = require('../core/transform');

module.exports = Class(Path, {

	onReset: function(){
		this.points = [];
		this.left = this.top = Infinity;
		this.right = this.bottom = -Infinity;
		this.width = this.height = 0;
		this.length = 0;
	},

	onMove: function(sx, sy, ex, ey){
		this.points.push(this.length, ex, ey);
	},

	onLine: function(sx, sy, ex, ey){
		var x = ex - sx, y = ey - sy;
		this.points.push((this.length += Math.sqrt(x * x + y * y)), ex, ey);
		this.left   = Math.min(this.left,   sx, x);
		this.right  = Math.max(this.right,  sx, x);
		this.top    = Math.min(this.top,    sy, y);
		this.bottom = Math.max(this.bottom, sy, y);
		this.width  = this.right - this.left;
		this.height = this.bottom - this.top;
	},

	point: function(lengthToPoint){
		// TODO: Binary search, store last distance-and-index to make second look ups faster
		var points = this.points, last = points.length - 3, next;
		if (last < 3) return null;
		for (var i = 3; i < last; i+=3)
			if (points[i] >= lengthToPoint)
				break;

		var l = points[i],
			x = points[i+1], y = points[i+2],

			dl = l - points[i-3],
		    dx = x - points[i-2], dy = y - points[i-1];

		var offset = (l - lengthToPoint) / dl,
		    cos = dx / dl, sin = dy / dl;
		x -= dx * offset; y -= dy * offset;
		return new Transform(cos, sin, -sin, cos, x, y);
	}

});


text:
package com.yesco.android.model;

/**
 * Created by lrs on 8/19/2015.
 */
public class AppSettings {
    private boolean SkipNativeLogin;
    private boolean SkipApplicationList;
    private boolean HideNavigationBar;
    private String DefaultHostname;
    private String DefaultApplicationURL;
    private String BackgroundColor;
    private String ForegroundColor;
    private String TintColor;

    public AppSettings() {
    }

    public AppSettings(boolean skipNativeLogin, boolean skipApplicationList, boolean hideNavigationBar, String defaultHostname, String defaultApplicationURL, String backgroundColor, String foregroundColor, String tintColor) {
        SkipNativeLogin = skipNativeLogin;
        SkipApplicationList = skipApplicationList;
        HideNavigationBar = hideNavigationBar;
        DefaultHostname = defaultHostname;
        DefaultApplicationURL = defaultApplicationURL;
        BackgroundColor = backgroundColor;
        ForegroundColor = foregroundColor;
        TintColor = tintColor;
    }

    public boolean skipNativeLogin() {
        return SkipNativeLogin;
    }

    public void setSkipNativeLogin(boolean skipNativeLogin) {
        SkipNativeLogin = skipNativeLogin;
    }

    public boolean skipApplicationList() {
        return SkipApplicationList;
    }

    public void setSkipApplicationList(boolean skipApplicationList) {
        SkipApplicationList = skipApplicationList;
    }

    public boolean hideNavigationBar() {
        return HideNavigationBar;
    }

    public void setHideNavigationBar(boolean hideNavigationBar) {
        HideNavigationBar = hideNavigationBar;
    }

    public String getDefaultHostname() {
        return DefaultHostname;
    }

    public void setDefaultHostname(String defaultHostname) {
        DefaultHostname = defaultHostname;
    }

    public String getDefaultApplicationURL() {
        return DefaultApplicationURL;
    }

    public void setDefaultApplicationURL(String defaultApplicationURL) {
        DefaultApplicationURL = defaultApplicationURL;
    }

    public String getBackgroundColor() {
        return BackgroundColor;
    }

    public void setBackgroundColor(String backgroundColor) {
        BackgroundColor = backgroundColor;
    }

    public String getForegroundColor() {
        return ForegroundColor;
    }

    public void setForegroundColor(String foregroundColor) {
        ForegroundColor = foregroundColor;
    }

    public String getTintColor() {
        return TintColor;
    }

    public void setTintColor(String tintColor) {
        TintColor = tintColor;
    }

    public boolean hasValidSettings(){
        return hasValidHostname() || hasValidApplicationURL();
    }

    public boolean hasValidHostname(){
        return getDefaultHostname() != null && !getDefaultHostname().isEmpty();
    }

    public boolean hasValidApplicationURL(){
        return getDefaultApplicationURL() != null && !getDefaultApplicationURL().isEmpty();
    }
}


text:
package org.bidtime.dbutils.params;

import org.bidtime.dbutils.utils.comm.PropEx;

public class StmtParams {

	private static final StmtParams instance = new StmtParams();

	public static StmtParams getInstance() {
		return instance;
	}

	private int stmtQueryTimeOut = 300;			//5m
	private int stmtUpdateTimeOut = 300;		//5m
	private int stmtBatchTimeOut = 600;			//10m
	private int fetchSize = 100;				//100per
	private int spanTimeOut = 30000;			//30s
	private Boolean debug = true;				//是否调试版本
	private Boolean sqlOutParam = false;		//sqlOutParam -> false: sql里面含有参数; true: sql和参数分别输出
	private Boolean formatSql = true;			//是否格式化sql

	public Boolean getSqlOutParam() {
		return sqlOutParam;
	}

	public void setSqlOutParam(Boolean sqlOutParam) {
		this.sqlOutParam = sqlOutParam;
	}

	public Boolean getFormatSql() {
		return formatSql;
	}

	public void setFormatSql(Boolean formatSql) {
		this.formatSql = formatSql;
	}

	public Boolean getDebug() {
		return debug;
	}

	public void setDebug(Boolean debug) {
		this.debug = debug;
	}

	public int getSpanTimeOut() {
		return spanTimeOut;
	}

	public void setSpanTimeOut(int spanTimeOut) {
		this.spanTimeOut = spanTimeOut;
	}

	public int getFetchSize() {
		return fetchSize;
	}

	public void setFetchSize(int fetchSize) {
		this.fetchSize = fetchSize;
	}

	public int getStmtQueryTimeOut() {
		return stmtQueryTimeOut;
	}

	public void setStmtQueryTimeOut(int stmtQueryTimeOut) {
		this.stmtQueryTimeOut = stmtQueryTimeOut;
	}

	public int getStmtUpdateTimeOut() {
		return stmtUpdateTimeOut;
	}

	public void setStmtUpdateTimeOut(int stmtUpdateTimeOut) {
		this.stmtUpdateTimeOut = stmtUpdateTimeOut;
	}

	public int getStmtBatchTimeOut() {
		return stmtBatchTimeOut;
	}

	public void setStmtBatchTimeOut(int stmtBatchTimeOut) {
		this.stmtBatchTimeOut = stmtBatchTimeOut;
	}

	public StmtParams() {
		loadOfSrc("stmtparams.properties");
	}

	public void loadOfSrc(String fileName) {
		PropEx propUtils = new PropEx();
		try {
			if (propUtils.loadOfSrcSlient(fileName)) {
				stmtQueryTimeOut = propUtils.getInteger("stmtQueryTimeOut", 300);
				stmtUpdateTimeOut = propUtils.getInteger("stmtUpdateTimeOut", 300);
				stmtBatchTimeOut = propUtils.getInteger("stmtBatchTimeOut", 600);
				spanTimeOut = propUtils.getInteger("spanTimeOut", 30000);
				fetchSize = propUtils.getInteger("fetchSize", 100);
				// dataSource = propUtils.getString("dataSource", dataSource);
				//many boolean prop
				debug = propUtils.getBoolean("debug", debug);
				sqlOutParam = propUtils.getBoolean("sqlOutOne", sqlOutParam);
				formatSql = propUtils.getBoolean("formatSql", formatSql);
			}
		} finally {
			propUtils = null;
		}
	}

}


text:
require 'classifier-reborn'

def classif
  # use bayes classification to train a classifier
  classifier = ClassifierReborn::Bayes.new 'Core', 'Unimportant'
  classifier.train_core "can you open the Gemfile for me?"
  classifier.train_core "open nickname"
  classifier.train_core "please, open something.pdf"
  classifier.train_core "open /some/path/to/some/file/file.jpg"
  classifier.train_unimportant "nothing"
  classifier.train_unimportant "i dont know"
  classifier.train_unimportant "some senseless sentence"
  return classifier
end


text:
title: Firestore
layout: docs
methods:

  - signature: firestore.addDocument(collectionRef, data)
    id: addDocument
    generator: true
    description: Adds a new document to this collection with the specified data, assigning it a document ID automatically.
    arguments:
      - name: collectionRef
        required: true
        type: String or [firebase.firestore.CollectionReference](https://firebase.google.com/docs/reference/js/firebase.firestore.CollectionReference)
        description: If using a string, it is a slash-separated path to a collection.
      - name: data
        required: true
        type: Object
        description: The data to store.
    output: A [DocumentReference](https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentReference)
    example: |
      ```js
      function* addDocument() {
        const doc = yield call(
          rsf.firestore.addDocument,
          'users',
          {
            firstName: 'Elon',
            lastName: 'Musk'
          }
        );
      }
      ```

  - signature: firestore.channel(pathOrRef, type)
    id: channel
    generator: false
    description: Returns a redux-saga [Channel](https://redux-saga.github.io/redux-saga/docs/advanced/Channels.html) which emits every time the data at `pathOrRef` in firestore changes.
    arguments:
      - name: pathOrRef
        required: true
        type: String, [firebase.firestore.CollectionReference](https://firebase.google.com/docs/reference/js/firebase.firestore.CollectionReference), [firebase.firestore.DocumentReference](https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentReference) or [firebase.firestore.Query](https://firebase.google.com/docs/reference/js/firebase.firestore.Query)
        description: To [filter](https://firebase.google.com/docs/firestore/query-data/get-data), [order or limit](https://firebase.google.com/docs/firestore/query-data/order-limit-data) data, pass a [firebase.firestore.Query](https://firebase.google.com/docs/reference/js/firebase.firestore.Query) (eg. `rsf.firestore.channel(colRef.where("capital", "==", true))`). If using a string, it is a slash-separated path to a document or a collection (unfiltered).
      - name: type
        required: false
        type: A string
        description: Either `collection` or `document`. Defaults to `collection`.
    output: A redux-saga [Channel](https://redux-saga.github.io/redux-saga/docs/advanced/Channels.html) which emits every time the data at `pathOrRef` in firestore changes.
    example: |
      ```js
      function* syncTodosSaga() {
        const channel = rsf.firestore.channel('todos');

        while(true) {
          const todos = yield take(channel);
          yield put(syncTodos(todos));
        }
      }
      ```

  - signature: firestore.deleteDocument(documentRef)
    id: deleteDocument
    generator: true
    description: Deletes the document referred to by this DocumentReference.
    arguments:
      - name: documentRef
        required: true
        type: String or [firebase.firestore.DocumentReference](https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentReference).
        description: If using a string, it is a slash-separated path to a document.
    example: |
      ```js
      function* deleteDocument() {
        yield call(rsf.firestore.deleteDocument, 'users/elonm');
      }
      ```

  - signature: firestore.getCollection(collectionRef)
    id: getCollection
    generator: true
    description: Reads the collection referred to by this collectionRef.
    arguments:
      - name: collectionRef
        required: true
        type: String or [firebase.firestore.CollectionReference](https://firebase.google.com/docs/reference/js/firebase.firestore.CollectionReference) or [firebase.firestore.Query](https://firebase.google.com/docs/reference/js/firebase.firestore.Query)
        description: To [filter](https://firebase.google.com/docs/firestore/query-data/get-data), [order or limit](https://firebase.google.com/docs/firestore/query-data/order-limit-data) data, pass a [Query](https://firebase.google.com/docs/reference/js/firebase.firestore.Query) (eg. `yield call(rsf.firestore.getCollection, colRef.where("capital", "==", true))`). If using a string, it is a slash-separated path to a collection (unfiltered).
    output: A [QuerySnapshot](https://firebase.google.com/docs/reference/js/firebase.firestore.QuerySnapshot)
    example: |
      ```js
      function* getCollection() {
        const snapshot = yield call(rsf.firestore.getCollection, 'users');
        let users;
        snapshot.forEach(user => {
            users = {
              ...users,
              [user.id]: user.data()
            }
        });

        yield put(gotUsers(users));
      }
      ```

  - signature: firestore.getDocument(documentRef)
    id: getDocument
    generator: true
    description: Reads the document referred to by this documentRef.
    arguments:
      - name: documentRef
        required: true
        type: String or [firebase.firestore.DocumentReference](https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentReference).
        description: If using a string, it is a slash-separated path to a document.
    output: A [DocumentSnapshot](https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentSnapshot)
    example: |
      ```js
      function* getDocument() {
        const snapshot = yield call(rsf.firestore.getDocument, 'users/1');
        const user = snapshot.data();

        yield put(gotUser(user));
      }
      ```

  - signature: firestore.setDocument(documentRef, data, options)
    id: setDocument
    generator: true
    description: Writes to the document referred to by this DocumentReference. If the document does not exist yet, it will be created. If you pass options, the provided data can be merged into the existing document.
    arguments:
      - name: documentRef
        required: true
        type: String or [firebase.firestore.DocumentReference](https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentReference).
        description: If using a string, it is a slash-separated path to a document.
      - name: data
        required: true
        type: Object
        description: An object of the fields and values for the document.
      - name: options
        required: false
        type: Object
        description: "An object to configure the set behavior. Pass `{ merge: true }` to only replace the values specified in the data argument. Fields omitted will remain untouched."
    example: |
      ```js
      function* setDocument() {
        yield call(
          rsf.firestore.setDocument,
          'users/1',
          { firstName: 'Leonardo' }
        );
      }
      ```

  - signature: firestore.syncCollection(pathOrRef, options)
    id: syncCollection
    generator: true
    description: Automatically dispatches a redux action every time the collection at `pathOrRef` changes.
    arguments:
      - name: pathOrRef
        required: true
        type: String or [firebase.firestore.CollectionReference](https://firebase.google.com/docs/reference/js/firebase.firestore.CollectionReference) or [firebase.firestore.Query](https://firebase.google.com/docs/reference/js/firebase.firestore.Query)
        description: To [filter](https://firebase.google.com/docs/firestore/query-data/get-data), [order or limit](https://firebase.google.com/docs/firestore/query-data/order-limit-data) data, pass a [Query](https://firebase.google.com/docs/reference/js/firebase.firestore.Query) (eg. `yield call(rsf.firestore.syncCollection, colRef.where("capital", "==", true), ...)`). If using a string, it is a slash-separated path to a collection (unfiltered).
      - name: options
        required: true
        type: Object
        description: "An object to configure how the collection should be synchronised. It must contain at least the `successActionCreator` which must take either a [DocumentSnapshot](https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentSnapshot) or a [QuerySnapshot](https://firebase.google.com/docs/reference/js/firebase.firestore.QuerySnapshot) as argument. The other possible options are `failureActionCreator` which is called on channel errors and `transform` which is an optional transformer function to be applied to the value before it's passed to the action creator. Default to the identity function (`x => x`)."
    output:
    example: |
      ```js
      import { syncTodos } from '../actionCreators/firestore';

      function* todosRootSaga() {
        yield [
          rsf.firestore.syncCollection('todos', { successActionCreator: syncTodos }),
        ];
      }
      ```

  - signature: firestore.syncDocument(pathOrRef, options)
    id: syncDocument
    generator: true
    description: Automatically dispatches a redux action every time the document at `pathOrRef` changes.
    arguments:
      - name: pathOrRef
        required: true
        type: String or [firebase.firestore.DocumentReference](https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentReference)
        description: If using a string, it is a slash-separated path to a document.
      - name: options
        required: true
        type: Object
        description: "An object to configure how the document should be synchronised. It must contain at least the `successActionCreator` which must take either a [DocumentSnapshot](https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentSnapshot) or a [QuerySnapshot](https://firebase.google.com/docs/reference/js/firebase.firestore.QuerySnapshot) as argument. The other possible options are `failureActionCreator` which is called on channel errors and `transform` which is an optional transformer function to be applied to the value before it's passed to the action creator. Default to the identity function (`x => x`)."
    output:
    example: |
      ```js
      import { syncTodo } from '../actionCreators/firestore';

      function* todosRootSaga() {
        yield [
          rsf.firestore.syncDocument('todos/1', { successActionCreator: syncTodo }),
        ];
      }
      ```

  - signature: firestore.updateDocument(documentRef, ...args)
    id: updateDocument
    generator: true
    description: Updates fields in the document referred to by this DocumentReference. The update will fail if applied to a document that does not exist.
    arguments:
      - name: documentRef
        required: true
        type: String or [firebase.firestore.DocumentReference](https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentReference)
        description: If using a string, it is a slash-separated path to a document.
      - name: args
        required: true
        type: Object
        description: Either an object containing all of the fields and values to update, or a series of arguments alternating between fields (as string or firebase.firestore.FieldPath objects) and values.
    example: |
      ```js
      function* updateDocument() {
        yield call(rsf.firestore.updateDocument, 'users/1', 'lastName', 'Da Vinci');
      }
      ```

---


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta name="Content-Type" content="text/html; charset=UTF-8" />
<title>Class: Object</title>
<link rel="stylesheet" href="css/style.css" type="text/css" media="screen" charset="utf-8" />
<link rel="stylesheet" href="css/common.css" type="text/css" media="screen" charset="utf-8" />

    Index (O) »

    Object

(no frames)

  Class List
  Method List
  File List

Class: Object

Inherits:

      BasicObject

Defined in:

lib/lazyeval.rb

Instance Method Summary

      - (Object) lazy(&block)

Instance Method Details

    - (<tt>Object</tt>) lazy(&block)

2
3
4

# File 'lib/lazyeval.rb', line 2

def lazy(&block)
  Lazy.new(self, &block)
end

  Generated on Tue May 11 16:34:44 2010 by
  yard
  0.5.3 (ruby-1.8.6).


text:
package lsp

import (
	"context"

	"golang.org/x/tools/internal/lsp/protocol"
	"golang.org/x/tools/internal/lsp/source"
	"golang.org/x/tools/internal/span"
)

func (s *Server) definition(ctx context.Context, params *protocol.TextDocumentPositionParams) ([]protocol.Location, error) {
	uri := span.NewURI(params.TextDocument.URI)
	view := s.session.ViewOf(uri)
	f, m, err := getGoFile(ctx, view, uri)
	if err != nil {
		return nil, err
	}
	spn, err := m.PointSpan(params.Position)
	if err != nil {
		return nil, err
	}
	rng, err := spn.Range(m.Converter)
	if err != nil {
		return nil, err
	}
	ident, err := source.Identifier(ctx, view, f, rng.Start)
	if err != nil {
		return nil, err
	}
	decSpan, err := ident.DeclarationRange().Span()
	if err != nil {
		return nil, err
	}
	_, decM, err := getSourceFile(ctx, view, decSpan.URI())
	if err != nil {
		return nil, err
	}
	loc, err := decM.Location(decSpan)
	if err != nil {
		return nil, err
	}
	return []protocol.Location{loc}, nil
}

func (s *Server) typeDefinition(ctx context.Context, params *protocol.TextDocumentPositionParams) ([]protocol.Location, error) {
	uri := span.NewURI(params.TextDocument.URI)
	view := s.session.ViewOf(uri)
	f, m, err := getGoFile(ctx, view, uri)
	if err != nil {
		return nil, err
	}
	spn, err := m.PointSpan(params.Position)
	if err != nil {
		return nil, err
	}
	rng, err := spn.Range(m.Converter)
	if err != nil {
		return nil, err
	}
	ident, err := source.Identifier(ctx, view, f, rng.Start)
	if err != nil {
		return nil, err
	}
	identSpan, err := ident.Type.Range.Span()
	if err != nil {
		return nil, err
	}
	_, identM, err := getSourceFile(ctx, view, identSpan.URI())
	if err != nil {
		return nil, err
	}
	loc, err := identM.Location(identSpan)
	if err != nil {
		return nil, err
	}
	return []protocol.Location{loc}, nil
}


text:
package org.locationtech.geomesa.utils.stats

import org.opengis.feature.simple.SimpleFeature

import scala.collection.immutable.ListMap
import scala.reflect.ClassTag

/**
 * An enumeration is merely a HashMap mapping values to number of occurrences
 *
 * @param attribute attribute index for the attribute the histogram is being made for
 * @tparam T some type T (which is restricted by the stat parser upstream of Histogram instantiation)
 */
class EnumerationStat[T](val attribute: Int)(implicit ct: ClassTag[T]) extends Stat {

  override type S = EnumerationStat[T]

  private lazy val stringify = Stat.stringifier(ct.runtimeClass)

  private [stats] val enumeration = scala.collection.mutable.HashMap.empty[T, Long].withDefaultValue(0)

  def size: Int = enumeration.size
  def values: Iterable[T] = enumeration.keys
  def frequency(value: T): Long = enumeration(value)
  def frequencies: Iterable[(T, Long)] = enumeration

  override def observe(sf: SimpleFeature): Unit = {
    val value = sf.getAttribute(attribute).asInstanceOf[T]
    if (value != null) {
      enumeration(value) += 1
    }
  }

  override def unobserve(sf: SimpleFeature): Unit = {
    val value = sf.getAttribute(attribute).asInstanceOf[T]
    if (value != null) {
      val current = enumeration(value)
      if (current == 1) {
        enumeration.remove(value)
      } else {
        enumeration(value) = current - 1
      }
    }
  }

  override def +(other: EnumerationStat[T]): EnumerationStat[T] = {
    val plus = new EnumerationStat[T](attribute)
    plus += this
    plus += other
    plus
  }

  override def +=(other: EnumerationStat[T]): Unit =
    other.enumeration.foreach { case (key, count) => enumeration(key) += count }

  override def toJsonObject = if (enumeration.isEmpty) Map.empty else ListMap(enumeration.toSeq.sortBy(_.toString):_*)

  override def isEmpty: Boolean = enumeration.isEmpty

  override def clear(): Unit = enumeration.clear()

  override def isEquivalent(other: Stat): Boolean = other match {
    case that: EnumerationStat[_] => attribute == that.attribute && enumeration == that.enumeration
    case _ => false
  }
}


text:
import { IBoleto } from './interfaces';
export declare const CreateBoleto: (options: any) => IBoleto;


text:
* [Creating a Workspace](#creating-a-workspace)
* [Deleting a Workspace](#deleting-a-workspace)
* [Uploading a File to a Workspace](#uploading-a-file-to-a-workspace)
* [Downloading a File from a Workspace](#downloading-a-file-from-a-workspace)

## Creating a Workspace

This RESTful API call creates a workspace, a scratch pad for temporarily storing the data to be wrangled in the backend.
A workspace is identified by a name containing either alphanumeric or underscore (_) characters.

* **URL**

  `workspaces/:workspaceid`

* **Method**

  `PUT`

* **URL Params**

  _None_

* **Data Params**

  _Not Applicable_

* **Success Response**

  * **Code** 200
    **Content**
    ```
      {
        'status': 200,
        'message': "Successfully created workspace ':workspaceid'"
      }
    ```

* **Error Responses**

  * **Code** 500 Server Error
    **Content**
    ```
      {
        'status': 500,
        'message': "<appropriate error message>"
      }
    ```
    or

  * **Code** 500 Server Error
    **Content**
    ```
      Unable to route to service <url>
    ```

* **Sample Call**

  ```
    $.ajax({
      url: "${base-url}/workspaces/${workspace}",
      dataType: "json",
      type : "PUT",
      success : function(r) {
        console.log(r);
      }
    });
  ```

* **Notes**

The API call will fail if the backend service is not started or if the dataset write fails.

## Deleting a Workspace

This RESTful API call deletes a workspace. This will also delete any data associated with it.

* **URL**

  `workspaces/:workspaceid`

* **Method**

  `DELETE`

* **URL Params**

  _None_

* **Data Params**

  _Not Applicable_

* **Success Response**

  * **Code** 200
    **Content**
    ```
      {
        'status': 200,
        'message': "Successfully deleted workspace ':workspaceid'"
      }
    ```

* **Error Responses**

  * **Code** 500 Server Error
    **Content**
    ```
      {
        'status': 500,
        'message': "<appropriate error message>"
      }
    ```
    or

  * **Code** 500 Server Error
    **Content**
    ```
      Unable to route to service <url>
    ```

* **Sample Call**

  ```
    $.ajax({
      url: "${base-url}/workspaces/${workspace}",
      dataType: "json",
      type : "DELETE",
      success : function(r) {
        console.log(r);
      }
    });
  ```

* **Notes**

The API call will fail if the backend service is not started or if the dataset write fails.

## Uploading a File to a Workspace

This RESTful API call will upload a file to a workspace. The file is split into lines based on a line delimiter (EOL).

* **URL**

  `workspaces/:workspaceid/upload`

* **Method**

  `POST`

* **URL Params**

  _None_

* **Data Params**

  _Not Applicable_

* **Success Response**

  * **Code** 200
    **Content**
    ```
      {
        'status': 200,
        'message': "Successfully uploaded data to workspace ':workspaceid' (records 1000)"
      }
    ```

* **Error Responses**

  * **Code** 500 Server Error
    **Content**
    ```
      {
        'status': 500,
        'message': "Body not present, please post the file containing the records to be wrangle."
      }
    ```
    or

  * **Code** 500 Server Error
    **Content**
    ```
      Unable to route to service <url>
    ```

    or

  * **Code** 500 Server Error
    **Content**
    ```
      {
        'status': 500,
        'message': "<appropriate error message>"
      }
    ```

* **Sample Call**

  ```
    $.ajax({
        url: "${base-url}/workspaces/${workspace}/upload",
        type: 'POST',
        data: data,
        cache: false,
        contentType: 'application/octet-stream',
        processData: false, // Don't process the files
        contentType: false,
        success: function(r) {
          console.log(r);
        },
        error: function(r) {
          console.log(r);
      }
    });
  ```

## Downloading a File from a Workspace

This RESTful API will download to a file the data stores in a workspace.

* **URL**

  `workspaces/:workspaceid/download`

* **Method**

  `GET`

* **URL Params**

  _None_

* **Data Params**

  _Not Applicable_

* **Success Response**

  * **Code** 200
    **Content**
    ```
      <data stored in workspace>
    ```

* **Error Responses**

  * **Code** 500 Server Error
    **Content**
    ```
      {
        'status': 500,
        'message': "No data exists in the workspace. Please upload the data to this workspace."
      }
    ```
    or

  * **Code** 500 Server Error
    **Content**
    ```
      Unable to route to service <url>
    ```

    or

  * **Code** 500 Server Error
    **Content**
    ```
      {
        'status': 500,
        'message': "<appropriate error message>"
      }
    ```

* **Sample Call**

  ```
    $.ajax({
        url: "${base-url}/workspaces/${workspace}/download",
        type: 'GET',
        success: function(r) {
          console.log(r);
        },
        error: function(r) {
          console.log(r);
      }
    });
  ```


text:
import sys
import os
import time
import numpy as np
from PIL import Image

APP_LIB = os.path.normpath(os.path.dirname(os.path.abspath(__file__)))
APP_ROOT = os.path.normpath(os.path.join(APP_LIB, os.pardir))

sys.path.append(APP_ROOT)

from util import system
from util.log import LOG as logger

BLACK = 0
WHITE = 255
THRESHOLD = 2

class ImageControl(object):

    def __init__(self, directory=""):
        if directory == "":
            self.Capture = system.APP_TMP
        else:
            self.Capture = directory

    def setDirectory(self, directory):
        system.DIRECTORY.create(directory)
        self.Capture = directory

    def to480P(self, image):
        img = self.__img(image)
        if img == None: return None
        resize_img = img.resize((640, 480))
        return resize_img.save(os.path.join(self.Capture, image),
            'PNG', quality=100, optimize=True)

    def to720P(self, image):
        img = self.__img(image)
        if img == None: return None
        resize_img = img.resize((1280, 720))
        return resize_img.save(os.path.join(self.Capture, image),
            'PNG', quality=100, optimize=True)

    def to1080P(self, image):
        img = self.__img(image)
        if img == None: return None
        resize_img = img.resize((1920, 1080))
        return resize_img.save(os.path.join(self.Capture, image),
            'PNG', quality=100, optimize=True)

    def rotate90(self, image):
        img = self.__img(image)
        if img == None: return None
        rotate_img = img.transpose(Image.ROTATE_90)
        return rotate_img.save(os.path.join(self.Capture, image),
            'PNG', quality=100, optimize=True)

    def getRGB(self, image):
        img = self.__img(image)
        if img == None: return None
        rgbimg = img.convert("RGB")
        rgb = np.array(rgbimg.getdata())
        return self.__round(rgb[:,0]), self.__round(rgb[:,1]), self.__round(rgb[:,2])

    def isWhite(self, image):
        r, g, b = self.getRGB(image)
        if r + int(THRESHOLD) > int(WHITE) \
            and g + int(THRESHOLD) > int(WHITE) \
            and b + int(THRESHOLD) > int(WHITE):
            return True
        else:
            return False

    def isBlack(self, image):
        r, g, b = self.getRGB(image)
        if r - int(THRESHOLD) < int(BLACK) \
            and g - int(THRESHOLD) < int(BLACK) \
            and b - int(THRESHOLD) < int(BLACK):
            return True
        else:
            return False

    def __img(self, image):
        try:
            path = os.path.join(self.Capture, image)
            return Image.open(os.path.join(self.Capture, image), 'r')
        except IOError, (errno, strerror):
            logger.info("I/O error(%s): %s" % (errno, strerror))
            raise IOError(strerror)

    def __round(self, array):
        return int(round(np.average(array)))

if __name__ == "__main__":
    img = ImageControl()
    print img.isBlack("black01.png")
    # print img.rotate90("base_tmp.png")


text:
import unittest
import paddle
import paddle.fluid as fluid
from paddle.fluid.transpiler.distribute_transpiler import (
    DistributeTranspilerConfig,
    ServerRuntimeConfig,
)
from paddle.fluid.incubate.fleet.parameter_server.distribute_transpiler.distributed_strategy import (
    StrategyFactory,
)
from paddle.fluid.incubate.fleet.parameter_server.distribute_transpiler import (
    fleet,
)
import paddle.fluid.incubate.fleet.base.role_maker as role_maker
import os

class TestStrategyFactor(unittest.TestCase):
    def test_sync_strategy(self):
        os.environ['CPU_NUM'] = "2"
        strategy = StrategyFactory.create_sync_strategy()
        self.assertEqual(strategy._program_config.sync_mode, False)
        self.assertEqual(strategy._program_config.runtime_split_send_recv, True)
        self.assertEqual(strategy._build_strategy.async_mode, True)
        self.assertEqual(strategy._execute_strategy.num_threads, 2)

        # test set_program_config using DistributeTranspilerConfig()
        program_config_class = DistributeTranspilerConfig()
        program_config_class.min_block_size = 81920
        strategy.set_program_config(program_config_class)
        program_config = strategy.get_program_config()
        self.assertEqual(program_config.min_block_size, 81920)

        # test set_program_config using dict
        program_config_dict = dict()
        program_config_dict['min_block_size'] = 8192
        strategy.set_program_config(program_config_dict)
        program_config = strategy.get_program_config()
        self.assertEqual(program_config.min_block_size, 8192)

        # test set_program_config exception
        program_config_dict['unknown'] = None
        self.assertRaises(
            Exception, strategy.set_program_config, program_config_dict
        )
        program_config_illegal = None
        self.assertRaises(
            Exception, strategy.set_program_config, program_config_illegal
        )

        trainer_runtime_config = strategy.get_trainer_runtime_config()
        trainer_runtime_config.runtime_configs[
            'communicator_send_queue_size'
        ] = '50'
        runtime_configs = trainer_runtime_config.get_communicator_flags()
        self.assertIn('communicator_send_queue_size', runtime_configs)
        self.assertNotIn(
            'communicator_independent_recv_thread', runtime_configs
        )
        self.assertEqual(runtime_configs['communicator_send_queue_size'], '2')

    def test_geo_strategy(self):
        strategy = StrategyFactory.create_geo_strategy(5)
        self.assertEqual(strategy._program_config.sync_mode, False)
        self.assertEqual(strategy._program_config.runtime_split_send_recv, True)
        self.assertEqual(strategy._program_config.geo_sgd_mode, True)
        self.assertEqual(strategy._program_config.geo_sgd_need_push_nums, 5)
        self.assertEqual(strategy._build_strategy.async_mode, True)

        # test set_build_strategy using fluid.BuildStrategy
        build_strategy_class = fluid.BuildStrategy()
        build_strategy_class.memory_optimize = False
        strategy.set_build_strategy(build_strategy_class)
        build_strategy = strategy.get_build_strategy()
        self.assertEqual(build_strategy.memory_optimize, False)

        # test set_build_strategy using dict
        build_strategy_dict = dict()
        build_strategy_dict['memory_optimize'] = True
        strategy.set_build_strategy(build_strategy_dict)
        build_strategy = strategy.get_build_strategy()
        self.assertEqual(build_strategy.memory_optimize, True)

        # test set_build_strategy exception
        build_strategy_dict['unknown'] = None
        self.assertRaises(
            Exception, strategy.set_build_strategy, build_strategy_dict
        )
        build_strategy_illegal = None
        self.assertRaises(
            Exception, strategy.set_build_strategy, build_strategy_illegal
        )

        os.environ["CPU_NUM"] = '100'
        trainer_runtime_config = strategy.get_trainer_runtime_config()
        runtime_configs = trainer_runtime_config.get_communicator_flags()
        self.assertIn('communicator_thread_pool_size', runtime_configs)
        self.assertIn('communicator_send_wait_times', runtime_configs)
        self.assertNotIn(
            'communicator_independent_recv_thread', runtime_configs
        )

    def test_async_strategy(self):
        os.environ["CPU_NUM"] = '100'

        strategy = StrategyFactory.create_async_strategy()
        self.assertEqual(strategy._program_config.sync_mode, False)
        self.assertEqual(strategy._program_config.runtime_split_send_recv, True)
        self.assertEqual(strategy._build_strategy.async_mode, True)

        trainer_runtime_config = strategy.get_trainer_runtime_config()
        self.assertEqual(
            trainer_runtime_config.runtime_configs[
                'communicator_send_queue_size'
            ],
            '100',
        )

        # test set_trainer_runtime_config using dict
        trainer_runtime_config_dict = dict()
        trainer_runtime_config_dict['communicator_send_queue_size'] = '20'
        strategy.set_trainer_runtime_config(trainer_runtime_config_dict)
        trainer_runtime_config = strategy.get_trainer_runtime_config()
        trainer_communicator_flags = (
            trainer_runtime_config.get_communicator_flags()
        )
        self.assertIn(
            'communicator_send_queue_size', trainer_communicator_flags
        )
        self.assertEqual(
            trainer_communicator_flags['communicator_send_queue_size'], '20'
        )

        # test set_trainer_runtime_config exception
        trainer_runtime_config_dict['unknown'] = None
        self.assertRaises(
            Exception,
            strategy.set_trainer_runtime_config,
            trainer_runtime_config_dict,
        )
        trainer_runtime_config_illegal = None
        self.assertRaises(
            Exception,
            strategy.set_trainer_runtime_config,
            trainer_runtime_config_illegal,
        )

        # test set_execute_strategy using fluid.ExecutionStrategy
        exec_strategy_class = fluid.ExecutionStrategy()
        exec_strategy_class.num_threads = 4
        strategy.set_execute_strategy(exec_strategy_class)
        exec_strategy = strategy.get_execute_strategy()
        self.assertEqual(exec_strategy.num_threads, 4)

        # test set_execute_strategy using dict
        exec_strategy_dict = dict()
        exec_strategy_dict['num_threads'] = 8
        strategy.set_execute_strategy(exec_strategy_dict)
        exec_strategy = strategy.get_execute_strategy()
        self.assertEqual(exec_strategy.num_threads, 8)

        # test set_execute_strategy exception
        exec_strategy_dict['unknown'] = None
        self.assertRaises(
            Exception, strategy.set_execute_strategy, exec_strategy_dict
        )
        exec_strategy_illegal = None
        self.assertRaises(
            Exception, strategy.set_execute_strategy, exec_strategy_illegal
        )

    def test_half_async_strategy(self):
        strategy = StrategyFactory.create_half_async_strategy()
        self.assertEqual(strategy._program_config.sync_mode, False)
        self.assertEqual(strategy._program_config.runtime_split_send_recv, True)
        self.assertEqual(strategy._build_strategy.async_mode, True)

        # test set_server_runtime_config using ServerRuntimeConfig
        server_runtime_config_class = ServerRuntimeConfig()
        server_runtime_config_class._rpc_send_thread_num = 24
        strategy.set_server_runtime_config(server_runtime_config_class)
        server_runtime_config = strategy.get_server_runtime_config()
        self.assertEqual(server_runtime_config._rpc_send_thread_num, 24)

        # test set_server_runtime_config using dict
        server_runtime_config_dict = dict()
        server_runtime_config_dict['_rpc_send_thread_num'] = 20
        strategy.set_server_runtime_config(server_runtime_config_dict)
        server_runtime_config = strategy.get_server_runtime_config()
        self.assertEqual(server_runtime_config._rpc_send_thread_num, 20)

        # test set_server_runtime_config exception
        server_runtime_config_dict['unknown'] = None
        self.assertRaises(
            Exception,
            strategy.set_server_runtime_config,
            server_runtime_config_dict,
        )
        server_runtime_config_illegal = None
        self.assertRaises(
            Exception,
            strategy.set_server_runtime_config,
            server_runtime_config_illegal,
        )

        os.environ["CPU_NUM"] = '100'
        trainer_runtime_config = strategy.get_trainer_runtime_config()
        trainer_runtime_config.runtime_configs[
            'communicator_send_queue_size'
        ] = '50'
        runtime_configs = trainer_runtime_config.get_communicator_flags()
        self.assertIn('communicator_send_queue_size', runtime_configs)
        self.assertNotIn(
            'communicator_independent_recv_thread', runtime_configs
        )
        self.assertEqual(runtime_configs['communicator_send_queue_size'], '100')

class TestCreateDefaultStrategy(unittest.TestCase):
    def test_default_strategy(self):
        role = role_maker.UserDefinedRoleMaker(
            current_id=0,
            role=role_maker.Role.WORKER,
            worker_num=2,
            server_endpoints=["127.0.0.1:6001", "127.0.0.1:6002"],
        )
        fleet.init(role)

        def type_error_optimizer():
            optimizer = fluid.optimizer.SGD(0.0001)
            optimizer = fleet.distributed_optimizer(optimizer)

        self.assertRaises(TypeError, type_error_optimizer)

class TestHalfAsyncStrategy(unittest.TestCase):
    def test_half_async_strategy(self):
        role = role_maker.UserDefinedRoleMaker(
            current_id=0,
            role=role_maker.Role.WORKER,
            worker_num=2,
            server_endpoints=["127.0.0.1:6001", "127.0.0.1:6002"],
        )
        fleet.init(role)

        half_async_config = DistributeTranspilerConfig()

        half_async_config.sync_mode = False
        half_async_config.geo_sgd_mode = False
        half_async_config.runtime_split_send_recv = False

        optimizer = fluid.optimizer.SGD(0.0001)
        optimizer = fleet.distributed_optimizer(optimizer, half_async_config)

class TestDebugInfo(unittest.TestCase):
    def test_debug_info(self):
        x = fluid.layers.data(name='x', shape=[1], dtype='float32')
        y = fluid.layers.data(name='y', shape=[1], dtype='float32')
        y_predict = fluid.layers.fc(input=x, size=1, act=None)
        cost = fluid.layers.square_error_cost(input=y_predict, label=y)
        avg_cost = paddle.mean(cost)

        role = role_maker.UserDefinedRoleMaker(
            current_id=0,
            role=role_maker.Role.WORKER,
            worker_num=2,
            server_endpoints=["127.0.0.1:6001", "127.0.0.1:6002"],
        )
        fleet.init(role)

        optimizer = fluid.optimizer.SGD(0.0001)
        strategy = StrategyFactory.create_sync_strategy()
        strategy.set_debug_opt(
            {
                "dump_param": ["fc_0.tmp_0"],
                "dump_fields": ["fc_0.tmp_0", "fc_0.tmp_0@GRAD"],
                "dump_fields_path": "dump_text/",
            }
        )
        optimizer = fleet.distributed_optimizer(optimizer, strategy)

if __name__ == '__main__':
    unittest.main()


text:
<?php
namespace presentator\api\models\forms;

use Yii;
use presentator\api\models\User;

/**
 * User password reset request form model.
 *
 * @author Gani Georgiev <gani.georgiev@gmail.com>
 */
class UserPasswordResetRequestForm extends ApiForm
{
    /**
     * @var string
     */
    public $email;

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        $labels = parent::attributeLabels();

        $labels['email'] = Yii::t('app', 'Email');

        return $labels;
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            ['email', 'required'],
            ['email', 'email'],
            ['email', 'string', 'max' => 255],
        ];
    }

    /**
     * Sends a forgotten password email to the provided form email address.
     *
     * NB! If the form data is valid this method will always return `true`,
     * no mather whether a user with such email exist or not,
     * in order to prevent unnecessary information disclosure and users enumeration.
     *
     * @return boolean
     */
    public function send(): bool
    {
        if (!$this->validate()) {
            return false;
        }

        if (
            ($user = User::findByEmail($this->email)) &&
            !User::isPasswordResetTokenValid((string) $user->passwordResetToken)
        ) {
            $user->generatePasswordResetToken();

            $user->save();

            $user->sendForgottenPasswordEmail();
        }

        return true;
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>statsmodels.tsa.stattools.grangercausalitytests — statsmodels v0.10.1 documentation</title>
    <link rel="stylesheet" href="../_static/nature.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />

    <link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="statsmodels.tsa.stattools.levinson_durbin" href="statsmodels.tsa.stattools.levinson_durbin.html" />
    <link rel="prev" title="statsmodels.tsa.stattools.q_stat" href="statsmodels.tsa.stattools.q_stat.html" />
<link rel="stylesheet" href="../_static/examples.css" type="text/css" />
<link rel="stylesheet" href="../_static/facebox.css" type="text/css" />

Navigation

          index

          modules |

          next |

          previous |

Install
  |

Support
  |

Bugs
  |

Develop
  |

Examples
  |

FAQ
  |

Time Series analysis tsa |

statsmodels.tsa.stattools.grangercausalitytests¶

statsmodels.tsa.stattools.grangercausalitytests(x, maxlag, addconst=True, verbose=True)[source]¶

four tests for granger non causality of 2 timeseries

all four tests give similar results
params_ftest and ssr_ftest are equivalent based on F test which is
identical to lmtest:grangertest in R

Parameters

xarray, 2d

data for test whether the time series in the second column Granger
causes the time series in the first column

maxlaginteger

the Granger causality test results are calculated for all lags up to
maxlag

verbosebool

print results if true

Returns

resultsdictionary

all test results, dictionary keys are the number of lags. For each
lag the values are a tuple, with the first element a dictionary with
teststatistic, pvalues, degrees of freedom, the second element are
the OLS estimation results for the restricted model, the unrestricted
model and the restriction (contrast) matrix for the parameter f_test.

Notes

TODO: convert to class and attach results properly

The Null hypothesis for grangercausalitytests is that the time series in
the second column, x2, does NOT Granger cause the time series in the first
column, x1. Grange causality means that past values of x2 have a
statistically significant effect on the current value of x1, taking past
values of x1 into account as regressors. We reject the null hypothesis
that x2 does not Granger cause x1 if the pvalues are below a desired size
of the test.

The null hypothesis for all four test is that the coefficients
corresponding to past values of the second time series are zero.

'params_ftest', 'ssr_ftest' are based on F distribution

'ssr_chi2test', 'lrtest' are based on chi-square distribution

References

http://en.wikipedia.org/wiki/Granger_causality
Greene: Econometric Analysis

Previous topic

statsmodels.tsa.stattools.q_stat

Next topic

statsmodels.tsa.stattools.levinson_durbin

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" />
      <input type="submit" value="Go" />
    </form>

        © Copyright 2009-2018, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
      Created using Sphinx 2.1.2.


text:
using Pinyin4net;
using Pinyin4net.Format;
using System.Linq;
using System.Text.RegularExpressions;

namespace MZBlog.Core.Extensions
{
    public static class StringExtensions
    {
        private static readonly HanyuPinyinOutputFormat format;

        static StringExtensions()
        {
            format = new HanyuPinyinOutputFormat();
            format.ToneType = HanyuPinyinToneType.WITHOUT_TONE;
            format.VCharType = HanyuPinyinVCharType.WITH_V;
            format.CaseType = HanyuPinyinCaseType.LOWERCASE;
        }

        public static bool IsNullOrWhitespace(this string text)
        {
            return string.IsNullOrWhiteSpace(text);
        }

        public static string FormatWith(this string text, params object[] args)
        {
            return string.Format(text, args);
        }

        public static string ToSlug(this string value)
        {
            value = value.ToLowerInvariant();

            value = ConvertChineseToPY(value);

            value = value.Replace("#", "-sharp ").Replace("@", "-at ")
                         .Replace("$", "-dollar ").Replace("%", "-percent ")
                         .Replace("&", "-and ").Replace("||", "-or ");

            value = Regex.Replace(value.TrimEnd(), @"\s", "-", RegexOptions.Compiled);

            value = Regex.Replace(value, @"[^a-z0-9\s-_]", "", RegexOptions.Compiled);

            value = value.Trim('-', '_');

            value = Regex.Replace(value, @"([-_]){2,}", "$1", RegexOptions.Compiled);

            return value;
        }

        private static string ConvertChineseToPY(string value)
        {
            return Regex.Replace(value, "[\u4e00-\u9fa5]", (m) => string.Format(" {0} ", m.Value.ChsToPinYin()));
        }

        #region 汉字转拼音

        /// <summary>
        /// 简体中文转拼音
        /// </summary>
        /// <param name="chs">简体中文字</param>
        /// <returns>拼音</returns>
        private static string ChsToPinYin(this string chs)
        {
            var myRegex = new Regex("^[\u4e00-\u9fa5]$");
            var returnstr = "";
            var nowchar = chs.ToCharArray();
            for (var j = 0; j < nowchar.Length; j++)
            {
                if (myRegex.IsMatch(nowchar[j].ToString()))
                {
                    var pingStrs = PinyinHelper.ToHanyuPinyinStringArray(nowchar[j], format);
                    if (pingStrs.Any())
                    {
                        returnstr += pingStrs[0];
                    }
                    else
                        returnstr += nowchar[j].ToString();
                }
                else
                {
                    returnstr += nowchar[j].ToString();
                }
            }
            return returnstr;
        }

        #endregion 汉字转拼音
    }
}


text:
from __future__ import (absolute_import, division, print_function, unicode_literals)
from builtins import (ascii, bytes, chr, dict, filter, hex, input, int, map, next, oct, open, pow, range, round, str,
                      super, zip)

import argparse
import imp
import sys

from ._helpers import HELP_FLAG_TEXT

ARCPYEXT_AVAILABLE = True
AGSADMIN_AVAILABLE = True

try:
    imp.find_module("arcpyext")
except ImportError:
    ARCPYEXT_AVAILABLE = False

try:
    imp.find_module("agsadmin")
except ImportError:
    AGSADMIN_AVAILABLE = False

_DIRS_TO_DELETE = []

DATA_SOURCE_TEMPLATES_HELP = """
-------------------------
CONFIGURATION INFORMATION
-------------------------
The JSON-encoded configuration file contains one mandatory key,
'dataSourceTemplates', which provides a mechanism for replacing layer data
sources using templates.

Data Source Templates
---------------------
The 'dataSourceTemplates' key contains an array of objects, with each one
taking the form of a dictionary containing two keys, "matchCriteria" and
"dataSource", both of which are also dictionaries.

Match criteria is a dictionary of key/value pairs that are compared to the
details of layers/table views.  If all listed match criteria are contained in
the layer/table view details, the template is a match and the date source
described in the "dataSource" key will be used to replace the table/layer
views data source.  Valid match keys for layers are 'name', 'longName',
'datasetName', 'dataSource', 'serviceType', 'userName', 'server', 'service',
and 'database'.  Valid match keys for table views are 'datasetName',
'dataSource', 'definitionQuery', and 'workspacePath'.  String values are
case sensitive.

Data source describes the replacement data source for a layer. As a minimum,
it should provide a "workspacePath" key that is the path (relative or absolute
to executing path) to a valid Arc workspace.  Optionally, the data source
dictionary also supports 'datasetName', 'workspaceType', and 'schema' keys,
allowing you to change these data source properties simultaneously.

Example
-------
{
    "dataSourceTemplates": [
        {
            "matchCriteria": {
                "server": "foo.server.local",
                "userName": "bar"
            },
            "dataSource": {
                "workspacePath": "./path/to/conn.sde"
            }
        }
    ]
}
"""

def main():
    parser_description = "Helper tools for performing ArcGIS Server administrative functions."

    if not ARCPYEXT_AVAILABLE and not AGSADMIN_AVAILABLE:
        parser_description = "{0} No compatible libraries are installed, only basic functions from arcpy are \
            available.  Please install arcpyext or agsadmin for additional functionality.".format(parser_description)
    elif not ARCPYEXT_AVAILABLE:
        parser_description = "{0} 'arcpy'/'arcpyext' are not available, functions limited to RESTful service \
            interaction only!".format(parser_description)
    elif not AGSADMIN_AVAILABLE:
        parser_description = "{0} 'agsadmin' is not available, functions limited to mapping and \
            data functions.".format(parser_description)

    parser = argparse.ArgumentParser(description = parser_description, add_help = False)
    parser.add_argument("-h", "--help", action = "help", help = HELP_FLAG_TEXT)
    subparsers = parser.add_subparsers()

    if ARCPYEXT_AVAILABLE:
        # arcpyext-based parsers, only added if arcpyext is available
        import agstools.arcpyext
        agstools.arcpyext.load_parsers(subparsers)

    if AGSADMIN_AVAILABLE:
        # agsadmin parsers, pure RESTful based parsers, only loaded if agsadmin is available
        import agstools.agsadmin
        agstools.agsadmin.load_parsers(subparsers)

    # pure arcpy parsers
    import agstools.arcpy
    agstools.arcpy.load_parsers(subparsers)

    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(1)

    try:
        args = parser.parse_args()
        args.func(args)
    finally:
        # Clean up temp directories, if any exist
        for dir in _DIRS_TO_DELETE:
            shutil.rmtree(dir)

if __name__ == "__main__":
    main()


text:
<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Vich\UploaderBundle\Mapping\Annotation as Vich;

/**
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks
 * @Gedmo\Loggable
 * @Vich\Uploadable
 */
class Vog extends Document
{

}


text:
<?php

namespace Junity\NowSms\Exceptions;

use Exception;
use Psr\Http\Message\ResponseInterface;

class CouldNotSendNotification extends Exception
{
    /**
     * @param  \Psr\Http\Message\ResponseInterface  $response
     * @return static
     */
	public static function serviceRespondedWithAnError(ResponseInterface $response)
    {
        $code = $response->getStatusCode();
        $message = $response->getBody();

        return new static("NowSMS responded with an error `{$code} - {$message}`");
    }

    /**
     * @param  \Exception  $exception
     * @return static
     */
    public static function communicationFailed(Exception $exception)
    {
        return new static("The communication with NowSMS failed because `{$exception->getCode()} - {$exception->getMessage()}`");
    }
}


text:
@(field: Field, checkboxMap: Map[String, Boolean], help:String = "")

      @for((checkboxName, isChecked) <- checkboxMap) {

            <input
            type="checkbox"
            name="@(field.name + "[]")"
            id="@checkboxName"
            value="@checkboxName"
            @if(isChecked) {checked}>
            @checkboxName

      }
      @help
      @{field.error.map { error => error.message }}


text:
const webpack = require('webpack');
const fs = require('fs');
const path = require('path');

const banner = fs.readFileSync(path.resolve(__dirname, 'LICENSE'), 'utf8');

module.exports = {
  mode: 'production',
  entry: './src/api.js',
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'xduce.min.js',
    library: 'xduce',
    libraryTarget: 'umd'
  },
  plugins: [new webpack.BannerPlugin({ banner, entryOnly: true })],
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader'
        }
      }
    ]
  }
};


text:
extern crate squish_the_bots;

use std::env;
use std::net::SocketAddr;

use squish_the_bots::example_bots::hunter;

fn main() {
    let command = env::args().nth(0).unwrap();
    let arg = match env::args().nth(1) {
        None => panic!("Usage: {} IP:PORT", command),
        Some(arg) => arg,
    };

    let address: SocketAddr = match arg.parse() {
        Err(..) => panic!("Invalid address \"{}\". Usage: {} IP:PORT", arg, command),
        Ok(address) => address,
    };

    hunter::run(address, "Hunter Bot".to_string(), true);
}


text:
{% extends "wagtailadmin/generic/index.html" %}
{% load i18n %}

{% block listing %}

        {% if collections %}

                                {% trans "Name" %}

                        {% for collection in collections %}

                                        {{ collection }}

                        {% endfor %}

        {% else %}
            {% url 'wagtailadmin_collections:add' as add_collection_url %}

{% blocktrans %}No collections have been created. Why not add one?{% endblocktrans %}

        {% endif %}

{% endblock %}


text:
var request = new XMLHttpRequest();

request.onreadystatechange = function() {
  if (request.readyState === 4) {
    print(request.responseText);
    output.responseArrived = true;
  }
};

request.open('GET', 'http://movie-database.herokuapp.com/movies');
request.setRequestHeader('Accept', 'application/json');
request.send();


text:
define(['ko', 'uberlearner/js/utils/dom', 'uberlearner/js/filestorage/uberphoto/list/models'], function(ko, domUtils, Models) {
    var viewModelFactory = function() {
        // PRIVATE SECTION
        /**
         * The ELLIPSES_PAGE is a dummy page that does not actually lead to images being displayed. It is merely for
         * the purpose of filling in gaps in the pagination buttons.
         * @type {Models.Page}
         */
        var ELLIPSES_PAGE = new Models.page([], '...', function(){}, false, false);
        var EMPTY_PAGE = new Models.page([], '', function(){}, false, false);
        var imageUrls = ko.observableArray([]); //this will be auto-populated by the url-list binding
        var imageData = ko.observableArray([]); //this will contain a list of page instances
        var currentImage= ko.observable();
        var currentPage = ko.observable(EMPTY_PAGE);
        var THUMBS_PER_PAGE = 15;
        var MAX_DISPLAYED_PAGE_COUNT = 7;

        /**
         * Generic method for each of the pagination titles.
         * @param pageNumber The page model instance
         * @return {Function}
         */
        var genericPageAction = function(page) {
            currentPage().isActive(false);
            page.isActive(true);
            currentPage(page);
        };
        /**
         * Calculates which pages should be visible in the pagination bar such that the current page is always
         * centred.
         * @type {*}
         */
        var visiblePages = ko.computed(function() {
            var numberOfPages = imageData().length;
            if (numberOfPages == 0)
                return [];

            var leftPadding = Math.floor((MAX_DISPLAYED_PAGE_COUNT-1)/2);
            var leftPageIndex, rightPageIndex;
            var leftElipsesVisibility=false, rightElipsesVisibility=false;

            leftPageIndex = imageData.indexOf(currentPage()) - leftPadding;
            if (leftPageIndex < 0) {
                leftPageIndex = 0;
            } else {
                leftElipsesVisibility = true;
            }
            rightPageIndex = leftPageIndex + MAX_DISPLAYED_PAGE_COUNT - 1;
            if (rightPageIndex >= numberOfPages){
                rightPageIndex = numberOfPages-1;
                leftPageIndex = rightPageIndex - MAX_DISPLAYED_PAGE_COUNT + 1;
            } else {
                rightElipsesVisibility = true;
            }
            var _visiblePages = imageData.slice(leftPageIndex, rightPageIndex+1);
            if (leftElipsesVisibility)
                _visiblePages.unshift(ELLIPSES_PAGE);
            if (rightElipsesVisibility)
                _visiblePages.push(ELLIPSES_PAGE);
            return _visiblePages;
        });

        /**
         * When the image urls variable changes, the image data needs to be refilled.
         */
        imageUrls.subscribe(function() {
            var totalThumbs = imageUrls().length;
            var maxPageNumber = Math.ceil(totalThumbs/THUMBS_PER_PAGE);
            var currentImageUrlIdx = 0;
            imageData([]);

            for (pageNumber = 1; pageNumber <= maxPageNumber; pageNumber++) {
                var pagePhotos = [];
                for(var photoIdx = 0; photoIdx < THUMBS_PER_PAGE; photoIdx++) {
                    if (currentImageUrlIdx < totalThumbs) {
                        var currentImageUrls = imageUrls()[currentImageUrlIdx];
                        pagePhotos.push(Models.photo(currentImageUrls['thumbnail'], currentImageUrls['original']));
                        currentImageUrlIdx++;
                    } else {
                        break;
                    }
                }
                imageData.push(Models.page(pagePhotos, pageNumber, genericPageAction, false, true));
            }
            if (imageData().length) {
                genericPageAction(imageData()[0]);
                currentImage(imageData()[0].photos[0]);
            } else
                currentPage(EMPTY_PAGE);
        });

        /**
         * This is the function that gets called when a user has finalized which image he/she will be using.
         */
        var selectImage = function() {
            var urlParams = domUtils.urlParams();
            var funcNum = urlParams.CKEditorFuncNum;
            try {
                window.opener.CKEDITOR.tools.callFunction(funcNum, currentImage().originalUrl);
            } catch (e) {
                alert('Image could not be applied to the editor.');
            }
            self.close();
        };

        // PUBLIC SECTION
        return {
            imageUrls: imageUrls,
            imageData: imageData,
            currentImage: currentImage,
            selectImage: selectImage,
            visiblePages: visiblePages,
            currentPage: currentPage
        };
    };
    return viewModelFactory;
});