text:
#region License

#endregion License

using System;
using System.Text;

using JsonFx.Json;
using JsonFx.Serialization;
using Xunit;

using Assert=JsonFx.AssertPatched;

namespace JsonFx.Bson
{
	public class BsonConverterTests
	{
		#region Constants

		private const string TraitName = "BSON";
		private const string TraitValue = "Conversion";

		#endregion Constants

		#region Round Trip Tests

		[Fact]
		[Trait(TraitName, TraitValue)]
		public void ConvertJson2Bson_HelloWorld_RoundTripsJsonToBsonAndBack()
		{
			// input from example at http://bsonspec.org/#/specification
			var inputText =
@"{
	""hello"" : ""world""
}";

			var expectedBinary = Encoding.UTF8.GetBytes(
				"\x16\x00\x00\x00\x02hello\x00"+
				"\x06\x00\x00\x00world\x00\x00");

			var expectedText = @"{""hello"":""world""}";

			var jsonTokenizer = new JsonReader.JsonTokenizer();
			var tokens1 = jsonTokenizer.GetTokens(inputText);

			var bsonFormatter = new BsonWriter.BsonFormatter();
			var actualBinary = bsonFormatter.Format(tokens1);

			Assert.Equal(expectedBinary, actualBinary);

			var bsonTokenizer = new BsonReader.BsonTokenizer();
			var tokens2 = bsonTokenizer.GetTokens(actualBinary);

			var jsonFormatter = new JsonWriter.JsonFormatter(new DataWriterSettings { PrettyPrint = false });
			var actualText = jsonFormatter.Format(tokens2);

			Assert.Equal(expectedText, actualText);
		}

		[Fact]
		[Trait(TraitName, TraitValue)]
		public void ConvertJson2Bson_ArrayAsProperty_RoundTripsJsonToBsonAndBack()
		{
			// input from example at http://bsonspec.org/#/specification
			var inputText =
@"{
	""BSON"" : [
		""awesome"",
		5.05,
		1986
	]
}";

			var expectedBinary = new byte[]
			{
				0x31, 0x00, 0x00, 0x00,
				0x04, (byte)'B', (byte)'S', (byte)'O', (byte)'N', 0x00,
				0x26, 0x00, 0x00, 0x00,
					0x02, (byte)'0', 0, 0x08, 0x00, 0x00, 0x00, (byte)'a', (byte)'w', (byte)'e', (byte)'s', (byte)'o', (byte)'m', (byte)'e', 0x00,
					0x01, (byte)'1', 0, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x14, 0x40,
					0x10, (byte)'2', 0, 0xC2, 0x07, 0x00, 0x00,
				0x00,
				0x00
			};

			var expectedText = @"{""BSON"":[""awesome"",5.05,1986]}";

			var jsonTokenizer = new JsonReader.JsonTokenizer();
			var tokens1 = jsonTokenizer.GetTokens(inputText);

			var bsonFormatter = new BsonWriter.BsonFormatter();
			var actualBinary = bsonFormatter.Format(tokens1);

			Assert.Equal(expectedBinary, actualBinary);

			var bsonTokenizer = new BsonReader.BsonTokenizer();
			var tokens2 = bsonTokenizer.GetTokens(actualBinary);

			var jsonFormatter = new JsonWriter.JsonFormatter(new DataWriterSettings { PrettyPrint = false });
			var actualText = jsonFormatter.Format(tokens2);

			Assert.Equal(expectedText, actualText);
		}

		[Fact]
		[Trait(TraitName, TraitValue)]
		public void ConvertJson2Bson_BooleanValue_RoundTripsJsonToBsonAndBack()
		{
			// input from example at http://codebetter.com/blogs/karlseguin/archive/2010/03/05/bson-serialization.aspx
			var inputText = @"{valid:true}";

			var expectedBinary = new byte[]
				{
					13, 0, 0, 0, 8, 118, 97, 108, 105, 100, 0, 1, 0
				};

			var expectedText =
@"{
	""valid"" : true
}";

			var jsonTokenizer = new JsonReader.JsonTokenizer();
			var tokens1 = jsonTokenizer.GetTokens(inputText);

			var bsonFormatter = new BsonWriter.BsonFormatter();
			var actualBinary = bsonFormatter.Format(tokens1);

			Assert.Equal(expectedBinary, actualBinary);

			var bsonTokenizer = new BsonReader.BsonTokenizer();
			var tokens2 = bsonTokenizer.GetTokens(actualBinary);

			var jsonFormatter = new JsonWriter.JsonFormatter(new DataWriterSettings { PrettyPrint = true });
			var actualText = jsonFormatter.Format(tokens2);

			Assert.Equal(expectedText, actualText);
		}

		#endregion Round Trip Tests
	}
}


text:
        <slot name="prepend" />

            -

            <slot name="prefix" />

        <input
            v-bind="$attrs"
            :value="value"
            ref="input"
            :name="name"
            :id="id"
            type="text"
            :tabindex="tabIndex"
            :disabled="isDisabled"
            :aria-disabled="isDisabled ? 'true' : false"
            :readonly="isReadonly"
            :aria-readonly="isReadonly ? 'true' : false"
            @input="onInput"
            @blur="onBlur"
        >

            <slot name="clearable" :clear="onClear">

            </slot>
            <slot name="suffix" />

            +

        <slot name="append" />

redpajama_set_name: RedPajamaGithub


text:
#ifndef DIOS_DB_COMMIT_OBJECT_H
#define DIOS_DB_COMMIT_OBJECT_H

#include "dios_db_custom_lib.h"

#include "dios/platform.h"

NS_DS_BEGIN

// Ìύ״̬;
enum DatabaseCommitStatus
{
	kDatabaseCommitStatusNone,
	kDatabaseCommitStatusInsert,
	kDatabaseCommitStatusUpdate,
	kDatabaseCommitStatusDelete,
};

/*
 *	Êý¾ÝÌá½»¶ÔÏó;
 */
class DIOS_DB_CUSTOM_DECL CDatabaseCommitObject
{
public:
	CDatabaseCommitObject(void);
	CDatabaseCommitObject(DatabaseCommitStatus commit_status);
	virtual ~CDatabaseCommitObject(void);

	inline DatabaseCommitStatus commit_status(void) { return commit_status_; }

