text:
require 'spec_helper'

module Tim
  describe ProviderImageObserver do

    before(:all) do
      ProviderImage.observers.enable Tim::ProviderImageObserver
      @pio = ProviderImageObserver.instance
    end

    after(:all) do
      ProviderImage.observers.disable Tim::ProviderImageObserver
    end

    before(:each) do
      TargetImage.any_instance.stub(:create_factory_target_image)
        .and_return(true)
      ProviderImage.any_instance.stub(:create_factory_provider_image)
        .and_return(true)
      @pi = FactoryGirl.build(:provider_image_with_full_tree)
    end

    describe "Create FSM" do

      it "should transition from new to pending when provider image is created" do
        @pi.should_receive(:fsm_create_request)
        @pi.save
      end

      describe "factory images (non-imported)" do
        before(:each) do
          @pi.stub(:imported?).and_return(false)
        end

        it "should send factory request after transition from pending to queued" do
          @pi.should_receive(:create_factory_provider_image)
          @pio.after_fsm_create_request(@pi, nil)
        end

        it "should transition to failed if factory request fails" do
          @pi.stub(:create_factory_provider_image).and_raise(Errno::ECONNREFUSED)
          @pi.should_receive(:fsm_create_fail)
          @pio.after_fsm_create_request(@pi, nil)
        end

        describe "after factory callback" do
          before(:each) do
            @pi.fsm_create_state = "queued"
          end

          it "should transition from queued through to completed when factory
                  returns complete" do
            @pi.status = "COMPLETE"
            @pi.should_receive(:fsm_create_start)
            @pi.should_receive(:fsm_create_complete)
            @pi.save
          end

          it "should transition from queued to in_progress when factory returns
               in_progress" do
            @pi.status = "BUILDING"
            @pi.should_receive(:fsm_create_start)
            @pi.save
          end

          it "should transition from queued through to failed when factory returns
               failed" do
            @pi.status = "FAILED"
            @pi.should_receive(:fsm_create_start)
            @pi.should_receive(:fsm_create_fail)
            @pi.save
          end
        end

      end

      describe "imported images" do
        before(:each) do
          @pi.stub(:imported?).and_return(true)
        end

        it "should transition through queued to complete on successful import" do
          @pi.stub(:create_import).and_return(true)
          @pi.should_receive(:fsm_create_accept)
          @pi.should_receive(:fsm_create_start)
          @pi.should_receive(:fsm_create_complete)
          @pio.after_fsm_create_request(@pi, nil)
        end

        it "should transition directly to failed on failed import" do
          @pi.stub(:create_import).and_return(false)
          @pi.should_receive(:fsm_create_fail)
          @pio.after_fsm_create_request(@pi, nil)
        end
      end
    end

    describe "Delete FSM", :delete => true do
      before (:each) do
        TargetImage.any_instance.stub(:delete_factory_target_image)
          .and_return(true)
        ProviderImage.any_instance.stub(:delete_factory_provider_image)
          .and_return(true)
      end

      it "should transition from inactive to pending when provider image destroy
            with credentials is called" do
        @pi.should_receive(:fsm_delete_request)
        @pi.destroy
      end

      describe "imported images (non-factory images)" do
        before(:each) do
          @pi.stub(:imported?).and_return(true)
        end

        it "should transition from pending through to completed when imported
            image is deleted" do
          @pi.should_receive(:fsm_delete_accept)
          @pi.should_receive(:fsm_delete_start)
          @pi.should_receive(:fsm_delete_complete)
          @pio.after_fsm_delete_request(@pi, nil)
        end
      end

      describe "factory images (non-imported)" do
        before(:each) do
          @pi.stub(:imported?).and_return(false)
        end

        it "should send factory delete request after transition from inactive to
              pending" do
          @pi.should_receive(:delete_factory_provider_image)
          @pio.after_fsm_delete_request(@pi, nil)
        end

        it "should transition to failed if factory delete request fails" do
          @pi.stub(:delete_factory_provider_image).and_raise(Errno::ECONNREFUSED)
          @pi.should_receive(:fsm_delete_fail)
          @pio.after_fsm_delete_request(@pi, nil)
        end

        describe "after factory callback" do
          before(:each) do
            @pi.fsm_delete_state = "queued"
          end

          it "should transition from queued through to completed when factory
                  returns deleted" do
            @pi.status = "DELETED"
            @pi.should_receive(:fsm_delete_start)
            @pi.should_receive(:fsm_delete_complete)
            @pi.save
          end

          it "should transition from queued to in_progress when factory returns
               deleting" do
            @pi.status = "DELETING"
            @pi.should_receive(:fsm_delete_start)
            @pi.save
          end

          it "should transition from queued through to failed when factory returns
               delete failed" do
            @pi.status = "DELETEFAILED"
            @pi.should_receive(:fsm_delete_start)
            @pi.should_receive(:fsm_delete_fail)
            @pi.save
          end

          it "should transition from in progress to complete when factory returns
               deleted and status is deleting" do
            @pi.fsm_delete_state = "in_progress"
            @pi.status = "DELETED"
            @pi.should_receive(:fsm_delete_complete)
            @pi.save
          end
        end
      end
    end

  end
end


text:
module.exports = {
    controller:"admin/ec/order"
};

redpajama_set_name: RedPajamaGithub


text:
package com.opengsn.controller.internal.model;

/**
 * This class will provide an internal data structure for storing VM data.
 *
 *
 * @author Fereydoun Farrahi Moghaddam (ffarrahi@synchromedia.ca)
 *
 */

import com.opengsn.controller.model.Host;
import com.opengsn.controller.model.VirtualMachine;

public class VMInternalCoreBased extends AbstractVMInternal {

	public VMInternalCoreBased(VirtualMachine vm, int coreNumber, int memorySizeMB, Host sourceHost) {
		super(vm, coreNumber, memorySizeMB, sourceHost);
	}

	/**
	 * Sort based on core number.
	 */
	public int compareTo(Object obj) {
		VMInternalCoreBased vm = (VMInternalCoreBased)obj;
		if (this.getCore()<vm.getCore())
			return -1;
		else if (this.getCore()>vm.getCore())
			return 1;
		else return 0;

	}

}


text:
class RemoveSaas < ActiveRecord::Migration
  def self.up
    drop_table :coupons
    drop_table :subscriptions
    drop_table :subscription_transactions

    remove_column :users, :customer_vault_id
  end

  def self.down
    # Nope, gonna have to write these later if we need to go back.
  end
end


text:
FROM python:2

RUN mkdir -p /app/uploads

WORKDIR /app

RUN apt-get update
RUN apt-get install -q -y curl
RUN curl -sL https://deb.nodesource.com/setup_6.x | bash -
RUN apt-get install -q -y \
    openjdk-7-jre-headless \
    nodejs \
    ruby-sass \
    libjpeg-dev
RUN npm install -g coffee-script

COPY dev.cfg ./app.cfg
COPY lmda ./lmda
COPY thumnail_create ./thumnail_create
COPY timeout.py .
COPY requirements.txt .
COPY start.sh /start.sh

RUN pip install -r requirements.txt
RUN pip install gunicorn

ENV LAMBDA_CONFIG /app/app.cfg

RUN chmod +x /start.sh
CMD ["/start.sh"]


text:
package modeltesthelper

import (
	"koding/db/models"
	"koding/db/mongodb/modelhelper"

	"gopkg.in/mgo.v2/bson"
)

func CreateGroup() (*models.Group, error) {
	g := &models.Group{
		Id:                             bson.NewObjectId(),
		Body:                           bson.NewObjectId().Hex(),
		Title:                          bson.NewObjectId().Hex(),
		Slug:                           bson.NewObjectId().Hex(),
		Privacy:                        "private",
		Visibility:                     "hidden",
		SocialApiChannelId:             "0",
		SocialApiAnnouncementChannelId: "0",
		// DefaultChannels holds the default channels for a group, when a user joins
		// to this group, participants will be automatically added to regarding
		// channels
		DefaultChannels: []string{"0"},
	}

	return g, modelhelper.CreateGroup(g)
}


text:
package com.example.spelldisaster.inventory;

import java.util.List;

import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.spelldisaster.R;

/**
 * @author horodysk
 */
public class InventoryListViewAdapter extends ArrayAdapter<InventoryItem> {

    private int _resource;

    /***/
    public InventoryListViewAdapter(Context context, int resource, List<InventoryItem> items) {
        super(context, resource, items);
        _resource = resource;
    }

    /***/
    public InventoryItem getEvent(int position) {
        return getItem(position);
    }

    @Override
    public View getView(int position, View convertView, @SuppressWarnings("unused") ViewGroup parent) {
        LinearLayout inventoryItemView = inflateTheView(convertView);
        initializeVIewItems(position, inventoryItemView);

        return inventoryItemView;
    }

    private LinearLayout inflateTheView(View convertView) {
        LinearLayout inventoryItemView;
        if (convertView == null) {
            inventoryItemView = new LinearLayout(getContext());
            String inflater = Context.LAYOUT_INFLATER_SERVICE;
            LayoutInflater vi;
            vi = (LayoutInflater) getContext().getSystemService(inflater);
            vi.inflate(_resource, inventoryItemView, true);
        }
        else {
            inventoryItemView = (LinearLayout) convertView;
        }
        return inventoryItemView;
    }

    private void initializeVIewItems(int position, LinearLayout inventoryItemView) {
        InventoryItem item = getItem(position);

        ImageView icon = (ImageView) inventoryItemView.findViewById(R.id.inventory_item_icon);
        TextView name = (TextView) inventoryItemView.findViewById(R.id.inventory_item_name);
        TextView weight = (TextView) inventoryItemView.findViewById(R.id.inventory_item_weight);

        icon.setImageResource(item.getIcon());
        name.setText(item.getName());
        weight.setText(Double.toString(item.getWeight()));

        Typeface font = Typeface.createFromAsset(getContext().getAssets(), "fonts/LibbyHand.ttf");
        name.setTypeface(font);
        weight.setTypeface(font);

    }

}


text:
package org.basex.query.up.primitives.node;

import static org.basex.query.QueryError.*;

import org.basex.data.*;
import org.basex.query.*;
import org.basex.query.up.*;
import org.basex.query.up.atomic.*;
import org.basex.query.up.primitives.*;
import org.basex.query.util.list.*;
import org.basex.util.*;

/**
 * Replace node primitive.
 *
 * @author BaseX Team 2005-16, BSD License
 * @author Lukas Kircher
 */
public final class ReplaceNode extends NodeCopy {
  /**
   * Constructor.
   * @param pre target node pre value
   * @param data target data instance
   * @param ii input info
   * @param nodes node copy insertion sequence
   */
  public ReplaceNode(final int pre, final Data data, final InputInfo ii, final ANodeList nodes) {
    super(UpdateType.REPLACENODE, pre, data, ii, nodes);
  }

  @Override
  public void update(final NamePool pool) {
    if(insseq == null) return;
    add(pool);
    pool.remove(node());
  }

  @Override
  public void merge(final Update update) throws QueryException {
    throw UPMULTREPL_X.get(info, node());
  }

  @Override
  public void addAtomics(final AtomicUpdateCache auc) {
    auc.addReplace(pre, insseq);
  }
}


text:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="40dp"
    android:height="40dp"
    android:viewportWidth="40"
    android:viewportHeight="40"
    android:tint="?attr/colorControlNormal">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M4.958,35.042V32.208H35.042V35.042ZM4.958,7.792V4.958H35.042V7.792Z"/>
</vector>


text:
package org.egzi.springconfigurator.locator;

