text:
<?php namespace CodeZero\Cookie;

use Illuminate\Support\ServiceProvider;

class LaravelCookieServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->registerCookie();
    }

    /**
     * Register the cookie service binding
     *
     * @return void
     */
    private function registerCookie()
    {
        $this->app->singleton(
            'CodeZero\Cookie\Cookie',
            'CodeZero\Cookie\LaravelCookie'
        );
    }
}


text:
package org.inuua.snmp;

import java.io.IOException;
import org.inuua.snmp.types.SnmpNull;
import org.inuua.util.ListHelpers;
import org.junit.Test;
import static org.junit.Assert.*;

public final class SnmpNullTest {

    @Test
    public void testEncoding() throws IOException {
        byte[] result = SnmpNull.newNull().encode().toByteArray();
        byte[] expResult = ListHelpers.byteArray(
                0x05, 0x00);
        assertArrayEquals(expResult, result);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package jobqueue

import (
    "canopy/datalayer"
    "errors"
    "fmt"
    "time"
)

type PigeonSystem struct {
    dl datalayer.PigeonSystem
}

type PigeonRequest struct {
    ReqJobKey string
    ReqBody map[string]interface{}
}

type PigeonResponse struct {
    RespBody map[string]interface{}
}

type PigeonRecieveHandler struct {
    ch chan map[string]interface{}
}

func NewPigeonRecieveHandler() *PigeonRecieveHandler{
    return &PigeonRecieveHandler{
        ch: make(chan map[string]interface{}),
    }
}

func (recvHandler *PigeonRecieveHandler) Handle(jobkey string,
        userCtx interface{},
        req Request,
        resp Response) {

    // Send it into channel
    recvHandler.ch <- req.Body()
}

func (recvHandler *PigeonRecieveHandler) Recieve(timeout time.Duration) (map[string]interface{}, error) {

    select {
        case msg := <- recvHandler.ch:
            return msg, nil
        case <- time.After(timeout):
            return nil, errors.New("Recieve timed out")
    }

}

func (pigeon *PigeonSystem) NewOutbox() Outbox {
    return &PigeonOutbox{
        sys: pigeon,
        timeoutms: -1,
    }
}

func (pigeon *PigeonSystem) NewResponse() Response {
    return &PigeonResponse{}
}

func (pigeon *PigeonSystem) StartServer(hostname string) (Server, error) {
    server := &PigeonServer{
        sys : pigeon,
        hostname: hostname,
        inboxesByMsgKey: map[string]([]*PigeonInbox){},
    }

    err := server.Start()
    if err != nil {
        return nil, err
    }

    return server, nil
}

func (pigeon *PigeonSystem) Server(hostname string) (Server, error) {
    return nil, fmt.Errorf("Not Implemented")
}

func (pigeon *PigeonSystem) Servers() ([]Server, error) {
    return nil, fmt.Errorf("Not Implemented")
}

func (resp *PigeonResponse) Body() map[string]interface{} {
    return resp.RespBody
}

func (resp *PigeonResponse) SetBody(body map[string]interface{}) {
    resp.RespBody = body
}

func (resp *PigeonResponse) AppendToBody(key string, value interface{}) {
    resp.RespBody[key] = value
}

func (req *PigeonRequest) Body() map[string]interface{} {
    return req.ReqBody
}


text:
package brick

// Factory create a service
type Factory interface {

	// New a service instance
	New() interface{}
}


text:
package water.parser;

import org.apache.commons.io.IOUtils;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import water.*;
import water.api.schemas3.ParseSetupV3;
import water.fvec.Frame;
import water.fvec.Vec;
import water.util.FileUtils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.security.KeyStore;
import java.util.Arrays;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static org.junit.Assert.*;

@RunWith(Parameterized.class)
public class ParseTestEncrypted extends TestUtil {

  @ClassRule
  public static TemporaryFolder tmp = new TemporaryFolder();

  private static String PLAINTEXT_FILE = "smalldata/demos/citibike_20k.csv";

  private static String KEYSTORE_TYPE = "JCEKS"; // Note: need to use JCEKS, default JKS cannot store non-private keys!
  private static String MY_CIPHER_SPEC = "AES/ECB/PKCS5Padding";
  private static char[] MY_PASSWORD = "Password123".toCharArray();
  private static String MY_KEY_ALIAS = "secretKeyAlias";

  private static File _jks;

  @Parameterized.Parameter
  public String _encrypted_name;

  @Parameterized.Parameters
  public static Iterable<? extends Object> data() { return Arrays.asList("encrypted.aes.csv", "encrypted.aes.zip"); };

  @BeforeClass
  public static void setup() throws Exception {
    SecretKey secretKey = generateSecretKey();
    // KeyStore
    _jks = writeKeyStore(secretKey);
    // Encrypted CSV
    writeEncrypted(FileUtils.getFile(PLAINTEXT_FILE), tmp.newFile("encrypted.aes.csv"), secretKey);
    // Encrypted CSV in a Zip
    writeEncryptedZip(FileUtils.getFile(PLAINTEXT_FILE), tmp.newFile("encrypted.aes.zip"), secretKey);

    TestUtil.stall_till_cloudsize(1);
  }

  private static SecretKey generateSecretKey() throws Exception {
    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(128);
    return keyGen.generateKey();
  }

  private static File writeKeyStore(SecretKey secretKey) throws Exception {
    KeyStore ks = KeyStore.getInstance(KEYSTORE_TYPE);
    ks.load(null);
    KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection(MY_PASSWORD);

    KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(secretKey);
    ks.setEntry(MY_KEY_ALIAS, skEntry, protParam);

    File jks = tmp.newFile("mykeystore.jks");
    FileOutputStream fos = null;
    try {
      fos = new FileOutputStream(jks);
      ks.store(fos, MY_PASSWORD);
      fos.close();
    } finally {
      IOUtils.closeQuietly(fos);
    }
    return jks;
  }

  private static void writeEncrypted(File source, File target, SecretKey secretKey) throws Exception {
    FileOutputStream fileOut = new FileOutputStream(target);
    try {
      encryptFile(source, fileOut, secretKey);
    } finally {
      IOUtils.closeQuietly(fileOut);
    }
  }

  private static void writeEncryptedZip(File source, File target, SecretKey secretKey) throws Exception {
    FileOutputStream fileOut = new FileOutputStream(target);
    try {
      ZipOutputStream zipOut = new ZipOutputStream(fileOut);
      ZipEntry ze = new ZipEntry(source.getName());
      zipOut.putNextEntry(ze);
      encryptFile(source, zipOut, secretKey);
      zipOut.closeEntry();
      zipOut.close();
    } finally {
      IOUtils.closeQuietly(fileOut);
    }
  }

  private static void encryptFile(File source, OutputStream outputStream, SecretKey secretKey) throws Exception {
    FileInputStream inputStream = new FileInputStream(source);
    try {
      Cipher cipher = Cipher.getInstance(MY_CIPHER_SPEC);
      cipher.init(Cipher.ENCRYPT_MODE, secretKey);

      byte[] inputBytes = new byte[(int) source.length()];
      IOUtils.readFully(inputStream, inputBytes);
      byte[] outputBytes = cipher.doFinal(inputBytes);
      outputStream.write(outputBytes);

      inputStream.close();
    } finally {
      IOUtils.closeQuietly(inputStream);
    }
  }

  @Test
  public void testParseEncrypted() {
    Scope.enter();
    try {
      // 1. Upload the Keystore file
      Vec jksVec = Scope.track(makeNfsFileVec(_jks.getAbsolutePath()));

      // 2. Set Decryption Tool Parameters
      DecryptionTool.DecryptionSetup ds = new DecryptionTool.DecryptionSetup();
      ds._decrypt_tool_id = Key.make("aes_decrypt_tool");
      ds._keystore_id = jksVec._key;
      ds._key_alias = MY_KEY_ALIAS;
      ds._keystore_type = KEYSTORE_TYPE;
      ds._password = MY_PASSWORD;
      ds._cipher_spec = MY_CIPHER_SPEC;

      // 3. Instantiate & Install the Decryption Tool into DKV
      Keyed<DecryptionTool> dt = Scope.track_generic(DecryptionTool.make(ds));

      // 4. Load encrypted file into a ByteVec
      Vec encVec = Scope.track(makeNfsFileVec(new File(tmp.getRoot(), _encrypted_name).getAbsolutePath()));

      // 5. Create Parse Setup with a given Decryption Tool
      ParseSetup ps = new ParseSetup(new ParseSetupV3()).setDecryptTool(dt._key);
      ParseSetup guessedSetup = ParseSetup.guessSetup(new Key[]{encVec._key}, ps);
      assertEquals("aes_decrypt_tool", guessedSetup._decrypt_tool.toString());
      assertEquals("CSV", guessedSetup._parse_type.name());

      // 6. Parse encrypted dataset
      Key<Frame> fKey = Key.make("decrypted_frame");
      Frame decrypted = Scope.track(ParseDataset.parse(fKey, new Key[]{encVec._key}, false, guessedSetup));

      // 7. Compare with source dataset
      Frame plaintext = Scope.track(parse_test_file(PLAINTEXT_FILE));
      assertArrayEquals(plaintext._names, decrypted._names);
      for (String n : plaintext._names) {
        switch (plaintext.vec(n).get_type_str()) {
          case "String":
            assertStringVecEquals(plaintext.vec(n), decrypted.vec(n));
            break;
          case "Enum":
            assertCatVecEquals(plaintext.vec(n), decrypted.vec(n));
            break;
          default:
            assertVecEquals(plaintext.vec(n), decrypted.vec(n), 0.001);
        }
      }
    } finally {
      Scope.exit();
    }
  }

}


text:
<resources>
    <string name="app_name">Luban</string>
    <string name="choose_image">选择图片</string>
</resources>


text:
package genyaml

import (
	"bytes"
	"encoding/json"
	yaml3 "gopkg.in/yaml.v3"
	"io/ioutil"
	aliases "k8s.io/test-infra/pkg/genyaml/testdata/alias_types"
	embedded "k8s.io/test-infra/pkg/genyaml/testdata/embedded_structs"
	interfaces "k8s.io/test-infra/pkg/genyaml/testdata/interface_types"
	multiline "k8s.io/test-infra/pkg/genyaml/testdata/multiline_comments"
	nested "k8s.io/test-infra/pkg/genyaml/testdata/nested_structs"
	tags "k8s.io/test-infra/pkg/genyaml/testdata/no_tags"
	omit "k8s.io/test-infra/pkg/genyaml/testdata/omit_if_empty"
	pointers "k8s.io/test-infra/pkg/genyaml/testdata/pointer_types"
	primitives "k8s.io/test-infra/pkg/genyaml/testdata/primitive_types"
	private "k8s.io/test-infra/pkg/genyaml/testdata/private_members"
	"path/filepath"
	"strings"
	"testing"
)

const (
	testDir = "testdata"
)

func resolvePath(t *testing.T, filename string) string {
	name := filepath.Base(t.Name())
	return strings.ToLower(filepath.Join(testDir, name, filename))
}

func readFile(t *testing.T, extension string) []byte {
	name := filepath.Base(t.Name())
	data, err := ioutil.ReadFile(strings.ToLower(filepath.Join(testDir, name, name+"."+extension)))
	if err != nil {
		t.Errorf("Failed reading .%s file: %v.", extension, err)
	}

	return data
}

func TestFmtRawDoc(t *testing.T) {
	tests := []struct {
		name     string
		rawDoc   string
		expected string
	}{
		{
			name:     "Single line comment",
			rawDoc:   "Owners of the cat.",
			expected: "Owners of the cat.",
		},
		{
			name:   "Multi line comment",
			rawDoc: "StringField comment\nsecond line\nthird line",
			expected: `StringField comment
second line
third line`,
		},
		{
			name:     "Delete trailing space(s)",
			rawDoc:   "Some comment    ",
			expected: "Some comment",
		},
		{
			name:     "Delete trailing newline(s)",
			rawDoc:   "Some comment\n\n\n\n",
			expected: "Some comment",
		},
		{
			name:     "Escape double quote(s)",
			rawDoc:   `"Some comment"`,
			expected: `"Some comment"`,
		},
		{
			name: "Convert tab to space",
			rawDoc: "tab	tab		tabtab",
			expected: "tab tab tabtab",
		},
		{
			name:     "Strip TODO prefixed comment",
			rawDoc:   "TODO: some future work",
			expected: "",
		},
		{
			name:     "Strip + prefixed comment",
			rawDoc:   "+: some future work",
			expected: "",
		},
		{
			name:     "Strip TODO prefixed comment from multi line comment",
			rawDoc:   "TODO: some future work\nmore comment",
			expected: "more comment",
		},
		{
			name:     "Strip + prefixed comment from multi line comment",
			rawDoc:   "+: some future work\nmore comment",
			expected: "more comment",
		},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			actualFormattedRawDoc := fmtRawDoc(test.rawDoc)

			if actualFormattedRawDoc != test.expected {
				t.Fatalf("Expected %q, but got result %q", test.expected, actualFormattedRawDoc)
			}
		})
	}
}