	// Ìá½»º¯Êý;
	void Commit(std::function<void(ds_boolean)> func);

	// ɾ³ý¼Ç¼º¯Êý;
	void set_deleted(void);

	// ÊÇ·ñÒѾÉ¾³ý;
	ds_boolean is_deleted(void);

	// Ìá½»º¯Êý;
	virtual void CommitInsert(std::function<void(ds_boolean)> func) {}
	virtual void CommitUpdate(std::function<void(ds_boolean)> func) {}
	virtual void CommitDelete(std::function<void(ds_boolean)> func) {}

protected:
	DatabaseCommitStatus commit_status_;
};

NS_DS_END

#endif


text:
package com.francetelecom.clara.cloud.sample.probe.jee;

import java.io.Serializable;

public class JeeMemoryUsage implements Serializable {

	private static final long serialVersionUID = 9004825875791737675L;

	/**
	 * maxHeapSize in bytes
	 */
	long maxHeapSize;
	/**
	 * usedHeapSize in bytes
	 */
	long usedHeapSize;

	/**
	 * @return maxHeapSize in bytes
	 */
	public long getMaxHeapSize() {
		return maxHeapSize;
	}

	public void setMaxHeapSize(long maxHeapSize) {
		this.maxHeapSize = maxHeapSize;
	}

	/**
	 * @return usedHeapSize in bytes
	 */
	public long getUsedHeapSize() {
		return usedHeapSize;
	}
	public void setUsedHeapSize(long usedHeapSize) {
		this.usedHeapSize = usedHeapSize;
	}

}


text:
package com.jakewharton.rxbinding2.support.v4.view;

import android.support.v4.view.MenuItemCompat.OnActionExpandListener;
import android.view.MenuItem;
import com.jakewharton.rxbinding2.view.MenuItemActionViewCollapseEvent;
import com.jakewharton.rxbinding2.view.MenuItemActionViewEvent;
import com.jakewharton.rxbinding2.view.MenuItemActionViewExpandEvent;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.MainThreadDisposable;
import io.reactivex.functions.Predicate;

import static android.support.v4.view.MenuItemCompat.setOnActionExpandListener;
import static com.jakewharton.rxbinding2.internal.Preconditions.checkMainThread;

final class MenuItemActionViewEventObservable extends Observable<MenuItemActionViewEvent> {
  private final MenuItem menuItem;
  private final Predicate<? super MenuItemActionViewEvent> handled;

  MenuItemActionViewEventObservable(MenuItem menuItem,
      Predicate<? super MenuItemActionViewEvent> handled) {
    this.menuItem = menuItem;
    this.handled = handled;
  }

  @Override protected void subscribeActual(Observer<? super MenuItemActionViewEvent> observer) {
    if (!checkMainThread(observer)) {
      return;
    }
    Listener listener = new Listener(menuItem, handled, observer);
    observer.onSubscribe(listener);
    setOnActionExpandListener(menuItem, listener);
  }

  static final class Listener extends MainThreadDisposable implements OnActionExpandListener {
    private final MenuItem menuItem;
    private final Predicate<? super MenuItemActionViewEvent> handled;
    private final Observer<? super MenuItemActionViewEvent> observer;

    Listener(MenuItem menuItem, Predicate<? super MenuItemActionViewEvent> handled,
        Observer<? super MenuItemActionViewEvent> observer) {
      this.menuItem = menuItem;
      this.handled = handled;
      this.observer = observer;
    }

    @Override public boolean onMenuItemActionExpand(MenuItem item) {
      return onEvent(MenuItemActionViewExpandEvent.create(item));
    }

    @Override public boolean onMenuItemActionCollapse(MenuItem item) {
      return onEvent(MenuItemActionViewCollapseEvent.create(item));
    }

    private boolean onEvent(MenuItemActionViewEvent event) {
      if (!isDisposed()) {
        try {
          if (handled.test(event)) {
            observer.onNext(event);
            return true;
          }
        } catch (Exception e) {
          observer.onError(e);
          dispose();
        }
      }
      return false;
    }

    @Override protected void onDispose() {
      setOnActionExpandListener(menuItem, null);
    }
  }
}


text:
'use strict'

const { isClassified } = require('./pontuations')

const countIssuesByType = ( issues, type ) =>
    issues.reduce( (total, issue ) => issue.type === type ? total + 1 : total, 0 )

const countIssuesByDifficulty = ( issues, difficulty ) =>
    issues.reduce( (total, issue ) => issue.difficulty === difficulty && isClassified(issue.type) ? total + 1 : total, 0 )

const sumPontuation = ( issues ) =>
    issues.reduce( (total, issue ) => isClassified(issue.type) ? total + issue.pontuation : total, 0 )

const sumTime = ( issues, type ) =>
    issues.reduce( (total, issue ) => issue.type === type ? total + issue.time : total, 0 )

const minutesToPoints = ( minutes, pointsPerHour ) => Math.round( ( minutes * (pointsPerHour / 60) ) )
const pointsPercentage = ( goal, points ) => ( (points * 100) / goal ).toFixed(2);
const hasScore = ( issue ) => issue.pontuation > 0 && isClassified(issue.type)
const scoredIssues = ( issues ) => issues.filter( issue => hasScore( issue ) )

module.exports = {
    countIssuesByType,
    countIssuesByDifficulty,
    sumPontuation,
    sumTime,
    hasScore,
    scoredIssues,
    minutesToPoints,
    pointsPercentage
}


text:
<?php

class IPF_Form_Widget_HiddenInput extends IPF_Form_Widget_Input
{
    public $input_type = 'hidden';
    public $is_hidden = true;
}


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Text;
using System.Threading.Tasks;

namespace Microsoft.WindowsAzure.Commands.SqlDatabase.Test.Utilities
{
    /// <summary>
    /// Custom implementation of the PSHostUserInterface to allow handling input in tests.
    /// </summary>
    public class SqlCustomPsHostUserInterface : PSHostUserInterface
    {
        /// <summary>
        /// Gets or sets an array of the inputs to supply to the prompt (in order)
        /// </summary>
        public PSObject[] PromptInputs { get; set; }

        /// <summary>
        /// Gets or sets the index of the option to choose when the user is prompted to choose from a list of options.
        /// </summary>
        public int PromptForChoiceInputIndex { get; set; }