import com.fasterxml.jackson.dataformat.javaprop.JavaPropsMapper;
import com.google.common.collect.Iterators;
import lombok.SneakyThrows;

import java.net.URL;
import java.util.Iterator;

/**
 * Load data from properties file in {@link ConfigDefinition}
 */
public class PropertiesContextDefinitionLocator extends ContextDefinitionLocatorSkeleton {

    protected static final String RELATIVE_ADDITIONAL_JAR_PATH = "/org/egzi/springconfigurator/";

    public PropertiesContextDefinitionLocator(String contextsConfigurationFile) {
        super(contextsConfigurationFile);
    }

    public PropertiesContextDefinitionLocator(String contextsConfigurationFile, ContextTreeNodeConverter converter) {
        super(contextsConfigurationFile, converter);
    }

    @Override
    @SneakyThrows
    public Iterator<ConfigDefinition> loadResources(URL resource) {
        JavaPropsMapper propertiesMapper = new JavaPropsMapper();
        return Iterators.singletonIterator(propertiesMapper.readValue(resource, ConfigDefinition.class));
    }

}


text:
'''OpenGL extension VERSION.GLX_1_1

This module customises the behaviour of the
OpenGL.raw.GLX.VERSION.GLX_1_1 to provide a more
Python-friendly API

The official definition of this extension is available here:
http://www.opengl.org/registry/specs/VERSION/GLX_1_1.txt
'''
from OpenGL import platform, constant, arrays
from OpenGL import extensions, wrapper
import ctypes
from OpenGL.raw.GLX import _types, _glgets
from OpenGL.raw.GLX.VERSION.GLX_1_1 import *
from OpenGL.raw.GLX.VERSION.GLX_1_1 import _EXTENSION_NAME

def glInitGlx11VERSION():
    '''Return boolean indicating whether this extension is available'''
    from OpenGL import extensions
    return extensions.hasGLExtension( _EXTENSION_NAME )

### END AUTOGENERATED SECTION


text:
package common.zeroquest.entity.ai;

import common.zeroquest.entity.EntityCustomTameable;

import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.ai.EntityAIBase;
import net.minecraft.entity.passive.EntityTameable;
import net.minecraft.pathfinding.PathNavigate;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;

public class EntityCustomAIFollowOwner extends EntityAIBase
{
    private EntityCustomTameable thePet;
    private EntityLivingBase theOwner;
    World theWorld;
    private double field_75336_f;
    private PathNavigate petPathfinder;
    private int field_75343_h;
    float maxDist;
    float minDist;
    private boolean field_75344_i;

    public EntityCustomAIFollowOwner(EntityCustomTameable par1EntityTameable, double par2, float par4, float par5)
    {
        this.thePet = par1EntityTameable;
        this.theWorld = par1EntityTameable.worldObj;
        this.field_75336_f = par2;
        this.petPathfinder = par1EntityTameable.getNavigator();
        this.minDist = par4;
        this.maxDist = par5;
        this.setMutexBits(3);
    }

    /**
     * Returns whether the EntityAIBase should begin execution.
     */
    public boolean shouldExecute()
    {
        EntityLivingBase entitylivingbase = this.thePet.func_130012_q();

        if (entitylivingbase == null)
        {
            return false;
        }
        else if (this.thePet.isSitting())
        {
            return false;
        }
        else if (this.thePet.getDistanceSqToEntity(entitylivingbase) < (double)(this.minDist * this.minDist))
        {
            return false;
        }
        else
        {
            this.theOwner = entitylivingbase;
            return true;
        }
    }

    /**
     * Returns whether an in-progress EntityAIBase should continue executing
     */
    public boolean continueExecuting()
    {
        return !this.petPathfinder.noPath() && this.thePet.getDistanceSqToEntity(this.theOwner) > (double)(this.maxDist * this.maxDist) && !this.thePet.isSitting();
    }

    /**
     * Execute a one shot task or start executing a continuous task
     */
    public void startExecuting()
    {
        this.field_75343_h = 0;
        this.field_75344_i = this.thePet.getNavigator().getAvoidsWater();
        this.thePet.getNavigator().setAvoidsWater(false);
    }

    /**
     * Resets the task
     */
    public void resetTask()
    {
        this.theOwner = null;
        this.petPathfinder.clearPathEntity();
        this.thePet.getNavigator().setAvoidsWater(this.field_75344_i);
    }