func TestInjectComment(t *testing.T) {
	tests := []struct {
		name         string
		typeSpec     string
		actualNode   *yaml3.Node
		expectedNode *yaml3.Node
	}{
		{
			name:     "Inject comments",
			typeSpec: "ExampleStruct",
			actualNode: &yaml3.Node{
				Kind: yaml3.DocumentNode,
				Content: []*yaml3.Node{
					{
						Kind: yaml3.MappingNode,
						Tag:  "!!map",
						Content: []*yaml3.Node{
							{
								Kind:  yaml3.ScalarNode,
								Tag:   "!!str",
								Value: "exampleKey",
							},
							{
								Kind:  yaml3.ScalarNode,
								Tag:   "!!bool",
								Value: "true",
							},
						},
					},
				},
			},
			expectedNode: &yaml3.Node{
				Kind: yaml3.DocumentNode,
				Content: []*yaml3.Node{
					{
						Kind: yaml3.MappingNode,
						Tag:  "!!map",
						Content: []*yaml3.Node{
							{
								Kind:        yaml3.ScalarNode,
								Tag:         "!!str",
								Value:       "exampleKey",
								HeadComment: "Some comment",
							},
							{
								Kind:  yaml3.ScalarNode,
								Tag:   "!!bool",
								Value: "true",
							},
						},
					},
				},
			},
		},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			cm := NewCommentMap()

			err := json.Unmarshal(readFile(t, "json"), &cm.comments)
			if err != nil {
				t.Errorf("Unexpected error unmarshalling JSON to comments: %v.", err)
			}

			cm.injectComment(test.actualNode, []string{test.typeSpec}, 0)

			expectedYaml, err := yaml3.Marshal(test.expectedNode)
			if err != nil {
				t.Errorf("Unexpected error marshalling Node to YAML: %v.", err)
			}

			actualYaml, err := yaml3.Marshal(test.actualNode)
			if err != nil {
				t.Errorf("Unexpected error marshalling Node to YAML: %v.", err)
			}

			if !bytes.Equal(expectedYaml, actualYaml) {
				t.Error("Expected yaml snippets to not be equal.")
			}
		})
	}
}

func TestAddPath(t *testing.T) {
	tests := []struct {
		name     string
		paths    []string
		expected bool
	}{
		{
			name:     "Single path",
			paths:    []string{"example_config.go"},
			expected: true,
		},
		{
			name:     "Multiple paths",
			paths:    []string{"example_config1.go", "example_config2.go"},
			expected: true,
		},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			cm := NewCommentMap()

			for _, f := range test.paths {
				cm.AddPath(resolvePath(t, f))
			}

			expectedComments := readFile(t, "json")
			actualComments, err := json.MarshalIndent(cm.comments, "", "  ")

			if err != nil {
				t.Errorf("Unexpected error generating JSON from comments: %v.", err)
			}

			equal := bytes.Equal(expectedComments, actualComments)

			if equal != test.expected {
				t.Errorf("Expected comments equality to be: %t.", test.expected)
			}
		})
	}

}

func TestSetPath(t *testing.T) {
	tests := []struct {
		name     string
		setup    func(cm *CommentMap)
		path     string
		expected bool
	}{
		{
			name: "Single path",
			setup: func(cm *CommentMap) {
				cm.comments = make(map[string]map[string]Comment)
			},
			path:     "example_config.go",
			expected: true,
		},
		{
			name: "Set path overwrite",
			setup: func(cm *CommentMap) {
				cm.comments["dummy_key"] = make(map[string]Comment)
				cm.comments["dummy_key"]["dummy_sub_key"] = Comment{
					Type:  "string",
					IsObj: false,
					Doc:   "Some preloaded comments",
				}
			},
			path:     "example_config.go",
			expected: true,
		},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			cm := NewCommentMap()
			test.setup(cm)

			cm.SetPath(resolvePath(t, test.path))

			expectedComments := readFile(t, "json")
			actualComments, err := json.MarshalIndent(cm.comments, "", "  ")

			if err != nil {
				t.Errorf("Unexpected error generating JSON from comments: %v.", err)
			}

			equal := bytes.Equal(expectedComments, actualComments)

			if equal != test.expected {
				t.Errorf("Expected comments equality to be: %t.", test.expected)
			}
		})
	}

}

func TestGenYAML(t *testing.T) {
	tests := []struct {
		name      string
		structObj interface{}
		expected  bool
	}{
		{
			name: "alias types",
			structObj: &aliases.Alias{
				StringField: "string",
			},
			expected: true,
		},
		{
			name: "primitive types",
			structObj: &primitives.Primitives{
				StringField:  "string",
				BooleanField: true,
				IntegerField: 1,
			},
			expected: true,
		},
		{
			name: "multiline comments",
			structObj: &multiline.Multiline{
				StringField1: "string1",
				StringField2: "string2",
				StringField3: "string3",
				StringField4: "string4",
				StringField5: "string5",
				StringField6: "string6",
			},
			expected: true,
		},
		{
			name: "nested structs",
			structObj: &nested.Parent{
				Age: 35,
				Children: []nested.Child{
					{Name: "Jimbo", Age: 4},
					{Name: "Jenny", Age: 5},
				},
				Name: "Mildred",
			},
			expected: true,
		},
		{
			name: "embedded structs",
			structObj: &embedded.Building{
				Address:  "123 North Main Street",
				Bathroom: embedded.Bathroom{Width: 100, Height: 200},
				Bedroom:  embedded.Bedroom{Width: 100, Height: 200},
			},
			expected: true,
		},
		{
			name: "no tags",
			structObj: &tags.Tagless{
				StringField:  "string",
				BooleanField: true,
				IntegerField: 1,
			},
			expected: true,
		},
		{
			name: "omit if empty",
			structObj: &omit.OmitEmptyStrings{
				StringFieldOmitEmpty: "",
				StringFieldKeepEmpty: "",
				BooleanField:         true,
				IntegerField:         1,
			},
			expected: true,
		},
		{
			name: "pointer types",
			structObj: &pointers.Zoo{
				Employees: []*pointers.Employee{
					{
						Name: "Jim",
						Age:  22,
					},
					{
						Name: "Jane",
						Age:  21,
					},
				},
			},
			expected: true,
		},
		{
			name:      "private members",
			structObj: private.NewPerson("gamer123", "password123"),
			expected:  true,
		},
		{
			name: "interface types",
			structObj: &interfaces.Zoo{
				Animals: []interfaces.Animal{
					&interfaces.Lion{
						Name: "Leo",
					},
					&interfaces.Cheetah{
						Name: "Charles",
					},
				},
			},
			// INFO: Interface type comments are not implemented.
			expected: false,
		},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			cm := NewCommentMap(resolvePath(t, "example_config.go"))
			expectedYaml := readFile(t, "yaml")

			actualYaml, err := cm.GenYaml(test.structObj)

			if err != nil {
				t.Errorf("Unexpected error generating YAML from struct: %v.", err)
			}

			equal := bytes.Equal(expectedYaml, []byte(actualYaml))

			if equal != test.expected {
				t.Errorf("Expected yaml snippets equality to be: %t.", test.expected)
			}
		})
	}
}


text:
package org.guzz.service.core.impl;

import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.guzz.Service;
import org.guzz.exception.GuzzException;
import org.guzz.orm.sql.BindedCompiledSQL;
import org.guzz.service.AbstractService;
import org.guzz.service.ServiceConfig;
import org.guzz.service.core.DebugService;
import org.guzz.util.ArrayUtil;
import org.guzz.util.StringUtil;

/**
 *
 *
 *
 * @author liukaixuan(liukaixuan@gmail.com)
 */
public class DebugServiceImpl extends AbstractService implements DebugService, Service {
	private transient static final Log log = LogFactory.getLog(DebugServiceImpl.class) ;

	private boolean isDebugMode = false ;

	private boolean haltOnError = false ;

	private boolean logOnError = true ;

	private boolean printSQL = false ;

	private boolean printSQLParams = false ;

	/**是否忽略后台线程执行的SQL语句*/
	private boolean ignoreDemonThreadSQL = false ;

	private boolean measureTime = false ;

	private long onlySlowSQLInNano = 0L ;

	public boolean isDebugMode() {
		return isDebugMode;
	}

	public boolean isLogSQL() {
		return printSQL ;
	}

	public boolean isMeasureTime() {
		return measureTime ;
	}

	public boolean isLogParams(){
		return printSQLParams ;
	}

	protected boolean isDemonThread(){
		Thread t = Thread.currentThread() ;

//		return t.isDaemon() ;

		String name =t.getName() ;
		if(name == null) return false ;

		return name.startsWith(DebugService.DEMON_NAME_PREFIX) ;
	}

	public void logSQL(String sql, long nanoTime){
		if(this.ignoreDemonThreadSQL && isDemonThread()){
			return ;
		}

		if(printSQL && nanoTime >= this.onlySlowSQLInNano){
			StringBuffer sb = new StringBuffer() ;
			sb.append("sql:[")
			  .append(sql)
			  .append("], timeCost:[")
			  .append(nanoTime)
			  .append("ns]") ;

			logInfo(sb.toString()) ;
		}
	}

	public void logBatch(String sql, int repeatTimes, long nanoTime) {
		if(this.ignoreDemonThreadSQL && isDemonThread()){
			return ;
		}

		if(printSQL && nanoTime >= this.onlySlowSQLInNano){
			StringBuffer sb = new StringBuffer() ;
			sb.append("batch sql:[")
			  .append(sql)
			  .append("], repeatTimes:[")
			  .append(repeatTimes)
			  .append("], timeCost:[")
			  .append(nanoTime)
			  .append("ns]") ;

			logInfo(sb.toString()) ;
		}
	}

	public void logSQL(String sql, Object[] params, long nanoTime) {
		if(this.ignoreDemonThreadSQL && isDemonThread()){
			return ;
		}

		if(printSQL && nanoTime >= this.onlySlowSQLInNano){
			StringBuffer sb = new StringBuffer() ;
			sb.append("sql:[")
			  .append(sql) ;

			if(printSQLParams){
			  sb.append("], params is:[")
			  .append(ArrayUtil.arrayToString(params)) ;
			}

			sb.append("], timeCost:[")
			  .append(nanoTime)
			  .append("ns]") ;

			logInfo(sb.toString()) ;
		}
	}

	public void logSQL(String sql, int[] params, long nanoTime) {
		if(this.ignoreDemonThreadSQL && isDemonThread()){
			return ;
		}

		if(printSQL && nanoTime >= this.onlySlowSQLInNano){
			StringBuffer sb = new StringBuffer() ;
			sb.append("sql:[")
			  .append(sql) ;

			if(printSQLParams){
			  sb.append("], params is:[")
			  .append(ArrayUtil.arrayToString(params)) ;
			}

			sb.append("], timeCost:[")
			  .append(nanoTime)
			  .append("ns]") ;

			logInfo(sb.toString()) ;
		}
	}

	public void logSQL(BindedCompiledSQL bsql, long nanoTime) {
		if(this.ignoreDemonThreadSQL && isDemonThread()){
			return ;
		}

		if(printSQL && nanoTime >= this.onlySlowSQLInNano){
			StringBuffer sb = new StringBuffer() ;
			sb.append("sql:[")
			  .append(bsql.getSQLToRun()) ;

			if(printSQLParams){
			  sb.append("], params is:[")
			  .append(bsql.getBindedParams()) ;
			}

			sb.append("], timeCost:[")
			  .append(nanoTime)
			  .append("ns]") ;

			logInfo(sb.toString()) ;
		}
	}

	public void logSQL(BindedCompiledSQL bsql, String sqlStatment, long nanoTime){
		if(this.ignoreDemonThreadSQL && isDemonThread()){
			return ;
		}

		if(printSQL && nanoTime >= this.onlySlowSQLInNano){
			StringBuffer sb = new StringBuffer() ;
			sb.append("sql:[")
			  .append(sqlStatment) ;

			if(printSQLParams){
			  sb.append("], params is:[")
			  .append(bsql.getBindedParams()) ;
			}

			sb.append("], timeCost:[")
			  .append(nanoTime)
			  .append("ns]") ;

			logInfo(sb.toString()) ;
		}
	}