        /// <summary>
        /// Default constructor.
        /// </summary>
        public SqlCustomPsHostUserInterface()
        {
            PromptForChoiceInputIndex = -1;
        }

        /// <summary>
        /// This is called when a parameter wasn't supplied for a cmdlet.  This will be called to prompt the user for the needed value.
        /// Here we use the values in PromptInputs instead of getting them from the user.
        /// </summary>
        /// <param name="caption">The caption for the prompt</param>
        /// <param name="message">The message to show the user</param>
        /// <param name="descriptions">The names of all the fields that need input</param>
        /// <returns>A dictionary containing the response from the user with the FieldDescription.Name as the key</returns>
        public override Dictionary<string, System.Management.Automation.PSObject> Prompt(string caption, string message, System.Collections.ObjectModel.Collection<FieldDescription> descriptions)
        {
            Assert.IsNotNull(PromptInputs);
            Assert.AreEqual(PromptInputs.Length, descriptions.Count, "The number of Prompt inputs needs to be the same as the number of prompts");

            Dictionary<string, PSObject> ret = new Dictionary<string, PSObject>();
            for (int i = 0; i < descriptions.Count; i++)
            {
                ret.Add(descriptions[i].Name, PromptInputs[i]);
            }
            return ret;
        }

        /// <summary>
        /// This is called when the user needs to select an option from a list (eg: "Are you sure you want to continue: Yes, No").
        /// Instead of getting the input from the user we get the index of the option to choose from the value of PromptForChoiceInputIndex.
        /// </summary>
        /// <param name="caption">The caption for the request for input</param>
        /// <param name="message">The message to show</param>
        /// <param name="choices">The list of available choices</param>
        /// <param name="defaultChoice">The default choice.</param>
        /// <returns>The index of the choice that was selected</returns>
        public override int PromptForChoice(string caption, string message, System.Collections.ObjectModel.Collection<ChoiceDescription> choices, int defaultChoice)
        {
            Assert.IsTrue(PromptForChoiceInputIndex < choices.Count, "Must provide an index within the range of choices.");
            Assert.IsTrue(PromptForChoiceInputIndex >= 0, "Cannot have a negative index");

            return PromptForChoiceInputIndex;
        }

        /// <summary>
        /// Not needed
        /// </summary>
        public override System.Management.Automation.PSCredential PromptForCredential(string caption, string message, string userName, string targetName, System.Management.Automation.PSCredentialTypes allowedCredentialTypes, System.Management.Automation.PSCredentialUIOptions options)
        {
            return null;
        }

        /// <summary>
        /// Not needed
        /// </summary>
        public override System.Management.Automation.PSCredential PromptForCredential(string caption, string message, string userName, string targetName)
        {
            return null;
        }

        /// <summary>
        /// Not needed
        /// </summary>
        public override PSHostRawUserInterface RawUI
        {
            get { return null; }
        }

        /// <summary>
        /// Reads a line from input.  Not used.
        /// </summary>
        /// <returns></returns>
        public override string ReadLine()
        {
            return Console.ReadLine();
        }

        /// <summary>
        /// Not needed
        /// </summary>
        public override System.Security.SecureString ReadLineAsSecureString()
        {
            throw new NotImplementedException();
        }
        /// <summary>
        /// Writes information to the console.
        /// </summary>
        /// <param name="foregroundColor">The foreground color to use</param>
        /// <param name="backgroundColor">The background color to use</param>
        /// <param name="value">What to write to the console</param>
        public override void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value)
        {
            var fg = Console.ForegroundColor;
            var bg = Console.BackgroundColor;
            Console.ForegroundColor = foregroundColor;
            Console.BackgroundColor = backgroundColor;
            Console.Write(value);
            Console.ForegroundColor = fg;
            Console.BackgroundColor = bg;
        }

        /// <summary>
        /// Write a string to the console
        /// </summary>
        /// <param name="value">The string to display</param>
        public override void Write(string value)
        {
            Console.Write(value);
        }

        /// <summary>
        /// Write debug information to the console.
        /// </summary>
        /// <param name="message">The debug message to display</param>
        public override void WriteDebugLine(string message)
        {
            DebugRecord r = new DebugRecord(message);
            Console.WriteLine(r);
        }

        /// <summary>
        /// Dispays an error to the console
        /// </summary>
        /// <param name="value">The error to display</param>
        public override void WriteErrorLine(string value)
        {
            Console.Error.Write(value);
        }

        /// <summary>
        /// Write a line to the console.
        /// </summary>
        /// <param name="value">The string to write</param>
        public override void WriteLine(string value)
        {
            Console.WriteLine(value);
        }

        /// <summary>
        /// Not needed
        /// </summary>
        public override void WriteProgress(long sourceId, System.Management.Automation.ProgressRecord record)
        {
        }

        /// <summary>
        /// Write verbose message to the console
        /// </summary>
        /// <param name="message">The message to display</param>
        public override void WriteVerboseLine(string message)
        {
            Console.WriteLine("VERBOSE: " + message);
        }

        /// <summary>
        /// Write a warning to the screen
        /// </summary>
        /// <param name="message">The warning to display</param>
        public override void WriteWarningLine(string message)
        {
            Console.WriteLine("WARNING: " + message);
        }
    }
}


text:
class CreateEvaluationResponses < ActiveRecord::Migration
  def self.up
    create_table :evaluation_responses do |t|
      t.integer :evaluation_id
      t.integer :evaluation_question_id
      t.text :response
      t.integer :creator_id
      t.integer :updater_id

      t.timestamps
    end
  end

  def self.down
    drop_table :evaluation_responses
  end
end


text:
namespace AddinX.Ribbon.Contract.Control.Button
{
    public interface IButtonLabel
    {
        IButtonExtra ShowLabel();

        IButtonExtra HideLabel();
    }
}


text:
package org.jboss.weld.tests.beanManager.beanAttributes;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.inject.Qualifier;

