text:
module StateShifter
  module Definition

    def self.included klass
      klass.send :include, InstanceMethods
      klass.extend ClassMethods

      if Object.const_defined?(:ActiveRecord)
        if klass < ActiveRecord::Base
          klass.send :include, ActiveRecordIntegrationMethods
          klass.send :_include_state_scopes=, true
          klass.before_validation :write_initial_state
        end
      end
    end

  end
end

redpajama_set_name: RedPajamaGithub


text:
package sorting

import org.salgo.sorting.GeneralSortingAlgorithm
import org.scalatest.{FunSuite, Matchers}

abstract class GenericSortSpec extends FunSuite with Matchers {
  test("Sort unsorted array") { this.getSortingAlgorithm.sortCopy(Array(4, 5, 3, 1, 2)) shouldEqual expectedShort }
  test("Sort empty array") { this.getSortingAlgorithm.sortCopy(Array[Int]()) shouldEqual Array[Int]() }
  test("Sort already sorted array") { this.getSortingAlgorithm.sortCopy(Array(1, 2, 3, 4, 5)) shouldEqual expectedShort }
  test("Sort single element array") { this.getSortingAlgorithm.sortCopy(Array(5)) shouldEqual Array(5) }
  test("Sort inverse ordered array") { this.getSortingAlgorithm.sortCopy(Array(5, 4, 3, 2, 1)) shouldEqual expectedShort }
  test("Sort array with duplicate elements") { this.getSortingAlgorithm.sortCopy(Array(4, 5, 3, 3, 5)) shouldEqual Array(3, 3, 4, 5, 5) }
  test("Sort array with single value") { this.getSortingAlgorithm.sortCopy(Array(4, 4, 4, 4, 4)) shouldEqual Array(4, 4, 4, 4, 4) }
  test("Sort long array") { this.getSortingAlgorithm.sortCopy(Array(6, 1, 0, 3, 3, 5, 7, 2, 1, 6, 5, 4 ,3 ,1, 2, 8, 8, 9 ,7)) shouldEqual Array(0, 1, 1, 1, 2, 2, 3, 3, 3, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9) }
  test("Sort long list") { this.getSortingAlgorithm.sortCopy(List(6, 1, 0, 3, 3, 5, 7, 2, 1, 6, 5, 4 ,3 ,1, 2, 8, 8, 9 ,7)) shouldEqual List(0, 1, 1, 1, 2, 2, 3, 3, 3, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9) }

  def getSortingAlgorithm: GeneralSortingAlgorithm

  private def expectedShort = Array(1, 2, 3, 4, 5)
}


text:
<?php

namespace Cuculcan\Core;

class Application {

    private $projectNamespace;

    public function __construct($projectNamespace) {
        $this->projectNamespace = $projectNamespace;
    }

    public function run() {

        //prepare request data
        $request = new Request();

        //create router
        $router = new Router($request, $this->projectNamespace);

        //search fo destination controller
        $controller = $router->getController();
        if(!$controller){
            $errorController = new ErrorController($request, $this->projectNamespace);
            $errorController->showErrorPage("404", "");
            exit;
        }

        //process request
        $controller->processRequest();
    }
}


text:
var services = require('./services'),
    Factory  = require('./factory'),
    utils    = require('./utils'),
    dom      = require('./dom');

var factories = {};

/**
 * Fetch data
 *
 * @param {String} service
 * @param {String} url
 * @param {Object} options
 * @return {Promise}
 */
module.exports = function (service, url, options) {
    if (!factories[service]) {
        factories[service] = {};
    }

    var counters = factories[service],
        counter  = counters[url];

    if (!options.forceUpdate && counter) {
        return counter;
    }

    counter = Factory();

    var href = utils.makeUrl(options.counterUrl, {
        url: url
    });

    services[service].counter(href, counter, url);

    counters[url] = counter;

    return counters[url];
};


text:
package io.bootique.cayenne.v41.junit5.tester;

import org.apache.cayenne.DataChannelQueryFilter;
import org.apache.cayenne.DataChannelQueryFilterChain;
import org.apache.cayenne.ObjectContext;
import org.apache.cayenne.QueryResponse;
import org.apache.cayenne.query.Query;

import java.util.concurrent.atomic.AtomicInteger;

import static org.junit.jupiter.api.Assertions.assertEquals;

/**
 * @since 2.0.B1
 */
public class QueryCounter implements DataChannelQueryFilter {

    private AtomicInteger count;

    public QueryCounter() {
        this.count = new AtomicInteger(0);
    }

    @Override
    public QueryResponse onQuery(ObjectContext objectContext, Query query, DataChannelQueryFilterChain dataChannelQueryFilterChain) {
        count.incrementAndGet();
        return dataChannelQueryFilterChain.onQuery(objectContext, query);
    }

    public void assertCount(int expectedCommits) {
        assertEquals(expectedCommits, count.get(), "Unexpected number of Cayenne queries executed");
    }

    public void reset() {
        count.set(0);
    }
}


text:
object SwapNodes extends App {

	sealed trait Tree {
		def inOrder: List[Int] = this match {
			case Empty => Nil
			case Node(left, value, right) => left.inOrder ++ (value :: right.inOrder)
			//case Node(left, value, right) => (value :: left.preOrder) ++ right.preOrder // preOrder
			//case Node(left, value, right) => left.postOrder ++ right.postOrder ++ List(value) // postOrder
		}

	}

	case object Empty extends Tree
	case class Node(left: Tree, value: Int, right: Tree) extends Tree

	object Tree {
		def build(value: Int, nodes: Map[Int, (Int, Int)]):Tree = nodes(value) match {
			case (-1, -1) => Node(Empty, value, Empty)
			case (-1, right) => Node(Empty, value, build(right, nodes))
			case (left, -1) => Node(build(left, nodes), value, Empty)
			case (left, right) => Node(build(left, nodes), value, build(right, nodes))
		}
		def swap(depth: Int, tree: Tree):Tree = {
			def swap(level: Int, tree: Tree): Tree = tree match {
				case Empty => Empty
				case Node(left, value, right) if level % depth == 0 => Node(swap(level + 1, right), value, swap(level + 1, left)) // swap!
				case Node(left, value, right) => Node(swap(level + 1, left), value, swap(level + 1, right))
			}
			swap(1, tree)
		}
	}

	val lines = io.Source.stdin.getLines

	val nNodes = lines.take(1).toList(0).toInt // number of nodes
	require(1 <= nNodes && nNodes <= 1024)
	val nodes = lines.take(nNodes).toList.map(_.split(" ").map(_.toInt)).zipWithIndex.map{case (xs, i) => (i + 1 -> (xs(0), xs(1))) }.toMap
	//println(nodes)

	var tree = Tree.build(1, nodes) // build the tree
	//println(tree.inOrder.mkString(" "))

	val nSwaps = lines.take(1).toList(0).toInt // number of swaps
	require(1 <= nSwaps && nSwaps <= 100)
	val dephs = lines.take(nSwaps).toList.map(_.toInt)

	for (depth <- dephs) {
		tree = Tree.swap(depth, tree)
		println(tree.inOrder.mkString(" "))
	}
}


text:
//-----------------------------------------------------------------------
// <copyright file="AssignSeatMap.cs" company="ShareKnowledge">
//     Copyright (c) ShareKnowledge. All rights reserved.
// </copyright>
// <author>Alejandro Perdomo</author>
//-----------------------------------------------------------------------

namespace Testing.FacadePattern.Pages
{
  #region Imports

  using static System.FormattableString;
  using OpenQA.Selenium;
  using Template;

  #endregion Imports

  internal class AssignSeatMap : BasePageElementMap
  {
    #region Properties

    public IWebElement Continue =>
        this.Driver.FindElement(By.CssSelector("button.btn:nth-child(2)"));

    #endregion Properties

    #region Methods

    public IWebElement Seat(int row, int column)
    {
      string selector = Invariant($"label[for=\'{row},{column}']");
      return this.Driver.FindElement(By.CssSelector(selector));
    }

    #endregion Methods
  }
}


text:
title: mobile-spec running on PhoneGap Android Froyo 2.2
date: 2010-05-20 22:08:04 Z
categories:
- app
author: Anis Kadri
link: http://blogs.nitobi.com/anis/?p=51
status: publish
type: post
format: html
---

Lots of new features have been added to Android Froyo 2.2\. Among the most exciting ones are: Better speed with the inclusion of the V8 Javascript engine, JIT compiler as well as a new set of backup/storage and cloud messaging APIs.

I wanted to see how PhoneGap would work on Froyo so I ran mobile-spec on it and below are the results.