	public void onErrorProcess(String msg, Exception e) {
		if(this.logOnError){
			this.logInfo(msg, e) ;
		}

		if(this.haltOnError){
			throw new GuzzException(msg, e) ;
		}
	}

	public boolean configure(ServiceConfig[] scs) {
		if(scs == null || scs.length == 0){
			if(log.isInfoEnabled()){
				log.info("[guzzDebug] not found. alter system to production mode.") ;
			}

			resetToDefaultConfig() ;
			printGuzzDebugInfo() ;

			return true ;
		}

		Properties prop = scs[0].getProps() ;

		this.isDebugMode = "debug".equalsIgnoreCase(prop.getProperty("runMode")) ;
		this.haltOnError = "halt".equalsIgnoreCase(prop.getProperty("onError")) ;
		this.logOnError = "log".equalsIgnoreCase(prop.getProperty("onError")) ;
		this.printSQL = "true".equalsIgnoreCase(prop.getProperty("printSQL")) ;
		this.printSQLParams = "true".equalsIgnoreCase(prop.getProperty("printSQLParams")) ;
		this.ignoreDemonThreadSQL = "true".equalsIgnoreCase(prop.getProperty("ignoreDemonThreadSQL")) ;
		this.measureTime = "true".equalsIgnoreCase(prop.getProperty("measureTime")) ;

		String ms = prop.getProperty("onlySlowSQLInMillSeconds") ;

		if(StringUtil.notEmpty(ms)){
			this.onlySlowSQLInNano = Long.parseLong(ms) * 1000000 ;
		}

		printGuzzDebugInfo() ;

		return true ;
	}

	public boolean isAvailable() {
		return true;
	}

	public void shutdown() {
		resetToDefaultConfig() ;
	}

	protected void printGuzzDebugInfo(){
		if(log.isInfoEnabled()){
			String result = "guzz debug info:" ;

			result += "debugMode:" + this.isDebugMode ;
			result += ",logOnError:" + this.logOnError ;
			result += ",haltOnError:" + this.haltOnError ;
			result += ",printSQL:" + this.printSQL ;
			result += ",printSQLParams:" + this.printSQLParams ;
			result += ",measureTime:" + this.measureTime ;
			result += ",onlySlowSQLInNano:" + this.onlySlowSQLInNano ;

			log.info(result) ;
		}
	}

	protected void resetToDefaultConfig(){
		isDebugMode = false ;
		haltOnError = false ;
		logOnError = true ;
		printSQL = false ;
		printSQLParams = false ;
		measureTime = false ;
		onlySlowSQLInNano = 0L ;
	}

	protected void logInfo(String msg){
		if(log.isInfoEnabled()){
			log.info(msg) ;
		}else{
			//如果log4j info级别无法输出,直接按照System.out输出,不在自动调高级别按warning,error等打印。避免引起维护人员对程序出错的误判。
			System.out.println(msg);
		}
	}

	protected void logInfo(String msg, Throwable e){
		if(log.isInfoEnabled()){
			log.info(msg, e) ;
		}else{
			//如果log4j info级别无法输出,直接按照System.out输出,不在自动调高级别按warning,error等打印。避免引起维护人员对程序出错的误判。

			System.err.println(msg);
			e.printStackTrace(System.err) ;
		}
	}

	public void startup() {
	}

}


text:
class Test {

    interface I1 {
       void m(String s);
    }

    interface I2 {
       void m(Integer s);
    }

    interface I3 {
       void m(Object o);
    }

    static class Foo<X extends Number> {
        Foo(X x) { }
    }

    static <X extends Number> void foo(X x) { }

    static void meth1(I1 s) { }

    static void meth2(I2 s) { }

    static void meth3(I3 s) { }

    static void meth4(I1 s) { }
    static void meth4(I2 s) { }
    static void meth4(I3 s) { }

    static {
        meth1(Foo::<error descr="Invalid constructor reference: String cannot be converted to Number">new</error>);
        meth2(Foo::new);
        meth3(Foo::<error descr="Invalid constructor reference: Object cannot be converted to Number">new</error>);
        meth4<error descr="Ambiguous method call: both 'Test.meth4(I1)' and 'Test.meth4(I2)' match">(Foo::new)</error>;

        meth1(Test::<error descr="Invalid method reference: String cannot be converted to X">foo</error>);
        meth2(Test::foo);
        meth3(Test::<error descr="Invalid method reference: Object cannot be converted to X">foo</error>);
        meth4<error descr="Ambiguous method call: both 'Test.meth4(I1)' and 'Test.meth4(I2)' match">(Test::foo)</error>;
    }

    <X extends Number> void fooInstance(X x) { }
    interface II1 {
        <X extends String> void m(X x);
    }

    interface II2 {
        <X extends Integer> void m(X x);
    }

    interface II3 {
        <X> void m(X x);
    }

    void test() {
      II1 i1 = this::<error descr="Invalid method reference: X cannot be converted to X">fooInstance</error>;
      II2 i2 = this::fooInstance;
      II3 i3 = this::<error descr="Invalid method reference: X cannot be converted to X">fooInstance</error>;
    }
}


text:
#ifndef __RENDER_H
#define __RENDER_H

#include "req.h"

extern char *render_template(struct req *req, const char *tmpl);
extern char *render_page(struct req *req, const char *str);

#endif


text:
package.path = "./?.lua;".."./proto/?.lua;" .. package.path

local skynet = require "skynet"
--local sprotoparser = require "sprotoparser"
local sprotoloader = require "sprotoloader"
local proto = require "proto"

skynet.start(function()
	sprotoloader.save(proto.c2s, 1)
	sprotoloader.save(proto.s2c, 2)
	-- don't call skynet.exit() , because sproto.core may unload and the global slot become invalid
end)


text:
namespace Microsoft.Azure.Management.RecoveryServices.SiteRecovery
{
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Models;
    using System.Collections;
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// ReplicationLogicalNetworksOperations operations.
    /// </summary>
    public partial interface IReplicationLogicalNetworksOperations
    {
        /// <summary>
        /// Gets the list of logical networks under a fabric.
        /// </summary>
        /// <remarks>
        /// Lists all the logical networks of the Azure Site Recovery fabric
        /// </remarks>
        /// <param name='fabricName'>
        /// Server Id.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<IPage<LogicalNetwork>>> ListByReplicationFabricsWithHttpMessagesAsync(string fabricName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Gets a logical network with specified server id and logical network
        /// name.
        /// </summary>
        /// <remarks>
        /// Gets the details of a logical network.
        /// </remarks>
        /// <param name='fabricName'>
        /// Server Id.
        /// </param>
        /// <param name='logicalNetworkName'>
        /// Logical network name.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<LogicalNetwork>> GetWithHttpMessagesAsync(string fabricName, string logicalNetworkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Gets the list of logical networks under a fabric.
        /// </summary>
        /// <remarks>
        /// Lists all the logical networks of the Azure Site Recovery fabric
        /// </remarks>
        /// <param name='nextPageLink'>
        /// The NextLink from the previous successful call to List operation.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="Microsoft.Rest.Azure.CloudException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<IPage<LogicalNetwork>>> ListByReplicationFabricsNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
    }
}


text:
package main