@Qualifier
@Target({ TYPE, METHOD, PARAMETER, FIELD })
@Retention(RUNTIME)
public @interface Natural {
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>game.logic</title>
<meta name="date" content="2015-10-14">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package game.logic

Class Summary

Class
Description

Level

Represents the level that the game is played on.

Player

Represents a player in the game.

Room

SpawnPoint

StealthGame

Main logic class, runs the actual game.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
count = 3
count = 8
x = count
count += 1
print("count is {} and x is {}".format(count, x))


text:
class API::V1::SessionsController < Devise::SessionsController
  include ApplicationHelper
  include Devise::Controllers::Helpers

  respond_to :json

  prepend_before_filter :require_no_authentication, :only => [:create]
  skip_before_filter :verify_authenticity_token, :if => Proc.new { |c| c.request.format == 'application/json' }
  before_filter :authenticate_user_from_token!, :except => :create

  def create
    return failure unless params[:user]
    resource = User.find_for_database_authentication(:email => params[:user][:email])
    return failure unless resource
    return render json: { :user => {:id => resource.id, :email => resource.email}, errors: ["api.v1.user.unconfirmed_user"]}, :status => "403" unless resource.confirmed?

    if resource.valid_password?(params[:user][:password])
      sign_in(:user, resource)
      resource.ensure_authentication_token!
      render :json=> {:success => true, :authentication_token => resource.authentication_token, :id => resource.id}
      return
    end
    failure
  end

  def destroy
    resource = current_user
    resource.reset_authentication_token!
    Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name)
    render :status => 200, :json => {:success => true}
  end

  def failure
    return render json: { success: false, errors: ['api.v1.sessions.invalid_login'] }, :status => :unauthorized
  end

end


text:
package powermock.examples.staticmocking;

import java.util.HashMap;
import java.util.Map;

public class ServiceRegistrator
{
   /**
    * Holds all services registrations that has been registered by this service registrator.
    */
   private final Map<Long, Object> serviceRegistrations = new HashMap<Long, Object>();

   public long registerService(Object service)
   {
      long id = IdGenerator.generateNewId();
      serviceRegistrations.put(id, service);
      return id;
   }
}


text:
<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/maven-v4_0_0.xsd">

    <groupId>org.dborm.core</groupId>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>dborm-core</artifactId>
    <packaging>jar</packaging>
    <version>1.1.5-SNAPSHOT</version>
    <name>${project.artifactId}</name>
    <url>http://www.dborm.org</url>

    <dependencies>

        <!--测试相关的依赖开始-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
            <scope>test</scope>
        </dependency>
        <!--测试相关的依赖结束-->

        <!--数据库相关的依赖开始-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.26</version>
            <scope>test</scope>
        </dependency>
        <dependency> <!--数据库事务-->
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.11</version>
            <scope>test</scope>
        </dependency>
        <!--数据库相关的依赖结束-->

    </dependencies>

    <build>
        <finalName>${project.artifactId}</finalName>

        <plugins>
            <!-- 拷贝依赖的jar包到lib目录 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>
                                ${project.build.directory}/lib
                            </outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <!-- 解决资源文件的编码问题 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <!-- 打包source文件为jar文件 -->
            <plugin>
                <artifactId>maven-source-plugin</artifactId>
                <configuration>
                    <attach>true</attach>
                </configuration>
                <executions>
                    <execution>
                        <phase>compile</phase>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>

    </build>

    <!-- 配置部署的远程仓库 -->
    <distributionManagement>
        <snapshotRepository>
            <id>nexus-snapshots</id>
            <name>nexus distribution snapshot repository</name>
            <!--要发布到snapshots仓库,构件的version必须以SNAPSHOT结尾才可以-->
            <url>http://112.124.54.136:6001/nexus/content/repositories/snapshots/</url>
        </snapshotRepository>
    </distributionManagement>

</project>


text:
import os
import random

# project
from config import get_confd_path
from util import check_yaml
from utils.singleton import Singleton

class NTPUtil():
    __metaclass__ = Singleton

    DEFAULT_VERSION = 3
    DEFAULT_TIMEOUT = 1  # in seconds
    DEFAULT_PORT = "ntp"

    def __init__(self, config=None):
        try:
            if config:
                ntp_config = config
            else:
                ntp_config = check_yaml(os.path.join(get_confd_path(), 'ntp.yaml'))
            settings = ntp_config['instances'][0]
        except Exception:
            settings = {}

        self.host = settings.get('host') or "{0}.datadog.pool.ntp.org".format(random.randint(0, 3))
        self.version = int(settings.get("version") or NTPUtil.DEFAULT_VERSION)
        self.port = settings.get('port') or NTPUtil.DEFAULT_PORT
        self.timeout = float(settings.get('timeout') or NTPUtil.DEFAULT_TIMEOUT)

        self.args = {
            'host':    self.host,
            'port':    self.port,
            'version': self.version,
            'timeout': self.timeout,
        }

    @classmethod
    def _drop(cls):
        if cls in cls._instances:
            del cls._instances[cls]


text:
package org.sirix.diff;

import org.checkerframework.checker.nullness.qual.NonNull;
import org.sirix.diff.DiffFactory.DiffType;

/**
 * Interface for observers, which are listening for diffs.
 *
 * @author Johannes Lichtenberger, University of Konstanz
 *
 */
public interface DiffObserver {
  /**
   * Called for every node comparsion.
   *
   * @param diffType the {@link DiffType} type
   * @param newNodeKey node key of node in new revision
   * @param oldNodeKey node key of node in old revision
   * @param depth current {@link DiffDepth} instance
   */
  void diffListener(@NonNull DiffType diffType, long newNodeKey, long oldNodeKey,
      @NonNull DiffDepth depth);

  /** Signals that the diff calculation is done. */
  void diffDone();
}


text:
<!DOCTYPE html>
<title>drag & drop - microdata when addElement is used</title>

xxx

yyy

Use your pointing device to drag the orange box to the pink box, then back to the blue box, and release it.

Enable JavaScript and reload


text:
<?php

namespace Aeria\Taxonomy;

use Aeria\Config\Traits\ValidateConfTrait;
use Aeria\Container\Interfaces\ValidateConfInterface;
use Aeria\Taxonomy\Exceptions\AlreadyExistingTaxonomyException;
use Aeria\Taxonomy\Exceptions\WordpressTaxonomyException;

/**
 * Taxonomy is the service in charge of registering post types
 *
 * @category Taxonomy
 * @package  Aeria
 * @author   Simone Montali <simone.montali@caffeina.com>
 * @license  https://github.com/caffeinalab/aeria/blob/master/LICENSE  MIT license
 * @link     https://github.com/caffeinalab/aeria
 */