[![Android Part 1](http://blogs.nitobi.com/anis/wp-content/uploads/2010/05/4.tiff)](http://blogs.nitobi.com/anis/wp-content/uploads/2010/05/1.tiff)

[![Android Part 2](http://blogs.nitobi.com/anis/wp-content/uploads/2010/05/4.tiff)](http://blogs.nitobi.com/anis/wp-content/uploads/2010/05/2.tiff)

[![Android Part 3](http://blogs.nitobi.com/anis/wp-content/uploads/2010/05/4.tiff)](http://blogs.nitobi.com/anis/wp-content/uploads/2010/05/3.tiff)

[![Android Part 4](http://blogs.nitobi.com/anis/wp-content/uploads/2010/05/4.tiff)](http://blogs.nitobi.com/anis/wp-content/uploads/2010/05/4.tiff)

As you can see it runs the same as on Android 2.1 and previous ! Some tests fail but there not relevant to the Android Platform (orientation etc…)

[› Visit the original post](http://blogs.nitobi.com/anis/?p=51)


text:
namespace BuildIt.CognitiveServices.Models
{
    using System.Linq;

    /// <summary>
    /// Information describing a usage event
    /// </summary>
    public partial class UsageEventInfo
    {
        /// <summary>
        /// Initializes a new instance of the UsageEventInfo class.
        /// </summary>
        public UsageEventInfo() { }

        /// <summary>
        /// Initializes a new instance of the UsageEventInfo class.
        /// </summary>
        /// <param name="eventType">The type of the event. Possible values
        /// include: 'Click', 'RecommendationClick', 'AddShopCart',
        /// 'RemoveShopCart', 'Purchase'</param>
        /// <param name="itemId">The id of the item in context</param>
        /// <param name="timestamp">The time of the event</param>
        /// <param name="count">The number of items</param>
        /// <param name="unitPrice">The price of the item in context</param>
        public UsageEventInfo(string eventType = default(string), string itemId = default(string), string timestamp = default(string), int? count = default(int?), double? unitPrice = default(double?))
        {
            EventType = eventType;
            ItemId = itemId;
            Timestamp = timestamp;
            Count = count;
            UnitPrice = unitPrice;
        }

        /// <summary>
        /// Gets or sets the type of the event. Possible values include:
        /// 'Click', 'RecommendationClick', 'AddShopCart', 'RemoveShopCart',
        /// 'Purchase'
        /// </summary>
        [Newtonsoft.Json.JsonProperty(PropertyName = "eventType")]
        public string EventType { get; set; }

        /// <summary>
        /// Gets or sets the id of the item in context
        /// </summary>
        [Newtonsoft.Json.JsonProperty(PropertyName = "itemId")]
        public string ItemId { get; set; }

        /// <summary>
        /// Gets or sets the time of the event
        /// </summary>
        [Newtonsoft.Json.JsonProperty(PropertyName = "timestamp")]
        public string Timestamp { get; set; }

        /// <summary>
        /// Gets or sets the number of items
        /// </summary>
        [Newtonsoft.Json.JsonProperty(PropertyName = "count")]
        public int? Count { get; set; }

        /// <summary>
        /// Gets or sets the price of the item in context
        /// </summary>
        [Newtonsoft.Json.JsonProperty(PropertyName = "unitPrice")]
        public double? UnitPrice { get; set; }

    }
}


text:
require 'neology'
require 'mocks/neology_user'

class NeologyRAuthoredComment

  include Neology::RelationshipMixin

  property :score, :type => Float

  index :score

  def init_on_create *args

    rel, source_node, dest_node, score = args

    self.score = score

  end

end


text:
import tornado.web
import tornado.gen
import json
import io
import logging
import datetime
import motor

from bson.objectid import ObjectId
from mickey.basehandler import BaseHandler
import mickey.commonconf

class ModGroupHandler(BaseHandler):
    @tornado.web.asynchronous
    @tornado.gen.coroutine
    def post(self):
        coll = self.application.db.groups
        publish = self.application.publish
        data = json.loads(self.request.body.decode("utf-8"))
        groupid = data.get("groupid", "")
        groupname = data.get("name", "")
        owner = data.get("owner", "")
        vip = data.get("vip", "")
        vipname = data.get("vipname", "")
        invite = data.get("invite", "")

        logging.info("begin to mod group, id = %s, groupname = %s, owner = %s, vip = %s, invite = %s" % (groupid, groupname, owner, vip, invite))

        if not groupid:
            logging.error("invalid request")
            self.set_status(403)
            self.finish()
            return

        group = yield coll.find_one({"_id":ObjectId(groupid)})
        group_oldinvite = None
        group_oldowner = None
        if not group:
            logging.error("group not exist")
            self.set_status(404)
            self.finish()
            return
        else:
            group_oldowner = group.get("owner", "")
            group_oldinvite = group.get("invite", "free")
            if group_oldowner != self.p_userid and group_oldinvite == "admin":
                logging.error("you are not the owner")
                self.set_status(403)
                self.finish()
                return

        groupinfo = {}

        if groupname:
            groupinfo["name"] = groupname

        if owner:
            groupinfo["owner"] = owner

        if group.get('expireAt', None):
            #set new expire date
            groupinfo['expireAt'] = datetime.datetime.utcnow() + datetime.timedelta(days = mickey.commonconf.conf_expire_time)

        result = yield coll.update({"_id":ObjectId(groupid)},
                                   {
                                     "$set":groupinfo,
                                     "$unset": {"garbage": 1}
                                   })

        if result:
            self.set_status(200)
            receivers = [x.get("id", "") for x in group.get("members", [])]

            notify = {}
            notify["name"] = "mx.group.group_change"
            notify["pub_type"] = "any"
            notify["nty_type"] = "app"
            notify["groupid"] = groupid
            notify["action"] = "info_change"

            publish.publish_multi(receivers, notify)
        else:
            logging.error("mod group failed")
            self.set_status(500)

        self.finish()


text:
from gapipy.resources.base import Resource

class DeclinedReason(Resource):
    _resource_name = 'declined_reasons'

    _as_is_fields = ['id', 'href', 'service', 'channels', 'name']


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Windows;
using Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls;
using Microsoft.VisualStudio.PlatformUI;

namespace Microsoft.VisualStudio.LanguageServices.Implementation.ExtractClass
{
    /// <summary>
    /// Interaction logic for ExtractClassDialog.xaml
    /// </summary>
    internal partial class ExtractClassDialog : DialogWindow
    {
        public string OK => ServicesVSResources.OK;
        public string Cancel => ServicesVSResources.Cancel;
        public string SelectMembers => ServicesVSResources.Select_members_colon;
        public string ExtractClassTitle => ServicesVSResources.Extract_Base_Class;
        public ExtractClassViewModel ViewModel { get; }
        public MemberSelection MemberSelectionControl { get; }
        public NewTypeDestinationSelection DestinationSelectionControl { get; }

        public ExtractClassDialog(ExtractClassViewModel viewModel)
        {
            ViewModel = viewModel;

            DataContext = ViewModel;

            MemberSelectionControl = new MemberSelection(ViewModel.MemberSelectionViewModel);
            DestinationSelectionControl = new NewTypeDestinationSelection(ViewModel.DestinationViewModel);

            InitializeComponent();
        }

        private void OK_Click(object sender, RoutedEventArgs e)
        {
            if (ViewModel.TrySubmit())
            {
                DialogResult = true;
            }
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
            => DialogResult = false;
    }
}


text:
#include <OgreStableHeaders.h>

#include "Math/Array/OgreArrayQuaternion.h"

#if __OGRE_HAVE_SSE

namespace Ogre
{
    const ArrayQuaternion ArrayQuaternion::ZERO( _mm_setzero_ps(), _mm_setzero_ps(), _mm_setzero_ps(), _mm_setzero_ps() );
    const ArrayQuaternion ArrayQuaternion::IDENTITY( _mm_set_ps1( 1.0f ), _mm_setzero_ps(), _mm_setzero_ps(), _mm_setzero_ps() );
}

#endif


text:
'use strict'

//import SCNNode from './SCNNode'
//import SCNRenderer from './SCNRenderer'

/**
 * Methods you can implement to use your own custom Metal or OpenGL drawing code to render content for a node.
 * @interface
 * @see https://developer.apple.com/documentation/scenekit/scnnoderendererdelegate
 */
export default class SCNNodeRendererDelegate {

  /**
   * constructor
   * @access public
   * @constructor
   */
  //construtor() {
  //}

  // Customizing the Rendering of a Node

  /**
   * Tells the delegate to perform rendering for a node.
   * @access public
   * @param {SCNNode} node - The node to render.
   * @param {SCNRenderer} renderer - The SceneKit object (such as an SCNView instance) responsible for rendering the scene.
   * @param {Map<string, Object>} _arguments -
   * @returns {void}
   * @desc Implement this method to perform custom rendering for a node. You should only execute Metal or OpenGL drawing commands (and any setup required to perform them) in this method—the results of modifying SceneKit objects in this method are undefined.To render using Metal, use the renderer parameter to retrieve the scene renderer's currentRenderCommandEncoder object and encode your own drawing commands. If you need to reference other Metal state, see the properties listed in SCNSceneRenderer.To render using OpenGL, simply call the relevant OpenGL drawing commands—SceneKit automatically makes its OpenGL context the current context before calling this method. If you need to reference the OpenGL context being rendered into, examine the context property of the renderer parameter.You must draw using the appropriate graphics technology for the view currently being rendered. Use the renderingAPI property of the renderer object to determine whether Metal or OpenGL is in use.
   * @see https://developer.apple.com/documentation/scenekit/scnnoderendererdelegate/1407993-rendernode
   */
  renderNode(node, renderer, _arguments) {
  }
}


text:
package org.jetbrains.plugins.scala.codeInspection.collections

import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElement
import org.jetbrains.plugins.scala.codeInspection.InspectionBundle

/**
 * @author Nikolay.Tropin
 */
class SideEffectsInMonadicTransformationInspection extends OperationOnCollectionInspection {

  override def actionFor(holder: ProblemsHolder): PartialFunction[PsiElement, Any] = {
    case qual`.monadicMethod`(arg) =>
      exprsWithSideEffects(arg).foreach {
        case expr => holder.registerProblem(expr, InspectionBundle.message("side.effects.in.monadic"), highlightType)
      }
  }

  override def possibleSimplificationTypes: Array[SimplificationType] = Array.empty
}


text:
package org.gradle.cache.internal;

import com.google.common.primitives.Ints;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;

import java.util.Arrays;

public final class CacheVersion implements Comparable<CacheVersion> {

    public static final String COMPONENT_SEPARATOR = ".";

    public static CacheVersion parse(String version) {
        String[] parts = StringUtils.split(version, COMPONENT_SEPARATOR);
        int[] components = new int[parts.length];
        for (int i = 0; i < parts.length; i++) {
            components[i] = Integer.parseInt(parts[i]);
        }
        return new CacheVersion(components);
    }

    public static CacheVersion empty() {
        return new CacheVersion(ArrayUtils.EMPTY_INT_ARRAY);
    }

    public static CacheVersion of(int component) {
        return new CacheVersion(new int[] {component});
    }

    public static CacheVersion of(int... components) {
        return new CacheVersion(ArrayUtils.clone(components));
    }

    private final int[] components;

    private CacheVersion(int[] components) {
        this.components = components;
    }

    public CacheVersion append(int additionalComponent) {
        int[] appendedComponents = new int[components.length + 1];
        System.arraycopy(components, 0, appendedComponents, 0, components.length);
        appendedComponents[components.length] = additionalComponent;
        return new CacheVersion(appendedComponents);
    }

    @Override
    public String toString() {
        return Ints.join(COMPONENT_SEPARATOR, components);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        CacheVersion that = (CacheVersion) o;
        return Arrays.equals(this.components, that.components);
    }

    @Override
    public int hashCode() {
        return Arrays.hashCode(components);
    }

    @Override
    public int compareTo(CacheVersion that) {
        int minLength = Math.min(this.components.length, that.components.length);
        for (int i = 0; i < minLength; i++) {
            int result = Ints.compare(this.components[i], that.components[i]);
            if (result != 0) {
                return result;
            }
        }
        return Ints.compare(this.components.length, that.components.length);
    }
}


text:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace ORM.DAL.Models
{
	public interface IBaseEntity<T>
	{
		[Key]
		[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
		T Id { get; set; }
	}
}


text:
package com.fireflysource.common.actor;

import com.fireflysource.common.func.Callback;
import com.fireflysource.common.slf4j.LazyLogger;
import com.fireflysource.common.sys.Result;
import com.fireflysource.common.sys.SystemLogger;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.locks.Lock;

import static com.fireflysource.common.sys.Result.runCaching;

public class BlockingTask<T> implements ForkJoinPool.ManagedBlocker {

    private static final LazyLogger log = SystemLogger.create(BlockingTask.class);

    private final Callable<T> callable;
    private final Callable<Result<T>> tryCallable;
    private T result;
    private boolean done = false;

    public BlockingTask(Callable<T> callable, Callable<Result<T>> tryCallable) {
        this.callable = callable;
        this.tryCallable = tryCallable;
    }

    @Override
    public boolean block() throws InterruptedException {
        try {
            result = callable.call();
        } catch (Exception e) {
            log.error("run blocking task exception.", e);
        }
        done = true;
        return true;
    }

    @Override
    public boolean isReleasable() {
        try {
            Result<T> r = tryCallable.call();
            done = r.isSuccess();
            if (done) {
                result = r.getValue();
            }
        } catch (Exception e) {
            done = false;
        }
        return done;
    }

    public static void runBlockingTask(Callback callback) {
        runBlockingTask(() -> {
            callback.call();
            return null;
        });
    }

    public static <T> Result<T> runBlockingTask(Callable<T> callable) {
        return runBlockingTask(callable, null);
    }

    public static <T> Result<T> runBlockingTask(Callable<T> callable, Callable<Result<T>> tryCallable) {
        return runCaching(() -> {
            BlockingTask<T> task = new BlockingTask<>(callable, tryCallable);
            ForkJoinPool.managedBlock(task);
            return task.result;
        });
    }

    public static void sleep(long millisecond) {
        runBlockingTask(() -> Thread.sleep(millisecond));
    }

    public static <T> T blockingTake(final BlockingQueue<T> queue) {
        Result<T> result = runBlockingTask(queue::take, () -> {
            T t = queue.poll();
            return new Result<>(t != null, t, null);
        });
        return result.getValue();
    }

    public static <T> T blockingLock(final Lock lock, Callable<T> callable) {
        Result<T> result = runBlockingTask(() -> {
            try {
                lock.lock();
                return callable.call();
            } finally {
                lock.unlock();
            }
        }, () -> {
            boolean success = lock.tryLock();
            if (success) {
                try {
                    return new Result<>(true, callable.call(), null);
                } finally {
                    lock.unlock();
                }
            } else {
                return new Result<>(false, null, null);
            }
        });
        return result.getValue();
    }
}


text:
package jamaica.faces.component;

import static jamaica.faces.novdl.set_value_expression.set_value_expression;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;

/**
 * This interface adds fluent methods on top of the standard methods.
 */
public interface FluentUISelectItems<T extends FluentUISelectItems> extends
            FluentUIInput<T> {

    public void setValue(Object value);
    public default T value(Object value) {
        setValue(value); return (T) this;
    }
    public default T valuex(String expression) {
        set_value_expression(FacesContext.getCurrentInstance(), (UIComponent) this,
                "value", expression); return (T) this;
    }
}


text:
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        } else if (p == null || q == null) {
            return false;
        } else {
            if (p.val != q.val) {
                return false;
            } else {
                return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
            }
        }
    }
}


text:
package org.vertexium.cypher.ast.model;

import java.util.stream.Stream;

public class CypherLiteralExpression extends CypherExpression {
    private final Object value;

    public CypherLiteralExpression(Object value) {
        this.value = value;
    }

    public Object getValue() {
        return value;
    }

    @Override
    public Stream<? extends CypherAstBase> getChildren() {
        if (value instanceof CypherAstBase) {
            return Stream.of((CypherAstBase) value);
        }
        return Stream.empty();
    }
}


text:
package com.android.server;

import static android.content.Intent.ACTION_UID_REMOVED;
import static android.content.Intent.EXTRA_UID;
import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
import static android.net.ConnectivityManager.TYPE_WIFI;
import static android.net.NetworkPolicy.LIMIT_DISABLED;
import static android.net.NetworkPolicy.WARNING_DISABLED;
import static android.net.NetworkPolicyManager.POLICY_NONE;
import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
import static android.net.NetworkPolicyManager.computeNextCycleBoundary;
import static android.net.TrafficStats.KB_IN_BYTES;
import static android.net.TrafficStats.MB_IN_BYTES;
import static android.text.format.DateUtils.DAY_IN_MILLIS;
import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
import static android.text.format.Time.TIMEZONE_UTC;
import static com.android.server.net.NetworkPolicyManagerService.TYPE_LIMIT;
import static com.android.server.net.NetworkPolicyManagerService.TYPE_LIMIT_SNOOZED;
import static com.android.server.net.NetworkPolicyManagerService.TYPE_WARNING;
import static org.easymock.EasyMock.anyInt;
import static org.easymock.EasyMock.anyLong;
import static org.easymock.EasyMock.aryEq;
import static org.easymock.EasyMock.capture;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.expectLastCall;
import static org.easymock.EasyMock.isA;

import android.app.IActivityManager;
import android.app.INotificationManager;
import android.app.IProcessObserver;
import android.app.Notification;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.net.ConnectivityManager;
import android.net.IConnectivityManager;
import android.net.INetworkManagementEventObserver;
import android.net.INetworkPolicyListener;
import android.net.INetworkStatsService;
import android.net.LinkProperties;
import android.net.NetworkInfo;
import android.net.NetworkInfo.DetailedState;
import android.net.NetworkPolicy;
import android.net.NetworkState;
import android.net.NetworkStats;
import android.net.NetworkTemplate;
import android.os.Binder;
import android.os.INetworkManagementService;
import android.os.IPowerManager;
import android.os.MessageQueue.IdleHandler;
import android.os.UserHandle;
import android.test.AndroidTestCase;
import android.test.mock.MockPackageManager;
import android.test.suitebuilder.annotation.LargeTest;
import android.test.suitebuilder.annotation.Suppress;
import android.text.format.Time;
import android.util.TrustedTime;

import com.android.server.net.NetworkPolicyManagerService;
import com.google.common.util.concurrent.AbstractFuture;

import org.easymock.Capture;
import org.easymock.EasyMock;
import org.easymock.IAnswer;

import java.io.File;
import java.util.LinkedHashSet;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Handler;

import libcore.io.IoUtils;

/**
 * Tests for {@link NetworkPolicyManagerService}.
 */
@LargeTest
public class NetworkPolicyManagerServiceTest extends AndroidTestCase {
    private static final String TAG = "NetworkPolicyManagerServiceTest";

    private static final long TEST_START = 1194220800000L;
    private static final String TEST_IFACE = "test0";
    private static final String TEST_SSID = "AndroidAP";

    private static NetworkTemplate sTemplateWifi = NetworkTemplate.buildTemplateWifi(TEST_SSID);

    private BroadcastInterceptingContext mServiceContext;
    private File mPolicyDir;

    private IActivityManager mActivityManager;
    private IPowerManager mPowerManager;
    private INetworkStatsService mStatsService;
    private INetworkManagementService mNetworkManager;
    private INetworkPolicyListener mPolicyListener;
    private TrustedTime mTime;
    private IConnectivityManager mConnManager;
    private INotificationManager mNotifManager;

    private NetworkPolicyManagerService mService;
    private IProcessObserver mProcessObserver;
    private INetworkManagementEventObserver mNetworkObserver;

    private Binder mStubBinder = new Binder();

    private long mStartTime;
    private long mElapsedRealtime;

    private static final int USER_ID = 0;

    private static final int APP_ID_A = android.os.Process.FIRST_APPLICATION_UID + 800;
    private static final int APP_ID_B = android.os.Process.FIRST_APPLICATION_UID + 801;

    private static final int UID_A = UserHandle.getUid(USER_ID, APP_ID_A);
    private static final int UID_B = UserHandle.getUid(USER_ID, APP_ID_B);

    private static final int PID_1 = 400;
    private static final int PID_2 = 401;
    private static final int PID_3 = 402;

    @Override
    public void setUp() throws Exception {
        super.setUp();

        setCurrentTimeMillis(TEST_START);

        // intercept various broadcasts, and pretend that uids have packages
        mServiceContext = new BroadcastInterceptingContext(getContext()) {
            @Override
            public PackageManager getPackageManager() {
                return new MockPackageManager() {
                    @Override
                    public String[] getPackagesForUid(int uid) {
                        return new String[] { "com.example" };
                    }

                    @Override
                    public PackageInfo getPackageInfo(String packageName, int flags) {
                        final PackageInfo info = new PackageInfo();
                        final Signature signature;
                        if ("android".equals(packageName)) {
                            signature = new Signature("F00D");
                        } else {
                            signature = new Signature("DEAD");
                        }
                        info.signatures = new Signature[] { signature };
                        return info;
                    }

                };
            }

            @Override
            public void startActivity(Intent intent) {
                // ignored
            }
        };

        mPolicyDir = getContext().getFilesDir();
        if (mPolicyDir.exists()) {
            IoUtils.deleteContents(mPolicyDir);
        }

        mActivityManager = createMock(IActivityManager.class);
        mPowerManager = createMock(IPowerManager.class);
        mStatsService = createMock(INetworkStatsService.class);
        mNetworkManager = createMock(INetworkManagementService.class);
        mPolicyListener = createMock(INetworkPolicyListener.class);
        mTime = createMock(TrustedTime.class);
        mConnManager = createMock(IConnectivityManager.class);
        mNotifManager = createMock(INotificationManager.class);

        mService = new NetworkPolicyManagerService(mServiceContext, mActivityManager, mPowerManager,
                mStatsService, mNetworkManager, mTime, mPolicyDir, true);
        mService.bindConnectivityManager(mConnManager);
        mService.bindNotificationManager(mNotifManager);

        // RemoteCallbackList needs a binder to use as key
        expect(mPolicyListener.asBinder()).andReturn(mStubBinder).atLeastOnce();
        replay();
        mService.registerListener(mPolicyListener);
        verifyAndReset();

        // catch IProcessObserver during systemReady()
        final Capture<IProcessObserver> processObserver = new Capture<IProcessObserver>();
        mActivityManager.registerProcessObserver(capture(processObserver));
        expectLastCall().atLeastOnce();

        // catch INetworkManagementEventObserver during systemReady()
        final Capture<INetworkManagementEventObserver> networkObserver = new Capture<
                INetworkManagementEventObserver>();
        mNetworkManager.registerObserver(capture(networkObserver));
        expectLastCall().atLeastOnce();

        // expect to answer screen status during systemReady()
        expect(mPowerManager.isInteractive()).andReturn(true).atLeastOnce();
        expect(mNetworkManager.isBandwidthControlEnabled()).andReturn(true).atLeastOnce();
        expectCurrentTime();

        replay();
        mService.systemReady();
        verifyAndReset();

        mProcessObserver = processObserver.getValue();
        mNetworkObserver = networkObserver.getValue();

    }

    @Override
    public void tearDown() throws Exception {
        for (File file : mPolicyDir.listFiles()) {
            file.delete();
        }

        mServiceContext = null;
        mPolicyDir = null;

        mActivityManager = null;
        mPowerManager = null;
        mStatsService = null;
        mPolicyListener = null;
        mTime = null;

        mService = null;
        mProcessObserver = null;

        super.tearDown();
    }

    @Suppress
    public void testPolicyChangeTriggersBroadcast() throws Exception {
        mService.setUidPolicy(APP_ID_A, POLICY_NONE);

        // change background policy and expect broadcast
        final Future<Intent> backgroundChanged = mServiceContext.nextBroadcastIntent(
                ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);

        mService.setUidPolicy(APP_ID_A, POLICY_REJECT_METERED_BACKGROUND);

        backgroundChanged.get();
    }

    public void testPidForegroundCombined() throws Exception {
        IdleFuture idle;

        // push all uid into background
        idle = expectIdle();
        mProcessObserver.onForegroundActivitiesChanged(PID_1, UID_A, false);
        mProcessObserver.onForegroundActivitiesChanged(PID_2, UID_A, false);
        mProcessObserver.onForegroundActivitiesChanged(PID_3, UID_B, false);
        idle.get();
        assertFalse(mService.isUidForeground(UID_A));
        assertFalse(mService.isUidForeground(UID_B));

        // push one of the shared pids into foreground
        idle = expectIdle();
        mProcessObserver.onForegroundActivitiesChanged(PID_2, UID_A, true);
        idle.get();
        assertTrue(mService.isUidForeground(UID_A));
        assertFalse(mService.isUidForeground(UID_B));

        // and swap another uid into foreground
        idle = expectIdle();
        mProcessObserver.onForegroundActivitiesChanged(PID_2, UID_A, false);
        mProcessObserver.onForegroundActivitiesChanged(PID_3, UID_B, true);
        idle.get();
        assertFalse(mService.isUidForeground(UID_A));
        assertTrue(mService.isUidForeground(UID_B));

        // push both pid into foreground
        idle = expectIdle();
        mProcessObserver.onForegroundActivitiesChanged(PID_1, UID_A, true);
        mProcessObserver.onForegroundActivitiesChanged(PID_2, UID_A, true);
        idle.get();
        assertTrue(mService.isUidForeground(UID_A));

        // pull one out, should still be foreground
        idle = expectIdle();
        mProcessObserver.onForegroundActivitiesChanged(PID_1, UID_A, false);
        idle.get();
        assertTrue(mService.isUidForeground(UID_A));

        // pull final pid out, should now be background
        idle = expectIdle();
        mProcessObserver.onForegroundActivitiesChanged(PID_2, UID_A, false);
        idle.get();
        assertFalse(mService.isUidForeground(UID_A));
    }

    public void testScreenChangesRules() throws Exception {
        Future<Void> future;

        expectSetUidMeteredNetworkBlacklist(UID_A, false);
        expectSetUidForeground(UID_A, true);
        future = expectRulesChanged(UID_A, RULE_ALLOW_ALL);
        replay();
        mProcessObserver.onForegroundActivitiesChanged(PID_1, UID_A, true);
        future.get();
        verifyAndReset();

        // push strict policy for foreground uid, verify ALLOW rule
        expectSetUidMeteredNetworkBlacklist(UID_A, false);
        expectSetUidForeground(UID_A, true);
        future = expectRulesChanged(UID_A, RULE_ALLOW_ALL);
        replay();
        mService.setUidPolicy(APP_ID_A, POLICY_REJECT_METERED_BACKGROUND);
        future.get();
        verifyAndReset();

        // now turn screen off and verify REJECT rule
        expect(mPowerManager.isInteractive()).andReturn(false).atLeastOnce();
        expectSetUidMeteredNetworkBlacklist(UID_A, true);
        expectSetUidForeground(UID_A, false);
        future = expectRulesChanged(UID_A, RULE_REJECT_METERED);
        replay();
        mServiceContext.sendBroadcast(new Intent(Intent.ACTION_SCREEN_OFF));
        future.get();
        verifyAndReset();

        // and turn screen back on, verify ALLOW rule restored
        expect(mPowerManager.isInteractive()).andReturn(true).atLeastOnce();
        expectSetUidMeteredNetworkBlacklist(UID_A, false);
        expectSetUidForeground(UID_A, true);
        future = expectRulesChanged(UID_A, RULE_ALLOW_ALL);
        replay();
        mServiceContext.sendBroadcast(new Intent(Intent.ACTION_SCREEN_ON));
        future.get();
        verifyAndReset();
    }

    public void testPolicyNone() throws Exception {
        Future<Void> future;

        expectSetUidMeteredNetworkBlacklist(UID_A, false);
        expectSetUidForeground(UID_A, true);
        future = expectRulesChanged(UID_A, RULE_ALLOW_ALL);
        replay();
        mProcessObserver.onForegroundActivitiesChanged(PID_1, UID_A, true);
        future.get();
        verifyAndReset();

        // POLICY_NONE should RULE_ALLOW in foreground
        expectSetUidMeteredNetworkBlacklist(UID_A, false);
        expectSetUidForeground(UID_A, true);
        future = expectRulesChanged(UID_A, RULE_ALLOW_ALL);
        replay();
        mService.setUidPolicy(APP_ID_A, POLICY_NONE);
        future.get();
        verifyAndReset();

        // POLICY_NONE should RULE_ALLOW in background
        expectSetUidMeteredNetworkBlacklist(UID_A, false);
        expectSetUidForeground(UID_A, false);
        future = expectRulesChanged(UID_A, RULE_ALLOW_ALL);
        replay();
        mProcessObserver.onForegroundActivitiesChanged(PID_1, UID_A, false);
        future.get();
        verifyAndReset();
    }

    public void testPolicyReject() throws Exception {
        Future<Void> future;

        // POLICY_REJECT should RULE_ALLOW in background
        expectSetUidMeteredNetworkBlacklist(UID_A, true);
        expectSetUidForeground(UID_A, false);
        future = expectRulesChanged(UID_A, RULE_REJECT_METERED);
        replay();
        mService.setUidPolicy(APP_ID_A, POLICY_REJECT_METERED_BACKGROUND);
        future.get();
        verifyAndReset();

        // POLICY_REJECT should RULE_ALLOW in foreground
        expectSetUidMeteredNetworkBlacklist(UID_A, false);
        expectSetUidForeground(UID_A, true);
        future = expectRulesChanged(UID_A, RULE_ALLOW_ALL);
        replay();
        mProcessObserver.onForegroundActivitiesChanged(PID_1, UID_A, true);
        future.get();
        verifyAndReset();

        // POLICY_REJECT should RULE_REJECT in background
        expectSetUidMeteredNetworkBlacklist(UID_A, true);
        expectSetUidForeground(UID_A, false);
        future = expectRulesChanged(UID_A, RULE_REJECT_METERED);
        replay();
        mProcessObserver.onForegroundActivitiesChanged(PID_1, UID_A, false);
        future.get();
        verifyAndReset();
    }

    public void testPolicyRejectAddRemove() throws Exception {
        Future<Void> future;

        // POLICY_NONE should have RULE_ALLOW in background
        expectSetUidMeteredNetworkBlacklist(UID_A, false);
        expectSetUidForeground(UID_A, false);
        future = expectRulesChanged(UID_A, RULE_ALLOW_ALL);
        replay();
        mProcessObserver.onForegroundActivitiesChanged(PID_1, UID_A, false);
        mService.setUidPolicy(APP_ID_A, POLICY_NONE);
        future.get();
        verifyAndReset();

        // adding POLICY_REJECT should cause RULE_REJECT
        expectSetUidMeteredNetworkBlacklist(UID_A, true);
        expectSetUidForeground(UID_A, false);
        future = expectRulesChanged(UID_A, RULE_REJECT_METERED);
        replay();
        mService.setUidPolicy(APP_ID_A, POLICY_REJECT_METERED_BACKGROUND);
        future.get();
        verifyAndReset();

        // removing POLICY_REJECT should return us to RULE_ALLOW
        expectSetUidMeteredNetworkBlacklist(UID_A, false);
        expectSetUidForeground(UID_A, false);
        future = expectRulesChanged(UID_A, RULE_ALLOW_ALL);
        replay();
        mService.setUidPolicy(APP_ID_A, POLICY_NONE);
        future.get();
        verifyAndReset();
    }

    public void testLastCycleBoundaryThisMonth() throws Exception {
        // assume cycle day of "5th", which should be in same month
        final long currentTime = parseTime("2007-11-14T00:00:00.000Z");
        final long expectedCycle = parseTime("2007-11-05T00:00:00.000Z");

        final NetworkPolicy policy = new NetworkPolicy(
                sTemplateWifi, 5, TIMEZONE_UTC, 1024L, 1024L, false);
        final long actualCycle = computeLastCycleBoundary(currentTime, policy);
        assertTimeEquals(expectedCycle, actualCycle);
    }

    public void testLastCycleBoundaryLastMonth() throws Exception {
        // assume cycle day of "20th", which should be in last month
        final long currentTime = parseTime("2007-11-14T00:00:00.000Z");
        final long expectedCycle = parseTime("2007-10-20T00:00:00.000Z");

        final NetworkPolicy policy = new NetworkPolicy(
                sTemplateWifi, 20, TIMEZONE_UTC, 1024L, 1024L, false);
        final long actualCycle = computeLastCycleBoundary(currentTime, policy);
        assertTimeEquals(expectedCycle, actualCycle);
    }

    public void testLastCycleBoundaryThisMonthFebruary() throws Exception {
        // assume cycle day of "30th" in february; should go to january
        final long currentTime = parseTime("2007-02-14T00:00:00.000Z");
        final long expectedCycle = parseTime("2007-01-30T00:00:00.000Z");

        final NetworkPolicy policy = new NetworkPolicy(
                sTemplateWifi, 30, TIMEZONE_UTC, 1024L, 1024L, false);
        final long actualCycle = computeLastCycleBoundary(currentTime, policy);
        assertTimeEquals(expectedCycle, actualCycle);
    }

    public void testLastCycleBoundaryLastMonthFebruary() throws Exception {
        // assume cycle day of "30th" in february, which should clamp
        final long currentTime = parseTime("2007-03-14T00:00:00.000Z");
        final long expectedCycle = parseTime("2007-02-28T23:59:59.000Z");

        final NetworkPolicy policy = new NetworkPolicy(
                sTemplateWifi, 30, TIMEZONE_UTC, 1024L, 1024L, false);
        final long actualCycle = computeLastCycleBoundary(currentTime, policy);
        assertTimeEquals(expectedCycle, actualCycle);
    }

    public void testCycleBoundaryLeapYear() throws Exception {
        final NetworkPolicy policy = new NetworkPolicy(
                sTemplateWifi, 29, TIMEZONE_UTC, 1024L, 1024L, false);

        assertTimeEquals(parseTime("2012-01-29T00:00:00.000Z"),
                computeNextCycleBoundary(parseTime("2012-01-14T00:00:00.000Z"), policy));
        assertTimeEquals(parseTime("2012-02-29T00:00:00.000Z"),
                computeNextCycleBoundary(parseTime("2012-02-14T00:00:00.000Z"), policy));
        assertTimeEquals(parseTime("2012-02-29T00:00:00.000Z"),
                computeLastCycleBoundary(parseTime("2012-03-14T00:00:00.000Z"), policy));
        assertTimeEquals(parseTime("2012-03-29T00:00:00.000Z"),
                computeNextCycleBoundary(parseTime("2012-03-14T00:00:00.000Z"), policy));

        assertTimeEquals(parseTime("2007-01-29T00:00:00.000Z"),
                computeNextCycleBoundary(parseTime("2007-01-14T00:00:00.000Z"), policy));
        assertTimeEquals(parseTime("2007-02-28T23:59:59.000Z"),
                computeNextCycleBoundary(parseTime("2007-02-14T00:00:00.000Z"), policy));
        assertTimeEquals(parseTime("2007-02-28T23:59:59.000Z"),
                computeLastCycleBoundary(parseTime("2007-03-14T00:00:00.000Z"), policy));
        assertTimeEquals(parseTime("2007-03-29T00:00:00.000Z"),
                computeNextCycleBoundary(parseTime("2007-03-14T00:00:00.000Z"), policy));
    }

    public void testNextCycleTimezoneAfterUtc() throws Exception {
        // US/Central is UTC-6
        final NetworkPolicy policy = new NetworkPolicy(
                sTemplateWifi, 10, "US/Central", 1024L, 1024L, false);
        assertTimeEquals(parseTime("2012-01-10T06:00:00.000Z"),
                computeNextCycleBoundary(parseTime("2012-01-05T00:00:00.000Z"), policy));
    }

    public void testNextCycleTimezoneBeforeUtc() throws Exception {
        // Israel is UTC+2
        final NetworkPolicy policy = new NetworkPolicy(
                sTemplateWifi, 10, "Israel", 1024L, 1024L, false);
        assertTimeEquals(parseTime("2012-01-09T22:00:00.000Z"),
                computeNextCycleBoundary(parseTime("2012-01-05T00:00:00.000Z"), policy));
    }

    public void testNextCycleSane() throws Exception {
        final NetworkPolicy policy = new NetworkPolicy(
                sTemplateWifi, 31, TIMEZONE_UTC, WARNING_DISABLED, LIMIT_DISABLED, false);
        final LinkedHashSet<Long> seen = new LinkedHashSet<Long>();

        // walk forwards, ensuring that cycle boundaries don't get stuck
        long currentCycle = computeNextCycleBoundary(parseTime("2011-08-01T00:00:00.000Z"), policy);
        for (int i = 0; i < 128; i++) {
            long nextCycle = computeNextCycleBoundary(currentCycle, policy);
            assertEqualsFuzzy(DAY_IN_MILLIS * 30, nextCycle - currentCycle, DAY_IN_MILLIS * 3);
            assertUnique(seen, nextCycle);
            currentCycle = nextCycle;
        }
    }

    public void testLastCycleSane() throws Exception {
        final NetworkPolicy policy = new NetworkPolicy(
                sTemplateWifi, 31, TIMEZONE_UTC, WARNING_DISABLED, LIMIT_DISABLED, false);
        final LinkedHashSet<Long> seen = new LinkedHashSet<Long>();

        // walk backwards, ensuring that cycle boundaries look sane
        long currentCycle = computeLastCycleBoundary(parseTime("2011-08-04T00:00:00.000Z"), policy);
        for (int i = 0; i < 128; i++) {
            long lastCycle = computeLastCycleBoundary(currentCycle, policy);
            assertEqualsFuzzy(DAY_IN_MILLIS * 30, currentCycle - lastCycle, DAY_IN_MILLIS * 3);
            assertUnique(seen, lastCycle);
            currentCycle = lastCycle;
        }
    }

    public void testCycleTodayJanuary() throws Exception {
        final NetworkPolicy policy = new NetworkPolicy(
                sTemplateWifi, 14, "US/Pacific", 1024L, 1024L, false);

        assertTimeEquals(parseTime("2013-01-14T00:00:00.000-08:00"),
                computeNextCycleBoundary(parseTime("2013-01-13T23:59:59.000-08:00"), policy));
        assertTimeEquals(parseTime("2013-02-14T00:00:00.000-08:00"),
                computeNextCycleBoundary(parseTime("2013-01-14T00:00:01.000-08:00"), policy));
        assertTimeEquals(parseTime("2013-02-14T00:00:00.000-08:00"),
                computeNextCycleBoundary(parseTime("2013-01-14T15:11:00.000-08:00"), policy));

        assertTimeEquals(parseTime("2012-12-14T00:00:00.000-08:00"),
                computeLastCycleBoundary(parseTime("2013-01-13T23:59:59.000-08:00"), policy));
        assertTimeEquals(parseTime("2013-01-14T00:00:00.000-08:00"),
                computeLastCycleBoundary(parseTime("2013-01-14T00:00:01.000-08:00"), policy));
        assertTimeEquals(parseTime("2013-01-14T00:00:00.000-08:00"),
                computeLastCycleBoundary(parseTime("2013-01-14T15:11:00.000-08:00"), policy));
    }

    public void testNetworkPolicyAppliedCycleLastMonth() throws Exception {
        NetworkState[] state = null;
        NetworkStats stats = null;
        Future<Void> future;

        final long TIME_FEB_15 = 1171497600000L;
        final long TIME_MAR_10 = 1173484800000L;
        final int CYCLE_DAY = 15;

        setCurrentTimeMillis(TIME_MAR_10);

        // first, pretend that wifi network comes online. no policy active,
        // which means we shouldn't push limit to interface.
        state = new NetworkState[] { buildWifi() };
        expect(mConnManager.getAllNetworkState()).andReturn(state).atLeastOnce();
        expectCurrentTime();
        expectClearNotifications();
        expectAdvisePersistThreshold();
        future = expectMeteredIfacesChanged();

        replay();
        mServiceContext.sendBroadcast(new Intent(CONNECTIVITY_ACTION));
        future.get();
        verifyAndReset();

        // now change cycle to be on 15th, and test in early march, to verify we
        // pick cycle day in previous month.
        expect(mConnManager.getAllNetworkState()).andReturn(state).atLeastOnce();
        expectCurrentTime();

        // pretend that 512 bytes total have happened
        stats = new NetworkStats(getElapsedRealtime(), 1)
                .addIfaceValues(TEST_IFACE, 256L, 2L, 256L, 2L);
        expect(mStatsService.getNetworkTotalBytes(sTemplateWifi, TIME_FEB_15, TIME_MAR_10))
                .andReturn(stats.getTotalBytes()).atLeastOnce();
        expectPolicyDataEnable(TYPE_WIFI, true);

        // TODO: consider making strongly ordered mock
        expectRemoveInterfaceQuota(TEST_IFACE);
        expectSetInterfaceQuota(TEST_IFACE, (2 * MB_IN_BYTES) - 512);

        expectClearNotifications();
        expectAdvisePersistThreshold();
        future = expectMeteredIfacesChanged(TEST_IFACE);

        replay();
        setNetworkPolicies(new NetworkPolicy(
                sTemplateWifi, CYCLE_DAY, TIMEZONE_UTC, 1 * MB_IN_BYTES, 2 * MB_IN_BYTES, false));
        future.get();
        verifyAndReset();
    }

    public void testUidRemovedPolicyCleared() throws Exception {
        Future<Void> future;

        // POLICY_REJECT should RULE_REJECT in background
        expectSetUidMeteredNetworkBlacklist(UID_A, true);
        expectSetUidForeground(UID_A, false);
        future = expectRulesChanged(UID_A, RULE_REJECT_METERED);
        replay();
        mService.setUidPolicy(APP_ID_A, POLICY_REJECT_METERED_BACKGROUND);
        future.get();
        verifyAndReset();

        // uninstall should clear RULE_REJECT
        expectSetUidMeteredNetworkBlacklist(UID_A, false);
        expectSetUidForeground(UID_A, false);
        future = expectRulesChanged(UID_A, RULE_ALLOW_ALL);
        replay();
        final Intent intent = new Intent(ACTION_UID_REMOVED);
        intent.putExtra(EXTRA_UID, UID_A);
        mServiceContext.sendBroadcast(intent);
        future.get();
        verifyAndReset();
    }

    public void testOverWarningLimitNotification() throws Exception {
        NetworkState[] state = null;
        NetworkStats stats = null;
        Future<Void> future;
        Future<String> tagFuture;

        final long TIME_FEB_15 = 1171497600000L;
        final long TIME_MAR_10 = 1173484800000L;
        final int CYCLE_DAY = 15;

        setCurrentTimeMillis(TIME_MAR_10);

        // assign wifi policy
        state = new NetworkState[] {};
        stats = new NetworkStats(getElapsedRealtime(), 1)
                .addIfaceValues(TEST_IFACE, 0L, 0L, 0L, 0L);

        {
            expectCurrentTime();
            expect(mConnManager.getAllNetworkState()).andReturn(state).atLeastOnce();
            expect(mStatsService.getNetworkTotalBytes(sTemplateWifi, TIME_FEB_15, currentTimeMillis()))
                    .andReturn(stats.getTotalBytes()).atLeastOnce();
            expectPolicyDataEnable(TYPE_WIFI, true);

            expectClearNotifications();
            expectAdvisePersistThreshold();
            future = expectMeteredIfacesChanged();

            replay();
            setNetworkPolicies(new NetworkPolicy(sTemplateWifi, CYCLE_DAY, TIMEZONE_UTC, 1
                    * MB_IN_BYTES, 2 * MB_IN_BYTES, false));
            future.get();
            verifyAndReset();
        }

        // bring up wifi network
        incrementCurrentTime(MINUTE_IN_MILLIS);
        state = new NetworkState[] { buildWifi() };
        stats = new NetworkStats(getElapsedRealtime(), 1)
                .addIfaceValues(TEST_IFACE, 0L, 0L, 0L, 0L);

        {
            expectCurrentTime();
            expect(mConnManager.getAllNetworkState()).andReturn(state).atLeastOnce();
            expect(mStatsService.getNetworkTotalBytes(sTemplateWifi, TIME_FEB_15, currentTimeMillis()))
                    .andReturn(stats.getTotalBytes()).atLeastOnce();
            expectPolicyDataEnable(TYPE_WIFI, true);

            expectRemoveInterfaceQuota(TEST_IFACE);
            expectSetInterfaceQuota(TEST_IFACE, 2 * MB_IN_BYTES);

            expectClearNotifications();
            expectAdvisePersistThreshold();
            future = expectMeteredIfacesChanged(TEST_IFACE);

            replay();
            mServiceContext.sendBroadcast(new Intent(CONNECTIVITY_ACTION));
            future.get();
            verifyAndReset();
        }

        // go over warning, which should kick notification
        incrementCurrentTime(MINUTE_IN_MILLIS);
        stats = new NetworkStats(getElapsedRealtime(), 1)
                .addIfaceValues(TEST_IFACE, 1536 * KB_IN_BYTES, 15L, 0L, 0L);

        {
            expectCurrentTime();
            expect(mStatsService.getNetworkTotalBytes(sTemplateWifi, TIME_FEB_15, currentTimeMillis()))
                    .andReturn(stats.getTotalBytes()).atLeastOnce();
            expectPolicyDataEnable(TYPE_WIFI, true);

            expectForceUpdate();
            expectClearNotifications();
            tagFuture = expectEnqueueNotification();

            replay();
            mNetworkObserver.limitReached(null, TEST_IFACE);
            assertNotificationType(TYPE_WARNING, tagFuture.get());
            verifyAndReset();
        }

        // go over limit, which should kick notification and dialog
        incrementCurrentTime(MINUTE_IN_MILLIS);
        stats = new NetworkStats(getElapsedRealtime(), 1)
                .addIfaceValues(TEST_IFACE, 5 * MB_IN_BYTES, 512L, 0L, 0L);

        {
            expectCurrentTime();
            expect(mStatsService.getNetworkTotalBytes(sTemplateWifi, TIME_FEB_15, currentTimeMillis()))
                    .andReturn(stats.getTotalBytes()).atLeastOnce();
            expectPolicyDataEnable(TYPE_WIFI, false);

            expectForceUpdate();
            expectClearNotifications();
            tagFuture = expectEnqueueNotification();

            replay();
            mNetworkObserver.limitReached(null, TEST_IFACE);
            assertNotificationType(TYPE_LIMIT, tagFuture.get());
            verifyAndReset();
        }

        // now snooze policy, which should remove quota
        incrementCurrentTime(MINUTE_IN_MILLIS);

        {
            expectCurrentTime();
            expect(mConnManager.getAllNetworkState()).andReturn(state).atLeastOnce();
            expect(mStatsService.getNetworkTotalBytes(sTemplateWifi, TIME_FEB_15, currentTimeMillis()))
                    .andReturn(stats.getTotalBytes()).atLeastOnce();
            expectPolicyDataEnable(TYPE_WIFI, true);

            // snoozed interface still has high quota so background data is
            // still restricted.
            expectRemoveInterfaceQuota(TEST_IFACE);
            expectSetInterfaceQuota(TEST_IFACE, Long.MAX_VALUE);
            expectAdvisePersistThreshold();
            expectMeteredIfacesChanged(TEST_IFACE);

            future = expectClearNotifications();
            tagFuture = expectEnqueueNotification();

            replay();
            mService.snoozeLimit(sTemplateWifi);
            assertNotificationType(TYPE_LIMIT_SNOOZED, tagFuture.get());
            future.get();
            verifyAndReset();
        }
    }

    public void testMeteredNetworkWithoutLimit() throws Exception {
        NetworkState[] state = null;
        NetworkStats stats = null;
        Future<Void> future;
        Future<String> tagFuture;

        final long TIME_FEB_15 = 1171497600000L;
        final long TIME_MAR_10 = 1173484800000L;
        final int CYCLE_DAY = 15;

        setCurrentTimeMillis(TIME_MAR_10);

        // bring up wifi network with metered policy
        state = new NetworkState[] { buildWifi() };
        stats = new NetworkStats(getElapsedRealtime(), 1)
                .addIfaceValues(TEST_IFACE, 0L, 0L, 0L, 0L);

        {
            expectCurrentTime();
            expect(mConnManager.getAllNetworkState()).andReturn(state).atLeastOnce();
            expect(mStatsService.getNetworkTotalBytes(sTemplateWifi, TIME_FEB_15, currentTimeMillis()))
                    .andReturn(stats.getTotalBytes()).atLeastOnce();
            expectPolicyDataEnable(TYPE_WIFI, true);

            expectRemoveInterfaceQuota(TEST_IFACE);
            expectSetInterfaceQuota(TEST_IFACE, Long.MAX_VALUE);

            expectClearNotifications();
            expectAdvisePersistThreshold();
            future = expectMeteredIfacesChanged(TEST_IFACE);

            replay();
            setNetworkPolicies(new NetworkPolicy(
                    sTemplateWifi, CYCLE_DAY, TIMEZONE_UTC, WARNING_DISABLED, LIMIT_DISABLED,
                    true));
            future.get();
            verifyAndReset();
        }
    }

    private static long parseTime(String time) {
        final Time result = new Time();
        result.parse3339(time);
        return result.toMillis(true);
    }

    private void setNetworkPolicies(NetworkPolicy... policies) {
        mService.setNetworkPolicies(policies);
    }

    private static NetworkState buildWifi() {
        final NetworkInfo info = new NetworkInfo(TYPE_WIFI, 0, null, null);
        info.setDetailedState(DetailedState.CONNECTED, null, null);
        final LinkProperties prop = new LinkProperties();
        prop.setInterfaceName(TEST_IFACE);
        return new NetworkState(info, prop, null, null, null, TEST_SSID);
    }

    private void expectCurrentTime() throws Exception {
        expect(mTime.forceRefresh()).andReturn(false).anyTimes();
        expect(mTime.hasCache()).andReturn(true).anyTimes();
        expect(mTime.currentTimeMillis()).andReturn(currentTimeMillis()).anyTimes();
        expect(mTime.getCacheAge()).andReturn(0L).anyTimes();
        expect(mTime.getCacheCertainty()).andReturn(0L).anyTimes();
    }

    private void expectForceUpdate() throws Exception {
        mStatsService.forceUpdate();
        expectLastCall().atLeastOnce();
    }

    private Future<Void> expectClearNotifications() throws Exception {
        final FutureAnswer future = new FutureAnswer();
        mNotifManager.cancelNotificationWithTag(
                isA(String.class), isA(String.class), anyInt(), anyInt());
        expectLastCall().andAnswer(future).anyTimes();
        return future;
    }

    private Future<String> expectEnqueueNotification() throws Exception {
        final FutureCapture<String> tag = new FutureCapture<String>();
        mNotifManager.enqueueNotificationWithTag(isA(String.class), isA(String.class),
                capture(tag.capture), anyInt(),
                isA(Notification.class), isA(int[].class), UserHandle.myUserId());
        return tag;
    }

    private void expectSetInterfaceQuota(String iface, long quotaBytes) throws Exception {
        mNetworkManager.setInterfaceQuota(iface, quotaBytes);
        expectLastCall().atLeastOnce();
    }

    private void expectRemoveInterfaceQuota(String iface) throws Exception {
        mNetworkManager.removeInterfaceQuota(iface);
        expectLastCall().atLeastOnce();
    }

    private void expectSetInterfaceAlert(String iface, long alertBytes) throws Exception {
        mNetworkManager.setInterfaceAlert(iface, alertBytes);
        expectLastCall().atLeastOnce();
    }

    private void expectRemoveInterfaceAlert(String iface) throws Exception {
        mNetworkManager.removeInterfaceAlert(iface);
        expectLastCall().atLeastOnce();
    }

    private void expectSetUidMeteredNetworkBlacklist(int uid, boolean rejectOnQuotaInterfaces)
            throws Exception {
        mNetworkManager.setUidMeteredNetworkBlacklist(uid, rejectOnQuotaInterfaces);
        expectLastCall().atLeastOnce();
    }

    private void expectSetUidForeground(int uid, boolean uidForeground) throws Exception {
        mStatsService.setUidForeground(uid, uidForeground);
        expectLastCall().atLeastOnce();
    }

    private Future<Void> expectRulesChanged(int uid, int policy) throws Exception {
        final FutureAnswer future = new FutureAnswer();
        mPolicyListener.onUidRulesChanged(eq(uid), eq(policy));
        expectLastCall().andAnswer(future);
        return future;
    }

    private Future<Void> expectMeteredIfacesChanged(String... ifaces) throws Exception {
        final FutureAnswer future = new FutureAnswer();
        mPolicyListener.onMeteredIfacesChanged(aryEq(ifaces));
        expectLastCall().andAnswer(future);
        return future;
    }

    private Future<Void> expectPolicyDataEnable(int type, boolean enabled) throws Exception {
        // TODO: bring back this test
        return null;
    }

    private void expectAdvisePersistThreshold() throws Exception {
        mStatsService.advisePersistThreshold(anyLong());
        expectLastCall().anyTimes();
    }

    private static class TestAbstractFuture<T> extends AbstractFuture<T> {
        @Override
        public T get() throws InterruptedException, ExecutionException {
            try {
                return get(5, TimeUnit.SECONDS);
            } catch (TimeoutException e) {
                throw new RuntimeException(e);
            }
        }
    }

    private static class FutureAnswer extends TestAbstractFuture<Void> implements IAnswer<Void> {
        @Override
        public Void answer() {
            set(null);
            return null;
        }
    }

    private static class FutureCapture<T> extends TestAbstractFuture<T> {
        public Capture<T> capture = new Capture<T>() {
            @Override
            public void setValue(T value) {
                super.setValue(value);
                set(value);
            }
        };
    }

    private static class IdleFuture extends AbstractFuture<Void> implements IdleHandler {
        @Override
        public Void get() throws InterruptedException, ExecutionException {
            try {
                return get(5, TimeUnit.SECONDS);
            } catch (TimeoutException e) {
                throw new RuntimeException(e);
            }
        }

        @Override
        public boolean queueIdle() {
            set(null);
            return false;
        }
    }

    /**
     * Wait until {@link #mService} internal {@link Handler} is idle.
     */
    private IdleFuture expectIdle() {
        final IdleFuture future = new IdleFuture();
        mService.addIdleHandler(future);
        return future;
    }

    private static void assertTimeEquals(long expected, long actual) {
        if (expected != actual) {
            fail("expected " + formatTime(expected) + " but was actually " + formatTime(actual));
        }
    }

    private static String formatTime(long millis) {
        final Time time = new Time(Time.TIMEZONE_UTC);
        time.set(millis);
        return time.format3339(false);
    }

    private static void assertEqualsFuzzy(long expected, long actual, long fuzzy) {
        final long low = expected - fuzzy;
        final long high = expected + fuzzy;
        if (actual < low || actual > high) {
            fail("value " + actual + " is outside [" + low + "," + high + "]");
        }
    }

    private static void assertUnique(LinkedHashSet<Long> seen, Long value) {
        if (!seen.add(value)) {
            fail("found duplicate time " + value + " in series " + seen.toString());
        }
    }

    private static void assertNotificationType(int expected, String actualTag) {
        assertEquals(
                Integer.toString(expected), actualTag.substring(actualTag.lastIndexOf(':') + 1));
    }

    private long getElapsedRealtime() {
        return mElapsedRealtime;
    }

    private void setCurrentTimeMillis(long currentTimeMillis) {
        mStartTime = currentTimeMillis;
        mElapsedRealtime = 0L;
    }

    private long currentTimeMillis() {
        return mStartTime + mElapsedRealtime;
    }

    private void incrementCurrentTime(long duration) {
        mElapsedRealtime += duration;
    }

    private void replay() {
        EasyMock.replay(mActivityManager, mPowerManager, mStatsService, mPolicyListener,
                mNetworkManager, mTime, mConnManager, mNotifManager);
    }

    private void verifyAndReset() {
        EasyMock.verify(mActivityManager, mPowerManager, mStatsService, mPolicyListener,
                mNetworkManager, mTime, mConnManager, mNotifManager);
        EasyMock.reset(mActivityManager, mPowerManager, mStatsService, mPolicyListener,
                mNetworkManager, mTime, mConnManager, mNotifManager);
    }
}


text:
    <cr-icon-button on-click="toggleDropdown" id="button"
        iron-icon="[[dropdownIcon_]],cr:arrow-drop-down" title$="[[header]]">
    </cr-icon-button>

        <template is="dom-if" if="[[!hideHeader]]">

{{header}}

        </template>

          <slot></slot>


text:
<?php

namespace Waavi\UrlShortener;

use Illuminate\Support\ServiceProvider;

class UrlShortenerServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([
            __DIR__ . '/../config/urlshortener.php' => config_path('urlshortener.php'),
        ]);
        $this->mergeConfigFrom(
            __DIR__ . '/../config/urlshortener.php', 'urlshortener'
        );
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('urlshortener.factory', Drivers\Factory::class);
        $this->app->singleton('urlshortener', function ($app) {
            $shortener = new UrlShortener($app['urlshortener.factory']);
            $shortener->setDriver($app['config']->get('urlshortener.driver'));
            return $shortener;
        });
    }
}


text:
@rem Copyright 2016 gRPC authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem     http://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.

@rem Convenience script to build gRPC protoc plugins from command line. protoc plugins are used to generate service stub code from .proto service defintions.

setlocal

@rem enter this directory
cd /d %~dp0

@rem Set VS variables (uses Visual Studio 2013)
@call "%VS120COMNTOOLS%\..\..\vc\vcvarsall.bat" x86

@rem Build third_party/protobuf
msbuild ..\third_party\protobuf\cmake\build\solution\protobuf.sln /p:Configuration=Release || goto :error

@rem Build the C# protoc plugins
msbuild grpc_protoc_plugins.sln /p:Configuration=Release || goto :error

endlocal

goto :EOF

:error
echo Failed!
exit /b %errorlevel%


text:
/**
 * Helps make sure mixed compile works.
 *
 * @version $Id$
 * @author Jason Dillon
 */
public class Testoid
{
    public static String getVersion() {
        return new VersionHelper().getVersion();
    }
}


text:
set -e
set -o pipefail

# To debug, uncomment the following line
# set -x

# Test whether the compile option -mprofile-kernel exists and generates
# profiling code (ie. a call to _mcount()).
echo "int func() { return 0; }" | \
    $* -S -x c -O2 -p -mprofile-kernel - -o - 2> /dev/null | \
    grep -q "_mcount"

# Test whether the notrace attribute correctly suppresses calls to _mcount().

echo -e "#include <linux/compiler.h>\nnotrace int func() { return 0; }" | \
    $* -S -x c -O2 -p -mprofile-kernel - -o - 2> /dev/null | \
    grep -q "_mcount" && \
    exit 1

echo "OK"
exit 0


text:
/**
 * @author Igor Ostapenko
 */
'use strict';

module.exports = class StringSerializer {
  constructor(ioc, ID) {
    this.ioc = ioc;
    this.ID = ID;
    this.ioc.serializers[ID] = this;
  }

  canBeUsedFor(value) {
    return typeof value === 'string';
  }

  serialize(item, fullyQualifiedFormat = true) {
    if (item === undefined || item === null) {
      if (fullyQualifiedFormat) {
        return Buffer.from([this.ID, 0x01]);
      }
      return this.ioc.intSerializer.serialize(0, false);
    }

    const bufs = [];
    if (fullyQualifiedFormat) {
      bufs.push(Buffer.from([this.ID, 0x00]));
    }
    const v = Buffer.from(String(item), 'utf8');
    bufs.push(this.ioc.intSerializer.serialize(v.length, false)); // TODO: what if len > INT32_MAX, for now it's backed by logic of IntSerializer.serialize itself
    bufs.push(v);

    return Buffer.concat(bufs);
  }

  deserialize(buffer, fullyQualifiedFormat = true, nullable = false) {
    let len = 0;
    let cursor = buffer;

    try {
      if (buffer === undefined || buffer === null || !(buffer instanceof Buffer)) {
        throw new Error('buffer is missing');
      }
      if (buffer.length < 1) {
        throw new Error('buffer is empty');
      }

      if (fullyQualifiedFormat) {
        const type_code = cursor.readUInt8();
        len++;
        if (type_code !== this.ID) {
          throw new Error('unexpected {type_code}');
        }
        cursor = cursor.slice(1);
      }
      if (fullyQualifiedFormat || nullable) {
        if (cursor.length < 1) {
          throw new Error('{value_flag} is missing');
        }
        const value_flag = cursor.readUInt8();
        len++;
        if (value_flag === 1) {
          return { v: null, len };
        }
        if (value_flag !== 0) {
          throw new Error('unexpected {value_flag}');
        }
        cursor = cursor.slice(1);
      }

      let length, length_len;
      try {
        ({ v: length, len: length_len } = this.ioc.intSerializer.deserialize(cursor, false));
        len += length_len;
      } catch (err) {
        err.message = '{length}: ' + err.message;
        throw err;
      }
      if (length < 0) {
        throw new Error('{length} is less than zero');
      }
      cursor = cursor.slice(length_len);

      if (cursor.length < length) {
        throw new Error('unexpected {text_value} length');
      }
      len += length;

      const v = cursor.toString('utf8', 0, length);
      return { v, len };
    } catch (err) {
      throw this.ioc.utils.des_error({ serializer: this, args: arguments, cursor, err });
    }
  }
};


text:
<?php
/**
 * Legacy Mode compatibility
 * @version		$Id: database.mysqli.php 10381 2008-06-01 03:35:53Z pasamio $
 * @package		Joomla.Legacy
 * @deprecated	As of version 1.5
 */

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.database.database' );
jimport( 'joomla.database.database.mysqli' );
/**
 * @package		Joomla
 * @deprecated As of version 1.5
 */
class database extends JDatabase {
	function __construct ($host='localhost', $user, $pass, $db='', $table_prefix='', $offline = true) {
		parent::__construct( 'mysqli', $host, $user, $pass, $db, $table_prefix );
	}
}
?>


text:
package p377

/**
Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.

Example:

nums = [1, 2, 3]
target = 4

The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)

Note that different sequences are counted as different combinations.

Therefore the output is 7.
*/

func combinationSum4(nums []int, target int) int {
	dp := make([]int, target+1)
	dp[0] = 1
	for i := 1; i <= target; i++ {
		for _, n := range nums {
			if i-n >= 0 {
				dp[i] += dp[i-n]
			}
		}
	}
	return dp[target]
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model common\models\MEmp */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'surname')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'user_id')->textInput() ?>

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
using std::string;
using namespace std;

namespace caffe {

template <typename Dtype>
void* DataLayerPrefetch(void* layer_pointer) {
  // LOG(INFO)<<"DataLayerPrefetch";
  // int i;
  // cin>>i;
  CHECK(layer_pointer);
  DataLayer<Dtype>* layer = reinterpret_cast<DataLayer<Dtype>*>(layer_pointer);
  CHECK(layer);
  Datum datum;
  CHECK(layer->prefetch_data_);
  Dtype* top_data = layer->prefetch_data_->mutable_cpu_data();
  Dtype* top_label = layer->prefetch_label_->mutable_cpu_data();
  const Dtype scale = layer->layer_param_.scale();
  const int batchsize = layer->layer_param_.batchsize();
  const int cropsize = layer->layer_param_.cropsize();
  const int cropsize_w = layer->layer_param_.cropsize();
  const int cropsize_h = cropsize_w;
  const bool mirror = layer->layer_param_.mirror();

  // cout<<"cropsize_w = "<<cropsize_w<<"\tcropsize_h = "
  //         <<cropsize_h<<"\tmirror = "<<mirror
  //         <<"\tcount = "<<layer->prefetch_data_->count()
  //         <<"\twidth = "<<layer->prefetch_data_->width()
  //         <<"\theight = "<<layer->prefetch_data_->height()
  //         <<"\tnum = "<<layer->prefetch_data_->num()<<endl;

  if (mirror && cropsize == 0) {
    LOG(INFO)<<"fatal"<<mirror<<" "<<cropsize;

    LOG(FATAL) << "Current implementation requires mirror and cropsize to be "
        << "set at the same time.";
  }
  // datum scales
  const int channels = layer->datum_channels_;
  const int height = layer->datum_height_;
  const int width = layer->datum_width_;
  const int size = layer->datum_size_;
  const Dtype* mean = layer->data_mean_.cpu_data();
  for (int itemid = 0; itemid < batchsize; ++itemid) {
    // get a blob
    CHECK(layer->iter_);
    CHECK(layer->iter_->Valid());
    datum.ParseFromString(layer->iter_->value().ToString());
    const string& data = datum.data();
    if (cropsize) {
      CHECK(data.size()) << "Image cropping only support uint8 data";
      int h_off, w_off;
      // We only do random crop when we do training.
      if (Caffe::phase() == Caffe::TRAIN) {
        // NOLINT_NEXT_LINE(runtime/threadsafe_fn)
        h_off = rand() % (height - cropsize_h);
        // NOLINT_NEXT_LINE(runtime/threadsafe_fn)
        w_off = rand() % (width - cropsize_w);
      } else {
        h_off = (height - cropsize_h) / 2;
        w_off = (width - cropsize_w) / 2;
      }
      //LOG(INFO)<<"h_off = "<<h_off<<"\tw_off = "<<w_off;
      // NOLINT_NEXT_LINE(runtime/threadsafe_fn)
      if (mirror && rand() % 2) {
        // Copy mirrored version
        for (int c = 0; c < channels; ++c) {
          for (int h = 0; h < cropsize_h; ++h) {
            for (int w = 0; w < cropsize_w; ++w) {
              top_data[((itemid * channels + c) * cropsize_h + h) * cropsize_w
                       + cropsize_w - 1 - w] =
                  (static_cast<Dtype>(
                      (uint8_t)data[(c * height + h + h_off) * width
                                    + w + w_off])
                    - mean[(c * height + h + h_off) * width + w + w_off])
                  * scale;
            }
          }
        }
      } else {
        // Normal copy
        for (int c = 0; c < channels; ++c) {
          for (int h = 0; h < cropsize_h; ++h) {
            for (int w = 0; w < cropsize_w; ++w) {
              top_data[((itemid * channels + c) * cropsize_h + h) * cropsize_w + w]
                  = (static_cast<Dtype>(
                      (uint8_t)data[(c * height + h + h_off) * width
                                    + w + w_off])
                     - mean[(c * height + h + h_off) * width + w + w_off])
                  * scale;
            }
          }
        }
      }
    } else {
      // we will prefer to use data() first, and then try float_data()
      if (data.size()) {
        //LOG(INFO)<<"data size = "<<data.size()<<" mean = "<<mean[0]<<"  "<<mean[783];
        for (int j = 0; j < size; ++j) {
          top_data[itemid * size + j] =
              (static_cast<Dtype>((uint8_t)data[j]) - mean[j]) * scale;
        }
      } else {
        for (int j = 0; j < size; ++j) {
          top_data[itemid * size + j] =
              (datum.float_data(j) - mean[j]) * scale;
        }
      }
    }

    top_label[itemid] = datum.label();
    // go to the next iter
    layer->iter_->Next();
    if (!layer->iter_->Valid()) {
      // We have reached the end. Restart from the first.
      DLOG(INFO) << "Restarting data prefetching from start.";
      layer->iter_->SeekToFirst();
    }
  }

  return reinterpret_cast<void*>(NULL);
}

template <typename Dtype>
DataLayer<Dtype>::~DataLayer<Dtype>() {
  // Finally, join the thread
  CHECK(!pthread_join(thread_, NULL)) << "Pthread joining failed.";
}

template <typename Dtype>
void DataLayer<Dtype>::SetUp(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top) {
  CHECK_EQ(bottom.size(), 0) << "Data Layer takes no input blobs.";
  CHECK_EQ(top->size(), 2) << "Data Layer takes two blobs as output.";
  // Initialize the leveldb
  leveldb::DB* db_temp;
  leveldb::Options options;
  options.create_if_missing = false;
  options.max_open_files = 100;
  LOG(INFO) << "Opening leveldb " << this->layer_param_.source();
  leveldb::Status status = leveldb::DB::Open(
      options, this->layer_param_.source(), &db_temp);
  CHECK(status.ok()) << "Failed to open leveldb "
      << this->layer_param_.source() << std::endl << status.ToString();
  db_.reset(db_temp);
  iter_.reset(db_->NewIterator(leveldb::ReadOptions()));
  iter_->SeekToFirst();
  // Check if we would need to randomly skip a few data points
  if (this->layer_param_.rand_skip()) {
    // NOLINT_NEXT_LINE(runtime/threadsafe_fn)
    unsigned int skip = rand() % this->layer_param_.rand_skip();
    LOG(INFO) << "Skipping first " << skip << " data points.";
    while (skip-- > 0) {
      iter_->Next();
      if (!iter_->Valid()) {
        iter_->SeekToFirst();
      }
    }
  }
  // Read a data point, and use it to initialize the top blob.
  Datum datum;
  datum.ParseFromString(iter_->value().ToString());
  // image
  int cropsize = this->layer_param_.cropsize();
  const int cropsize_w = cropsize;
  const int cropsize_h = cropsize_w;
  if (cropsize > 0) {
    (*top)[0]->Reshape(
        this->layer_param_.batchsize(), datum.channels(), cropsize_h, cropsize_w);
    prefetch_data_.reset(new Blob<Dtype>(
        this->layer_param_.batchsize(), datum.channels(), cropsize_h, cropsize_w));
  } else {
    (*top)[0]->Reshape(
        this->layer_param_.batchsize(), datum.channels(), datum.height(),
        datum.width());
    prefetch_data_.reset(new Blob<Dtype>(
        this->layer_param_.batchsize(), datum.channels(), datum.height(),
        datum.width()));
  }
  LOG(INFO) << "output data size: " << (*top)[0]->num() << ","
      << (*top)[0]->channels() << "," << (*top)[0]->height() << ","
      << (*top)[0]->width();
  // label
  (*top)[1]->Reshape(this->layer_param_.batchsize(), 1, 1, 1);
  prefetch_label_.reset(
      new Blob<Dtype>(this->layer_param_.batchsize(), 1, 1, 1));
  // datum size
  datum_channels_ = datum.channels();
  datum_height_ = datum.height();
  datum_width_ = datum.width();
  datum_size_ = datum.channels() * datum.height() * datum.width();
  CHECK_GT(datum_height_, cropsize);
  CHECK_GT(datum_width_, cropsize);
  // check if we want to have mean
  if (this->layer_param_.has_meanfile()) {
    BlobProto blob_proto;
    LOG(INFO) << "Loading mean file from" << this->layer_param_.meanfile();
    ReadProtoFromBinaryFile(this->layer_param_.meanfile().c_str(), &blob_proto);
    data_mean_.FromProto(blob_proto);
    CHECK_EQ(data_mean_.num(), 1);
    CHECK_EQ(data_mean_.channels(), datum_channels_);
    CHECK_EQ(data_mean_.height(), datum_height_);
    CHECK_EQ(data_mean_.width(), datum_width_);
  } else {
    // Simply initialize an all-empty mean.
    data_mean_.Reshape(1, datum_channels_, datum_height_, datum_width_);
  }
  // Now, start the prefetch thread. Before calling prefetch, we make two
  // cpu_data calls so that the prefetch thread does not accidentally make
  // simultaneous cudaMalloc calls when the main thread is running. In some
  // GPUs this seems to cause failures if we do not so.
  LOG(INFO)<<"prefetch_data_->mutable_cpu_data();";
  prefetch_data_->mutable_cpu_data();
  prefetch_label_->mutable_cpu_data();
  data_mean_.cpu_data();
  DLOG(INFO) << "Initializing prefetch";
  CHECK(!pthread_create(&thread_, NULL, DataLayerPrefetch<Dtype>,
      reinterpret_cast<void*>(this))) << "Pthread execution failed.";
  DLOG(INFO) << "Prefetch initialized.";
}

template <typename Dtype>
void DataLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
      vector<Blob<Dtype>*>* top) {
  //LOG(INFO)<<"Forward_cpu\n";
  // First, join the thread
  CHECK(!pthread_join(thread_, NULL)) << "Pthread joining failed.";
  // Copy the data
  memcpy((*top)[0]->mutable_cpu_data(), prefetch_data_->cpu_data(),
      sizeof(Dtype) * prefetch_data_->count());
  memcpy((*top)[1]->mutable_cpu_data(), prefetch_label_->cpu_data(),
      sizeof(Dtype) * prefetch_label_->count());
  // Start a new prefetch thread
  CHECK(!pthread_create(&thread_, NULL, DataLayerPrefetch<Dtype>,
      reinterpret_cast<void*>(this))) << "Pthread execution failed.";
}

// The backward operations are dummy - they do not carry any computation.
template <typename Dtype>
Dtype DataLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
      const bool propagate_down, vector<Blob<Dtype>*>* bottom) {
  return Dtype(0.);
}

INSTANTIATE_CLASS(DataLayer);

}  // namespace caffe


text:
var context = require.context('./test', true, /.+\.spec\.jsx?$/);
context.keys().forEach(context);
module.exports = context;


text:
package filter

import (
	"errors"
	"regexp"
	"strings"

	"github.com/yosisa/craft/rpc"
)

var (
	ErrInvalidSyntax  = errors.New("Error invalid syntax")
	ErrStackRemaining = errors.New("Error stack remaining")
)

type Evaluator interface {
	Eval(*rpc.Capability) bool
}

type not struct {
	e Evaluator
}

func (e *not) Eval(cap *rpc.Capability) bool {
	return !e.e.Eval(cap)
}

type and struct {
	l Evaluator
	r Evaluator
}

func (e *and) Eval(cap *rpc.Capability) bool {
	return e.l.Eval(cap) && e.r.Eval(cap)
}

type or struct {
	l Evaluator
	r Evaluator
}

func (e *or) Eval(cap *rpc.Capability) bool {
	return e.l.Eval(cap) || e.r.Eval(cap)
}

type agent struct {
	re *regexp.Regexp
}

func (e *agent) Eval(cap *rpc.Capability) bool {
	return e.re.MatchString(cap.Agent)
}

type label struct {
	name  string
	value string
}

func (e *label) Eval(cap *rpc.Capability) bool {
	v, ok := cap.Labels[e.name]
	return ok && v == e.value
}

func (p *parser) pushStack(e Evaluator) {
	p.stack = append(p.stack, e)
}

func (p *parser) popStack() (e Evaluator) {
	n := len(p.stack)
	e, p.stack = p.stack[n-1], p.stack[:n-1]
	return
}

func (p *parser) Agent(s string) {
	re, err := regexp.Compile(s)
	if err != nil {
		p.err = err
	}
	p.pushStack(&agent{re})
}

func (p *parser) Label(s string) {
	parts := strings.SplitN(s, ":", 2)
	p.pushStack(&label{name: parts[0], value: parts[1]})
}

func (p *parser) Not() {
	p.pushStack(&not{p.popStack()})
}

func (p *parser) And() {
	p.pushStack(&and{p.popStack(), p.popStack()})
}

func (p *parser) Or() {
	p.pushStack(&or{p.popStack(), p.popStack()})
}

func Parse(s string) (Evaluator, error) {
	p := parser{Buffer: s}
	p.Init()
	if err := p.Parse(); err != nil {
		return nil, ErrInvalidSyntax
	}
	p.Execute()
	if p.err != nil {
		return nil, p.err
	}
	if len(p.stack) > 1 {
		return nil, ErrStackRemaining
	}
	return p.stack[0], nil
}


text:
module FayeShard

  class Shard

    attr_accessor :configuration

    #  Creates a shard instance and assigns the config to it.
    #
    #  * <tt>config</tt>:: Config to use.
    #
    def initialize(config)
      self.configuration = config.with_indifferent_access
    end

    #  Returns URL for client.
    #
    #  * <tt>https</tt>:: Specifies whether to use SSL connection or not
    #
    def url(https = false)
      secured = (configuration['secured'] || false) & https
      port = secured ? configuration["secured_port"] : configuration["port"]
      "http#{secured ? 's' : ''}://#{configuration["host"]}:#{port}/faye"
    end

    #  Returns default client JS url
    #
    #  * <tt>https</tt>:: Specifies whether to use SSL connection or not
    #
    def js_url(https = false)
      url(https) + '.js'
    end

    #  Local url, needed for RoR <-> Faye communication
    #
    def local_url
      host = configuration["local_host"] || configuration["host"]
      "http://#{host}:#{configuration["port"]}/faye"
    end

    #  Pushes data to a Faye shard
    #
    #  * <tt>channel</tt>:: User's channel
    #  * <tt>data</tt>::    Data to push
    #  * <tt>ext</tt>::     Faye extensions, eg. auth_token
    #
    def push(channel, data, ext = {})
      uri = URI.parse(self.local_url)
      http = Net::HTTP.new(uri.host, uri.port)
      req = Net::HTTP::Post.new uri.path
      req.set_form_data('message' => {'channel' => channel, 'data' => data, 'ext' => ext}.to_json)
      http.request req
    end

  end

end


text:
<?xml version="1.0" encoding="UTF-8" ?>

<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>

      <title>marcin-chwedczuk.github.io/</title>

   <link>http://blog.marcinchwedczuk.pl</link>
   <description>A place where I share my thoughts about programming.</description>
   <language>en-uk</language>
   <managingEditor>mc</managingEditor>
   <atom:link href="rss" rel="self" type="application/rss+xml" />

	<item>
	  <title>Connecting to Raspberry PI from Linux via UART</title>
	  <link>http://blog.marcinchwedczuk.pl/connecting-to-raspberry-pi-via-uart</link>
	  <author>mc</author>
	  <pubDate>2020-07-07T02:00:01+02:00</pubDate>
	  <guid>http://blog.marcinchwedczuk.pl/connecting-to-raspberry-pi-via-uart</guid>

		<description>
In this blog post we will learn how to connect to a Raspberry PI via UART
(think serial terminal).
Before we begin we need to get a cheap USB &lt;-&gt; UART converter.
Make sure that the converter supports 3.3V voltage.
Most of the converters support other voltages e.g. 5V and you
can select which voltage you want by moving a jumper.
If your converter has such a jumper make sure that it is in 3.3V position.

</description>

	</item>

</channel>
</rss>


text:
namespace Evidyon {

class Item;
typedef std::pair<int,int> WorldRegion_Sublocation;
typedef std::multimap<WorldRegion_Sublocation, Item*> WorldRegion_LocalItems;

}

#endif


text:
package io.searchbox.core;

import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import io.searchbox.action.AbstractAction;
import io.searchbox.action.AbstractMultiTypeActionBuilder;
import io.searchbox.action.GenericResultAbstractAction;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Dogukan Sonmez
 * @author cihat keser
 */
public class MultiGet extends GenericResultAbstractAction {

    protected MultiGet(AbstractAction.Builder builder) {
        super(builder);
        setURI(buildURI());
    }

    protected MultiGet(Builder.ByDoc builder) {
        this((AbstractAction.Builder) builder);
        this.payload = ImmutableMap.of("docs", docsToMaps(builder.docs));
    }

    protected MultiGet(Builder.ById builder) {
        this((AbstractAction.Builder) builder);
        this.payload = ImmutableMap.of("ids", builder.ids);
    }

    protected Object docsToMaps(List<Doc> docs) {
        return Lists.transform(docs, new Function<Doc, Object>() {
            @Override
            public Object apply(Doc doc) {
                return doc.toMap();
            }
        });
    }

    @Override
    protected String buildURI() {
        return super.buildURI() + "/_mget";
    }

    @Override
    public String getRestMethodName() {
        return "GET";
    }

    @Override
    public String getPathToResult() {
        return "docs/_source";
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder()
                .appendSuper(super.hashCode())
                .toHashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (obj == this) {
            return true;
        }
        if (obj.getClass() != getClass()) {
            return false;
        }

        return new EqualsBuilder()
                .appendSuper(super.equals(obj))
                .isEquals();
    }

    public static class Builder {
        private Builder() {
        }

        public static class ById extends AbstractMultiTypeActionBuilder<MultiGet, ById> {
            private List<String> ids = new LinkedList<String>();

            /**
             * The mget API allows for _type to be optional. Set it to _all or leave it empty in order to
             * fetch the first document matching the id across all types. If you don't set the type and
             * have many documents sharing the same _id, you will end up getting only the first matching document.
             */
            public ById(String index, String type) {
                addIndex(index);
                addType(type);
            }

            public ById addId(Collection<? extends String> ids) {
                this.ids.addAll(ids);
                return this;
            }

            public ById addId(String id) {
                ids.add(id);
                return this;
            }

            @Override
            public MultiGet build() {
                return new MultiGet(this);
            }
        }

        public static class ByDoc extends GenericResultAbstractAction.Builder<MultiGet, ByDoc> {
            private List<Doc> docs = new LinkedList<Doc>();

            /**
             * The mget API allows for _type to be optional. Set it to _all or leave it empty in order to
             * fetch the first document matching the id across all types. If you don't set the type and
             * have many documents sharing the same _id, you will end up getting only the first matching document.
             */
            public ByDoc(Collection<? extends Doc> docs) {
                this.docs.addAll(docs);
            }

            public ByDoc(Doc doc) {
                docs.add(doc);
            }

            public ByDoc addDoc(Collection<? extends Doc> docs) {
                this.docs.addAll(docs);
                return this;
            }

            public ByDoc addDoc(Doc doc) {
                docs.add(doc);
                return this;
            }

            @Override
            public MultiGet build() {
                return new MultiGet(this);
            }
        }
    }
}