    /**
     * Updates the task
     */
    public void updateTask()
    {
        this.thePet.getLookHelper().setLookPositionWithEntity(this.theOwner, 10.0F, (float)this.thePet.getVerticalFaceSpeed());

        if (!this.thePet.isSitting())
        {
            if (--this.field_75343_h <= 0)
            {
                this.field_75343_h = 10;

                if (!this.petPathfinder.tryMoveToEntityLiving(this.theOwner, this.field_75336_f))
                {
                    if (!this.thePet.getLeashed())
                    {
                        if (this.thePet.getDistanceSqToEntity(this.theOwner) >= 144.0D)
                        {
                            int i = MathHelper.floor_double(this.theOwner.posX) - 2;
                            int j = MathHelper.floor_double(this.theOwner.posZ) - 2;
                            int k = MathHelper.floor_double(this.theOwner.boundingBox.minY);

                            for (int l = 0; l <= 4; ++l)
                            {
                                for (int i1 = 0; i1 <= 4; ++i1)
                                {
                                    if ((l < 1 || i1 < 1 || l > 3 || i1 > 3) && this.theWorld.doesBlockHaveSolidTopSurface(i + l, k - 1, j + i1) && !this.theWorld.isBlockNormalCube(i + l, k, j + i1) && !this.theWorld.isBlockNormalCube(i + l, k + 1, j + i1))
                                    {
                                        this.thePet.setLocationAndAngles((double)((float)(i + l) + 0.5F), (double)k, (double)((float)(j + i1) + 0.5F), this.thePet.rotationYaw, this.thePet.rotationPitch);
                                        this.petPathfinder.clearPathEntity();
                                        return;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}


text:
import {TrackModel} from './track.model';
export class JournalModel {
  title: string;
  keyWords: string;
  id: number;
  journalId: string;
  volCoverImg: string;
  relativeVols: string;
  volDate: string;
  volDesc: string;
  tracks: TrackModel[];
}


text:
set -eou pipefail

function server_lsof() {
    lsof -a -P -d 0-1024 -p "$1"
}

function stop_server() {
    sleep 0.5 # just to make sure all the fds could be closed
    kill -0 "$1" # assert server is still running
    kill "$1" # tell server to shut down gracefully
    for f in $(seq 20); do
        if ! kill -0 "$1" 2> /dev/null; then
            break # good, dead
        fi
        ps auxw | grep "$1" || true
        sleep 0.1
    done
    if kill -0 "$1" 2> /dev/null; then
        fail "server $1 still running"
    fi
}

# Simple thing to do. Start the server in the background.
# Allow extra build arguments from the command line - eg tsan.
swift build $@
"$(swift build --show-bin-path)/NIOHTTP2Server" 127.0.0.1 8888 > /dev/null & disown
SERVER_PID=$!
echo "$SERVER_PID"

# Wait for the server to bind a socket.
worked=false
for f in $(seq 20); do
    port=$(server_lsof "$SERVER_PID" | grep -Eo 'TCP .*:[0-9]+ ' | grep -Eo '[0-9]{4,5} ' | tr -d ' ' || true)
    if [[ -n "$port" ]]; then
	worked=true
	break
    else
	sleep 0.1 # wait for the socket to be bound
    fi
done
"$worked" || fail "Could not reach server 2s after lauching..."

# Run h2spec
h2spec -p 8888

stop_server "$SERVER_PID"


text:
'use strict';
const common = require('../common');
const assert = require('assert');
const path = require('path');
const fs = require('fs');

const tmpdir = require('../common/tmpdir');

let watchSeenOne = 0;
let watchSeenTwo = 0;
let watchSeenThree = 0;
let watchSeenFour = 0;

const testDir = tmpdir.path;

const filenameOne = 'watch.txt';
const filepathOne = path.join(testDir, filenameOne);

const filenameTwo = 'hasOwnProperty';
const filepathTwo = filenameTwo;
const filepathTwoAbs = path.join(testDir, filenameTwo);

const filenameThree = 'charm'; // Because the third time is

const filenameFour = 'get';

process.on('exit', function() {
  fs.unlinkSync(filepathOne);
  fs.unlinkSync(filepathTwoAbs);
  fs.unlinkSync(filenameThree);
  fs.unlinkSync(filenameFour);
  assert.strictEqual(watchSeenOne, 1);
  assert.strictEqual(watchSeenTwo, 2);
  assert.strictEqual(watchSeenThree, 1);
  assert.strictEqual(watchSeenFour, 1);
});

fs.writeFileSync(filepathOne, 'hello');

assert.throws(
  () => { fs.watchFile(filepathOne); },
  { code: 'ERR_INVALID_ARG_TYPE' }
);

// Does not throw.
fs.watchFile(filepathOne, function() {
  fs.unwatchFile(filepathOne);
  ++watchSeenOne;
});

setTimeout(function() {
  fs.writeFileSync(filepathOne, 'world');
}, 1000);

process.chdir(testDir);

fs.writeFileSync(filepathTwoAbs, 'howdy');

assert.throws(
  () => { fs.watchFile(filepathTwo); },
  { code: 'ERR_INVALID_ARG_TYPE' }
);

{ // Does not throw.
  function a() {
    fs.unwatchFile(filepathTwo, a);
    ++watchSeenTwo;
  }

  function b() {
    fs.unwatchFile(filepathTwo, b);
    ++watchSeenTwo;
  }
  fs.watchFile(filepathTwo, a);
  fs.watchFile(filepathTwo, b);
}

setTimeout(function() {
  fs.writeFileSync(filepathTwoAbs, 'pardner');
}, 1000);

{ // Does not throw.
  function b() {
    fs.unwatchFile(filenameThree, b);
    ++watchSeenThree;
  }
  const uncalledListener = common.mustNotCall();
  fs.watchFile(filenameThree, uncalledListener);
  fs.watchFile(filenameThree, b);
  fs.unwatchFile(filenameThree, uncalledListener);
}

setTimeout(function() {
  fs.writeFileSync(filenameThree, 'pardner');
}, 1000);

setTimeout(function() {
  fs.writeFileSync(filenameFour, 'hey');
}, 200);

setTimeout(function() {
  fs.writeFileSync(filenameFour, 'hey');
}, 500);

{ // Does not throw.
  function a() {
    ++watchSeenFour;
    assert.strictEqual(watchSeenFour, 1);
    fs.unwatchFile(`.${path.sep}${filenameFour}`, a);
  }
  fs.watchFile(filenameFour, a);
}


text:
""" Test that using starred nodes in unpacking
does not trigger a false positive on Python 3.
"""

__revision__ = 1

def test():
    """ Test that starred expressions don't give false positives. """
    first, second, *last = (1, 2, 3, 4)
    *last, = (1, 2)
    return (first, second, last)


text:
define(['dgrid/OnDemandGrid', 'js/data'],
	function (OnDemandGrid, data) {
		var entries = {
			grid: new OnDemandGrid({
				store: data.store,
				columns: [
					{ label: "Expense Type", field: "expenseType"},
					{ label: "Expense Amount", field: "expenseAmount"},
					{ label: "Expense Date", field: "expenseDate"}
				],
			}, "gridDiv")
		};
		return entries;
	}
);


text:
@implementation NSDate (LiberalDates)

+ (NSDate *)dateWithInternetString:(NSString *)dateString;
{
    return [self dateWithInternetString:dateString useFormatter:nil];
}

+ (NSDate *)dateWithInternetString:(NSString *)dateString useFormatter:(NSDateFormatter **)outFormatter;
{
    if (outFormatter && *outFormatter) return [*outFormatter dateFromString:dateString];

	NSDate *date = nil;

	for (NSDateFormatter *formatter in [NSDateFormatter allISO8601DateFormatters]) {
		date = [formatter dateFromString:dateString];
		if (date)
        {
            if (outFormatter) *outFormatter = formatter;
            return date;
        }
	}

	for (NSDateFormatter *formatter in [NSDateFormatter allRFC2822DateFormatters]) {
		date = [formatter dateFromString:dateString];
		if (date)
        {
            if (outFormatter) *outFormatter = formatter;
            return date;
        }
	}

	for (NSDateFormatter *formatter in [NSDateFormatter allInternetDateFormatters]) {
		date = [formatter dateFromString:dateString];
		if (date)
        {
            if (outFormatter) *outFormatter = formatter;
            return date;
        }
	}

	return date;
}

@end


text:
from asyncflux import AsyncfluxClient
from asyncflux.database import Database
from asyncflux.shardspace import ShardSpace
from asyncflux.testing import AsyncfluxTestCase, gen_test

class ShardSpaceTestCase(AsyncfluxTestCase):

    def test_class_instantiation(self):
        client = AsyncfluxClient()

        name = 'default'
        database = 'foo'
        regex = '/.*/'
        retention_policy = 'inf'
        shard_duration = '7d'
        replication_factor = 5
        split = 3
        shard_space = ShardSpace(client, name=name, database=database,
                                 regex=regex, retention_policy=retention_policy,
                                 shard_duration=shard_duration,
                                 replication_factor=replication_factor,
                                 split=split)
        self.assertIsInstance(shard_space.database, Database)
        self.assertEqual(shard_space.database.name, database)

        database = Database(client, 'foo')
        shard_space = ShardSpace(client, name=name, database=database,
                                 regex=regex, retention_policy=retention_policy,
                                 shard_duration=shard_duration,
                                 replication_factor=replication_factor,
                                 split=split)
        self.assertIsInstance(shard_space.database, Database)
        self.assertEqual(shard_space.database.name, database.name)

    @gen_test
    def test_get_shard_spaces(self):
        client = AsyncfluxClient()
        shard_spaces = [{'name': 'default', 'database': 'foo', 'regex': '/.*/',
                         'retentionPolicy': 'inf', 'shardDuration': '7d',
                         'replicationFactor': 1, 'split': 1},
                        {'name': 'second', 'database': 'bar', 'regex': '/.*/',
                         'retentionPolicy': '365d', 'shardDuration': '15m',
                         'replicationFactor': 5, 'split': 5},
                        {'name': 'default', 'database': 'bar', 'regex': '/.*/',
                         'retentionPolicy': 'inf', 'shardDuration': '7d',
                         'replicationFactor': 1, 'split': 1}]

        with self.patch_fetch_mock(client) as m:
            self.setup_fetch_mock(m, 200, body=shard_spaces)
            response = yield client.get_shard_spaces()
            for actual, expected in zip(response, shard_spaces):
                self.assertIsInstance(actual, ShardSpace)
                self.assertEqual(actual.client, client)
                self.assertEqual(actual.name, expected['name'])
                self.assertIsInstance(actual.database, Database)
                self.assertEqual(actual.database.name, expected['database'])
                self.assertEqual(actual.regex, expected['regex'])
                self.assertEqual(actual.retention_policy,
                                 expected['retentionPolicy'])
                self.assertEqual(actual.shard_duration,
                                 expected['shardDuration'])
                self.assertEqual(actual.replication_factor,
                                 expected['replicationFactor'])
                self.assertEqual(actual.split, expected['split'])

                self.assert_mock_args(m, '/cluster/shard_spaces')


text:
<?php

abstract class APICommand
{

    public function execute(APIRequest $request){

        return $this->doExecute($request);
    }

    abstract function doExecute(APIRequest $request);
}

?>


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using Microsoft.Azure.WebJobs.Extensions.Storage;
using Microsoft.Azure.WebJobs.Hosting;
using Microsoft.Extensions.Hosting;

[assembly: WebJobsStartup(typeof(AzureStorageBlobsWebJobsStartup))]

namespace Microsoft.Azure.WebJobs.Extensions.Storage
{
    /// <inheritdoc cref="IWebJobsStartup"/>
    public class AzureStorageBlobsWebJobsStartup : IWebJobsStartup
    {
        /// <inheritdoc />
        public void Configure(IWebJobsBuilder builder)
        {
            builder.AddAzureStorageBlobs();
        }
    }
}


text:
from __future__ import unicode_literals

from django.db import models, migrations
import jsonfield.fields
import post_office.fields
import post_office.validators
import post_office.models

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Attachment',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('file', models.FileField(upload_to=post_office.models.get_upload_path)),
                ('name', models.CharField(help_text='The original filename', max_length=255)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Email',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('from_email', models.CharField(max_length=254, validators=[post_office.validators.validate_email_with_name])),
                ('to', post_office.fields.CommaSeparatedEmailField(blank=True)),
                ('cc', post_office.fields.CommaSeparatedEmailField(blank=True)),
                ('bcc', post_office.fields.CommaSeparatedEmailField(blank=True)),
                ('subject', models.CharField(max_length=255, blank=True)),
                ('message', models.TextField(blank=True)),
                ('html_message', models.TextField(blank=True)),
                ('status', models.PositiveSmallIntegerField(blank=True, null=True, db_index=True, choices=[(0, 'sent'), (1, 'failed'), (2, 'queued')])),
                ('priority', models.PositiveSmallIntegerField(blank=True, null=True, choices=[(0, 'low'), (1, 'medium'), (2, 'high'), (3, 'now')])),
                ('created', models.DateTimeField(auto_now_add=True, db_index=True)),
                ('last_updated', models.DateTimeField(auto_now=True, db_index=True)),
                ('scheduled_time', models.DateTimeField(db_index=True, null=True, blank=True)),
                ('headers', jsonfield.fields.JSONField(null=True, blank=True)),
                ('context', jsonfield.fields.JSONField(null=True, blank=True)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='EmailTemplate',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(help_text=b"e.g: 'welcome_email'", max_length=255)),
                ('description', models.TextField(help_text='Description of this template.', blank=True)),
                ('subject', models.CharField(blank=True, max_length=255, validators=[post_office.validators.validate_template_syntax])),
                ('content', models.TextField(blank=True, validators=[post_office.validators.validate_template_syntax])),
                ('html_content', models.TextField(blank=True, validators=[post_office.validators.validate_template_syntax])),
                ('created', models.DateTimeField(auto_now_add=True)),
                ('last_updated', models.DateTimeField(auto_now=True)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Log',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('date', models.DateTimeField(auto_now_add=True)),
                ('status', models.PositiveSmallIntegerField(choices=[(0, 'sent'), (1, 'failed')])),
                ('exception_type', models.CharField(max_length=255, blank=True)),
                ('message', models.TextField()),
                ('email', models.ForeignKey(related_name='logs', editable=False, to='post_office.Email')),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.AddField(
            model_name='email',
            name='template',
            field=models.ForeignKey(blank=True, to='post_office.EmailTemplate', null=True),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='attachment',
            name='emails',
            field=models.ManyToManyField(related_name='attachments', to='post_office.Email'),
            preserve_default=True,
        ),
    ]


text:
<?php

namespace Composer\Package\LinkConstraint;

use Composer\Semver\Constraint\ConstraintInterface;

@trigger_error('The ' . __NAMESPACE__ . '\LinkConstraintInterface interface is deprecated, use Composer\Semver\Constraint\ConstraintInterface instead.', E_USER_DEPRECATED);

/**
 * @deprecated use Composer\Semver\Constraint\ConstraintInterface instead
 */
interface LinkConstraintInterface extends ConstraintInterface
{
}


text:
function [c] = mrdivide(a,b)
%C=A/B
%   [C]=MRDIVIDE(A,B) Division of a QTT-Tucker tensor by number
%
%
% TT-Toolbox 2.2, 2009-2012
%
%This is TT Toolbox, written by Ivan Oseledets et al.
%Institute of Numerical Mathematics, Moscow, Russia
%webpage: http://spring.inm.ras.ru/osel
%
%For all questions, bugs and suggestions please mail
%ivan.oseledets@gmail.com
%---------------------------
if isa(a,'qtt_tucker') && numel(b) == 1
c=a*(1.0./b);
else
    error('Use mrdivide(full(A),full(B)).');
end


text:
/** @module node-ordering */

import initialOrdering from './initial-ordering';
import swapNodes from './swap-nodes';
import countCrossings from './count-crossings';
import sortNodes from './weighted-median';

/**
 * Return an ordering for the graph G.
 *
 * The ordering is a list of lists of node ids, corresponding to the ranks of
 * the graphs, and the order of nodes within each rank.
 *
 * @param {Graph} G - The graph. Nodes must have a `rank` attribute.
 *
 */
export default function ordering(G, maxIterations=25) {
  let order = initialOrdering(G),
      best = order,
      i = 0;

  while (i++ < maxIterations) {
    sortNodes(G, order, (i % 2 == 0));
    swapNodes(G, order);
    if (allCrossings(G, order) < allCrossings(G, best)) {
      // console.log('improved', allCrossings(G, order), order);
      best = copy(order);
    }
  }

  // Put all nodes into the same band
  best = best.map(rank => [rank]);

  return best;
}

function allCrossings(G, order) {
  let count = 0;
  for (let i = 0; i < order.length - 1; ++i) {
    count += countCrossings(G, order[i], order[i + 1]);
  }
  return count;
}

function copy(order) {
  let result = [];
  for (let rank of order) {
    let r = [];
    result.push(r);
    for (let node of rank) r.push(node);
  }
  return result;
}


text:
"""``fixtures.py``

`Useful fixture functions/patterns for TAF`

"""
import functools
import os
import copy
import operator
from collections import namedtuple

import pytest

from .helpers import grouper
from . import loggers
from .dev_linux_host import GenericLinuxHost

def sshlog(request, env_name=None, env_obj=None, instance_class=GenericLinuxHost):
    """Register additional file handler for linux_host ssh loggers per test case.

    Args:
        request(pytest.request):  fixture request object.
        env_name(str):  Name of Environment class instance [optional].
        env_obj(Environment):  Environment instance [optional].
        instance_class(object):  SSH logger has to be crated only for environment attributes which are instances of this class [optional].

    Examples:

    Define your fixture based on this function::

        # My Environment fixture
        @pytest.fixture
        def my_env(request):
            env = Environment(...)
            request.addfinalizer(env.shutdown)
            env.initialize()
            return env

        @pytest.fixture(autouse=True)
        def ssh_logger(request):
            fixtures.sshlog(request, "my_env")

        def test_something(my_env):
            my_env.lhost[1].ssh.exec_command("command_to_be_executed")

    After that you have to see additional files in defined with \--logdir option folder.\n

    Also you can use it like function to modify existing env fixture::

        @pytest.fixture(autouse=True)
        def env_new(request, env):
            fixtures.sshlog(request, env_obj=env)
            return env

    """
    # Skip fixture if logdir isn't set.
    if not loggers.LOG_DIR:
        return

    def add_handler(log_adapter, log_file):
        """Register new file handler.

        """
        log_file_handler = loggers.logging.FileHandler(log_file)
        # Set the same formatter
        if log_adapter.logger.handlers and log_adapter.logger.handlers[0].formatter:
            log_file_handler.setFormatter(log_adapter.logger.handlers[0].formatter)
        log_adapter.logger.addHandler(log_file_handler)
        return log_file_handler

    def remove_handlers(env, log_handlers):
        """Remove all created and saved in log_handlers list additional file handlers.

        """
        for obj in list(env.id_map.values()):
            if obj.id in log_handlers:
                log_handlers[obj.id].flush()
                log_handlers[obj.id].close()
                obj.ssh.class_logger.logger.removeHandler(log_handlers[obj.id])
                log_handlers.pop(obj.id)

    # log_file_handlers to remove
    log_handlers = {}

    # Check if env is used in TC and file logging is enabled
    if env_obj is None and (env_name not in request.fixturenames or loggers.LOG_DIR is None):
        return
    if env_obj is None and env_name:
        env_obj = request.getfuncargvalue(env_name)

    request.addfinalizer(lambda: remove_handlers(env_obj, log_handlers))
    file_prefix = os.path.join(loggers.LOG_DIR, "{0}_{1}_".format(request.function.__name__, os.getpid()))

    # Search for LinuxHost objects
    for obj in list(env_obj.id_map.values()):
        if isinstance(obj, instance_class):
            log_file = "{0}_id_{1}_type_{2}.log".format(file_prefix, obj.id, obj.type)
            log_handlers[obj.id] = add_handler(obj.ssh.class_logger, log_file)

def autolog(request, logger_name="suite_logger"):
    """Inject logger object to test class.

    Args:
        request(pytest.request):  py.test request object.
        logger_name(str):  name of logger class attribute to create

    Notes:
        This fixture has to have scope level "class".
        You do not need to pass this fixture to test function in case you set autouse.

    Examples::

        @pytest.fixture(scope="class", autouse=True)
        def autolog(request):
            return fixtures.autolog(request, "wishful_logger_instance_name")

    """
    def remove_logger(cls):
        """Explicit close log handlers.

        """
        while getattr(cls, logger_name).logger.handlers:
            getattr(cls, logger_name).logger.handlers[0].flush()
            getattr(cls, logger_name).logger.handlers[0].close()
            getattr(cls, logger_name).logger.removeHandler(getattr(cls, logger_name).logger.handlers[0])
        delattr(cls, logger_name)

    taf_logger = loggers.module_logger(request.cls.__module__, request.cls.__name__)
    request.addfinalizer(lambda: remove_logger(request.cls))
    setattr(request.cls, logger_name, taf_logger)
    getattr(request.cls, logger_name).debug("Starting %s test suite." % (request.cls.__name__, ))
    del taf_logger

Device_Tuple = namedtuple('Device_Tuple', ['device_ids', 'lag_id'])

Ports_Tuple = namedtuple('Port_Tuple', ['ports', 'ports_list'])

class LagIdGenerator(object):

    INITIAL_LAG = 3800

    def __init__(self):
        super(LagIdGenerator, self).__init__()
        self.free_lags = {}

    @classmethod
    def id_to_key(cls, lag_id):
        """Get LAG key by LAG ID.

        Args:
            lag_id(int):  LAG ID

        Returns:
            int:  LAG key

        """
        return lag_id - cls.INITIAL_LAG

    def _default_set(self, max_lags):
        # create set since we will be intersecting
        # since we allocate after intersecting, initial order doesn't matter
        # we have to sort anyway
        return set(range(self.INITIAL_LAG, self.INITIAL_LAG + max_lags - 1))

    def generate_lag(self, *args):
        """Get lag ID for specific device.

        Args:
            args(list[SwitchGeneral]): list of devices to generate lag ids for

        Raises:
            StopIteration:  if cross part contains more than 2 devices

        Returns:
            int|None:  LAG ID

        """
        non_empty = [_f for _f in args if _f]
        if not non_empty:
            # in case device is not in cross connection
            return None
        lag_sets = [self.free_lags.setdefault(dev.id, self._default_set(dev.hw.max_lags)) for
                    dev in non_empty]
        # intersect all the sets using reduce
        # operator.and_ is & is intersection
        intersection = functools.reduce(operator.and_, lag_sets)
        # intersection of sets shouldn't have an ordering so we always have to sort
        # next will raise StopIteration if it can't allocate
        lag = next(iter(sorted(intersection)))
        for lag_set in lag_sets:
            # use discard so we don't raise an error in case we were passed
            # in the same device twice
            lag_set.discard(lag)
        return lag

class LagPortEnv(object):
    """Class for fixture that replaces ports with LAGs.

    """

    def __init__(self, request, env):
        super(LagPortEnv, self).__init__()
        self.cross_part_copy = copy.deepcopy(env.setup['cross'])
        self.ports_dict = {}
        self.request = request
        self.env = env
        self.lag_generator = LagIdGenerator()
        self.lags_to_create = {}
        self.cleanups = {}
        self.creates = {}

    def get_cross_part_lag(self, cross_part):
        """Get LAG ID for cross connection.

        Args:
            cross_part(list):  connection from setup file, e.g. ["03", 1, "1", 1]

        Raises:
            StopIteration:  if port is already in LAG

        Returns:
            tuple(dict{device_id: link_id}, LAG_ID):  dictionary of device_id: port_id and LAG ID

        """
        device_dict = {}  # store device.id: link_id pairs
        get_lag_args = []  # store  device objects
        # iterator over _id, _port_id pairs in cross_part
        for _id, _port_id in grouper(cross_part, 2):
            device = self.env.id_map[self.env.get_device_id(_id)]
            max_lags = getattr(getattr(device, 'hw', None), "max_lags", 0)
            # check if device supports LAG
            if max_lags:
                device_dict.update({device.id: _port_id})
                dev = device
                get_lag_args.append(dev)

        for dev_id, port_id in device_dict.items():
            device = self.env.id_map[self.env.get_device_id(dev_id)]
            real_port_id = self.env.get_real_port_name(dev_id, port_id)
            # check if port is not a LAG member
            ports_lags_table = device.ui.get_table_ports2lag()
            if any(r for r in ports_lags_table if r['portId'] == real_port_id):
                raise StopIteration("Port is already in LAG")

        lag = self.lag_generator.generate_lag(*get_lag_args)

        return Device_Tuple(device_dict, lag)

    def setup(self):
        for cross in self.env.setup['cross'].values():
            for cross_part in cross:
                for _id, _port_id in grouper(cross_part, 2):
                    device = self.env.id_map[self.env.get_device_id(_id)]
                    max_lags = getattr(getattr(device, 'hw', None), "max_lags", 0)
                    # check if device supports LAG
                    if max_lags:
                        # Wrap original clearconfig in order to recreate LAGs
                        if device.id not in self.cleanups:
                            self.cleanups[device.id] = device.clearconfig
                            device.clearconfig = self.add_lags(device, device.clearconfig)
                            self.creates[device.id] = device.start
                            device.start = self.add_lags(device, device.start)

    def setup_lags(self):
        """Define LAGs that will be created.

        Notes:
            This method changes initial device's attributes (ports and port_list).
            Initial configuration should be restored after test execution

        """
        for cross in self.env.setup["cross"].values():
            for cross_part in cross:
                # get LAG ID for specific cross connection
                try:
                    lag_env = self.get_cross_part_lag(cross_part)
                except StopIteration:
                    # Restore initial configuration in case of error
                    self.teardown()
                    # Skip test execution
                    pytest.skip("Test case could not be executed on LAGs: Port is already in LAG")
                if lag_env.lag_id:
                    for dev_id, port_id in lag_env.device_ids.items():
                        device = self.env.id_map[dev_id]
                        real_port_id = self.env.get_real_port_name(dev_id, port_id)
                        # backup ports and ports_list
                        self.ports_dict.setdefault(device.id,
                                                   Ports_Tuple(copy.deepcopy(device.ports),
                                                               copy.deepcopy(device.port_list)))
                        # Add LAGs to be created on device
                        self.lags_to_create.setdefault(device.id, []).append((lag_env.lag_id,
                                                                              real_port_id))
                        # Add changes in setup
                        # Add LAG ID in ports or port_list
                        # Change link ID in cross connection
                        if getattr(device, "port_list", None):
                            speed = self.env.get_port_speed(dev_id, port_id)
                            device.port_list.append([lag_env.lag_id, speed])
                            device.ports.append(lag_env.lag_id)
                            cross_part[cross_part.index(dev_id) + 1] = len(device.port_list)
                        elif getattr(device, "ports", None):
                            device.ports.append(lag_env.lag_id)
                            cross_part[cross_part.index(dev_id) + 1] = len(device.ports)

    def teardown(self):
        """Restore initial configuration.

        """
        # Restore setup JSON file
        for cross_id in self.env.setup["cross"]:
            del self.env.setup['cross'][cross_id][:]
            self.env.setup['cross'][cross_id].extend(self.cross_part_copy[cross_id])
        # Restore device's attributes ports and ports_list
        for dev_id in self.ports_dict:
            device = self.env.id_map[dev_id]
            device.ports = self.ports_dict[dev_id].ports
            device.port_list = self.ports_dict[dev_id].ports_list
        # Restore original clearconfig
        for dev_id in self.cleanups:
            device = self.env.id_map[dev_id]
            device.clearconfig = self.cleanups[dev_id]
            device.start = self.creates[dev_id]

    def add_lags(self, device, func):
        """Wrap original device's method e.g. clearconfig or restart.

        """
        def wrapper(*args, **kwargs):
            func(*args, **kwargs)
            if not self.lags_to_create:
                self.setup_lags()
            for lag_id, port_id in self.lags_to_create[device.id]:
                device.ui.create_lag(lag=lag_id,
                                     key=self.lag_generator.id_to_key(lag_id),
                                     lag_type="Static", hash_mode="None")
                device.ui.create_lag_ports(ports=[port_id, ],
                                           lag=lag_id,
                                           key=self.lag_generator.id_to_key(lag_id))
        return wrapper

def env_lag(request, env):
    """Replace physical ports in setup file with LAGs.

    Args:
        request(pytest.Request):  pytest request fixture
        env(Environment):  env fixture

    Notes:
        For correct functioning new fixture for test cases should be created.

    Examples::

        # Code in conftest file or test module
        from testlib.fixtures import env_lag

        @pytest.fixture(scope='module', autouse=True)
        def env_replace_lag(request, env_init):
            env_lag(request, env_init)

    """
    lag_env = LagPortEnv(request, env)
    request.addfinalizer(lag_env.teardown)
    lag_env.setup()

def lhost_to_switch(request, env_init):
    """Add Linux Hosts as Switch devices into environment.

    Notes:
        For correct functioning new fixture for test cases should be created.

    Examples::

        # Code in conftest file or test module
        from testlib.fixtures import lhost_to_switch

        @pytest.fixture(scope='module', autouse=True)
        def env_switch_lhost(request, env_init):
            lhost_to_switch(request, env_init)

    """
    # Get initial version of Environment object
    added_switches = []
    init_dut_map = copy.deepcopy(env_init.dut_map)

    def setup():
        # Add lhost instances into env.switch dictionary
        for _lhost in getattr(env_init, 'lhost', {}).values():
            switches = getattr(env_init, 'switch', {})
            eid = len(switches) + 1
            env_init.dut_map["sw{}".format(eid)] = _lhost.id
            if not hasattr(env_init, 'switch'):
                setattr(env_init, 'switch', {})
            env_init.switch[eid] = _lhost
            added_switches.append(eid)

    def teardown():
        # Rollback all changes
        env_init.dut_map = init_dut_map
        for _key in added_switches:
            env_init.switch.pop(_key)

    request.addfinalizer(teardown)
    setup()

def chef_prep(request, env_main, cll):
    """Do steps required by configuration management system tests.

    Notes:
        For correct functioning new fixture for test cases should be created.

    Examples::

        # Code in conftest file or test module
        from testlib.fixtures import chef_prep

        @pytest.fixture(scope='class', autouse=True)
        def suite_prep(request, env_main):
            chef_prep(request, env_main)

    """
    def _remove_chef_client():
        """Uninstall chef client and do cleanup of chef dir.

        """
        assert env_main.switch[1].ui.cli_send_command('yum erase -y chef*')[-1] == 0
        assert env_main.switch[1].ui.cli_send_command('rm -rf /etc/chef/')[-1] == 0
        env_main.chef[1].delete_node(cll.fqdn_hostname)

    def _remove_local_role_files():
        for x in os.listdir(cll.configs_path):
            os.remove(os.path.join(cll.configs_path, x))
        os.rmdir(cll.configs_path)

    def _teardown():
        # _remove_chef_client()
        env_main.chef[1].remove_role()
        _remove_local_role_files()

    cll.fqdn_hostname = env_main.switch[1].ui.cli_send_command('hostname -f')[0].strip()
    cll.configs_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'chef_roles')
    if not os.path.exists(cll.configs_path):
        os.makedirs(cll.configs_path)
    # Perform teardown sequence
    request.addfinalizer(_teardown)


text:
:orphan:

.. _zend.form.view.helper.form-reset:

FormReset
^^^^^^^^^

The ``FormReset`` view helper can be used to render a ``<input type="reset">``
HTML form input.

``FormText`` extends from :ref:`Zend\\Form\\View\\Helper\\FormInput <zend.form.view.helper.form-input>`.

.. _zend.form.view.helper.form-reset.usage:

Basic usage:

.. code-block:: php
   :linenos:

   use Zend\Form\Element;

   $element = new Element('my-reset');
   $element->setAttribute('value', 'Reset');

   // Within your view...
   echo $this->formReset($element);

Output:

.. code-block:: html
   :linenos:

   <input type="reset" name="my-reset" value="Reset">


text:
{-# LANGUAGE GeneralizedNewtypeDeriving, StandaloneDeriving, MultiParamTypeClasses, FlexibleContexts, FlexibleInstances, UndecidableInstances #-}

-----------------------------------------------------------------------------
-- |
-- Module      :  Network.Policy.Types
-- Copyright   :  (c) 2014 Stefan Bühler
-- License     :  MIT-style (see the file COPYING)
--
-- Maintainer  :  stbuehler@web.de
-- Stability   :  experimental
-- Portability :  portable
--
-- More types for Network.Policy.
--
-----------------------------------------------------------------------------

module Network.Policy.Types
	( module Network.Policy.Action
	, PolicyParameters
	, PolicyHandler
	) where

import Network.Policy.Action

import qualified Data.Text as T
import qualified Data.Map.Strict as M

{-|
Type alias for parameters in a policy request (mapping keys to values).
-}
type PolicyParameters = M.Map T.Text T.Text

{-|
Type alias for functions handling a policy request
-}
type PolicyHandler = PolicyParameters -> IO PolicyAction


text:
package com.facebook.buck.core.build.engine.impl;

import com.facebook.buck.core.build.execution.context.ExecutionContext;
import com.facebook.buck.core.cell.CellPathResolver;
import com.facebook.buck.core.cell.TestCellPathResolver;
import com.facebook.buck.event.BuckEventBusForTests;
import com.facebook.buck.io.filesystem.impl.DefaultProjectFilesystemFactory;
import com.facebook.buck.io.filesystem.impl.FakeProjectFilesystem;
import com.facebook.buck.testutil.TestConsole;
import com.facebook.buck.util.ClassLoaderCache;
import com.facebook.buck.util.FakeProcessExecutor;
import com.facebook.buck.util.environment.EnvVariablesProvider;
import com.facebook.buck.util.environment.Platform;
import com.facebook.buck.util.timing.FakeClock;
import java.util.concurrent.ConcurrentHashMap;

public class TestExecutionContextUtils {

  public static ExecutionContext.Builder executionContextBuilder() {
    FakeProjectFilesystem filesystem = new FakeProjectFilesystem();
    CellPathResolver cellPathResolver = TestCellPathResolver.get(filesystem);

    return ExecutionContext.builder()
        .setConsole(new TestConsole())
        .setBuckEventBus(BuckEventBusForTests.newInstance())
        .setPlatform(Platform.detect())
        .setEnvironment(EnvVariablesProvider.getSystemEnv())
        .setClassLoaderCache(new ClassLoaderCache())
        .setProcessExecutor(new FakeProcessExecutor())
        .setCellPathResolver(cellPathResolver)
        .setProjectFilesystemFactory(new DefaultProjectFilesystemFactory())
        .setBuildCellRootPath(filesystem.getRootPath().getPath())
        .setClock(FakeClock.doNotCare())
        .setWorkerToolPools(new ConcurrentHashMap<>());
  }
}


text:
/* All rights reserved.                                                            */

/* Redistribution and use in source and binary forms, with or without              */
/* modification, are permitted provided that the following conditions are met:     */

/*   * Redistributions of source code must retain the above copyright notice,      */
/*     this list of conditions and the following disclaimer.                       */
/*   * Redistributions in binary form must reproduce the above copyright notice,   */
/*     this list of conditions and the following disclaimer in the documentation   */
/*     and/or other materials provided with the distribution.                      */
/*   * Neither the name of the <ORGANIZATION> nor the names of its contributors    */
/*     may be used to endorse or promote products derived from this software       */
/*     without specific prior written permission.                                  */

/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */
/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED   */
/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE          */
/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE    */
/* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL      */
/* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR      */
/* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER      */
/* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,   */
/* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE   */
/* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.            */

#include "lift/algo/search.h"

static
bool __is_least(const type_t *type, const void *a, const void *b)
{
  if (a == NULL)
  { return(false); }
  if (b == NULL)
  { return(true); }
  else
  { return(type->compare(type, a, b) == LT); }
}

static
bool __is_greatest(const type_t *type, const void *a, const void *b)
{
  if (a == NULL)
  { return(false); }
  if (b == NULL)
  { return(true); }
  else
  { return(type->compare(type, a, b) == GT); }
}

static inline
const list_node_t *__find_elem(const list_t *l, const list_node_t *start, const list_node_t *end, bool (*f) (const type_t *, const void *, const void *b))
{
  const void *tmp_a, *tmp_b;
  const list_node_t *found = NULL;

  while (start!=NULL)
  {
    tmp_a = (found==NULL ? NULL : list_get_data(l, found));
    tmp_b = list_get_data(l, start);
    found = (f(&l->type, tmp_a, tmp_b) ? found : start);

    if (start == end)
    { break; }
    else
    { start = list_next(l, start); }
  }

  return(found);
}

int binary_search(const list_t *xs, const void *x)
{
  int low  = 0;
  int high = list_size(xs);
  int mid, cmp;
  const list_node_t *tmp;

  if (high == 0)
  { return(NOT_FOUND); }

  while (low<=high)
  {
    mid = low + ((high-low) >> 1);
    tmp = list_at(xs, mid);
    cmp = xs->type.compare(&xs->type, x, list_get_data(xs, tmp));

    if (cmp == EQ)
    { return(mid); }
    else if (cmp == LT)
    { high = mid - 1; }
    else /* if (cmp == GT) */
    { low = mid + 1; }
  }

  return(NOT_FOUND);
}

const list_node_t *least_elem(const list_t *l, const list_node_t *start, const list_node_t *end)
{ return(__find_elem(l, start, end, __is_least)); }

const list_node_t *greatest_elem(const list_t *l, const list_node_t *start, const list_node_t *end)
{ return(__find_elem(l, start, end, __is_greatest)); }


text:
package com.github.sarxos.securetoken.impl;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Scanner;

public class Hardware4Win {

	private static String sn = null;

	public static final String getSerialNumber() {

		if (sn != null) {
			return sn;
		}

		OutputStream os = null;
		InputStream is = null;

		Runtime runtime = Runtime.getRuntime();
		Process process = null;
		try {
			process = runtime.exec(new String[] { "wmic", "bios", "get", "serialnumber" });
		} catch (IOException e) {
			throw new RuntimeException(e);
		}

		os = process.getOutputStream();
		is = process.getInputStream();

		try {
			os.close();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}

		Scanner sc = new Scanner(is);
		try {
			while (sc.hasNext()) {
				String next = sc.next();
				if ("SerialNumber".equals(next)) {
					sn = sc.next().trim();
					break;
				}
			}
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}

		if (sn == null) {
			throw new RuntimeException("Cannot find computer SN");
		}

		return sn;
	}
}


text:
// Generated by BUCKLESCRIPT VERSION 4.0.5, PLEASE EDIT WITH CARE

import * as Add from "./add.js";

var result = Add.add(1, 4);

export {
  result ,

}
/* result Not a pure module */


text:
#include "google/fhir/primitive_wrapper.h"

#include <stddef.h>
#include <stdint.h>
#include <string.h>

#include <memory>
#include <sstream>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>

#include "google/protobuf/descriptor.h"
#include "google/protobuf/message.h"
#include "absl/container/flat_hash_map.h"
#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/escaping.h"
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "absl/time/time.h"
#include "google/fhir/annotations.h"
#include "google/fhir/codes.h"
#include "google/fhir/extensions.h"
#include "google/fhir/fhir_types.h"
#include "google/fhir/proto_util.h"
#include "google/fhir/status/status.h"
#include "google/fhir/status/statusor.h"
#include "google/fhir/util.h"
#include "proto/google/fhir/proto/annotations.pb.h"
#include "re2/re2.h"

namespace google {
namespace fhir {

using ::absl::InvalidArgumentError;
using ::google::protobuf::Descriptor;
using ::google::protobuf::FieldDescriptor;
using ::google::protobuf::Message;
using ::google::protobuf::Reflection;

namespace primitives_internal {

absl::StatusOr<bool> HasPrimitiveHasNoValue(const Message& message) {
  const FieldDescriptor* field =
      message.GetDescriptor()->FindFieldByName("extension");
  std::vector<const Message*> no_value_extensions;
  ForEachMessage<Message>(message, field, [&](const Message& extension) {
    std::string scratch;
    const std::string& url_value = GetExtensionUrl(extension, &scratch);
    if (url_value == kPrimitiveHasNoValueUrl) {
      no_value_extensions.push_back(&extension);
    }
  });
  if (no_value_extensions.size() > 1) {
    return InvalidArgumentError(absl::StrCat(
        "Message has more than one PrimitiveHasNoValue extension: ",
        message.GetDescriptor()->full_name()));
  }
  if (no_value_extensions.empty()) {
    return false;
  }
  const Message& no_value_extension = *no_value_extensions.front();
  const Message& value_msg = no_value_extension.GetReflection()->GetMessage(
      no_value_extension,
      no_value_extension.GetDescriptor()->FindFieldByName("value"));
  const Message& boolean_msg = value_msg.GetReflection()->GetMessage(
      value_msg, value_msg.GetDescriptor()->FindFieldByName("boolean"));
  return boolean_msg.GetReflection()->GetBool(
      boolean_msg, boolean_msg.GetDescriptor()->FindFieldByName("value"));
}

}  // namespace primitives_internal

absl::Status BuildHasNoValueExtension(Message* extension) {
  const Descriptor* descriptor = extension->GetDescriptor();
  const Reflection* reflection = extension->GetReflection();

  if (!IsExtension(descriptor)) {
    return InvalidArgumentError(
        absl::StrCat("Not a valid extension type: ", descriptor->full_name()));
  }

  const FieldDescriptor* url_field = descriptor->FindFieldByName("url");
  FHIR_RETURN_IF_ERROR(
      SetPrimitiveStringValue(reflection->MutableMessage(extension, url_field),
                              primitives_internal::kPrimitiveHasNoValueUrl));

  Message* value = reflection->MutableMessage(
      extension, descriptor->FindFieldByName("value"));

  Message* boolean_message = value->GetReflection()->MutableMessage(
      value, value->GetDescriptor()->FindFieldByName("boolean"));

  boolean_message->GetReflection()->SetBool(
      boolean_message,
      boolean_message->GetDescriptor()->FindFieldByName("value"), true);

  return absl::OkStatus();
}

}  // namespace fhir
}  // namespace google


text:
package edu.isi.karma.controller.command.cleaning;

import javax.servlet.http.HttpServletRequest;

import org.json.JSONArray;
import org.json.JSONException;

import edu.isi.karma.controller.command.Command;
import edu.isi.karma.controller.command.JSONInputCommandFactory;
import edu.isi.karma.controller.history.HistoryJsonUtil;
import edu.isi.karma.rep.Workspace;
import edu.isi.karma.util.CommandInputJSONUtil;
import edu.isi.karma.webserver.KarmaException;

public class SubmitCleaningCommandFactory extends JSONInputCommandFactory {

	private enum Arguments {
		hNodeId, worksheetId, hTableId,
		examples, selectionName
	}

	@Override
	public Command createCommand(HttpServletRequest request, Workspace workspace) {
		String hNodeid = request.getParameter(Arguments.hNodeId.name());
		String w = request.getParameter(Arguments.worksheetId.name());
		String exps = request.getParameter(Arguments.examples.name());
		String selectionName = request.getParameter(Arguments.selectionName.name());
		SubmitCleaningCommand sCleanningCommand = new SubmitCleaningCommand(
				getNewId(workspace), hNodeid, w, exps,
				selectionName);
		return sCleanningCommand;
	}

	@Override
	public Command createCommand(JSONArray inputJson, Workspace workspace)
			throws JSONException, KarmaException {
		String hNodeId = HistoryJsonUtil.getStringValue(
				Arguments.hNodeId.name(), inputJson);
		String worksheetId = HistoryJsonUtil.getStringValue(
				Arguments.worksheetId.name(), inputJson);
		String examples = HistoryJsonUtil.getStringValue(
				Arguments.examples.name(), inputJson);
		this.normalizeSelectionId(worksheetId, inputJson, workspace);
		String selectionName = CommandInputJSONUtil.getStringValue(Arguments.selectionName.name(), inputJson);
		SubmitCleaningCommand comm = new SubmitCleaningCommand(
				getNewId(workspace), hNodeId, worksheetId, examples,
				selectionName);
		comm.setInputParameterJson(inputJson.toString());
		return comm;
	}

	@Override
	public Class<? extends Command> getCorrespondingCommand()
	{
		return SubmitCleaningCommand.class;
	}
}


text:
package com.newbiechen.commonviewdemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.MediaController;

import com.newbiechen.commonviewdemo.view.CheckBoxView;

public class MainActivity extends AppCompatActivity {
    private CheckBoxView mCheckBoxView;
    private Button mBtnUnCheck;
    private Button mBtnCheck;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
/*        mCheckBoxView = (CheckBoxView) findViewById(R.id.checkbox_view);
        mBtnUnCheck = (Button) findViewById(R.id.uncheck);
        mBtnCheck = (Button) findViewById(R.id.check);
        mBtnUnCheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCheckBoxView.unCheck();
            }
        });
        mBtnCheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCheckBoxView.check();
            }
        });*/
    }
}


text:
layout: page
title: Contact
---
Contact list:

* [Email us on :](indiadeeplearning.group@gmail.com)
* [Facebook page :](https://www.facebook.com/groups/1479309132086977/)


text:
	<form method='post' enctype="multipart/form-data" autocomplete=off action="{% url 'login' %}" style="width:60%;" name="loginForm" id="loginFrom" >
		{% csrf_token %}

username
			<input type="text" name="username" class="form-control" ng-model="loginFrom.username"required></input>

				 Name Required

password
			<input type="password" name="password" class="form-control" ng-model="loginFrom.pass" required></input>

				 Name Required

		<input type="submit" class="btn btn-success btn-block" value="Login">

	</form>


text:
/*
 * Default jvFloat theme.
 * modify it as you wish!
 */

.jvFloat {
	position: relative;
	display: inline;
	margin-top: 1em;
}

.jvFloat .placeHolder.required {
	color: red;
}

/* Start CSS3 Animations on supported browser */
.jvFloat .placeHolder {
	position: absolute;
	top: 0;
	left: 0;
	width: auto;
	color: #0c61fc;
	font-size: .8em;
	font-weight: bold;
	-webkit-transform: translate(0, 0);
	-moz-transform: translate(0, 0);
	-o-transform: translate(0, 0);
	-ms-transform: translate(0, 0);
	transform: translate(0, 0);
	-webkit-transition: -webkit-transform 150ms, opacity 100ms, visibility 100ms;
	transition: transform 150ms, opacity 100ms, visibility 100ms;
	opacity: 0;
	visibility: hidden;
	white-space: nowrap;
}

/*Allows textarea floating placeholder to be positioned distinctly from the normal .placeHolder class
 * This is required when working with Multiline text areas
 */
.jvFloat .placeHolder.textarea {
	/*top: 0px;*/
}

.jvFloat .placeHolder.active {
	display: block;
	visibility: visible;
	-webkit-transform: translate(0, -1em);
	-moz-transform: translate(0, -1em);
	-o-transform: translate(0, -1em);
	-ms-transform: translate(0, -1em);
	transform: translate(0, -1em);
	-webkit-transition: -webkit-transform 100ms, opacity 120ms, visibility 120ms;
	transition: transform 100ms, opacity 120ms, visibility 120ms;
	opacity: 1;
}
/* End CSS3 */

/* Legacy browser */
/*.jvFloat .placeHolder {
	position: absolute;
	top: -1em;
	left: 0;
	color: #0c61fc;
	font-size: .85em;
	font-weight: bold;
	opacity: 0;
	visibility: hidden;
}
.jvFloat .placeHolder.active {
	display: block;
	visibility: visible;
	opacity: 1;
}*/
/* End Legacy */


text:
package backend.flowNetwork

import scala.concurrent.duration._

/**
 * Extends a FlowNode with a configurable Tick rate.
 *
 * When extended with this a FlowNode will receive
 * Tick case objects in a configurable frequency. By
 * default 1 Hz.
 *
 * The frontend can reconfigure this via the exposed
 * configuration property "freq".
 *
 * @note When a too high frequency is set the internal
 *       timer resolution might not be sufficient to produce
 *       Tick messages at the requested rate.
 */
trait TickingFlow extends FlowNode {
  case object Tick

  import context.dispatcher

  private var tick = context.system.scheduler.schedule(1 second, 1 second, self, Tick)
  var tickFrequency = 1.0
  val tickPropName = "freq"

  addConfigMapGetters(() => Map(
    tickPropName -> tickFrequency.toString
  ))

  addConfigSetters({
    case (`tickPropName`, f) =>
      log.info(s"Changing frequency to $f")
      tickFrequency = f.toDouble

      tick.cancel()
      if (tickFrequency > 0)
        tick = context.system.scheduler.schedule(0 seconds, (1.0 / tickFrequency) second, self, Tick)
  })

  override def postStop() =
    tick.cancel()
    super.postStop()
}


text:
namespace PortForward.Utilities
{
    public interface ILogger
    {
        void Log(string message, params object[] args);
        void Error(string message, params object[] args);
    }
}


text:
import java.io.*;
import java.util.*;

import static java.lang.Math.*;

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner in = new Scanner(System.in);

        int tests = in.nextInt();
        int down, up;

        for (int t = 0; t < tests; t++) {

            down = (int) ceil(sqrt(in.nextInt()));
            up = (int) floor(sqrt(in.nextInt()));

            System.out.println(up + 1 - down);
        }
    }
}


text:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="48dp"
    android:height="48dp"
    android:viewportWidth="48"
    android:viewportHeight="48"
    android:tint="?attr/colorControlNormal">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M13.5,33.2V14.8H15V33.2ZM34.5,33.2 L21.05,24 34.5,14.8Z"/>
</vector>


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

package org.apache.tapestry.html;

import java.io.CharArrayWriter;
import java.io.PrintWriter;

import org.apache.tapestry.IMarkupWriter;

/**
 *  Subclass of {@link HTMLWriter} that is nested.  A nested writer
 *  buffers its output, then inserts it into its parent writer when it is
 *  closed.
 *
 *  @author Howard Ship
 *  @version $Id$
 */

public class NestedHTMLWriter extends HTMLWriter
{
	private IMarkupWriter _parent;
	private CharArrayWriter _internalBuffer;

	public NestedHTMLWriter(IMarkupWriter parent)
	{
		super(parent.getContentType());

		_parent = parent;

		_internalBuffer = new CharArrayWriter();

		setWriter(new PrintWriter(_internalBuffer));
	}

	/**
	*  Invokes the {@link HTMLWriter#close() super-class
	*  implementation}, then gets the data accumulated in the
	*  internal buffer and provides it to the containing writer using
	*  {@link IMarkupWriter#printRaw(char[], int, int)}.
	*
	*/

	public void close()
	{
		super.close();

		char[] data = _internalBuffer.toCharArray();

		_parent.printRaw(data, 0, data.length);

		_internalBuffer = null;
		_parent = null;
	}
}


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

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

  constructor() { }

  ngOnInit() {
  }

}


text:
package me.moxun.dreamcatcher.connector.jsonrpc.protocol;

import me.moxun.dreamcatcher.connector.jsonrpc.JsonRpcResult;

public class EmptyResult implements JsonRpcResult {
}


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('hamask', '0019_exercise_category'),
    ]

    operations = [
        migrations.AddField(
            model_name='workout_log',
            name='lifter',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='hamask.Lifter'),
        ),
        migrations.AlterField(
            model_name='exercise',
            name='category',
            field=models.CharField(blank=True, choices=[('MAIN', 'Main Lift'), ('MAIN_VARTN', 'Main Lift Variation'), ('COMPN_ACESR', 'Compound Accessory'), ('STRON', 'Strongman'), ('ISOLT_ACESR', 'Isolation')], max_length=30, null=True),
        ),
    ]


text:
/*!
 * Module dependencies.
 */

'use strict';

const MongooseError = require('./');

/*!
 * MissingSchema Error constructor.
 *
 * @inherits MongooseError
 */

function MissingSchemaError(name) {
  const msg = 'Schema hasn\'t been registered for model "' + name + '".\n'
          + 'Use mongoose.model(name, schema)';
  MongooseError.call(this, msg);
  this.name = 'MissingSchemaError';
  if (Error.captureStackTrace) {
    Error.captureStackTrace(this);
  } else {
    this.stack = new Error().stack;
  }
}

/*!
 * Inherits from MongooseError.
 */

MissingSchemaError.prototype = Object.create(MongooseError.prototype);
MissingSchemaError.prototype.constructor = MongooseError;

/*!
 * exports
 */

module.exports = MissingSchemaError;


text:
require 'spec_helper'

require 'runners/server_selection_rtt'

describe 'Server Selection moving average round trip time calculation' do

  include Mongo::ServerSelection::RTT

  SERVER_SELECTION_RTT_TESTS.each do |file|

    spec = Mongo::ServerSelection::RTT::Spec.new(file)

    context(spec.description) do

      let(:averager) do
        Mongo::Server::RoundTripTimeAverager.new
      end

      before do
        averager.instance_variable_set(:@average_round_trip_time, spec.average_rtt)
        averager.instance_variable_set(:@last_round_trip_time, spec.new_rtt)
        averager.send(:update_average_round_trip_time)
      end

      it 'correctly calculates the moving average round trip time' do
        expect(averager.average_round_trip_time).to eq(spec.new_average_rtt)
      end
    end
  end
end


text:
layout: post
title:  Season 5 Dates Announced!
date:   2017-05-24 08:00:00
categories: event
author: "Eric Wright"
---
The next season of Virtual Design Master is upon us.  We are happy to have all of the judges signed up and a growing list of great community sponsors.

We will be featuring this years excitement from June to August with our episodes being shown live on Thursdays at 8:00 PM Eastern time.  This year's introductory episode will be presented on June 22nd to introduce our competitors and to officially mark the start of the event.

Here are our live show dates for Virtual Design Master Season 5:

June 22 - Introduction for Season 5

June 29 - First challenge

July 6 - Judging and second challenge

July 13 - Judging and third challenge

July 20 - Judging and finall challenge issued

August 3 - Season finale and winner announcement

Each episode will be hosted on Google Hangouts and will be published directly to YouTube for viewing immediately after.  Being a part of the live event is fun and easy as you can follow along on on the [live page in real-time][livesite] and then see all the recordings as soon as they are completed on our [Season 5 page][season5site] on-demand.

Good luck to all of our Season 5 competitors.  We look forward to some exciting and challenging designs!

Virtual Design Master
Challenge. Learn. Share.

[season5site]:      http://virtualdesignmaster.com/season5.html
[livesite]:      	http://virtualdesignmaster.com/live.html


text:
namespace quic {

namespace {

// Maximum length of header name and header value.  This limits the amount of
// memory the peer can make the decoder allocate when sending string literals.
const size_t kStringLiteralLengthLimit = 1024 * 1024;

}  // namespace

QpackInstructionDecoder::QpackInstructionDecoder(const QpackLanguage* language,
                                                 Delegate* delegate)
    : language_(language),
      delegate_(delegate),
      s_bit_(false),
      varint_(0),
      varint2_(0),
      is_huffman_encoded_(false),
      string_length_(0),
      error_detected_(false),
      state_(State::kStartInstruction) {}

void QpackInstructionDecoder::Decode(QuicStringPiece data) {
  DCHECK(!data.empty());
  DCHECK(!error_detected_);

  while (true) {
    size_t bytes_consumed = 0;

    switch (state_) {
      case State::kStartInstruction:
        DoStartInstruction(data);
        break;
      case State::kStartField:
        DoStartField();
        break;
      case State::kReadBit:
        DoReadBit(data);
        break;
      case State::kVarintStart:
        bytes_consumed = DoVarintStart(data);
        break;
      case State::kVarintResume:
        bytes_consumed = DoVarintResume(data);
        break;
      case State::kVarintDone:
        DoVarintDone();
        break;
      case State::kReadString:
        bytes_consumed = DoReadString(data);
        break;
      case State::kReadStringDone:
        DoReadStringDone();
        break;
    }

    if (error_detected_) {
      return;
    }

    DCHECK_LE(bytes_consumed, data.size());

    data = QuicStringPiece(data.data() + bytes_consumed,
                           data.size() - bytes_consumed);

    // Stop processing if no more data but next state would require it.
    if (data.empty() && (state_ != State::kStartField) &&
        (state_ != State::kVarintDone) && (state_ != State::kReadStringDone)) {
      return;
    }
  }
}

bool QpackInstructionDecoder::AtInstructionBoundary() const {
  return state_ == State::kStartInstruction;
}

void QpackInstructionDecoder::DoStartInstruction(QuicStringPiece data) {
  DCHECK(!data.empty());

  instruction_ = LookupOpcode(data[0]);
  field_ = instruction_->fields.begin();

  state_ = State::kStartField;
}

void QpackInstructionDecoder::DoStartField() {
  if (field_ == instruction_->fields.end()) {
    // Completed decoding this instruction.

    if (!delegate_->OnInstructionDecoded(instruction_)) {
      error_detected_ = true;
      return;
    }

    state_ = State::kStartInstruction;
    return;
  }

  switch (field_->type) {
    case QpackInstructionFieldType::kSbit:
    case QpackInstructionFieldType::kName:
    case QpackInstructionFieldType::kValue:
      state_ = State::kReadBit;
      return;
    case QpackInstructionFieldType::kVarint:
    case QpackInstructionFieldType::kVarint2:
      state_ = State::kVarintStart;
      return;
  }
}

void QpackInstructionDecoder::DoReadBit(QuicStringPiece data) {
  DCHECK(!data.empty());

  switch (field_->type) {
    case QpackInstructionFieldType::kSbit: {
      const uint8_t bitmask = field_->param;
      s_bit_ = (data[0] & bitmask) == bitmask;

      ++field_;
      state_ = State::kStartField;

      return;
    }
    case QpackInstructionFieldType::kName:
    case QpackInstructionFieldType::kValue: {
      const uint8_t prefix_length = field_->param;
      DCHECK_GE(7, prefix_length);
      const uint8_t bitmask = 1 << prefix_length;
      is_huffman_encoded_ = (data[0] & bitmask) == bitmask;

      state_ = State::kVarintStart;

      return;
    }
    default:
      DCHECK(false);
  }
}

size_t QpackInstructionDecoder::DoVarintStart(QuicStringPiece data) {
  DCHECK(!data.empty());
  DCHECK(field_->type == QpackInstructionFieldType::kVarint ||
         field_->type == QpackInstructionFieldType::kVarint2 ||
         field_->type == QpackInstructionFieldType::kName ||
         field_->type == QpackInstructionFieldType::kValue);

  http2::DecodeBuffer buffer(data.data() + 1, data.size() - 1);
  http2::DecodeStatus status =
      varint_decoder_.Start(data[0], field_->param, &buffer);

  size_t bytes_consumed = 1 + buffer.Offset();
  switch (status) {
    case http2::DecodeStatus::kDecodeDone:
      state_ = State::kVarintDone;
      return bytes_consumed;
    case http2::DecodeStatus::kDecodeInProgress:
      state_ = State::kVarintResume;
      return bytes_consumed;
    case http2::DecodeStatus::kDecodeError:
      OnError("Encoded integer too large.");
      return bytes_consumed;
#if defined(STARBOARD)
    default:
      NOTREACHED();
      return 0;
#endif
  }
}

size_t QpackInstructionDecoder::DoVarintResume(QuicStringPiece data) {
  DCHECK(!data.empty());
  DCHECK(field_->type == QpackInstructionFieldType::kVarint ||
         field_->type == QpackInstructionFieldType::kVarint2 ||
         field_->type == QpackInstructionFieldType::kName ||
         field_->type == QpackInstructionFieldType::kValue);

  http2::DecodeBuffer buffer(data);
  http2::DecodeStatus status = varint_decoder_.Resume(&buffer);

  size_t bytes_consumed = buffer.Offset();
  switch (status) {
    case http2::DecodeStatus::kDecodeDone:
      state_ = State::kVarintDone;
      return bytes_consumed;
    case http2::DecodeStatus::kDecodeInProgress:
      DCHECK_EQ(bytes_consumed, data.size());
      DCHECK(buffer.Empty());
      return bytes_consumed;
    case http2::DecodeStatus::kDecodeError:
      OnError("Encoded integer too large.");
      return bytes_consumed;
  }
#if defined(STARBOARD)
  NOTREACHED();
  return 0;
#endif
}

void QpackInstructionDecoder::DoVarintDone() {
  DCHECK(field_->type == QpackInstructionFieldType::kVarint ||
         field_->type == QpackInstructionFieldType::kVarint2 ||
         field_->type == QpackInstructionFieldType::kName ||
         field_->type == QpackInstructionFieldType::kValue);

  if (field_->type == QpackInstructionFieldType::kVarint) {
    varint_ = varint_decoder_.value();

    ++field_;
    state_ = State::kStartField;
    return;
  }

  if (field_->type == QpackInstructionFieldType::kVarint2) {
    varint2_ = varint_decoder_.value();

    ++field_;
    state_ = State::kStartField;
    return;
  }

  string_length_ = varint_decoder_.value();
  if (string_length_ > kStringLiteralLengthLimit) {
    OnError("String literal too long.");
    return;
  }

  QuicString* const string =
      (field_->type == QpackInstructionFieldType::kName) ? &name_ : &value_;
  string->clear();

  if (string_length_ == 0) {
    ++field_;
    state_ = State::kStartField;
    return;
  }

  string->reserve(string_length_);

  state_ = State::kReadString;
}

size_t QpackInstructionDecoder::DoReadString(QuicStringPiece data) {
  DCHECK(!data.empty());
  DCHECK(field_->type == QpackInstructionFieldType::kName ||
         field_->type == QpackInstructionFieldType::kValue);

  QuicString* const string =
      (field_->type == QpackInstructionFieldType::kName) ? &name_ : &value_;
  DCHECK_LT(string->size(), string_length_);

  size_t bytes_consumed =
      std::min(string_length_ - string->size(), data.size());
  string->append(data.data(), bytes_consumed);

  DCHECK_LE(string->size(), string_length_);
  if (string->size() == string_length_) {
    state_ = State::kReadStringDone;
  }
  return bytes_consumed;
}

void QpackInstructionDecoder::DoReadStringDone() {
  DCHECK(field_->type == QpackInstructionFieldType::kName ||
         field_->type == QpackInstructionFieldType::kValue);

  QuicString* const string =
      (field_->type == QpackInstructionFieldType::kName) ? &name_ : &value_;
  DCHECK_EQ(string->size(), string_length_);

  if (is_huffman_encoded_) {
    huffman_decoder_.Reset();
    // HpackHuffmanDecoder::Decode() cannot perform in-place decoding.
    QuicString decoded_value;
    huffman_decoder_.Decode(*string, &decoded_value);
    if (!huffman_decoder_.InputProperlyTerminated()) {
      OnError("Error in Huffman-encoded string.");
      return;
    }
    *string = std::move(decoded_value);
  }

  ++field_;
  state_ = State::kStartField;
}

const QpackInstruction* QpackInstructionDecoder::LookupOpcode(
    uint8_t byte) const {
  for (const auto* instruction : *language_) {
    if ((byte & instruction->opcode.mask) == instruction->opcode.value) {
      return instruction;
    }
  }
  // |language_| should be defined such that instruction opcodes cover every
  // possible input.
  DCHECK(false);
  return nullptr;
}

void QpackInstructionDecoder::OnError(QuicStringPiece error_message) {
  DCHECK(!error_detected_);

  error_detected_ = true;
  delegate_->OnError(error_message);
}

}  // namespace quic


text:
require 'rails_helper'

describe SessionsController, type: :controller do
  describe 'GET new' do
    before do
      get :new
    end

    it { is_expected.to redirect_to('/auth/github') }
  end

  describe 'GET destroy' do
    before do
      session[:user_id] = 1
      get :destroy
    end

    it { is_expected.to set_session(:user_id).to(nil) }
    it { is_expected.to redirect_to(root_path) }
  end

  describe 'GET failure' do
    before do
      get :failure, message: 'foobar'
    end

    it { is_expected.to set_the_flash[:notice].to('foobar') }
    it { is_expected.to redirect_to(root_path) }
  end
end


text:
from distutils.core import setup

setup(name='kao_operators',
      version='0.0.1',
      description="",
      author='',
      author_email='',
      packages=['kao_operators'],
     )


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace FPS.ViewModels.Timekeeping
{
    public class AttendanceSummary
    {
        public string EmployeeName { get; set; }
        public DateTime From { get; set; }
        public WorkTime Late { get; set; }
        public WorkTime Overtime { get; set; }
        public DateTime To { get; set; }
        public WorkTime Undertime { get; set; }
        public WorkTime Worktime { get; set; }
        public ICollection<TimeAttendance> Attendance { get; set; }

        public AttendanceSummary()
        {
            Attendance = new HashSet<TimeAttendance>();
        }

        public static ICollection<AttendanceSummary> Create(IEnumerable<TimeAttendance> collection)
        {
            return collection.GroupBy(q => q.EmployeeName)
                .Select(q => new AttendanceSummary
                {
                    EmployeeName = q.Key,
                    From = q.Min(t => t.Date),
                    To = q.Max(t => t.Date),
                    Worktime = WorkTime.Parse(q.Select(t => t.Worktime).ToList()),
                    Overtime = WorkTime.Parse(q.Select(t => t.Overtime).ToList()),
                    Late = WorkTime.Parse(q.Select(t => t.Late).ToList()),
                    Undertime = WorkTime.Parse(q.Select(t => t.Undertime).ToList()),
                    Attendance = q.OrderBy(t => t.Date).ToList()
                }).OrderBy(q => q.EmployeeName).ToList();
        }
    }
}


text:
description: Enable client-side transitions between routes with the built-in Link component.
---

# next/link

  Examples

Hello World

Active className on Link

> Before moving forward, we recommend you to read [Routing Introduction](/docs/routing/introduction.md) first.

Client-side transitions between routes can be enabled via the `Link` component exported by `next/link`.

For an example, consider a `pages` directory with the following files:

- `pages/index.js`
- `pages/about.js`
- `pages/blog/[slug].js`

We can have a link to each of these pages like so:

```jsx
import Link from 'next/link'

function Home() {
  return (
    <ul>
      <li>
        <Link href="/">
          <a>Home</a>
        </Link>
      </li>
      <li>
        <Link href="/about">
          <a>About Us</a>
        </Link>
      </li>
      <li>
        <Link href="/blog/hello-world">
          <a>Blog Post</a>
        </Link>
      </li>
    </ul>
  )
}

export default Home
```

`Link` accepts the following props:

- `href` - The path or URL to navigate to. This is the only required prop
- `as` - Optional decorator for the path that will be shown in the browser URL bar. Before Next.js 9.5.3 this was used for dynamic routes, check our [previous docs](https://nextjs.org/docs/tag/v9.5.2/api-reference/next/link#dynamic-routes) to see how it worked. Note: when this path differs from the one provided in `href` the previous `href`/`as` behavior is used as shown in the [previous docs](https://nextjs.org/docs/tag/v9.5.2/api-reference/next/link#dynamic-routes).
- [`passHref`](#if-the-child-is-a-custom-component-that-wraps-an-a-tag) - Forces `Link` to send the `href` property to its child. Defaults to `false`
- `prefetch` - Prefetch the page in the background. Defaults to `true`. Any `<Link />` that is in the viewport (initially or through scroll) will be preloaded. Prefetch can be disabled by passing `prefetch={false}`. When `prefetch` is set to `false`, prefetching will still occur on hover. Pages using [Static Generation](/docs/basic-features/data-fetching/get-static-props.md) will preload `JSON` files with the data for faster page transitions. Prefetching is only enabled in production.
- [`replace`](#replace-the-url-instead-of-push) - Replace the current `history` state instead of adding a new url into the stack. Defaults to `false`
- [`scroll`](#disable-scrolling-to-the-top-of-the-page) - Scroll to the top of the page after a navigation. Defaults to `true`
- [`shallow`](/docs/routing/shallow-routing.md) - Update the path of the current page without rerunning [`getStaticProps`](/docs/basic-features/data-fetching/get-static-props.md), [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md) or [`getInitialProps`](/docs/api-reference/data-fetching/get-initial-props.md). Defaults to `false`
- `locale` - The active locale is automatically prepended. `locale` allows for providing a different locale. When `false` `href` has to include the locale as the default behavior is disabled.

## If the route has dynamic segments

There is nothing to do when linking to a [dynamic route](/docs/routing/dynamic-routes.md), including [catch all routes](/docs/routing/dynamic-routes.md#catch-all-routes), since Next.js 9.5.3 (for older versions check our [previous docs](https://nextjs.org/docs/tag/v9.5.2/api-reference/next/link#dynamic-routes)). However, it can become quite common and handy to use [interpolation](/docs/routing/introduction.md#linking-to-dynamic-paths) or an [URL Object](#with-url-object) to generate the link.

For example, the dynamic route `pages/blog/[slug].js` will match the following link:

```jsx
import Link from 'next/link'

function Posts({ posts }) {
  return (
    <ul>
      {posts.map((post) => (
        <li key={post.id}>
          <Link href={`/blog/${encodeURIComponent(post.slug)}`}>
            <a>{post.title}</a>
          </Link>
        </li>
      ))}
    </ul>
  )
}

export default Posts
```

## If the child is a custom component that wraps an `<a>` tag

If the child of `Link` is a custom component that wraps an `<a>` tag, you must add `passHref` to `Link`. This is necessary if you're using libraries like [styled-components](https://styled-components.com/). Without this, the `<a>` tag will not have the `href` attribute, which hurts your site's accessibility and might affect SEO. If you're using [ESLint](/docs/basic-features/eslint.md#eslint-plugin), there is a built-in rule `next/link-passhref` to ensure correct usage of `passHref`.

```jsx
import Link from 'next/link'
import styled from 'styled-components'

// This creates a custom component that wraps an <a> tag
const RedLink = styled.a`
  color: red;
`

function NavLink({ href, name }) {
  // Must add passHref to Link
  return (
    <Link href={href} passHref>
      <RedLink>{name}</RedLink>
    </Link>
  )
}

export default NavLink
```

- If you're using [emotion](https://emotion.sh/)'s JSX pragma feature (`@jsx jsx`), you must use `passHref` even if you use an `<a>` tag directly.
- The component should support `onClick` property to trigger navigation correctly

## If the child is a functional component

If the child of `Link` is a functional component, in addition to using `passHref`, you must wrap the component in [`React.forwardRef`](https://reactjs.org/docs/react-api.html#reactforwardref):

```jsx
import Link from 'next/link'

// `onClick`, `href`, and `ref` need to be passed to the DOM element
// for proper handling
const MyButton = React.forwardRef(({ onClick, href }, ref) => {
  return (
    <a href={href} onClick={onClick} ref={ref}>
      Click Me
    </a>
  )
})

function Home() {
  return (
    <Link href="/about" passHref>
      <MyButton />
    </Link>
  )
}

export default Home
```

## With URL Object

`Link` can also receive a URL object and it will automatically format it to create the URL string. Here's how to do it:

```jsx
import Link from 'next/link'

function Home() {
  return (
    <ul>
      <li>
        <Link
          href={{
            pathname: '/about',
            query: { name: 'test' },
          }}
        >
          <a>About us</a>
        </Link>
      </li>
      <li>
        <Link
          href={{
            pathname: '/blog/[slug]',
            query: { slug: 'my-post' },
          }}
        >
          <a>Blog Post</a>
        </Link>
      </li>
    </ul>
  )
}

export default Home
```

The above example has a link to:

- A predefined route: `/about?name=test`
- A [dynamic route](/docs/routing/dynamic-routes.md): `/blog/my-post`

You can use every property as defined in the [Node.js URL module documentation](https://nodejs.org/api/url.html#url_url_strings_and_url_objects).

## Replace the URL instead of push

The default behavior of the `Link` component is to `push` a new URL into the `history` stack. You can use the `replace` prop to prevent adding a new entry, as in the following example:

```jsx
<Link href="/about" replace>
  <a>About us</a>
</Link>
```

## Disable scrolling to the top of the page

The default behavior of `Link` is to scroll to the top of the page. When there is a hash defined it will scroll to the specific id, like a normal `<a>` tag. To prevent scrolling to the top / hash `scroll={false}` can be added to `Link`:

```jsx
<Link href="/#hashid" scroll={false}>
  <a>Disables scrolling to the top</a>
</Link>
```


text:
namespace ash {
namespace tether {

class TestTimerFactory : public TimerFactory {
 public:
  TestTimerFactory();
  ~TestTimerFactory() override;

  // TimerFactory:
  std::unique_ptr<base::OneShotTimer> CreateOneShotTimer() override;

  void set_device_id_for_next_timer(
      const std::string& device_id_for_next_timer) {
    device_id_for_next_timer_ = device_id_for_next_timer;
  }

  base::MockOneShotTimer* GetTimerForDeviceId(const std::string& device_id) {
    return device_id_to_timer_map_[device_id_for_next_timer_];
  }

  void ClearTimerForDeviceId(const std::string& device_id) {
    device_id_to_timer_map_.erase(device_id_for_next_timer_);
  }

 private:
  std::string device_id_for_next_timer_;
  base::flat_map<std::string, base::MockOneShotTimer*> device_id_to_timer_map_;
};

}  // namespace tether
}  // namespace ash

#endif  // CHROMEOS_ASH_COMPONENTS_TETHER_TEST_TIMER_FACTORY_H_


text:
import { __decorate, __metadata } from "tslib";
import * as au from "../aurelia";
let MdNavbar = class MdNavbar {
    constructor(element) {
        this.element = element;
    }
    attached() {
        this.fixedAttributeManager = new au.AttributeManager(this.fixedAnchor);
        this.navAttributeManager = new au.AttributeManager(this.nav);
        if (this.fixed) {
            this.fixedAttributeManager.addClasses("navbar-fixed");
        }
        if (this.autoHeight) {
            this.navAttributeManager.addClasses("auto-height");
        }
        if (this.extended) {
            this.navAttributeManager.addClasses("nav-extended");
        }
    }
    detached() {
        if (this.fixed) {
            this.fixedAttributeManager.removeClasses("navbar-fixed");
        }
        if (this.autoHeight) {
            this.navAttributeManager.removeClasses("auto-height");
        }
        if (this.extended) {
            this.navAttributeManager.removeClasses("nav-extended");
        }
    }
};
__decorate([
    au.ato.bindable.booleanMd({ defaultBindingMode: au.bindingMode.oneTime }),
    __metadata("design:type", Boolean)
], MdNavbar.prototype, "extended", void 0);
__decorate([
    au.ato.bindable.booleanMd({ defaultBindingMode: au.bindingMode.oneTime }),
    __metadata("design:type", Boolean)
], MdNavbar.prototype, "fixed", void 0);
__decorate([
    au.ato.bindable.booleanMd({ defaultBindingMode: au.bindingMode.oneTime }),
    __metadata("design:type", Boolean)
], MdNavbar.prototype, "autoHeight", void 0);
MdNavbar = __decorate([
    au.customElement("md-navbar"),
    au.autoinject,
    __metadata("design:paramtypes", [Element])
], MdNavbar);
export { MdNavbar };
//# sourceMappingURL=navbar.js.map