class Taxonomy implements ValidateConfInterface
{
    use ValidateConfTrait;
    /**
     * Returns a validation structure for taxonomy configs
     *
     * @return array the validation structure
     *
     * @access public
     * @since  Method available since Release 3.0.0
     */
    public function getValidationStructure() : array
    {
        $namespace = Taxonomy::class;
        return [
            'taxonomy' => $this->makeRegExValidator(
                "/^[a-z0-9_-]{1,32}$/"
            ),
            'args' => $this->combineOrValidator(
                $this->makeIsArrayValidator(),
                $this->makeIsEqualToValidator('null')
            )
        ];
    }
    /**
     * Checks if a post type exists
     *
     * @return void
     * @throws \Exception if the post type doesn't exist
     *
     * @access public
     * @static
     * @since  Method available since Release 3.0.0
     */
    static function validateThatPostTypeExist(string $post_type_name)
    {
        if (!post_type_exists($post_type_name)) {
            throw new \Exception("Post type '{$post_type_name}' do not exsist");
        }
    }
    /**
     * Creates a new taxonomy
     *
     * @return WP_Taxonomy the taxonomy
     * @throws AlreadyExistingTaxonomyException if the taxonomy already exists
     * @throws WordpressTaxonomyException if WP throws an exception
     *
     * @access public
     * @since  Method available since Release 3.0.0
     */
    public function create($taxonomy)
    {
        $this->validate($taxonomy);

        if ($this->exists($taxonomy)) {
            throw new AlreadyExistingTaxonomyException(
                "{$taxonomy['taxonomy']} already exist"
            );
        }

        $taxonomy_obj = register_taxonomy(
            $taxonomy['taxonomy'],
            $taxonomy['object_type'],
            $taxonomy['args']
        );

        if ($taxonomy_obj instanceof WP_Error) {
            throw new WordpressTaxonomyException(
                $taxonomy_obj,
                'Unable to register a post type during PostType->create()'
            );
        }

        return $taxonomy_obj;
    }
    /**
     * Checks if a taxonomy exists
     *
     * @return bool whether the taxonomy exists or not
     *
     * @access public
     * @since  Method available since Release 3.0.0
     */
    public function exists(array $taxonomy) : bool
    {
        return taxonomy_exists($taxonomy['taxonomy']);
    }
    /**
     * Validates a taxonomy configuration
     *
     * @param array $conf the taxonomy configuration
     *
     * @return void
     * @throws ConfigValidationException if the config is invalid
     *
     * @access private
     * @since  Method available since Release 3.0.0
     */
    private function validate($conf)
    {
        $exception = $this->isValid($conf);
        if (!is_null($exception)) {
            throw $exception;
        }
    }
}


text:
package Exercise.Animals.Classes;

import Exercise.Animals.AbstractClasses.AnimalImp;

public class Tomcat extends AnimalImp {

    public Tomcat(String kind, String name, String gender, int age) {
        super(kind, name, gender, age);
    }

    @Override
    public String produceSound() {
        return "Give me one million b***h";
    }
}


text:
import unittest

from conans import tools
from conans.test.utils.tools import TestClient
import os
from conans.paths import CONANFILE
from conans.util.files import load, mkdir
from conans.test.utils.test_files import temp_folder
from nose_parameterized import parameterized