import (
	"archive/zip"
	"bitbucket.org/kardianos/osext"
	"errors"
	"flag"
	"fmt"
	"github.com/BrentNoorda/slfsrv/browser"
	"github.com/BrentNoorda/slfsrv/bundle"
	"github.com/BrentNoorda/slfsrv/compiler"
	"github.com/BrentNoorda/slfsrv/config"
	"github.com/BrentNoorda/slfsrv/ssutil"
	"github.com/BrentNoorda/slfsrv/tempdir"
	"github.com/BrentNoorda/slfsrv/webserver"
	"math/rand"
	"os"
	"path"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

func parse_command_line() (helpWanted bool,
	bundleOut string,
	compile string, compileFrom string, compileReplaceOK bool,
	port int, verbose bool, configFile string, args []string, err error) {
	err = nil
	flag.BoolVar(&helpWanted, "help", false, "show help screen")
	flag.StringVar(&bundleOut, "bundle", "", "bundle directory into single file")
	flag.StringVar(&compile, "compile", "", "compile into standalone executable")
	flag.StringVar(&compileFrom, "compile-from", "", "executable source for standalone")
	flag.BoolVar(&compileReplaceOK, "-replace", false, "OK to replace bundle or compile output")
	flag.IntVar(&port, "port", 0, "port to server localhost app from")
	flag.BoolVar(&verbose, "verbose", false, "verbose")
	flag.StringVar(&configFile, "config-file", "", "filename of configuration json file")

	flag.Parse()
	args = flag.Args()

	if 2 < len(args) {
		err = errors.New("Huh? too many paths specified")
	} else if (bundleOut != "") && (compile != "") {
		err = errors.New("Cannot use both -bundle and -compile flags")
	} else if compileReplaceOK && (compile == "") && (bundleOut == "") {
		err = errors.New("Huh? -replace has no meaning without -compile or -bundle")
	} else if (compileFrom != "") && (compile == "") {
		err = errors.New("Huh? compile-from has no meaning without -compile")
	} else {
		if bundleOut != "" {
			lowerBundle := strings.ToLower(bundleOut)
			if !strings.HasSuffix(lowerBundle, ".slfsrv") {
				bundleOut = bundleOut + ".slfsrv"
			}
		}
	}
	return
}

func parse_compiled_command_line() (port int, verbose bool, err error) {
	err = nil
	flag.IntVar(&port, "port", 0, "port to server localhost app from")
	flag.BoolVar(&verbose, "verbose", false, "verbose")

	flag.Parse()

	return
}

func generate_secret_key() string {
	s := ""
	for i := 0; i < 5; i++ {
		var seg int = 100000 + rand.Intn(100000) // 100000 -> 199999
		s += strconv.Itoa(seg)
	}
	return s
}

func usage() {
	for _, t := range [...]string{
		"",
		"slfsrv - Launch web browser and serve local HTML/CSS/JS/ASSET files to",
		"         it; or compile everything into a standalone executable, for",
		"         multiple platforms, as distributable localhost apps;",
		"         or wrap a GUI around a command-line program.",
		"         For more info, see https://github.com/BrentNoorda/slfsrv/",
		"",
		"USAGE: slfsrv [flags...] [filePath [initialUrlPath]",
		"WHERE: filePath - path to initial file or directory to serve; if file (e.g.",
		"           index.html) then start with that file; if directory then",
		"           look for index.html (or index.htm) in that directory; if not",
		"           specified then look for index.html (or index.htm) in the",
		"           current directory",
		"           path may also be a *.slfsrv bundle created with -bundle",
		"       initialUrlPath - when filePath is simply a directory, then initialUrlPath",
		"           is the path to the first page to load within that directory",
		"flags:",
		"  -help - this help text",
		"  -bundle <out.slfsrv> - zip all contents of path into self-contained file",
		"                         to be executed later with slfsrv - the .slfsrv",
		"                         extension is required",
		"  -compile <output-name> - compile slfsrv and all contents of directory",
		"                           tree into a standalone executable",
		"  -compile-from <ss-source> - used with the '-compile' flag, this specifies a",
		"                              slfsrv executable to use (else will use",
		"                              the current slfsrv executable); this flag is",
		"                              useful for making cross-platform distributals (e.g.",
		"                              creating a windows executable from OSX)",
		"  -replace - used with the '-compile' or '-bundle' flags, this specifies",
		"             whether it is OK to replace the <output-name> file",
		"  -port <port#> - specify port to run server on, else will look for a random port",
		"                  that is not in use",
		"  -config-file <json file> - path to json config file name",
		"  -verbose - write out lots of message about what's going on (else silent)",
		"EXAMPLES:",
		"  slfsrv",
		"  slfsrv /myapp",
		"  slfsrv ../htmlgame/index.html",
		"  slfsrv -compile /myapp",
		"  slfsrv -compile /myapp -compile-from /tools/ss/win/slfsrv.exe",
		"  slfsrv c:\\user\\me photo/tools/photoview.html",
		"  slfsrv c:\\user\\me photo/tools/photoview.html -config-file ./config.json",
		"VERSION: " + bundle.Version,
		"",
	} {
		fmt.Println(filepath.FromSlash(t))
	}
}

func main() {

	var precompiled int = compiler.OffsetOfAppendedData()
	var err error = nil
	var bundleOut, compile, compileFrom, patharg, fullpatharg, initPathUrl, initQuery, storeFilespec, configFile string
	var helpWanted, compileReplaceOK, verbose, isdir bool
	var port int
	var cwd string
	var args []string
	var zipReader *zip.Reader

	rand.Seed(time.Now().Unix())

	var myselfExecutable string
	myselfExecutable, err = osext.Executable()
	if err != nil {
		fmt.Fprintf(os.Stderr, "could not determine location of self-server executable\n")
		return
	}

	if precompiled != 0 {
		helpWanted = false
		bundleOut = ""
		compile = ""
		compileFrom = ""
		configFile = ""
		fullpatharg = ""
		patharg = ""
		compileReplaceOK = false
		isdir = false
		args = []string{}

		port, verbose, err = parse_compiled_command_line()
		if err != nil {
			fmt.Fprintf(os.Stderr, "%s\n", err)
			return
		}

		zipReader, initPathUrl, err = bundle.Reader(myselfExecutable, precompiled)
		if err != nil {
			fmt.Fprintf(os.Stderr, "%s\n", err)
			return
		}

		storeFilespec = myselfExecutable + ".slfsrv-data"

	} else {

		// parse command-line inputs
		helpWanted, bundleOut, compile, compileFrom, compileReplaceOK, port, verbose, configFile, args, err = parse_command_line()
		if err != nil {
			fmt.Fprintf(os.Stderr, "%s\n", err)
			helpWanted = true
		}
		if helpWanted {
			usage()
			return
		}

		// figure out the initial path and root file to serve from
		if cwd, err = os.Getwd(); err != nil {
			fmt.Fprintf(os.Stderr, "%s\n", err)
			os.Exit(1)
		}
		cwd = filepath.ToSlash(cwd)

		config.ParseConfigFile(configFile)
		settings := config.GetSettings()
		fmt.Printf("config: %+v\n", *settings)

		if settings.Port != 0 {
			port = settings.Port
		}

		if len(args) < 2 {
			initPathUrl = ""
		} else {
			initPathUrl = args[1]
		}
		if len(args) == 0 {
			patharg = cwd
		} else {
			patharg = filepath.ToSlash(path.Clean(args[0]))
		}

		var queryIdx int = strings.Index(initPathUrl, "?")
		if queryIdx == -1 {
			initQuery = ""
		} else {
			initQuery = initPathUrl[queryIdx+1:]
			initPathUrl = initPathUrl[:queryIdx]
		}

		if initPathUrl == "" {
			// figure out if path arg is just a path (in which case add index.htm or index.html) or a full file
			if isdir, err = ssutil.IsDir(patharg); err != nil {
				fmt.Fprintf(os.Stderr, "%s\n", err)
				os.Exit(1)
			}
			if !isdir {
				patharg, initPathUrl = path.Split(patharg)
			}
		}
		fullpatharg = path.Clean(patharg)

		// if patharg is a subfolder of cwd then skip the cwd part so it is prettier
		patharg = ssutil.CleanPathRelativeToCwd(fullpatharg, cwd)

		// if initPathUrl not specified then guess at "index.htm" or "index.html"
		if initPathUrl == "" {
			var exists bool
			initPathUrl = "index.htm"
			if exists, _ = ssutil.FileOrDirExists(filepath.FromSlash(fullpatharg + "/" + initPathUrl)); !exists {
				initPathUrl = "index.html"
			}
		}
		storeFilespec = filepath.FromSlash(path.Join(fullpatharg, initPathUrl+".slfsrv-data"))

	}

	if bundleOut != "" {
		// BUNDLE into a standalone zip file
		if verbose {
			fmt.Printf("create compiled version from %s\n", filepath.FromSlash(patharg))
		}
		bundleOut = ssutil.CleanPathRelativeToCwd(bundleOut, cwd)
		err = bundle.Bundle(bundleOut, compileReplaceOK, patharg, initPathUrl, verbose)
		if err == nil {
			if verbose {
				fmt.Println("bundle SUCCESS! Created:", bundleOut)
			}
		}
		if err != nil {
			fmt.Fprintf(os.Stderr, "ERROR: %s\n", err)
		}

	} else if compile != "" {
		// COMPILE
		if compileFrom == "" {
			compileFrom = myselfExecutable
		}
		compileFrom = ssutil.CleanPathRelativeToCwd(compileFrom, cwd)
		if verbose {
			fmt.Printf("create compiled version from %s executable\n", compileFrom)
			fmt.Printf("with source files from %s/%s\n", filepath.FromSlash(patharg), initPathUrl)
		}

		compile = ssutil.CleanPathRelativeToCwd(compile, cwd)
		err = compiler.Compile(compile, compileReplaceOK, compileFrom, patharg, initPathUrl, verbose)
		if err == nil {
			if verbose {
				fmt.Println("compilation SUCCESS! Created:", compile)
			}
		}
		if err != nil {
			fmt.Fprintf(os.Stderr, "ERROR: %s\n", err)
		}
	} else {
		// SERVE
		exitChan := make(chan int)

		// we may be reading from a pre-bundled file, determine now if that is the case
		if (precompiled == 0) && !isdir {
			var zip_initPathUrl string
			zipReader, zip_initPathUrl, err = bundle.Reader(path.Join(patharg, initPathUrl), 0)

			if err == nil {
				storeFilespec = filepath.FromSlash(path.Join(fullpatharg, initPathUrl) + ".slfsrv-data")
				initPathUrl = zip_initPathUrl
			} else {
				zipReader = nil
			}
		}

		var secretKey string
		var keepAliveSeconds int64
		settings := config.GetSettings()

		if settings.SecretKey != "" {
			secretKey = settings.SecretKey
		} else {
			secretKey = generate_secret_key()
		}

		if settings.KeepAliveSeconds != 0 {
			keepAliveSeconds = settings.KeepAliveSeconds
		} else {
			keepAliveSeconds = 2
		}

		port = webserver.ListenAndServe(port, secretKey, keepAliveSeconds, zipReader, patharg, fullpatharg, initPathUrl,
			verbose, exitChan, myselfExecutable, storeFilespec)

		browser.LaunchDefaultBrowser(port, secretKey, initPathUrl, initQuery, verbose)

		<-exitChan

		tempdir.Cleanup(verbose)
	}
}


text:
<!--
  Copyright The Ohio State University Research Foundation, The University of Chicago -
Argonne National Laboratory, Emory University, SemanticBits LLC, and Ekagra Software Technologies Ltd.

  Distributed under the OSI-approved BSD 3-Clause License.
  See http://ncip.github.com/cagrid-core/LICENSE.txt for details.
-->
<?xml version="1.0"?>

<ivy-module version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:noNamespaceSchemaLocation="http://incubator.apache.org/ivy/schemas/ivy.xsd">

  <info organisation="caGrid" module="testUtils" revision="${project.version}">
    <license name="caGrid" url="http://cagrid.org/wiki/CaGrid:LICENSE-1.3"/>
    <description>System Testing Tools</description>
  </info>

  <configurations>
    <!-- Public Configurations-->
    <conf name="impl"  extends="default" visibility="private"/>

    <conf name="default" visibility="public"/>

    <!-- Containers-->
    <conf name="containers" visibility="public" description="All containers"
      extends="globus.container,tomcat.container,secure.tomcat.container"/>
    <conf name="globus.container" visibility="public"
      description="The globus container"/>
    <conf name="tomcat.container" visibility="public"
      description="The tomcat container"/>
    <conf name="secure.tomcat.container" visibility="public"
      description="The secure tomcat container"/>
  </configurations>

  <publications>
    <artifact name="caGrid-${ivy.module}" conf="default" type="jar"/>
    <artifact name="minimal-tomcat-5.0.28-with-globus-4.0.3" conf="tomcat.container" type="zip"/>
    <artifact name="apache-tomcat-6.0.32-testing" conf="tomcat.container" type="zip"/>
    <artifact name="minimal-secure-tomcat-5.0.28-with-globus-4.0.3" conf="secure.tomcat.container" type="zip"/>
    <artifact name="apache-tomcat-6.0.32-secure-testing" conf="secure.tomcat.container" type="zip"/>
  </publications>

  <dependencies>
  	<dependency rev="latest.integration" org="caGrid" name="testing" conf="default->system"/>
 	<dependency rev="latest.integration" org="caGrid" name="core" conf="default->default,test"/>

    <dependency rev="1.0" org="jdom" name="jdom" conf="default->*"/>
  </dependencies>
</ivy-module>


text:
<?php
/**
 * CPAC_Column_Post_Order
 *
 * @since 2.0
 */
class CPAC_Column_Post_Order extends CPAC_Column {

	/**
	 * @see CPAC_Column::init()
	 * @since 2.2.1
	 */
	public function init() {
		parent::init();

		$this->properties['type'] = 'column-order';
		$this->properties['label'] = __( 'Order', 'codepress-admin-columns' );
	}

	/**
	 * @see CPAC_Column::apply_conditional()
	 * @since 2.0
	 */
	public function apply_conditional() {
		return is_post_type_hierarchical( $this->get_post_type() ) || post_type_supports( $this->get_post_type(), 'page-attributes' );
	}

	/**
	 * @see CPAC_Column::get_value()
	 * @since 2.0
	 */
	public function get_value( $post_id ) {
		return $this->get_raw_value( $post_id );
	}

	/**
	 * @see CPAC_Column::get_raw_value()
	 * @since 2.0.3
	 */
	public function get_raw_value( $post_id ) {
		return get_post_field( 'menu_order', $post_id );
	}
}


text:
package com.opengamma.web.analytics.formatting;

import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import com.opengamma.analytics.financial.provider.curve.CurveBuildingBlock;
import com.opengamma.analytics.financial.provider.curve.CurveBuildingBlockBundle;
import com.opengamma.analytics.math.matrix.DoubleMatrix2D;
import com.opengamma.engine.value.ValueSpecification;
import com.opengamma.util.tuple.Pair;

/**
 *
 */
public class CurveBuildingBlockBundleFormatter extends AbstractFormatter<CurveBuildingBlockBundle> {
  private static final String MATRIX = "matrix";

  /**
   * @param doubleFormatter
   *          formats the discount factors
   */
  /* package */ CurveBuildingBlockBundleFormatter(final DoubleFormatter doubleFormatter) {
    super(CurveBuildingBlockBundle.class);
    addFormatter(new Formatter<CurveBuildingBlockBundle>(Format.EXPANDED) {
      @Override
      protected Object formatValue(final CurveBuildingBlockBundle value, final ValueSpecification valueSpec, final Object inlineKey) {
        return formatExpanded(value, valueSpec);
      }
    });
  }

  @Override
  public Object formatCell(final CurveBuildingBlockBundle value, final ValueSpecification valueSpec, final Object inlineKey) {
    return "Jacobian";
  }

  /**
   * Transforms the details object to an amount that can be displayed.
   *
   * @param value
   *          the FX forward details
   * @param valueSpec
   *          the value specification
   * @return the data
   */
  /* package */ Map<String, Object> formatExpanded(final CurveBuildingBlockBundle value, final ValueSpecification valueSpec) {
    final Map<String, Pair<CurveBuildingBlock, DoubleMatrix2D>> data = value.getData();
    int rows = 0;
    int columns = 0;
    for (final Map.Entry<String, Pair<CurveBuildingBlock, DoubleMatrix2D>> entry : data.entrySet()) {
      rows += entry.getValue().getSecond().getNumberOfRows();
      columns += entry.getValue().getSecond().getNumberOfColumns();
    }
    rows *= data.size();
    columns *= data.size();
    final String[] xLabels = new String[rows];
    final String[] yLabels = new String[columns];
    Arrays.fill(xLabels, "");
    Arrays.fill(yLabels, "");
    for (final Map.Entry<String, Pair<CurveBuildingBlock, DoubleMatrix2D>> entry1 : data.entrySet()) {
      final LinkedHashMap<String, Pair<Integer, Integer>> block = entry1.getValue().getFirst().getData();
      for (final Map.Entry<String, Pair<Integer, Integer>> entry2 : block.entrySet()) {
        xLabels[entry2.getValue().getFirst()] = entry2.getKey();
        yLabels[entry2.getValue().getFirst()] = entry2.getKey();
      }
    }
    final Map<String, Object> results = new HashMap<>();
    final Object[][] values = new Object[rows][columns];

    results.put(MATRIX, values);
    return results;
  }

  @Override
  public DataType getDataType() {
    return DataType.LABELLED_MATRIX_2D;
  }

}


text:
class Chouette::Geometry::AccessPointPresenter
  include Chouette::Geometry::GeneralPresenter

  def initialize(access_point)
    @access_point = access_point
  end

  def geometry
    to_point_feature( @access_point)
  end
end


text:
require "./db/seed_data"

data = []
10.times do
  post_id = SeedData.get_random(Post).id
  data += [ { user_id: SeedData.get_random(User).id, post_id: post_id, created_by: SeedData.get_random(User).id } ]
  data += [ { user_id: SeedData.get_random(User).id, post_id: post_id, created_by: SeedData.get_random(User).id } ]
end

SeedData.new('PostContributor').load(data)


text:
package org.apache.catalina.storeconfig;

import java.io.PrintWriter;

public interface IStoreFactory {
    StoreAppender getStoreAppender();

    void setStoreAppender(StoreAppender storeWriter);

    void setRegistry(StoreRegistry aRegistry);

    StoreRegistry getRegistry();

    void store(PrintWriter aWriter, int indent, Object aElement)
            throws Exception;

    void storeXMLHead(PrintWriter aWriter);
}


text:
package com.uber.tchannel.messages;

import com.google.common.collect.ImmutableMap;
import com.uber.tchannel.headers.ArgScheme;
import com.uber.tchannel.tracing.Trace;
import com.uber.tchannel.tracing.TraceableRequest;
import com.uber.tchannel.utils.TChannelUtilities;
import io.netty.buffer.ByteBuf;

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

public abstract class EncodedRequest<T> extends Request implements TraceableRequest {

    private static final ImmutableMap<ArgScheme, Serializer.SerializerInterface> DEFAULT_SERIALIZERS =
            ImmutableMap.of(ArgScheme.JSON, new JSONSerializer(), ArgScheme.THRIFT, new ThriftSerializer());

    private static final Serializer serializer = new Serializer(DEFAULT_SERIALIZERS);

    protected Map<String, String> headers;
    protected T body = null;

    protected EncodedRequest(Builder<T> builder) {
        super(builder);
        this.body = builder.body;
        this.headers = builder.headers;
    }

    protected EncodedRequest(long id, long ttl, Trace trace,
                         String service, Map<String, String> transportHeaders,
                         ByteBuf arg1, ByteBuf arg2, ByteBuf arg3) {
        super(id, ttl, trace, service, transportHeaders, arg1, arg2, arg3);
    }

    @Override
    public Map<String, String> getHeaders() {
        if (headers == null) {
            if (arg2 != null) {
                headers = serializer.decodeHeaders(this);
            } else {
                return new HashMap<>();
            }
        }

        return headers;
    }

    public String getHeader(String key) {
        return getHeaders().get(key);
    }

    @Override
    public void setHeaders(Map<String, String> headers) {
        if (arg2 != null) {
            arg2.release();
        }
        arg2 = serializer.encodeHeaders(headers, getArgScheme());
        this.headers = null;
    }

    public T getBody(Class<T> bodyType) {
        if (body == null) {
            if (arg3 != null) {
                body = serializer.decodeBody(this, bodyType);
            } else {
                return null;
            }
        }

        return body;
    }

    /**
     * @param <T> request body type
     */
    public static class Builder<T> extends Request.Builder {

        protected Map<String, String> headers = new HashMap<>();
        protected T body = null;
        protected ArgScheme argScheme;

        public Builder(String service, String endpoint) {
            super(service, endpoint);
        }

        public Builder(String service, ByteBuf arg1) {
            super(service, arg1);
        }

        @Override
        public Builder<T> setArg2(ByteBuf arg2) {
            if (arg2 != null && !this.headers.isEmpty()) {
                throw new IllegalStateException("Cannot set both `arg2` and `headers`.");
            }

            super.setArg2(arg2);
            return this;
        }

        @Override
        public Builder<T> setArg3(ByteBuf arg3) {
            if (arg3 != null && this.body != null) {
                throw new IllegalStateException("Cannot set both `arg3` and `body`.");
            }

            super.setArg3(arg3);
            return this;
        }

        public Builder<T> setHeader(String key, String value) {
            this.headers.put(key, value);
            return this;
        }

        public Builder<T> setHeaders(Map<String, String> headers) {
            this.headers = headers;
            return this;
        }

        public Builder<T> setBody(T body) {
            this.body = body;
            return this;
        }

        private Builder<T> validateHeader() {
            if (arg2 != null) {
                return this;
            }

            arg2 = serializer.encodeHeaders(this.headers, argScheme);

            return this;
        }

        private Builder<T> validateBody() {
            if (arg3 != null) {
                return this;
            }

            if (body == null) {
                arg3 = TChannelUtilities.emptyByteBuf;
            } else {
                arg3 = serializer.encodeBody(this.body, argScheme);
            }

            return this;
        }

        @Override
        public Builder<T> validate() {
            super.validate();
            this.validateHeader();
            this.validateBody();
            return this;
        }

    }

}


text:
package com.cloudera.sqoop.lib;

import junit.framework.TestCase;

/**
 * Test the boolean parser.
 */
public class TestBooleanParser extends TestCase {
  public void testBoolParser() {
    assertTrue(BooleanParser.valueOf("true"));
    assertTrue(BooleanParser.valueOf("TRUE"));
    assertTrue(BooleanParser.valueOf("True"));
    assertTrue(BooleanParser.valueOf("t"));
    assertTrue(BooleanParser.valueOf("T"));
    assertTrue(BooleanParser.valueOf("on"));
    assertTrue(BooleanParser.valueOf("On"));
    assertTrue(BooleanParser.valueOf("ON"));
    assertTrue(BooleanParser.valueOf("yes"));
    assertTrue(BooleanParser.valueOf("yEs"));
    assertTrue(BooleanParser.valueOf("YES"));
    assertTrue(BooleanParser.valueOf("1"));

    assertFalse(BooleanParser.valueOf(null));

    assertFalse(BooleanParser.valueOf("no"));
    assertFalse(BooleanParser.valueOf("false"));
    assertFalse(BooleanParser.valueOf("FALSE"));
    assertFalse(BooleanParser.valueOf("0"));
    assertFalse(BooleanParser.valueOf("off"));
    assertFalse(BooleanParser.valueOf("OFF"));
    assertFalse(BooleanParser.valueOf("anything else in the world"));
  }
}


text:
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/websockets/websocket_basic_handshake_stream.h"

#include <stddef.h>
#include <algorithm>
#include <iterator>
#include <set>
#include <string>
#include <unordered_set>
#include <utility>
#include <vector>

#include "base/base64.h"
#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/metrics/histogram_macros.h"
#include "base/metrics/sparse_histogram.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/time/time.h"
#include "crypto/random.h"
#include "net/base/io_buffer.h"
#include "net/http/http_request_headers.h"
#include "net/http/http_request_info.h"
#include "net/http/http_response_body_drainer.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_status_code.h"
#include "net/http/http_stream_parser.h"
#include "net/socket/client_socket_handle.h"
#include "net/socket/websocket_transport_client_socket_pool.h"
#include "net/websockets/websocket_basic_stream.h"
#include "net/websockets/websocket_deflate_parameters.h"
#include "net/websockets/websocket_deflate_predictor.h"
#include "net/websockets/websocket_deflate_predictor_impl.h"
#include "net/websockets/websocket_deflate_stream.h"
#include "net/websockets/websocket_deflater.h"
#include "net/websockets/websocket_extension_parser.h"
#include "net/websockets/websocket_handshake_challenge.h"
#include "net/websockets/websocket_handshake_constants.h"
#include "net/websockets/websocket_handshake_request_info.h"
#include "net/websockets/websocket_handshake_response_info.h"
#include "net/websockets/websocket_stream.h"

namespace net {

namespace {

const char kConnectionErrorStatusLine[] = "HTTP/1.1 503 Connection Error";

}  // namespace

// TODO(ricea): If more extensions are added, replace this with a more general
// mechanism.
struct WebSocketExtensionParams {
  bool deflate_enabled = false;
  WebSocketDeflateParameters deflate_parameters;
};

namespace {

enum GetHeaderResult {
  GET_HEADER_OK,
  GET_HEADER_MISSING,
  GET_HEADER_MULTIPLE,
};

std::string MissingHeaderMessage(const std::string& header_name) {
  return std::string("'") + header_name + "' header is missing";
}

std::string MultipleHeaderValuesMessage(const std::string& header_name) {
  return
      std::string("'") +
      header_name +
      "' header must not appear more than once in a response";
}

std::string GenerateHandshakeChallenge() {
  std::string raw_challenge(websockets::kRawChallengeLength, '\0');
  crypto::RandBytes(string_as_array(&raw_challenge), raw_challenge.length());
  std::string encoded_challenge;
  base::Base64Encode(raw_challenge, &encoded_challenge);
  return encoded_challenge;
}

void AddVectorHeaderIfNonEmpty(const char* name,
                               const std::vector<std::string>& value,
                               HttpRequestHeaders* headers) {
  if (value.empty())
    return;
  headers->SetHeader(name, base::JoinString(value, ", "));
}

GetHeaderResult GetSingleHeaderValue(const HttpResponseHeaders* headers,
                                     const base::StringPiece& name,
                                     std::string* value) {
  size_t iter = 0;
  size_t num_values = 0;
  std::string temp_value;
  while (headers->EnumerateHeader(&iter, name, &temp_value)) {
    if (++num_values > 1)
      return GET_HEADER_MULTIPLE;
    *value = temp_value;
  }
  return num_values > 0 ? GET_HEADER_OK : GET_HEADER_MISSING;
}

bool ValidateHeaderHasSingleValue(GetHeaderResult result,
                                  const std::string& header_name,
                                  std::string* failure_message) {
  if (result == GET_HEADER_MISSING) {
    *failure_message = MissingHeaderMessage(header_name);
    return false;
  }
  if (result == GET_HEADER_MULTIPLE) {
    *failure_message = MultipleHeaderValuesMessage(header_name);
    return false;
  }
  DCHECK_EQ(result, GET_HEADER_OK);
  return true;
}

bool ValidateUpgrade(const HttpResponseHeaders* headers,
                     std::string* failure_message) {
  std::string value;
  GetHeaderResult result =
      GetSingleHeaderValue(headers, websockets::kUpgrade, &value);
  if (!ValidateHeaderHasSingleValue(result,
                                    websockets::kUpgrade,
                                    failure_message)) {
    return false;
  }

  if (!base::LowerCaseEqualsASCII(value, websockets::kWebSocketLowercase)) {
    *failure_message =
        "'Upgrade' header value is not 'WebSocket': " + value;
    return false;
  }
  return true;
}

bool ValidateSecWebSocketAccept(const HttpResponseHeaders* headers,
                                const std::string& expected,
                                std::string* failure_message) {
  std::string actual;
  GetHeaderResult result =
      GetSingleHeaderValue(headers, websockets::kSecWebSocketAccept, &actual);
  if (!ValidateHeaderHasSingleValue(result,
                                    websockets::kSecWebSocketAccept,
                                    failure_message)) {
    return false;
  }

  if (expected != actual) {
    *failure_message = "Incorrect 'Sec-WebSocket-Accept' header value";
    return false;
  }
  return true;
}

bool ValidateConnection(const HttpResponseHeaders* headers,
                        std::string* failure_message) {
  // Connection header is permitted to contain other tokens.
  if (!headers->HasHeader(HttpRequestHeaders::kConnection)) {
    *failure_message = MissingHeaderMessage(HttpRequestHeaders::kConnection);
    return false;
  }
  if (!headers->HasHeaderValue(HttpRequestHeaders::kConnection,
                               websockets::kUpgrade)) {
    *failure_message = "'Connection' header value must contain 'Upgrade'";
    return false;
  }
  return true;
}

bool ValidateSubProtocol(
    const HttpResponseHeaders* headers,
    const std::vector<std::string>& requested_sub_protocols,
    std::string* sub_protocol,
    std::string* failure_message) {
  size_t iter = 0;
  std::string value;
  std::unordered_set<std::string> requested_set(requested_sub_protocols.begin(),
                                                requested_sub_protocols.end());
  int count = 0;
  bool has_multiple_protocols = false;
  bool has_invalid_protocol = false;

  while (!has_invalid_protocol || !has_multiple_protocols) {
    std::string temp_value;
    if (!headers->EnumerateHeader(&iter, websockets::kSecWebSocketProtocol,
                                  &temp_value))
      break;
    value = temp_value;
    if (requested_set.count(value) == 0)
      has_invalid_protocol = true;
    if (++count > 1)
      has_multiple_protocols = true;
  }

  if (has_multiple_protocols) {
    *failure_message =
        MultipleHeaderValuesMessage(websockets::kSecWebSocketProtocol);
    return false;
  } else if (count > 0 && requested_sub_protocols.size() == 0) {
    *failure_message =
        std::string("Response must not include 'Sec-WebSocket-Protocol' "
                    "header if not present in request: ")
        + value;
    return false;
  } else if (has_invalid_protocol) {
    *failure_message =
        "'Sec-WebSocket-Protocol' header value '" +
        value +
        "' in response does not match any of sent values";
    return false;
  } else if (requested_sub_protocols.size() > 0 && count == 0) {
    *failure_message =
        "Sent non-empty 'Sec-WebSocket-Protocol' header "
        "but no response was received";
    return false;
  }
  *sub_protocol = value;
  return true;
}

bool ValidateExtensions(const HttpResponseHeaders* headers,
                        std::string* accepted_extensions_descriptor,
                        std::string* failure_message,
                        WebSocketExtensionParams* params) {
  size_t iter = 0;
  std::string header_value;
  std::vector<std::string> header_values;
  // TODO(ricea): If adding support for additional extensions, generalise this
  // code.
  bool seen_permessage_deflate = false;
  while (headers->EnumerateHeader(&iter, websockets::kSecWebSocketExtensions,
                                  &header_value)) {
    WebSocketExtensionParser parser;
    if (!parser.Parse(header_value)) {
      // TODO(yhirano) Set appropriate failure message.
      *failure_message =
          "'Sec-WebSocket-Extensions' header value is "
          "rejected by the parser: " +
          header_value;
      return false;
    }

    const std::vector<WebSocketExtension>& extensions = parser.extensions();
    for (const auto& extension : extensions) {
      if (extension.name() == "permessage-deflate") {
        if (seen_permessage_deflate) {
          *failure_message = "Received duplicate permessage-deflate response";
          return false;
        }
        seen_permessage_deflate = true;
        auto& deflate_parameters = params->deflate_parameters;
        if (!deflate_parameters.Initialize(extension, failure_message) ||
            !deflate_parameters.IsValidAsResponse(failure_message)) {
          *failure_message = "Error in permessage-deflate: " + *failure_message;
          return false;
        }
        // Note that we don't have to check the request-response compatibility
        // here because we send a request compatible with any valid responses.
        // TODO(yhirano): Place a DCHECK here.

        header_values.push_back(header_value);
      } else {
        *failure_message = "Found an unsupported extension '" +
                           extension.name() +
                           "' in 'Sec-WebSocket-Extensions' header";
        return false;
      }
    }
  }
  *accepted_extensions_descriptor = base::JoinString(header_values, ", ");
  params->deflate_enabled = seen_permessage_deflate;
  return true;
}

}  // namespace

WebSocketBasicHandshakeStream::WebSocketBasicHandshakeStream(
    std::unique_ptr<ClientSocketHandle> connection,
    WebSocketStream::ConnectDelegate* connect_delegate,
    bool using_proxy,
    std::vector<std::string> requested_sub_protocols,
    std::vector<std::string> requested_extensions,
    WebSocketStreamRequest* request)
    : state_(connection.release(), using_proxy),
      connect_delegate_(connect_delegate),
      http_response_info_(nullptr),
      requested_sub_protocols_(requested_sub_protocols),
      requested_extensions_(requested_extensions),
      stream_request_(request) {
  DCHECK(connect_delegate);
  DCHECK(request);
}

WebSocketBasicHandshakeStream::~WebSocketBasicHandshakeStream() {}

int WebSocketBasicHandshakeStream::InitializeStream(
    const HttpRequestInfo* request_info,
    RequestPriority priority,
    const BoundNetLog& net_log,
    const CompletionCallback& callback) {
  url_ = request_info->url;
  state_.Initialize(request_info, priority, net_log, callback);
  return OK;
}

int WebSocketBasicHandshakeStream::SendRequest(
    const HttpRequestHeaders& headers,
    HttpResponseInfo* response,
    const CompletionCallback& callback) {
  DCHECK(!headers.HasHeader(websockets::kSecWebSocketKey));
  DCHECK(!headers.HasHeader(websockets::kSecWebSocketProtocol));
  DCHECK(!headers.HasHeader(websockets::kSecWebSocketExtensions));
  DCHECK(headers.HasHeader(HttpRequestHeaders::kOrigin));
  DCHECK(headers.HasHeader(websockets::kUpgrade));
  DCHECK(headers.HasHeader(HttpRequestHeaders::kConnection));
  DCHECK(headers.HasHeader(websockets::kSecWebSocketVersion));
  DCHECK(parser());

  http_response_info_ = response;

  // Create a copy of the headers object, so that we can add the
  // Sec-WebSockey-Key header.
  HttpRequestHeaders enriched_headers;
  enriched_headers.CopyFrom(headers);
  std::string handshake_challenge;
  if (handshake_challenge_for_testing_) {
    handshake_challenge = *handshake_challenge_for_testing_;
    handshake_challenge_for_testing_.reset();
  } else {
    handshake_challenge = GenerateHandshakeChallenge();
  }
  enriched_headers.SetHeader(websockets::kSecWebSocketKey, handshake_challenge);

  AddVectorHeaderIfNonEmpty(websockets::kSecWebSocketExtensions,
                            requested_extensions_,
                            &enriched_headers);
  AddVectorHeaderIfNonEmpty(websockets::kSecWebSocketProtocol,
                            requested_sub_protocols_,
                            &enriched_headers);

  handshake_challenge_response_ =
      ComputeSecWebSocketAccept(handshake_challenge);

  DCHECK(connect_delegate_);
  std::unique_ptr<WebSocketHandshakeRequestInfo> request(
      new WebSocketHandshakeRequestInfo(url_, base::Time::Now()));
  request->headers.CopyFrom(enriched_headers);
  connect_delegate_->OnStartOpeningHandshake(std::move(request));

  return parser()->SendRequest(
      state_.GenerateRequestLine(), enriched_headers, response, callback);
}

int WebSocketBasicHandshakeStream::ReadResponseHeaders(
    const CompletionCallback& callback) {
  // HttpStreamParser uses a weak pointer when reading from the
  // socket, so it won't be called back after being destroyed. The
  // HttpStreamParser is owned by HttpBasicState which is owned by this object,
  // so this use of base::Unretained() is safe.
  int rv = parser()->ReadResponseHeaders(
      base::Bind(&WebSocketBasicHandshakeStream::ReadResponseHeadersCallback,
                 base::Unretained(this),
                 callback));
  if (rv == ERR_IO_PENDING)
    return rv;
  return ValidateResponse(rv);
}

int WebSocketBasicHandshakeStream::ReadResponseBody(
    IOBuffer* buf,
    int buf_len,
    const CompletionCallback& callback) {
  return parser()->ReadResponseBody(buf, buf_len, callback);
}

void WebSocketBasicHandshakeStream::Close(bool not_reusable) {
  // This class ignores the value of |not_reusable| and never lets the socket be
  // re-used.
  if (parser())
    parser()->Close(true);
}

bool WebSocketBasicHandshakeStream::IsResponseBodyComplete() const {
  return parser()->IsResponseBodyComplete();
}

bool WebSocketBasicHandshakeStream::IsConnectionReused() const {
  return parser()->IsConnectionReused();
}

void WebSocketBasicHandshakeStream::SetConnectionReused() {
  parser()->SetConnectionReused();
}

bool WebSocketBasicHandshakeStream::CanReuseConnection() const {
  return false;
}

int64_t WebSocketBasicHandshakeStream::GetTotalReceivedBytes() const {
  return 0;
}

int64_t WebSocketBasicHandshakeStream::GetTotalSentBytes() const {
  return 0;
}

bool WebSocketBasicHandshakeStream::GetLoadTimingInfo(
    LoadTimingInfo* load_timing_info) const {
  return state_.connection()->GetLoadTimingInfo(IsConnectionReused(),
                                                load_timing_info);
}

void WebSocketBasicHandshakeStream::GetSSLInfo(SSLInfo* ssl_info) {
  parser()->GetSSLInfo(ssl_info);
}

void WebSocketBasicHandshakeStream::GetSSLCertRequestInfo(
    SSLCertRequestInfo* cert_request_info) {
  parser()->GetSSLCertRequestInfo(cert_request_info);
}

bool WebSocketBasicHandshakeStream::GetRemoteEndpoint(IPEndPoint* endpoint) {
  if (!state_.connection() || !state_.connection()->socket())
    return false;

  return state_.connection()->socket()->GetPeerAddress(endpoint) == OK;
}

void WebSocketBasicHandshakeStream::PopulateNetErrorDetails(
    NetErrorDetails* /*details*/) {
  return;
}

Error WebSocketBasicHandshakeStream::GetSignedEKMForTokenBinding(
    crypto::ECPrivateKey* key,
    std::vector<uint8_t>* out) {
  NOTREACHED();
  return ERR_NOT_IMPLEMENTED;
}

void WebSocketBasicHandshakeStream::Drain(HttpNetworkSession* session) {
  HttpResponseBodyDrainer* drainer = new HttpResponseBodyDrainer(this);
  drainer->Start(session);
  // |drainer| will delete itself.
}

void WebSocketBasicHandshakeStream::SetPriority(RequestPriority priority) {
  // TODO(ricea): See TODO comment in HttpBasicStream::SetPriority(). If it is
  // gone, then copy whatever has happened there over here.
}

UploadProgress WebSocketBasicHandshakeStream::GetUploadProgress() const {
  return UploadProgress();
}

HttpStream* WebSocketBasicHandshakeStream::RenewStreamForAuth() {
  // Return null because we don't support renewing the stream.
  return nullptr;
}

std::unique_ptr<WebSocketStream> WebSocketBasicHandshakeStream::Upgrade() {
  // The HttpStreamParser object has a pointer to our ClientSocketHandle. Make
  // sure it does not touch it again before it is destroyed.
  state_.DeleteParser();
  WebSocketTransportClientSocketPool::UnlockEndpoint(state_.connection());
  std::unique_ptr<WebSocketStream> basic_stream(
      new WebSocketBasicStream(state_.ReleaseConnection(), state_.read_buf(),
                               sub_protocol_, extensions_));
  DCHECK(extension_params_.get());
  if (extension_params_->deflate_enabled) {
    UMA_HISTOGRAM_ENUMERATION(
        "Net.WebSocket.DeflateMode",
        extension_params_->deflate_parameters.client_context_take_over_mode(),
        WebSocketDeflater::NUM_CONTEXT_TAKEOVER_MODE_TYPES);

    return std::unique_ptr<WebSocketStream>(new WebSocketDeflateStream(
        std::move(basic_stream), extension_params_->deflate_parameters,
        std::unique_ptr<WebSocketDeflatePredictor>(
            new WebSocketDeflatePredictorImpl)));
  } else {
    return basic_stream;
  }
}

void WebSocketBasicHandshakeStream::SetWebSocketKeyForTesting(
    const std::string& key) {
  handshake_challenge_for_testing_.reset(new std::string(key));
}

void WebSocketBasicHandshakeStream::ReadResponseHeadersCallback(
    const CompletionCallback& callback,
    int result) {
  callback.Run(ValidateResponse(result));
}

void WebSocketBasicHandshakeStream::OnFinishOpeningHandshake() {
  DCHECK(http_response_info_);
  WebSocketDispatchOnFinishOpeningHandshake(connect_delegate_,
                                            url_,
                                            http_response_info_->headers,
                                            http_response_info_->response_time);
}

int WebSocketBasicHandshakeStream::ValidateResponse(int rv) {
  DCHECK(http_response_info_);
  // Most net errors happen during connection, so they are not seen by this
  // method. The histogram for error codes is created in
  // Delegate::OnResponseStarted in websocket_stream.cc instead.
  if (rv >= 0) {
    const HttpResponseHeaders* headers = http_response_info_->headers.get();
    const int response_code = headers->response_code();
    UMA_HISTOGRAM_SPARSE_SLOWLY("Net.WebSocket.ResponseCode", response_code);
    switch (response_code) {
      case HTTP_SWITCHING_PROTOCOLS:
        OnFinishOpeningHandshake();
        return ValidateUpgradeResponse(headers);

      // We need to pass these through for authentication to work.
      case HTTP_UNAUTHORIZED:
      case HTTP_PROXY_AUTHENTICATION_REQUIRED:
        return OK;

      // Other status codes are potentially risky (see the warnings in the
      // WHATWG WebSocket API spec) and so are dropped by default.
      default:
        // A WebSocket server cannot be using HTTP/0.9, so if we see version
        // 0.9, it means the response was garbage.
        // Reporting "Unexpected response code: 200" in this case is not
        // helpful, so use a different error message.
        if (headers->GetHttpVersion() == HttpVersion(0, 9)) {
          OnFailure("Error during WebSocket handshake: Invalid status line");
        } else {
          OnFailure(base::StringPrintf(
              "Error during WebSocket handshake: Unexpected response code: %d",
              headers->response_code()));
        }
        OnFinishOpeningHandshake();
        return ERR_INVALID_RESPONSE;
    }
  } else {
    if (rv == ERR_EMPTY_RESPONSE) {
      OnFailure("Connection closed before receiving a handshake response");
      return rv;
    }
    OnFailure(std::string("Error during WebSocket handshake: ") +
              ErrorToString(rv));
    OnFinishOpeningHandshake();
    // Some error codes (for example ERR_CONNECTION_CLOSED) get changed to OK at
    // higher levels. To prevent an unvalidated connection getting erroneously
    // upgraded, don't pass through the status code unchanged if it is
    // HTTP_SWITCHING_PROTOCOLS.
    if (http_response_info_->headers &&
        http_response_info_->headers->response_code() ==
            HTTP_SWITCHING_PROTOCOLS) {
      http_response_info_->headers->ReplaceStatusLine(
          kConnectionErrorStatusLine);
    }
    return rv;
  }
}

int WebSocketBasicHandshakeStream::ValidateUpgradeResponse(
    const HttpResponseHeaders* headers) {
  extension_params_.reset(new WebSocketExtensionParams);
  std::string failure_message;
  if (ValidateUpgrade(headers, &failure_message) &&
      ValidateSecWebSocketAccept(
          headers, handshake_challenge_response_, &failure_message) &&
      ValidateConnection(headers, &failure_message) &&
      ValidateSubProtocol(headers,
                          requested_sub_protocols_,
                          &sub_protocol_,
                          &failure_message) &&
      ValidateExtensions(headers,
                         &extensions_,
                         &failure_message,
                         extension_params_.get())) {
    return OK;
  }
  OnFailure("Error during WebSocket handshake: " + failure_message);
  return ERR_INVALID_RESPONSE;
}

void WebSocketBasicHandshakeStream::OnFailure(const std::string& message) {
  stream_request_->OnFailure(message);
}

}  // namespace net


text:
<!--
  Author:       Sam Ruby (http://www.intertwingly.net/blog/)
  Copyright:    Copyright (c) 2006 Sam Ruby
-->

<!--
  Description:  valid rating - v-chip
  Expect:       !InvalidMediaRating
-->

<rss version="2.0" xmlns:media="http://search.yahoo.com/mrss/">
<channel>
<title>My Movie Review Site</title>
<link>http://www.foo.com</link>
<description>I review movies.</description>
        <item>
                <title>Movie Title: Is this a good movie?</title>
                <link>http://www.foo.com/item1.htm</link>
                <media:content url="http://www.foo.com/trailer.mov"
                fileSize="12216320" type="video/quicktime" expression="sample"/>
                <media:rating scheme="urn:v-chip">tv-pg</media:rating>
        </item>
</channel>
</rss>


text:
class CreateEpisodeCategories < ActiveRecord::Migration
  def change
    create_table :episode_categories do |t|
      t.string  :name
      t.integer :episodes_count, default: 1

      t.timestamps
    end
  end
end


text:
/*
Script: Language.pl.js
	MooTools FileManager - Language Strings in Polish

Translation:
	[Marek Kalucki](http://www.webdeco.pl)
    [Grzegorz Nakonieczny](http://naki.info/)
*/

FileManager.Language.pl = {
	more: 'Szczegóły',
	width: 'Szerokość:',
	height: 'Wysokość:',

	ok: 'Ok',
	open: 'Wybierz plik',
	upload: 'Wyślij',
	create: 'Utwórz folder',
	createdir: 'Podaj nazwę folderu:',
	cancel: 'Anuluj',
	error: 'Błąd',

	information: 'Informacje',
	type: 'Typ:',
	size: 'Rozmiar:',
	dir: 'Ścieżka:',
	modified: 'Ost. modyfikacja:',
	preview: 'Podgląd',
	close: 'Zamknij',
	destroy: 'Usuń',
	destroyfile: 'Czy na pewno chcesz usunąć ten plik?',

	rename: 'Zmień nazwę',
	renamefile: 'Podaj nową nazwę pliku:',
	rn_mv_cp: 'Rename/Move/Copy',

	download: 'Pobierz',
	nopreview: 'Podgląd niedostępny',

	title: 'Tytuł:',
	artist: 'Wykonawca:',
	album: 'Płyta:',
	length: 'Długość:',
	bitrate: 'Przepływność:',

	deselect: 'Odznacz',

	nodestroy: 'Usuwanie plików z serwera zostało wyłączone.',

	toggle_side_boxes: 'Thumbnail view',
	toggle_side_list: 'List view',
	show_dir_thumb_gallery: 'Show thumbnails of the files in the preview pane',
	drag_n_drop: 'Drag & drop has been enabled for this directory',
	drag_n_drop_disabled: 'Drag & drop has been temporarily disabled for this directory',
	goto_page: 'Go to page',

	'backend.disabled': 'Wysyłanie plików na serwer zostało wyłączone.',
	'backend.authorized': 'Nie jesteś upoważniony do wysyłania plików na serwer.',
	'backend.path': 'Folder do wysyłania plików nie istnieje. Skontaktuj się z administratorem.',
	'backend.exists': 'Folder do wysyłania plików istnieje. Skontaktuj się z administratorem.',
	'backend.mime': 'Typ wybranego pliku jest niedozwolony.',
	'backend.extension': 'Wysyłany plik ma nieznane lub niedozwolone rozszerzenie.',
	'backend.size': 'Rozmiar wysyłanego pliku jest zbyt duży. Wyślij mniejszy plik (jeśli wysyłasz obrazy-zmniejsz obraz na swoim komputerze i ponów wysyłanie).',
	'backend.partial': 'Plik nie został wysłany w całości. Ponów próbę wysyłki pliku.',
	'backend.nofile': 'Nie wybrano pliku do wysyłki.',
	'backend.default': 'Wystąpił błąd w trakcie wysyłki.',
	'backend.path_not_writable': 'You do not have write/upload permissions for this directory.',
	'backend.filename_maybe_too_large': 'The filename/path is probably too long for the server filesystem. Please retry with a shorter file name.',
	'backend.fmt_not_allowed': 'You are not allowed to upload this file format/name.',
	'backend.read_error': 'Cannot read / download the specified file.',
	'backend.unidentified_error': 'An unindentified error occurred while communicating with the backend (web server).',

	'backend.nonewfile': 'A new name for the file to be moved / copied is missing.',
	'backend.corrupt_img': 'This file is a not a image or a corrupt file: ', // path
	'backend.resize_inerr': 'This file could not be resized due to an internal error.',
	'backend.copy_failed': 'An error occurred while copying the file / directory: ', // oldlocalpath : newlocalpath
	'backend.delete_cache_entries_failed': 'An error occurred when attempting to delete the item cache (thumbnails, metadata)',
	'backend.mkdir_failed': 'An error occurred when attempting to create the directory: ', // path
	'backend.move_failed': 'An error occurred while moving / renaming the file / directory: ', // oldlocalpath : newlocalpath
	'backend.path_tampering': 'Path tampering detected.',
	'backend.realpath_failed': 'Cannot translate the given file specification to a valid storage location: ', // $path
	'backend.unlink_failed': 'An error occurred when attempting to delete the file / directory: ',  // path

	// Image.class.php:
	'backend.process_nofile': 'The image processing unit did not receive a valid file location to work on.',
	'backend.imagecreatetruecolor_failed': 'The image processing unit failed: GD imagecreatetruecolor() failed.',
	'backend.imagealphablending_failed': 'The image processing unit failed: cannot perform the required image alpha blending.',
	'backend.imageallocalpha50pctgrey_failed': 'The image processing unit failed: cannot allocate space for the alpha channel and the 50% background.',
	'backend.imagecolorallocatealpha_failed': 'The image processing unit failed: cannot allocate space for the alpha channel for this color image.',
	'backend.imagerotate_failed': 'The image processing unit failed: GD imagerotate() failed.',
	'backend.imagecopyresampled_failed': 'The image processing unit failed: GD imagecopyresampled() failed. Image resolution: ', /* x * y */
	'backend.imagecopy_failed': 'The image processing unit failed: GD imagecopy() failed.',
	'backend.imageflip_failed': 'The image processing unit failed: cannot flip the image.',
	'backend.imagejpeg_failed': 'The image processing unit failed: GD imagejpeg() failed.',
	'backend.imagepng_failed': 'The image processing unit failed: GD imagepng() failed.',
	'backend.imagegif_failed': 'The image processing unit failed: GD imagegif() failed.',
	'backend.imagecreate_failed': 'The image processing unit failed: GD imagecreate() failed.',
	'backend.cvt2truecolor_failed': 'conversion to True Color failed. Image resolution: ', /* x * y */
	'backend.no_imageinfo': 'Corrupt image or not an image file at all.',
	'backend.img_will_not_fit': 'Server error: image does not fit in available RAM; minimum required (estimate): ', /* XXX MBytes */
	'backend.unsupported_imgfmt': 'unsupported image format: ',    /* jpeg/png/gif/... */

	/* FU */
	uploader: {
		unknown: 'Wystąpił nieznany błąd.',
		sizeLimitMin: 'Nie można wybrać "${name}" (${size}), minimalny rozmiar pliku to ${size_min}!',
		sizeLimitMax: 'Nie można wybrać "${name}" (${size}), maksymalny rozmiar pliku to ${size_max}!',
		mod_security: 'No response was given from the uploader, this may mean that "mod_security" is active on the server and one of the rules in mod_security has cancelled this request.  If you can not disable mod_security, you may need to use the NoFlash Uploader.'
	},

	flash: {
		hidden: 'Aby włączyć wysyłanie plików, odblokuj go w swojej przeglądarce i odśwież stronę (prawdopodobnie wysyłanie plików jest blokowane przez wtyczkę Adblock).',
		disabled: 'Aby włączyć wysyłanie plików, odblokuj obiekt Flash i odśwież stronę (prawdopodobnie wysyłanie plików blokowane jest przez wtyczkę Flashblock).',
		flash: 'Aby wysyłać pliki na serwer, należy zainstalować w przeglądarce wtyczkę Adobe Flash.'
	},

	resizeImages: 'Zmniejsz duże obrazy w trakcie wysyłania',

    serialize: 'Zapisz galerię',
    gallery: {
        text: 'Podpis',
        save: 'Zapisz',
        remove: 'Usuń element z galerii',
        drag: 'Przeciągnij tutaj elementy aby utworzyć galerię...'
    }
};


text:
import {
  customAttribute,
  View,
  BoundViewFactory,
  ViewSlot,
  ViewResources,
  TargetInstruction,
  bindable,
  templateController
} from 'aurelia-templating';
import {
  updateOverrideContext,
  ArrayRepeatStrategy,
  createFullOverrideContext,
  RepeatStrategyLocator,
  AbstractRepeater,
  getItemsSourceExpression,
  isOneTime,
  unwrapExpression,
  updateOneTimeBinding,
  viewsRequireLifecycle
} from 'aurelia-templating-resources';
import {
  inject,
  Container
} from 'aurelia-dependency-injection';
import {
  DOM
} from 'aurelia-pal';
import {
  ObserverLocator
} from 'aurelia-binding';
export declare interface TemplateStrategy {
  getScrollContainer(element: Element): Element;
  moveViewFirst(view: View, topBuffer: Element): void;
  moveViewLast(view: View, bottomBuffer: Element): void;
  createTopBufferElement(element: Element): Element;
  createBottomBufferElement(element: Element): Element;
  removeBufferElements(element: Element, topBuffer: Element, bottomBuffer: Element): void;
  getFirstElement(topBuffer: Element): Element;
  getLastView(bottomBuffer: Element): Element;
  getTopBufferDistance(topBuffer: Element): number;
}
export declare class DomHelper {
  getElementDistanceToTopOfDocument(element: Element): number;
  hasOverflowScroll(element: Element): boolean;
}

//Placeholder attribute to prohibit use of this attribute name in other places
export declare class VirtualRepeatNext {
  constructor();
  attached(): any;
  bind(bindingContext?: any, overrideContext?: any): void;
}
export declare function calcOuterHeight(element: Element): number;
export declare function insertBeforeNode(view: View, bottomBuffer: number): void;

/**
* Update the override context.
* @param startIndex index in collection where to start updating.
*/
export declare function updateVirtualOverrideContexts(repeat: VirtualRepeat, startIndex: number): void;
export declare function rebindAndMoveView(repeat: VirtualRepeat, view: View, index: number, moveToBottom: boolean): void;
export declare function getStyleValue(element: Element, style: string): any;
export declare function getElementDistanceToBottomViewPort(element: Element): number;
export declare function getElementDistanceToTopViewPort(element: Element): number;

/**
* A strategy for repeating a template over an array.
*/
export declare class ArrayVirtualRepeatStrategy extends ArrayRepeatStrategy {

  // create first item to calculate the heights
  createFirstItem(repeat: VirtualRepeat): void;

  /**
    * Handle the repeat's collection instance changing.
    * @param repeat The repeater instance.
    * @param items The new array instance.
    */
  instanceChanged(repeat: VirtualRepeat, items: Array<any>): void;

  /**
    * Handle the repeat's collection instance mutating.
    * @param repeat The repeat instance.
    * @param array The modified array.
    * @param splices Records of array changes.
    */
  instanceMutated(repeat: VirtualRepeat, array: Array<any>, splices: any): void;
}
export declare class TemplateStrategyLocator {
  constructor(container: Container);
  getStrategy(element: Element): TemplateStrategy;
}
export declare class TableStrategy {
  tableCssReset: any;
  constructor(domHelper?: any);
  getScrollContainer(element: Element): Element;
  moveViewFirst(view: View, topBuffer: Element): void;
  moveViewLast(view: View, bottomBuffer: Element): void;
  createTopBufferElement(element: Element): Element;
  createBottomBufferElement(element: Element): Element;
  removeBufferElements(element: Element, topBuffer: Element, bottomBuffer: Element): void;
  getFirstElement(topBuffer: Element): Element;
  getLastElement(bottomBuffer: Element): Element;
  getTopBufferDistance(topBuffer: Element): number;
}
export declare class DefaultTemplateStrategy {
  getScrollContainer(element: Element): Element;
  moveViewFirst(view: View, topBuffer: Element): void;
  moveViewLast(view: View, bottomBuffer: Element): void;
  createTopBufferElement(element: Element): Element;
  createBottomBufferElement(element: Element): Element;
  removeBufferElements(element: Element, topBuffer: Element, bottomBuffer: Element): void;
  getFirstElement(topBuffer: Element): Element;
  getLastElement(bottomBuffer: Element): Element;
  getTopBufferDistance(topBuffer: Element): number;
}
export declare class VirtualRepeatStrategyLocator extends RepeatStrategyLocator {
  constructor();
}
export declare class VirtualRepeat extends AbstractRepeater {
  items: any;
  local: any;
  constructor(element: Element, viewFactory: BoundViewFactory, instruction: TargetInstruction, viewSlot: ViewSlot, viewResources: ViewResources, observerLocator: ObserverLocator, strategyLocator: VirtualRepeatStrategyLocator, templateStrategyLocator: TemplateStrategyLocator, domHelper: DomHelper);
  attached(): void;
  bind(bindingContext?: any, overrideContext?: any): void;
  call(context?: any, changes?: any): void;
  detached(): void;
  itemsChanged(): void;
  unbind(): void;
  handleCollectionMutated(collection?: any, changes?: any): void;
  handleInnerCollectionMutated(collection?: any, changes?: any): void;

  // @override AbstractRepeater
  viewCount(): any;
  views(): any;
  view(index?: any): any;
  addView(bindingContext?: any, overrideContext?: any): any;
  insertView(index?: any, bindingContext?: any, overrideContext?: any): any;
  removeAllViews(returnToCache?: any, skipAnimation?: any): any;
  removeView(index?: any, returnToCache?: any, skipAnimation?: any): any;
  updateBindings(view: View): any;
}


text:
(function(angular){
	"use strict";
	angular.module('workzone.orchestration')
		.controller('addScriptParamsCtrl',['$scope', '$modalInstance','items', 'toastr',function($scope, $modalInstance,$items, toastr){
			//default selection type
			$scope.params=[];
			for(var i =0; i < $items.noOfParams; i++){
				$scope.params.push({});
			}
			$scope.add = function() {
			  $scope.params.push({});
			};
			$scope.removeScriptInputParams = function(paramInput) {
				if($scope.params.length > 1){
					var idx = $scope.params.indexOf(paramInput);
					$scope.params.splice(idx,1);
				}else{
					toastr.error('Cannot delete the row');
				}
			};
			$scope.cancel = function() {
				$modalInstance.dismiss('cancel');
			};
			$scope.ok=function(){
				var checkParam = false;
				for(var i =0; i<$scope.params.length; i++){
					if(Object.keys($scope.params[i]).length === 0){
						checkParam = false;
						toastr.error('Please enter parameters');
						return false;
					}else{
						checkParam = true;
					}
				}
				if(checkParam){
					$modalInstance.close($scope.params);
				}

			};
		}
	]);
})(angular);


text:
from pytest import raises
import numpy as np

from neuroanalysis.data import TSeries

def test_trace_timing():
    # Make sure sample timing is handled exactly--need to avoid fp error here
    a = np.random.normal(size=300)
    sr = 50000
    dt = 2e-5
    t = np.arange(len(a)) * dt

    # trace with no timing information
    tr = TSeries(a)
    assert not tr.has_timing
    assert not tr.has_time_values
    with raises(TypeError):
        tr.dt
    with raises(TypeError):
        tr.sample_rate
    with raises(TypeError):
        tr.time_values
    with raises(TypeError):
        tr.time_at(0)
    with raises(TypeError):
        tr.index_at(0.1)
    with raises(TypeError):
        tr.value_at(0.1)

    view = tr[100:200]
    assert not tr.has_timing
    assert not tr.has_time_values

    # invalid data
    with raises(ValueError):
        TSeries(data=np.zeros((10, 10)))

    # invalid timing information
    with raises(TypeError):
        TSeries(data=a, dt=dt, time_values=t)
    with raises(TypeError):
        TSeries(data=a, sample_rate=sr, time_values=t)
    with raises(TypeError):
        TSeries(data=a, dt=dt, t0=0, time_values=t)
    with raises(TypeError):
        TSeries(data=a, dt=dt, t0=0, sample_rate=sr)
    with raises(ValueError):
        TSeries(data=a, time_values=t[:-1])

    # trace with only dt
    tr = TSeries(a, dt=dt)
    assert tr.dt == dt
    assert np.allclose(tr.sample_rate, sr)
    check_trace(tr, data=a, time_values=t, has_timing=True, has_time_values=False, regularly_sampled=True)

    # trace with only sample_rate
    tr = TSeries(a, sample_rate=sr)
    assert tr.dt == dt
    assert tr.sample_rate == sr
    assert np.all(tr.time_values == t)
    check_trace(tr, data=a, time_values=t, has_timing=True, has_time_values=False, regularly_sampled=True)

    # trace with only regularly-sampled time_values
    tr = TSeries(a, time_values=t)
    assert tr.dt == dt
    assert np.allclose(tr.sample_rate, sr)
    assert np.all(tr.time_values == t)
    check_trace(tr, data=a, time_values=t, has_timing=True, has_time_values=True, regularly_sampled=True)

    # trace with irregularly-sampled time values
    t1 = np.cumsum(np.random.normal(loc=1, scale=0.02, size=a.shape))
    tr = TSeries(a, time_values=t1)
    assert tr.dt == t1[1] - t1[0]
    assert np.all(tr.time_values == t1)
    check_trace(tr, data=a, time_values=t1, has_timing=True, has_time_values=True, regularly_sampled=False)

def check_trace(tr, data, time_values, has_timing, has_time_values, regularly_sampled):
    """Make sure trace timing is working for his trace and nested views on it.
    """
    check_timing(tr, data, time_values, has_timing, has_time_values, regularly_sampled)

    # modify t0
    t0 = time_values[0]
    tr.t0 = 123.4
    check_timing(tr, data=data, time_values=time_values+(123.4-t0), has_timing=has_timing, has_time_values=has_time_values, regularly_sampled=regularly_sampled)
    # and return back
    tr.t0 = t0

    if tr.has_time_values:  # fp errors for views are different based on whether time value array was specified
        time_values = (time_values + (123.4 - t0)) + (t0 - 123.4)
    check_timing(tr, data=data, time_values=time_values, has_timing=has_timing, has_time_values=has_time_values, regularly_sampled=regularly_sampled)

    # test view
    view = tr[100:200]
    t = tr.time_values
    assert view.t0 == t[100]
    assert view.time_values[0] == view.t0
    assert view._meta['dt'] == tr._meta['dt']
    assert view._meta['sample_rate'] == tr._meta['sample_rate']

    if tr.has_time_values:  # fp errors for views are different based on whether time value array was specified
        view_t = tr.time_values[100:200]
    else:
        view_t = tr.time_values[100] + tr.time_values[:100]
    check_timing(view, data=tr.data[100:200], time_values=view_t, has_timing=has_timing, has_time_values=has_time_values, regularly_sampled=regularly_sampled)

    # test nested view
    if tr.regularly_sampled:
        view2 = view.time_slice(view.t0 + 20*tr.dt, view.t0 + 50*tr.dt)

    else:
        # don't try time_slice with irregularly sampled
        view2 = view[20:50]
    assert view2.t0 == view.time_values[20] == tr.time_values[120]
    if tr.has_time_values:  # fp errors for views are different based on whether time value array was specified
        view_t2 = tr.time_values[120:150]
    else:
        view_t2 = view.time_values[20] + tr.time_values[:30]
    check_timing(view2, data=tr.data[120:150], time_values=view_t2, has_timing=has_timing, has_time_values=has_time_values, regularly_sampled=regularly_sampled)

    # modify view t0
    view.t0 = 0
    assert view.t0 == 0
    # make sure view has updated time values
    if tr.has_time_values:  # fp errors for views are different based on whether time value array was specified
        view_t = tr.time_values[100:200]-tr.time_values[100]
    else:
        view_t = tr.time_values[:100]
    check_timing(view, data=tr.data[100:200], time_values=view_t, has_timing=has_timing, has_time_values=has_time_values, regularly_sampled=regularly_sampled)
    # make sure the original trace and the sub-view are unaffected
    check_timing(tr, data, time_values, has_timing, has_time_values, regularly_sampled)
    check_timing(view2, data=tr.data[120:150], time_values=view_t2, has_timing=has_timing, has_time_values=has_time_values, regularly_sampled=regularly_sampled)

def check_timing(tr, data, time_values, has_timing, has_time_values, regularly_sampled):
    assert np.all(tr.time_values == time_values)
    assert tr.has_timing is has_timing
    assert tr.has_time_values is has_time_values
    assert tr.regularly_sampled is regularly_sampled

    assert tr.t_end == tr.time_values[-1]

    # test scalar argument for index_at, time_at, and value_at
    index = 5
    assert tr.value_at(time_values[index]) == tr.data[index]
    assert tr.time_at(index) == time_values[index]
    dt = time_values[index] - time_values[index-1]
    for t in [time_values[index], time_values[index]+dt*0.4, time_values[index]-dt*0.4]:
        index2 = tr.index_at(t)
        assert isinstance(index2, int)
        assert index2 == index

    # test array argument for index_at, time_at, and value_at
    t = [time_values[5], time_values[10]]
    indices = tr.index_at(t)
    assert np.all(indices == [5, 10])
    assert indices.dtype == int
    assert np.all(tr.value_at(t) == tr.data[indices])
    assert np.all(tr.time_at([5, 10]) == t)
    indices = np.arange(len(tr))
    assert np.all(tr.value_at(tr.time_at(indices)) == tr.data)
    assert np.all(tr.index_at(tr.time_at(indices)) == indices)


text:
module PdflibMini
  module Handle
    class Data3d < Base
      def initialize(data3d, p)
        super(data3d)
        @p = p
      end
    end
  end
end


text:
<?php

class HTMLPurifier_AttrDef_CSS_AlphaValue extends HTMLPurifier_AttrDef_CSS_Number
{

    public function __construct()
    {
        parent::__construct(false); // opacity is non-negative, but we will clamp it
    }

    /**
     * @param string               $number
     * @param HTMLPurifier_Config  $config
     * @param HTMLPurifier_Context $context
     * @return string
     */
    public function validate($number, $config, $context)
    {
        $result = parent::validate($number, $config, $context);
        if ($result === false) {
            return $result;
        }
        $float = (float)$result;
        if ($float < 0.0) {
            $result = '0';
        }
        if ($float > 1.0) {
            $result = '1';
        }

        return $result;
    }
}

// vim: et sw=4 sts=4


text:
<?php

require '../vendor/autoload.php';

class defaultController {
	function defaultAction($data = array()) {
		header('Location: ' . baseurl('note', true));
	}
}