class PackageLocalCommandTest(unittest.TestCase):

    def package_with_destination_test(self):
        client = TestClient()

        def prepare_for_package(the_client):
            the_client.save({"src/header.h": "contents"}, clean_first=True)
            the_client.run("new lib/1.0 -s")

            # don't need build method
            tools.replace_in_file(os.path.join(client.current_folder,
                                               "conanfile.py"),
                                               "def build",
                                               "def skip_build")
            the_client.run("install . --install-folder build")
            mkdir(os.path.join(client.current_folder, "build2"))

        # In current dir subdir
        prepare_for_package(client)
        client.run("package . --build-folder build2 --install-folder build --package-folder=subdir")
        self.assertNotIn("package(): WARN: No files copied!", client.out)
        self.assertTrue(os.path.exists(os.path.join(client.current_folder, "subdir")))

        # In current dir subdir with conanfile path
        prepare_for_package(client)
        client.run("package ./conanfile.py --build-folder build2 --install-folder build --package-folder=subdir")
        self.assertTrue(os.path.exists(os.path.join(client.current_folder, "subdir")))

        # Default path
        prepare_for_package(client)
        client.run("package . --build-folder build")
        self.assertNotIn("package(): WARN: No files copied!", client.out)
        self.assertTrue(os.path.exists(os.path.join(client.current_folder, "build", "package")))

        # Default path with conanfile path
        prepare_for_package(client)
        client.run("package conanfile.py --build-folder build")
        self.assertTrue(os.path.exists(os.path.join(client.current_folder, "build", "package")))

        # Abs path
        prepare_for_package(client)
        pf = os.path.join(client.current_folder, "mypackage/two")
        client.run("package . --build-folder build --package-folder='%s'" % pf)
        self.assertNotIn("package(): WARN: No files copied!", client.out)
        self.assertTrue(os.path.exists(os.path.join(client.current_folder, "mypackage", "two")))

        # Abs path with conanfile path
        prepare_for_package(client)
        pf = os.path.join(client.current_folder, "mypackage/two")
        os.rename(os.path.join(client.current_folder, "conanfile.py"),
                  os.path.join(client.current_folder, "my_conanfile.py"))
        client.run("package ./my_conanfile.py --build-folder build --package-folder='%s'" % pf)
        self.assertTrue(os.path.exists(os.path.join(client.current_folder, "mypackage", "two")))

    def package_with_path_errors_test(self):
        client = TestClient()
        client.save({"conanfile.txt": "contents"}, clean_first=True)

        # Path with conanfile.txt
        error = client.run("package conanfile.txt --build-folder build2 --install-folder build",
                           ignore_error=True)
        self.assertTrue(error)
        self.assertIn("A conanfile.py is needed (not valid conanfile.txt)", client.out)

        # Path with wrong conanfile path
        error = client.run("package not_real_dir/conanfile.py --build-folder build2 --install-folder build",
                           ignore_error=True)
        self.assertTrue(error)
        self.assertIn("Conanfile not found: %s" % os.path.join(client.current_folder, "not_real_dir",
                                                               "conanfile.py"), client.out)

    def package_with_reference_errors_test(self):
        client = TestClient()
        error = client.run("package MyLib/0.1@lasote/stable", ignore_error=True)
        self.assertTrue(error)
        self.assertIn("conan package' doesn't accept a reference anymore",
                      client.out)

    def local_package_test(self):
        client = TestClient()
        conanfile_template = """
from conans import ConanFile

class MyConan(ConanFile):
    def package(self):
        self.copy(pattern="*.h", dst="include", src="include")
"""
        client.save({"include/file.h": "foo",
                     CONANFILE: conanfile_template})
        client.run("install .")
        path = client.current_folder
        client.run('package "%s"' % path)
        package_folder = os.path.join(client.current_folder, "package")
        content = load(os.path.join(package_folder, "include/file.h"))
        self.assertEqual(content, "foo")
        self.assertEqual(sorted(os.listdir(package_folder)),
                         sorted(["include", "conaninfo.txt", "conanmanifest.txt"]))
        self.assertEqual(os.listdir(os.path.join(package_folder, "include")), ["file.h"])

    @parameterized.expand([(False, False), (True, False), (True, True), (False, True)])
    def local_package_build_test(self, default_folder, conanfile_path):
        client = TestClient()
        conanfile_template = """
from conans import ConanFile

class MyConan(ConanFile):
    def package(self):
        self.copy(pattern="*.h", dst="include", src="include")
        self.copy(pattern="*.lib")
"""

        client.save({"include/file.h": "foo",
                     "build/lib/mypkg.lib": "mylib",
                     CONANFILE: conanfile_template})
        path = client.current_folder
        client.current_folder = os.path.join(client.current_folder, "build")
        client.run("install ..")

        if default_folder:
            package_folder = os.path.join(client.current_folder, "package")
            path = "../conanfile.py" if conanfile_path else ".."
            client.run('package {0} --build-folder=.'.format(path))
            self.assertEqual(sorted(os.listdir(package_folder)),
                             sorted(["include", "lib", "conaninfo.txt", "conanmanifest.txt"]))
        else:
            package_folder = temp_folder()
            client.current_folder = package_folder
            build_folder = os.path.join(path, "build")

            if conanfile_path:
                path = os.path.join(path, "conanfile.py")

            client.run('package "{0}" --build-folder="{2}"'
                       ' --package-folder="{1}"'.format(path, package_folder, build_folder))
            self.assertEqual(sorted(os.listdir(package_folder)),
                             sorted(["include", "lib", "conaninfo.txt",
                                     "conanmanifest.txt"]))

        content = load(os.path.join(package_folder, "include/file.h"))
        self.assertEqual(content, "foo")
        self.assertEqual(os.listdir(os.path.join(package_folder, "include")), ["file.h"])
        self.assertEqual(os.listdir(os.path.join(package_folder, "lib")), ["mypkg.lib"])

    @parameterized.expand([(False, False), (True, False), (True, True), (False, True)])
    def local_package_source_test(self, default_folder, conanfile_path):
        client = TestClient()
        conanfile_template = """
from conans import ConanFile

class MyConan(ConanFile):
    def package(self):
        self.copy(pattern="*.h", dst="include", src="include")
        self.copy(pattern="*.lib")
"""

        client.save({"src/include/file.h": "foo",
                     "build/lib/mypkg.lib": "mylib",
                     CONANFILE: conanfile_template})
        conanfile_folder = client.current_folder
        path = conanfile_folder
        client.current_folder = os.path.join(client.current_folder, "build")
        client.run("install ..")

        if default_folder:
            package_folder = os.path.join(client.current_folder, "package")
            path = "../conanfile.py" if conanfile_path else ".."
            client.run('package {0} --build-folder=. --source-folder=../src'.format(path))
        else:
            package_folder = temp_folder()

            if conanfile_path:
                path = os.path.join(path, "conanfile.py")

            client.run('package "{0}" --build-folder="{1}/build" '
                       '--package-folder="{2}" --source-folder="{1}/src"'.
                       format(path, conanfile_folder, package_folder))
        content = load(os.path.join(package_folder, "include/file.h"))
        self.assertEqual(content, "foo")
        self.assertEqual(sorted(os.listdir(package_folder)),
                         sorted(["include", "lib", "conaninfo.txt", "conanmanifest.txt"]))
        self.assertEqual(os.listdir(os.path.join(package_folder, "include")), ["file.h"])
        self.assertEqual(os.listdir(os.path.join(package_folder, "lib")), ["mypkg.lib"])


text:
// +build !agent
// +build !controller

/*
Package scripts includes scripts that are embedded in REX-Ray during the
build process that is driven by the make file.
*/
package scripts

import (
	// depend upon this tool with a nil import in order to preserve it
	// in the dependency list
	_ "github.com/jteeuwen/go-bindata"
)


text:
package com.vaadin.book.examples.layout;

import com.vaadin.book.examples.BookExampleBundle;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.VerticalLayout;

public class SpacingExample extends CustomComponent implements BookExampleBundle {
    private static final long serialVersionUID = 4598073828719119575L;

    public void init (String context) {
        addStyleName("spacingexample");

        if ("vertical".equals(context))
            vertical();
        else if ("horizontal".equals(context))
            horizontal();
        else if ("grid".equals(context))
            grid();
        else
            setCompositionRoot(new Label("Error"));
    }

    void vertical() {
        HorizontalLayout layout = new HorizontalLayout();

        VerticalLayout layout1 = new VerticalLayout();
        layout1.setSpacing(false);
        layout1.addComponent(new Label("Item 1"));
        layout1.addComponent(new Label("Item 2"));
        layout1.addComponent(new Label("Item 3"));
        layout1.addComponent(new Label("Item 4"));
        layout1.addComponent(new Label("Item 5"));
        layout.addComponent(layout1);

        VerticalLayout layout2 = new VerticalLayout();
        layout2.setSpacing(true);
        layout2.addComponent(new Label("Item 1"));
        layout2.addComponent(new Label("Item 2"));
        layout2.addComponent(new Label("Item 3"));
        layout2.addComponent(new Label("Item 4"));
        layout2.addComponent(new Label("Item 5"));
        layout.addComponent(layout2);

        setCompositionRoot(layout);
    }

    void horizontal() {
        VerticalLayout layout = new VerticalLayout();

        HorizontalLayout layout1 = new HorizontalLayout();
        layout1.setSpacing(false);
        layout1.addComponent(new Label("Item 1"));
        layout1.addComponent(new Label("Item 2"));
        layout1.addComponent(new Label("Item 3"));
        layout1.addComponent(new Label("Item 4"));
        layout1.addComponent(new Label("Item 5"));
        layout.addComponent(layout1);

        HorizontalLayout layout2 = new HorizontalLayout();
        layout2.setSpacing(true);
        layout2.addComponent(new Label("Item 1"));
        layout2.addComponent(new Label("Item 2"));
        layout2.addComponent(new Label("Item 3"));
        layout2.addComponent(new Label("Item 4"));
        layout2.addComponent(new Label("Item 5"));
        layout.addComponent(layout2);

        setCompositionRoot(layout);
    }

    void grid() {
        HorizontalLayout layout = new HorizontalLayout();

        GridLayout layout1 = new GridLayout(3, 3);
        layout1.setSpacing(false);
        layout1.addComponent(new Label("Item 1,1"));
        layout1.addComponent(new Label("Item 1,2"));
        layout1.addComponent(new Label("Item 1,3"));
        layout1.addComponent(new Label("Item 2,1"));
        layout1.addComponent(new Label("Item 2,2"));
        layout1.addComponent(new Label("Item 2,3"));
        layout1.addComponent(new Label("Item 3,1"));
        layout1.addComponent(new Label("Item 3,2"));
        layout1.addComponent(new Label("Item 3,3"));
        layout.addComponent(layout1);

        GridLayout layout2 = new GridLayout(3, 3);
        layout2.setSpacing(true);
        layout2.addComponent(new Label("Item 1,1"));
        layout2.addComponent(new Label("Item 1,2"));
        layout2.addComponent(new Label("Item 1,3"));
        layout2.addComponent(new Label("Item 2,1"));
        layout2.addComponent(new Label("Item 2,2"));
        layout2.addComponent(new Label("Item 2,3"));
        layout2.addComponent(new Label("Item 3,1"));
        layout2.addComponent(new Label("Item 3,2"));
        layout2.addComponent(new Label("Item 3,3"));
        layout.addComponent(layout2);

        setCompositionRoot(layout);
    }
}


text:
package org.apache.hadoop.hdfs.nfs;

import java.io.IOException;
import java.net.InetAddress;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.nfs.conf.NfsConfigKeys;
import org.apache.hadoop.hdfs.nfs.conf.NfsConfiguration;
import org.apache.hadoop.hdfs.nfs.mount.RpcProgramMountd;
import org.apache.hadoop.hdfs.nfs.nfs3.Nfs3;
import org.apache.hadoop.hdfs.nfs.nfs3.RpcProgramNfs3;
import org.apache.hadoop.oncrpc.XDR;
import org.junit.Test;
import static org.junit.Assert.assertTrue;

public class TestMountd {

  public static final Log LOG = LogFactory.getLog(TestMountd.class);

  @Test
  public void testStart() throws IOException {
    // Start minicluster
    NfsConfiguration config = new NfsConfiguration();
    MiniDFSCluster cluster = new MiniDFSCluster.Builder(config).numDataNodes(1)
        .build();
    cluster.waitActive();

    // Use emphral port in case tests are running in parallel
    config.setInt("nfs3.mountd.port", 0);
    config.setInt("nfs3.server.port", 0);

    int newTimeoutMillis = 1000; // 1s
    // Set the new portmap rpc timeout values and check
    config.setInt(NfsConfigKeys.NFS_UDP_CLIENT_PORTMAP_TIMEOUT_MILLIS_KEY,
                  newTimeoutMillis);
    assertTrue(config.getInt(
                      NfsConfigKeys.NFS_UDP_CLIENT_PORTMAP_TIMEOUT_MILLIS_KEY,
          0) == newTimeoutMillis);

    // Start nfs
    Nfs3 nfs3 = new Nfs3(config);
    nfs3.startServiceInternal(false);

    RpcProgramMountd mountd = (RpcProgramMountd) nfs3.getMountd()
        .getRpcProgram();
    mountd.nullOp(new XDR(), 1234, InetAddress.getByName("localhost"));
    assertTrue(mountd.getPortmapUdpTimeoutMillis() == newTimeoutMillis);
    RpcProgramNfs3 nfsd = (RpcProgramNfs3) nfs3.getRpcProgram();
    nfsd.nullProcedure();
    assertTrue(nfsd.getPortmapUdpTimeoutMillis() == newTimeoutMillis);

    cluster.shutdown();
  }
}


text:
typedef void (^SearchResultDidSelectRowAtIndexPathBlock)(UITableView* tableView, NSIndexPath* indexPath, NSArray *searchList);

@interface eLongGeographySelectSearchResults : NSObject<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, copy) SearchResultDidSelectRowAtIndexPathBlock suggestionSearchDidSelectBlock;
@property (nonatomic, copy) UITableViewCellForRowAtIndexPathBlock cellForRowAtIndexPath;

- (instancetype)initWithGeographySelectModel:(eLongGeographySelectModel *)selectModel withDataSourceModel:(eLongGeographySelectDataSourceModel *)dataSourceModel;

- (void)updateSearchList:(NSArray *)searchList;
- (NSMutableArray *)searchSuggestionKeyWordFromLocal:(NSString *)suggestionKeyWord;

@end


text:
using System.Collections.Generic;
using System.Linq;
using UnityEditor.ShaderGraph.Drawing.Controls;
using UnityEngine;
using UnityEditor.Graphing;

namespace UnityEditor.ShaderGraph
{
    [Title("Input", "Basic", "Vector 2")]
    class Vector2Node : AbstractMaterialNode, IGeneratesBodyCode, IPropertyFromNode
    {
        [SerializeField]
        private Vector2 m_Value = Vector2.zero;

        const string kInputSlotXName = "X";
        const string kInputSlotYName = "Y";
        const string kOutputSlotName = "Out";

        public const int OutputSlotId = 0;
        public const int InputSlotXId = 1;
        public const int InputSlotYId = 2;

        public Vector2Node()
        {
            name = "Vector 2";
            UpdateNodeAfterDeserialization();
        }

        public sealed override void UpdateNodeAfterDeserialization()
        {
            AddSlot(new Vector1MaterialSlot(InputSlotXId, kInputSlotXName, kInputSlotXName, SlotType.Input, m_Value.x));
            AddSlot(new Vector1MaterialSlot(InputSlotYId, kInputSlotYName, kInputSlotYName, SlotType.Input, m_Value.y, label1: "Y"));
            AddSlot(new Vector2MaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, Vector4.zero));
            RemoveSlotsNameNotMatching(new[] { OutputSlotId, InputSlotXId, InputSlotYId });
        }

        public void GenerateNodeCode(ShaderGenerator visitor, GraphContext graphContext, GenerationMode generationMode)
        {
            var inputXValue = GetSlotValue(InputSlotXId, generationMode);
            var inputYValue = GetSlotValue(InputSlotYId, generationMode);
            var outputName = GetVariableNameForSlot(OutputSlotId);

            var s = string.Format("{0}2 {1} = {0}2({2},{3});",
                    precision,
                    outputName,
                    inputXValue,
                    inputYValue);
            visitor.AddShaderChunk(s, false);
        }

        public AbstractShaderProperty AsShaderProperty()
        {
            var slotX = FindInputSlot<Vector1MaterialSlot>(InputSlotXId);
            var slotY = FindInputSlot<Vector1MaterialSlot>(InputSlotYId);
            return new Vector2ShaderProperty { value = new Vector2(slotX.value, slotY.value) };
        }

        int IPropertyFromNode.outputSlotId { get { return OutputSlotId; } }
    }
}


text:
class CreateFriendships < ActiveRecord::Migration

  def self.up
    create_table :friendships, :force => true do |t|
      t.column "user_id",     :integer, :null => false
      t.column "friend_id",   :integer, :null => false
      t.column "created_at",  :datetime
      t.column "accepted_at", :datetime
    end
  end

  def self.down
    drop_table :friendships
  end

end


text:
class RepositoryProtectedBranche < ActiveRecord::Base
  unloadable

  VALID_PERMS  = ['RW+', 'RW', 'R', '-']
  DEFAULT_PERM = 'RW+'

  acts_as_list

  ## Attributes
  attr_accessible :path, :permissions, :position, :user_ids, :group_ids

  ## Relations
  belongs_to :repository
  has_many   :protected_branches_members, foreign_key: :protected_branch_id, dependent: :destroy
  has_many   :members, through: :protected_branches_members, source: :principal

  ## Validations
  validates :repository_id, presence: true
  validates :path,          presence: true, uniqueness: { scope: [:permissions, :repository_id] }
  validates :permissions,   presence: true, inclusion: { in: VALID_PERMS }

  ## Scopes
  default_scope { order('position ASC') }

  class << self

    def clone_from(parent)
      parent = find_by_id(parent) unless parent.kind_of? RepositoryProtectedBranche
      copy = self.new
      copy.attributes = parent.attributes
      copy.repository = parent.repository
      copy
    end

  end

  # Accessors
  #
  def users
    members.select { |m| m.class.name == 'User' }.uniq
  end

  def groups
    members.select { |m| m.class.name == 'Group' }
  end

  def allowed_users
    users.map { |u| u.gitolite_identifier }.sort
  end

  # Mass assignment
  #
  def user_ids=(ids)
    current_ids = users.map(&:id)
    create_member(ids, current_ids, 'User')
  end

  def group_ids=(ids)
    current_ids = groups.map(&:id)
    create_member(ids, current_ids, 'Group') do |group|
      ids = group.users.map(&:id)
      current_ids = users_by_group_id(group.id).map(&:id)
      create_member(ids, current_ids, 'User', inherited_by: group.id, destroy: false)
    end
  end

  # Triggered by Group callbacks
  #
  def add_user_member(user, group)
    ids = users_by_group_id(group.id).push(user).map(&:id)
    current_ids = users_by_group_id(group.id).map(&:id)
    create_member(ids, current_ids, 'User', inherited_by: group.id, destroy: false)
  end

  def remove_user_member(user, group)
    return unless users_by_group_id(group.id).include?(user)
    member = protected_branches_members.find_by_protected_branch_id_and_principal_id_and_inherited_by(id, user.id, group.id)
    member.destroy! unless member.nil?
  end

  private

    def users_by_group_id(id)
      protected_branches_members.select { |pbm| pbm.principal.class.name == 'User' && pbm.inherited_by == id }.map(&:principal)
    end

    def create_member(ids, current_ids, klass, destroy: true, inherited_by: nil, &block)
      ids = (ids || []).collect(&:to_i) - [0]
      new_ids = ids - current_ids

      new_ids.each do |id|
        object = klass.constantize.find_by_id(id)
        next if object.nil?
        protected_branches_members.create(principal_id: object.id, inherited_by: inherited_by)
        yield object if block_given?
      end

      if destroy
        member_to_destroy = protected_branches_members.select { |m| m.principal.class.name == klass && !ids.include?(m.principal.id) }
        member_to_destroy.each(&:destroy) if member_to_destroy.any?
      end
    end

end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<title>R: Apply Function to Matrix Permutations for Randomization Tests</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="R.css">

randomize {matR}	R Documentation

Apply Function to Matrix Permutations for Randomization Tests

Description

Applies given function repeatedly to random permutation of a given matrix, providing a general-purpose routine to facilitate randomization tests.

Usage

randomize(x, ntimes = 1, method = c("sample", "dataset", "complete"), seed = NULL, FUN = identity, ...)

Arguments

x

matrix

ntimes

how many permutations (numeric)

method

type of permutation (character)

seed

seed for random number generation (numeric)

FUN

should accept single matrix argument and return summary value (function)

...

currently unused

Value

The form of results depends on the return value of the supplied summarizing function.  By  default, the random permutation matrices themselves are returned as a list, but a function should be supplied in place of the identity.

Author(s)

Kevin P. Keegan, Daniel T. Braithwaite

Examples

##

[Package matR version 0.9.9 Index]