text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.Collections;

namespace CCFTools
{
    public delegate void SaveNeededEventHandler(Object sender, SaveNeededEventArgs e);
    public delegate void CreateNeededEventHandler(Object sender, CreateNeededEventArgs e);

    public delegate string UpdateObject(ref object data);
    //public delegate string CreateObject(ref object data);
    public delegate string ValidateObject(object data);

    class ExtendedDataGridView : DataGridView
    {
        //private BindingSource dataBindingSource;
        //private string[] dataProperties;

        public event SaveNeededEventHandler SaveNeeded;
        public event CreateNeededEventHandler CreateNeeded;

        private UpdateObject updateObject;
        //private CreateObject createObject;
        private ValidateObject validateObject;

        private bool onlyAdding;
        public bool OnlyAdding
        {
            get
            {
                return onlyAdding;
            }
            set
            {
                onlyAdding = (bool)value;
            }
        }

        /*
        public object DataBindingSource
        {
            get
            {
                return dataBindingSource;
            }
            set
            {
                dataBindingSource = (BindingSource )value;
                dataBindingSource.CurrentChanged += new EventHandler(dataBindingSource_CurrentChanged);
            }
        }
        */
        void ExtendedDataGridView_CurrentChanged(object sender, EventArgs e)
        {
            BindingSource dataBindingSource = (BindingSource)DataSource;
            if (dataBindingSource.Current == null)
            {
                currentValue = null;
            }
            else
            {
                currentValue = Clone(dataBindingSource.Current);
            }
        }

        /*public string[] DataProperties
        {
            get
            {
                return dataProperties;
            }
            set
            {
                dataProperties = value;
            }
        }
         * */
        public UpdateObject UpdateObjectDelegate
        {
            get
            {
                return updateObject;
            }
            set
            {
                updateObject = value;
            }
        }
       public ValidateObject ValidateObjectDelegate
        {
            get
            {
                return validateObject;
            }
            set
            {
                validateObject = value;
            }
        }

        private object currentValue;
        private bool rowCancel;
//        private bool newRow;

        public ExtendedDataGridView()
        {
            this.EditMode = DataGridViewEditMode.EditOnEnter;
            this.VirtualMode = true;
            this.RowLeave += new DataGridViewCellEventHandler(ExtendedDataGridView_RowLeave);
            this.CancelRowEdit += new QuestionEventHandler(ExtendedDataGridView_CancelRowEdit);
            this.RowValidating += new DataGridViewCellCancelEventHandler(ExtendedDataGridView_RowValidating);
            this.DataSourceChanged += new EventHandler(ExtendedDataGridView_DataSourceChanged);
            this.RowEnter += new DataGridViewCellEventHandler(ExtendedDataGridView_RowEnter);
            this.ShowRowErrors = true;
        }

        void ExtendedDataGridView_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (onlyAdding == true)
            {
                this.ReadOnly = false;
                if (this.Rows[e.RowIndex].IsNewRow || this.IsCurrentRowDirty)
                {
                    this.Rows[e.RowIndex].ReadOnly = false;
                }
                else
                {
                    this.Rows[e.RowIndex].ReadOnly = true;
                }
            }
//            else
//            {
//                this.Rows[e.RowIndex].ReadOnly = false;
//            }
        }

        void ExtendedDataGridView_DataSourceChanged(object sender, EventArgs e)
        {
            ((BindingSource)this.DataSource).CurrentChanged += new EventHandler(ExtendedDataGridView_CurrentChanged);

        }

        void ExtendedDataGridView_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (rowCancel)
            {
                e.Cancel = true;
                rowCancel = false;
            }
            else
            {
                if (CurrentRow != null)
                    CurrentRow.ErrorText = "";
            }
        }

        void ExtendedDataGridView_CancelRowEdit(object sender, QuestionEventArgs e)
        {
            BindingSource dataBindingSource = (BindingSource)DataSource;

            CopyObject(currentValue, dataBindingSource.Current);

            NotifyCurrentCellDirty(false);
            CurrentRow.ErrorText = "";
        }

        void ExtendedDataGridView_RowLeave(object sender, DataGridViewCellEventArgs e)
        {

            saveCurrentItem();

        }

        public void saveCurrentItem()
        {
            if (IsCurrentRowDirty)
            {
                BindingSource dataBindingSource = (BindingSource)DataSource;

                this.EndEdit();
                string err = validateObject(dataBindingSource.Current);
                if (err != null)
                {
                }
                else
                {
                    object tempObject = Clone(dataBindingSource.Current);
                    err = updateObject(ref tempObject);
                    CopyObject(tempObject, dataBindingSource.Current);
                }
                if (err != null)
                {
                    rowCancel = true;
                    CurrentRow.ErrorText = err;
                }
            }
        }

        protected bool RaiseSaveNeeded(object toSave)
        {
            if (SaveNeeded != null)
            {
                SaveNeededEventArgs args = new SaveNeededEventArgs(toSave);
                SaveNeeded(this, args);
                return args.Success;
            }
            return true;
        }
        protected bool RaiseCreateNeeded(object toSave)
        {
            if (CreateNeeded != null)
            {
                CreateNeededEventArgs args = new CreateNeededEventArgs(toSave);
                CreateNeeded(this, args);
                return args.Success;
            }
            return true;
        }

        public bool IsEqual(object o1, object o2)
        {
            FieldInfo[] fields1 = o1.GetType().GetFields();
            PropertyInfo[] properties1 = o1.GetType().GetProperties();
            FieldInfo[] fields2 = o2.GetType().GetFields();
            PropertyInfo[] properties2 = o2.GetType().GetProperties();

            int i = 0;
            foreach (PropertyInfo p1 in properties1)
            {
                if (p1.GetValue(o1, null) == null && properties2[i].GetValue(o2, null) == null)
                {

                }
                else
                {
                    if (p1.GetValue(o1, null) == null && properties2[i].GetValue(o2, null) != null)
                    {
                        return false;
                    }
                    if (p1.GetValue(o1, null) != null && properties2[i].GetValue(o2, null) == null)
                    {
                        return false;
                    }

                    if (!(p1.GetValue(o1, null).Equals(properties2[i].GetValue(o2, null))))
                    {
                        return false;
                    }
                }
                i++;
            }
            i = 0;
            foreach (FieldInfo f1 in fields1)
            {
                if (!f1.GetValue(o1).Equals(fields2[i].GetValue(o2)))
                {
                    return false;
                }
            }
            return true;
        }

        public object Clone(object toClone)
        {
            //First we create an instance of this specific type.
            object newObject = Activator.CreateInstance(toClone.GetType());
            CopyObject(toClone, newObject);
            return newObject;
        }

        public void CopyObject(object toCopy, object target)
        {
            //We get the array of fields for the new type instance.
            FieldInfo[] fields = target.GetType().GetFields();
            PropertyInfo[] properties = target.GetType().GetProperties();

            int i = 0;
            foreach (PropertyInfo fi in toCopy.GetType().GetProperties())
            {
                //We query if the fiels support the ICloneable interface.
                Type ICloneType = fi.PropertyType.
                            GetInterface("ICloneable", true);

                if (ICloneType != null && fi.GetValue(toCopy, null) != null)
                {
                    //Getting the ICloneable interface from the object.
                    ICloneable IClone = (ICloneable)fi.GetValue(toCopy, null);

                    //We use the clone method to set the new value to the field.
                    properties[i].SetValue(target, IClone.Clone(), null);
                }
                else
                {
                    // If the field doesn't support the ICloneable
                    // interface then just set it.
                    properties[i].SetValue(target, fi.GetValue(toCopy, null), null);
                }

                //Now we check if the object support the
                //IEnumerable interface, so if it does
                //we need to enumerate all its items and check if
                //they support the ICloneable interface.
                Type IEnumerableType = fi.PropertyType.GetInterface
                                ("IEnumerable", true);
                if (IEnumerableType != null)
                {
                    //Get the IEnumerable interface from the field.
                    IEnumerable IEnum = (IEnumerable)fi.GetValue(toCopy, null);

                    //This version support the IList and the
                    //IDictionary interfaces to iterate on collections.
                    Type IListType = properties[i].PropertyType.GetInterface
                                        ("IList", true);
                    Type IDicType = properties[i].PropertyType.GetInterface
                                        ("IDictionary", true);

                    int j = 0;
                    if (IListType != null)
                    {
                        //Getting the IList interface.
                        IList list = (IList)properties[i].GetValue(target, null);

                        foreach (object obj in IEnum)
                        {
                            //Checking to see if the current item
                            //support the ICloneable interface.
                            ICloneType = obj.GetType().
                                GetInterface("ICloneable", true);

                            if (ICloneType != null)
                            {
                                //If it does support the ICloneable interface,
                                //we use it to set the clone of
                                //the object in the list.
                                ICloneable clone = (ICloneable)obj;

                                list[j] = clone.Clone();
                            }

                            //NOTE: If the item in the list is not
                            //support the ICloneable interface then in the
                            //cloned list this item will be the same
                            //item as in the original list
                            //(as long as this type is a reference type).

                            j++;
                        }
                    }
                    else if (IDicType != null)
                    {
                        //Getting the dictionary interface.
                        IDictionary dic = (IDictionary)properties[i].
                                            GetValue(target, null);
                        j = 0;

                        foreach (DictionaryEntry de in IEnum)
                        {
                            //Checking to see if the item
                            //support the ICloneable interface.
                            ICloneType = de.Value.GetType().
                                GetInterface("ICloneable", true);

                            if (ICloneType != null)
                            {
                                ICloneable clone = (ICloneable)de.Value;

                                dic[de.Key] = clone.Clone();
                            }
                            j++;
                        }
                    }
                }
                i++;
            }

            i = 0;
            foreach (FieldInfo fi in toCopy.GetType().GetFields())
            {
                //We query if the fiels support the ICloneable interface.
                Type ICloneType = fi.FieldType.
                            GetInterface("ICloneable", true);

                if (ICloneType != null)
                {
                    //Getting the ICloneable interface from the object.
                    ICloneable IClone = (ICloneable)fi.GetValue(this);

                    //We use the clone method to set the new value to the field.
                    fields[i].SetValue(target, IClone.Clone());
                }
                else
                {
                    // If the field doesn't support the ICloneable
                    // interface then just set it.
                    fields[i].SetValue(target, fi.GetValue(this));
                }

                //Now we check if the object support the
                //IEnumerable interface, so if it does
                //we need to enumerate all its items and check if
                //they support the ICloneable interface.
                Type IEnumerableType = fi.FieldType.GetInterface
                                ("IEnumerable", true);
                if (IEnumerableType != null)
                {
                    //Get the IEnumerable interface from the field.
                    IEnumerable IEnum = (IEnumerable)fi.GetValue(this);

                    //This version support the IList and the
                    //IDictionary interfaces to iterate on collections.
                    Type IListType = fields[i].FieldType.GetInterface
                                        ("IList", true);
                    Type IDicType = fields[i].FieldType.GetInterface
                                        ("IDictionary", true);

                    int j = 0;
                    if (IListType != null)
                    {
                        //Getting the IList interface.
                        IList list = (IList)fields[i].GetValue(target);

                        foreach (object obj in IEnum)
                        {
                            //Checking to see if the current item
                            //support the ICloneable interface.
                            ICloneType = obj.GetType().
                                GetInterface("ICloneable", true);

                            if (ICloneType != null)
                            {
                                //If it does support the ICloneable interface,
                                //we use it to set the clone of
                                //the object in the list.
                                ICloneable clone = (ICloneable)obj;

                                list[j] = clone.Clone();
                            }

                            //NOTE: If the item in the list is not
                            //support the ICloneable interface then in the
                            //cloned list this item will be the same
                            //item as in the original list
                            //(as long as this type is a reference type).

                            j++;
                        }
                    }
                    else if (IDicType != null)
                    {
                        //Getting the dictionary interface.
                        IDictionary dic = (IDictionary)fields[i].
                                            GetValue(target);
                        j = 0;

                        foreach (DictionaryEntry de in IEnum)
                        {
                            //Checking to see if the item
                            //support the ICloneable interface.
                            ICloneType = de.Value.GetType().
                                GetInterface("ICloneable", true);

                            if (ICloneType != null)
                            {
                                ICloneable clone = (ICloneable)de.Value;

                                dic[de.Key] = clone.Clone();
                            }
                            j++;
                        }
                    }
                }
                i++;
            }
        }

    }

    public class SaveNeededEventArgs : EventArgs
    {
        private object toSave;
        private bool success;
        private string errorMessage;
        public SaveNeededEventArgs(object toSave)
        {
            this.toSave = toSave;
        }

        public object ToSave
        {
            get
            {
                return toSave;
            }
        }
        public bool Success
        {
            get
            {
                return success;
            }
            set
            {
                success = value;
            }
        }
        public String ErrorMessage
        {
            get
            {
                return errorMessage;
            }
            set
            {
                errorMessage = value;
            }
        }

    }

    public class CreateNeededEventArgs : EventArgs
    {
        private object toCreate;
        private bool success;
        private string errorMessage;
        public CreateNeededEventArgs(object toCreate)
        {
            this.toCreate = toCreate;
        }

        public object ToCreate
        {
            get
            {
                return toCreate;
            }
        }

        public bool Success
        {
            get
            {
                return success;
            }
            set
            {
                success = value;
            }
        }
        public String ErrorMessage
        {
            get
            {
                return errorMessage;
            }
            set
            {
                errorMessage = value;
            }
        }

    }
}


text:
using System.ComponentModel.Composition;

namespace GameRes.Formats.UMeSoft
{
    [Export(typeof(AudioFormat))]
    public sealed class WstrAudio : AudioFormat
    {
        public override string         Tag { get { return "STR"; } }
        public override string Description { get { return "U-Me Soft audio file"; } }
        public override uint     Signature { get { return 0x52545357; } } // 'WSTR'
        public override bool      CanWrite { get { return false; } }

        public override SoundInput TryOpen (IBinaryStream file)
        {
            var header = file.ReadHeader (0x20);
            var format = new WaveFormat {
                FormatTag = 1,
                Channels = header.ToUInt16 (4),
                SamplesPerSecond = header.ToUInt32 (8),
                BitsPerSample = header.ToUInt16 (6),
            };
            format.BlockAlign = (ushort)(format.Channels * format.BitsPerSample / 8);
            format.SetBPS();
            var input = new StreamRegion (file.AsStream, 0x20);
            return new RawPcmInput (input, format);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * Renderer class for php files
 *
 * @author      Oliver Rockstedt, <info@sourcebox.de>
 * @license     BSD
 */

/**
 * Renderer class
 *
 * @package     Xote
 */
class Xote_Renderer_Php extends Xote_Renderer
{
    /**
     * Render
     *
     * @param	string			$file				File
     * @param	array			$options			Additional options
     * @return  void
     */
    public function render($file, $options = NULL)
    {
        ob_start();
        include($file);
        $result = ob_get_contents();
        ob_end_clean();
        return $result;
    }
}

?>


text:
NS_ASSUME_NONNULL_BEGIN

static NSString * const EXUpdatesDatabaseV7Filename = @"expo-v7.db";

@implementation EXUpdatesDatabaseMigration7To8

- (NSString *)filename
{
  return EXUpdatesDatabaseV7Filename;
}

- (BOOL)runMigrationOnDatabase:(struct sqlite3 *)db error:(NSError ** _Nullable)error
{
  // https://www.sqlite.org/lang_altertable.html#otheralter
  if (sqlite3_exec(db, @"ALTER TABLE \"assets\" ADD COLUMN \"extra_request_headers\" TEXT".UTF8String, NULL, NULL, NULL) != SQLITE_OK) return NO;
  return YES;
}

@end

NS_ASSUME_NONNULL_END


text:
require File.dirname(__FILE__) + '/../test_helper'

class ExpressionTest < Test::Unit::TestCase
  fixtures :expressions

  def setup
    @expression = Expression.find(1)
  end

  # Replace this with your real tests.
  def test_truth
    assert_kind_of Expression,  @expression
  end
end


text:
package main

import (
	"bytes"
	"crypto/tls"
	"encoding/json"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"os/user"
	"path/filepath"
	"runtime"
	"strings"
	"time"
)

type HostGetter struct {
	DownloadLocation *string
	CacheLocation    *string
	User             *string
	Password         *string
	CacheFileName    *string
	HostPattern      *string
	HostPrefix       string
	CacheDuration    *time.Duration
}

type HostData struct {
	Name string
}
type Host struct {
	Host HostData
}

func (self *HostGetter) downloadHosts() ([]byte, error) {
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	client := &http.Client{Transport: tr}
	req, err := http.NewRequest("GET", *self.DownloadLocation, nil)
	if err != nil {
		log.Printf("could not create new http request for %s", self.DownloadLocation)
		return nil, err
	}
	req.SetBasicAuth(*self.User, *self.Password)
	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("Accept", "application/json")
	res, err := client.Do(req)
	if err != nil {
		log.Printf("could not open http connection to download config from %s", *self.DownloadLocation)
		return nil, err
	}

	data, err := ioutil.ReadAll(res.Body)
	defer res.Body.Close()
	if err != nil {
		log.Printf("could not download config from %s", self.DownloadLocation)
		return nil, err
	}
	return data, nil
}

func (self *HostGetter) getHosts() (rt string, err error) {
	cacheLoc := filepath.Join(*self.CacheLocation, *self.CacheFileName)
	fi, err := os.Stat(cacheLoc)
	if err != nil {
		log.Printf("no file in cache, downloading %s (%v)", cacheLoc, err)
	} else if !time.Now().After(fi.ModTime().Add(*self.CacheDuration)) {
		log.Printf("found file in cache")
		var data []byte
		data, err = ioutil.ReadFile(cacheLoc)
		if err != nil {
			log.Printf("corrupt file in cache, downloading %s (%v)", cacheLoc, err)
		} else {
			rt = string(data)
			return
		}
	}

	rt, err = self.downloadParseHosts()
	if err == nil {
		log.Printf("downloaded and parsed - trying to save to cache")
		errd := os.MkdirAll(*self.CacheLocation, os.ModePerm)
		if errd != nil {
			log.Printf("could not create cache dir %s (%v)", *self.CacheLocation, errd)
			return
		}
		errf := ioutil.WriteFile(cacheLoc, []byte(rt), os.ModePerm)
		if errf != nil {
			log.Printf("downloaded and parsed ok, could not save to cache %v", errf)
		} else {
			log.Printf("saved hosts in cache")
		}
	} else {
		log.Printf("could not get hosts", err)
	}

	return
}

func (self *HostGetter) downloadParseHosts() (rt string, err error) {
	var data []byte
	var hosts []Host

	data, err = self.downloadHosts()
	if err != nil {
		log.Printf("failed to download")
		return
	}
	hosts, err = self.parse(data)
	if err != nil {
		log.Printf("could not parse")
		return
	}
	var buffer bytes.Buffer
	for _, host := range hosts {
		buffer.WriteString(host.Host.Name + "\n")
	}
	rt = buffer.String()
	return
}

func (self *HostGetter) parse(data []byte) (hosts []Host, err error) {
	err = json.Unmarshal(data, &hosts)
	if err != nil {
		log.Print("error:", err)
	}
	return
}

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())

	log.SetOutput(os.Stderr)

	usr, err := user.Current()
	if err != nil {
		log.Fatal(err)
	}

	getter := HostGetter{
		DownloadLocation: flag.String("url", "https://<forman-host>/hosts", "url to use"),
		CacheLocation:    flag.String("cachedir", filepath.Join(usr.HomeDir, ".gethosts"), "url to use"),
		CacheFileName:    flag.String("cachefile", "hostslist.txt", "url to use"),
		User:             flag.String("user", "", "user name for authentication"),
		Password:         flag.String("password", "", "password"),
		CacheDuration:    flag.Duration("cacheduration", time.Hour, "cache duration before trying to refresh")}

	flag.Parse() // Scan the arguments list

	if len(flag.Args()) > 0 {
		patt := flag.Arg(0)
		i := strings.Index(patt, "@")
		if i != -1 {
			getter.HostPrefix = patt[:i+1]
			patt = patt[i+1:]
		}
		getter.HostPattern = &patt
		log.Printf("requesting pattern %s, for prefix %s", patt, getter.HostPrefix)
	}

	hosts, err := getter.getHosts()
	if err != nil {
		log.Fatal("failed to download hosts")
	}

	if getter.HostPattern != nil {
		hostArr := strings.Split(hosts, "\n")

		for _, line := range hostArr {
			if strings.HasPrefix(line, *getter.HostPattern) {
				fmt.Fprintln(os.Stdout, getter.HostPrefix+line)
			}
		}
	} else {

		fmt.Fprintln(os.Stdout, hosts)
	}
}


text:
#ifndef DRIVEMIX_HPP_55D4E32D_1B01_4FDB_879E_E5CB54401677
#define DRIVEMIX_HPP_55D4E32D_1B01_4FDB_879E_E5CB54401677
#pragma once

/*
drivemix.hpp

Misc functions for drive/disk info
*/
/*
Copyright © 1996 Eugene Roshal
Copyright © 2000 Far Group
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. The name of the authors may not be used to endorse or promote products
   derived from this software without specific prior written permission.

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

// Internal:

// Platform:
#include "platform.fs.hpp"

// Common:

// External:

//----------------------------------------------------------------------------

void UpdateSavedDrives(const std::any& Payload);

os::fs::drives_set allowed_drives_mask();

namespace os
{
	namespace fs
	{
		drives_set get_logical_drives();
	}
}

#endif // DRIVEMIX_HPP_55D4E32D_1B01_4FDB_879E_E5CB54401677


text:
package org.quattor.pan.dml.functions;

import static org.quattor.pan.utils.MessageUtils.MSG_2_OR_3_ARGS;

import org.quattor.pan.dml.Operation;
import org.quattor.pan.dml.data.Element;
import org.quattor.pan.dml.data.LongProperty;
import org.quattor.pan.dml.data.StringProperty;
import org.quattor.pan.exceptions.EvaluationException;
import org.quattor.pan.exceptions.SyntaxException;
import org.quattor.pan.ttemplate.Context;
import org.quattor.pan.ttemplate.SourceRange;

/**
 * Extract a substring from a string.
 *
 * @author loomis
 *
 */
final public class Substr extends BuiltInFunction {

	private Substr(SourceRange sourceRange, Operation... operations)
			throws SyntaxException {
		super("substr", sourceRange, operations);
	}

	public static Operation getInstance(SourceRange sourceRange,
			Operation... operations) throws SyntaxException {

		// There can be two or three arguments.
		if (operations.length < 2 || operations.length > 3) {
			throw SyntaxException
					.create(sourceRange, MSG_2_OR_3_ARGS, "substr");
		}

		return new Substr(sourceRange, operations);
	}

	@Override
	public Element execute(Context context) {

		assert (ops.length == 2 || ops.length == 3);

		String string = null;
		try {
			string = ((StringProperty) ops[0].execute(context)).getValue();

		} catch (ClassCastException cce) {
			throw new EvaluationException(
					"first argument to substr() must be a string",
					getSourceRange(), context);
		}

		int start = 0;
		try {

			// Extract the value and make sure it can be safely converted to an
			// integer.
			long slong = ((LongProperty) ops[1].execute(context)).getValue()
					.longValue();
			if (slong > (long) Integer.MAX_VALUE
					|| slong < (long) Integer.MIN_VALUE) {
				throw new EvaluationException(
						"second argument to substr() cannot be converted to int: "
								+ slong, getSourceRange(), context);
			}

			// Get the starting index. Negative values indicate number of
			// characters from the end of the string.
			start = (int) slong;
			if (start < 0) {
				start = string.length() + start;
			}

			// Check that the index is (still) valid.
			if (start > string.length()) {
				throw new EvaluationException(
						"start index in substr() is greater than the string length",
						getSourceRange(), context);
			}
			if (start < 0) {
				throw new EvaluationException(
						"start index in substr() is less than zero",
						getSourceRange(), context);
			}

		} catch (ClassCastException cce) {
			throw new EvaluationException(
					"second argument to substr() must be a long",
					getSourceRange(), context);
		}

		int end = string.length();
		if (ops.length == 3) {
			try {
				long slong = ((LongProperty) ops[2].execute(context))
						.getValue().longValue();
				if (slong > (long) Integer.MAX_VALUE
						|| slong < (long) Integer.MIN_VALUE) {
					throw new EvaluationException(
							"third argument to substr() cannot be converted to int: "
									+ slong, getSourceRange(), context);
				}

				int temp = (int) slong;
				if (temp >= 0) {
					end = start + temp;
				} else {
					end = string.length() + temp;
				}

				// Check that the index is (still) valid.
				if (end > string.length()) {
					throw new EvaluationException(
							"end index in substr() is greater than the string length",
							getSourceRange(), context);
				}
				if (end < 0) {
					throw new EvaluationException(
							"end index in substr() is less than zero",
							getSourceRange(), context);
				}

			} catch (ClassCastException cce) {
				throw new EvaluationException(
						"second and optional third arguments to substr() must be longs",
						getSourceRange(), context);
			}

			// Check the arguments.
			if (end < start) {
				throw new EvaluationException(
						"start index is after ending index in substr()",
						getSourceRange(), context);
			}

		}
		return StringProperty.getInstance(string.substring(start, end));
	}
}


text:
<taskDefinition xmlns="http://schemas.microsoft.com/iis/media/v4/TM/TaskDefinition#">
  <name>MP4 to Smooth Streams</name>
  <id>5e1e1a1c-bba6-11df-8991-0019d1916af0</id>
  <description xml:lang="en" />
  <inputFolder />
  <properties namespace="http://schemas.microsoft.com/iis/media/V4/TM/MP4ToSmooth#" prefix="mp4">
    <property name="keepSourceNames" value="false" />
  </properties>
  <taskCode>
    <type>Microsoft.Web.Media.TransformManager.MP4toSmooth.MP4toSmooth_Task, Microsoft.Web.Media.TransformManager.MP4toSmooth, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35</type>
  </taskCode>
</taskDefinition>


text:
require_relative '../../../plugins/http/http-json-graphite'
require_relative '../../../spec_helper'

describe HttpJsonGraphite do

  it 'is able to parse json and output graphite data' do

    input_file = File.open('spec/fixtures/plugins/http/input.json', 'r')
    data = input_file.read
    input_file.close

    RestClient.stub(:get).and_return(data)

    expected = expect do
      begin
        checker = HttpJsonGraphite.new
        checker.config[:object] = 'value'
        checker.config[:metric] = 'Connections::numConnections,BusyConnections::numBusyConnections'
        checker.config[:scheme] = 'localhost.c3p0'
        checker.config[:url] = 'http://localhost:8080'
        checker.run
      rescue SystemExit
        puts
      end
    end
    expected.to output(/localhost.c3p0.Connections 15\s\d+\nlocalhost.c3p0.BusyConnections 0\s\d+/).to_stdout
  end

end


text:
from __future__ import division

__all__ = ['write_hoomdxml']

from copy import deepcopy
from math import floor, radians

import numpy as np

def RB_to_OPLS(c0, c1, c2, c3, c4, c5):
    """Converts Ryckaert-Bellemans type dihedrals to OPLS type.

    Parameters
    ----------
    c0, c1, c2, c3, c4, c5 : Ryckaert-Belleman coefficients (in kcal/mol)

    Returns
    -------
    opls_coeffs : np.array, shape=(4,)
        Array containing the OPLS dihedrals coeffs f1, f2, f3, and f4
        (in kcal/mol)
    """

    f1 = (-1.5 * c3) - (2 * c1)
    f2 = c0 + c1 + c3
    f3 = -0.5 * c3
    f4 = -0.25 * c4

    opls_coeffs = np.array([f1,f2,f3,f4])

    return opls_coeffs

def write_hoomdxml(structure, filename, forcefield, box, ref_distance=1.0,
                   ref_mass=1.0, ref_energy=1.0, rigid_bodies=None):
    """Output a HOOMD XML file.

    Parameters
    ----------
    structure : parmed.Structure
        Parmed structure object
    filename : str
        Path of the output file.
    box : mb.Box
        Box information to save to XML file
    forcefield : str, default=None
        Name of the force field to be applied to the compound
    ref_distance : float, default=1.0
        Reference distance for conversion to reduced units
    ref_mass : float, default=1.0
        Reference mass for conversion to reduced units
    rigid_bodies : list, default=None
        List of rigid body information following the HOOMD XML format.
        An integer value is required for each atom corresponding to the
        number of the rigid body with which the atom should be included.
        A value of -1 indicates the atom is not part of a rigid body.

    Elements
    --------
    The following elements are always written:

    Position : atomic positions
    Type : atom types
    Mass : atom masses (default 1.0)
    Charge : atom charges

    The following elements may be written if applicable:
    Pair_Coeffs : Pair coefficients for each atom type, assumes a 12-6
                  LJ pair style. The following information is written:
                  type : atom type
                  epsilon : LJ epsilon
                  sigma : LJ sigma
    Bond_Coeffs : Coefficients for each bond type, assumes a harmonic
                  bond style. The following information is written:
                  type : bond type
                  k : force constant (units of energy/distance^2)
                  r0 : bond rest length (units of distance)
    Bond : system bonds
    Angle_Coeffs : Coefficients for each angle type, assumes a harmonic
                   angle style. The following information is written:
                   type : angle type
                   k : force constant (units of energy/radians^2)
                   theta : rest angle (units of radians)
    Angle : system angles
    Dihedral_Coeffs : Coefficients for each dihedral type, assumes an OPLS
                      dihedral style. The following information is written:
                      type : dihedral type
                      k1, k2, k3, k4 : force coefficients (units of energy)
    Dihedral : system dihedrals
    Body : rigid body to which each atom belongs
    """

    xyz = np.array([[atom.xx, atom.xy, atom.xz] for atom in structure.atoms])

    # Center box at origin and remap coordinates into box
    box.maxs *= 10.
    box.mins *= 10.
    box_init = deepcopy(box)
    box.mins = np.array([-d/2 for d in box_init.lengths])
    box.maxs = np.array([d/2 for d in box_init.lengths])

    shift = [box_init.maxs[i] - max for i, max in enumerate(box.maxs)]
    for i, pos in enumerate(xyz):
        for j, coord in enumerate(pos):
            xyz[i, j] -= shift[j]
            rep = floor((xyz[i, j] - box.mins[j]) / box.lengths[j])
            xyz[i, j] -= (rep * box.lengths[j])

    with open(filename, 'w') as xml_file:
        xml_file.write('<?xml version="1.2" encoding="UTF-8"?>\n')
        xml_file.write('<hoomd_xml version="1.2">\n')
        xml_file.write('<configuration time_step="0">\n')
        xml_file.write('<box units="sigma"  Lx="{}" Ly="{}" Lz="{}"/>\n'.format(*box.lengths/ref_distance))

        xml_file.write('<position units="sigma" num="{}">\n'.format(len(structure.atoms)))

        for pos in xyz:
            xml_file.write('{}\t{}\t{}\n'.format(*pos/ref_distance))
        xml_file.write('</position>\n')

        if forcefield:
            types = [atom.type for atom in structure.atoms]
        else:
            types = [atom.name for atom in structure.atoms]
        xml_file.write('<type>\n')
        for atom_type in types:
            xml_file.write('{}\n'.format(atom_type))
        xml_file.write('</type>\n')

        masses = [atom.mass for atom in structure.atoms]
        xml_file.write('<mass>\n')
        for mass in masses:
            if mass == 0:
                mass = 1.0
            xml_file.write('{}\n'.format(mass/ref_mass))
        xml_file.write('</mass>\n')

        charges = [atom.charge for atom in structure.atoms]
        xml_file.write('<charge>\n')
        for charge in charges:
            xml_file.write('{}\n'.format(charge))
        xml_file.write('</charge>\n')

        if forcefield:
            pair_coeffs = list(set((atom.type,atom.epsilon,atom.sigma) for atom in structure.atoms))
            pair_coeffs.sort(key=lambda pair_type: pair_type[0])
            xml_file.write('<pair_coeffs>\n')
            for param_set in pair_coeffs:
                xml_file.write('{}\t{:.4f}\t{:.4f}\n'.format(param_set[0],param_set[1]/ref_energy,param_set[2]/ref_distance))
            xml_file.write('</pair_coeffs>\n')

        bonds = [[bond.atom1.idx, bond.atom2.idx] for bond in structure.bonds]
        if bonds:
            if len(structure.bond_types) == 0:
                bond_types = np.zeros(len(bonds),dtype=int)
            else:
                unique_bond_types = dict(enumerate(set([(round(bond.type.k,3),
                                                         round(bond.type.req,3)) for bond in structure.bonds])))
                unique_bond_types = {y:x for x,y in unique_bond_types.items()}
                bond_types = [unique_bond_types[(round(bond.type.k,3),
                                                 round(bond.type.req,3))] for bond in structure.bonds]
                xml_file.write('<bond_coeffs>\n')
                for params,idx in unique_bond_types.items():
                    xml_file.write('{}\t{}\t{}\n'.format(idx,((params[0]*2.)/ref_energy)*(ref_distance**2.),params[1]/ref_distance))
                xml_file.write('</bond_coeffs>\n')
            xml_file.write('<bond>\n')
            for idx,bond in enumerate(bonds):
                xml_file.write('{}\t{}\t{}\n'.format(bond_types[idx],*bond))
            xml_file.write('</bond>\n')

        angles = [[angle.atom1.idx,
                   angle.atom2.idx,
                   angle.atom3.idx] for angle in structure.angles]
        if angles:
            unique_angle_types = dict(enumerate(set([(round(angle.type.k,3),
                                                      round(angle.type.theteq,3)) for angle in structure.angles])))
            unique_angle_types = {y:x for x,y in unique_angle_types.items()}
            angle_types = [unique_angle_types[(round(angle.type.k,3),
                                               round(angle.type.theteq,3))] for angle in structure.angles]
            xml_file.write('<angle_coeffs>\n')
            for params,idx in unique_angle_types.items():
                xml_file.write('{}\t{}\t{:.5f}\n'.format(idx,(params[0]*2.)/ref_energy,radians(params[1])))
            xml_file.write('</angle_coeffs>\n')
            xml_file.write('<angle>\n')
            for idx,angle in enumerate(angles):
                xml_file.write('{}\t{}\t{}\t{}\n'.format(angle_types[idx],*angle))
            xml_file.write('</angle>\n')

        dihedrals = [[dihedral.atom1.idx,
                      dihedral.atom2.idx,
                      dihedral.atom3.idx,
                      dihedral.atom4.idx] for dihedral in structure.rb_torsions]
        if dihedrals:
            unique_dihedral_types = dict(enumerate(set([(round(dihedral.type.c0,3),
                                                         round(dihedral.type.c1,3),
                                                         round(dihedral.type.c2,3),
                                                         round(dihedral.type.c3,3),
                                                         round(dihedral.type.c4,3),
                                                         round(dihedral.type.c5,3),
                                                         round(dihedral.type.scee,1),
                                                         round(dihedral.type.scnb,1)) for dihedral in structure.rb_torsions])))
            unique_dihedral_types = {y:x for x,y in unique_dihedral_types.items()}
            dihedral_types = [unique_dihedral_types[(round(dihedral.type.c0,3),
                                                     round(dihedral.type.c1,3),
                                                     round(dihedral.type.c2,3),
                                                     round(dihedral.type.c3,3),
                                                     round(dihedral.type.c4,3),
                                                     round(dihedral.type.c5,3),
                                                     round(dihedral.type.scee,1),
                                                     round(dihedral.type.scnb,1))] for dihedral in structure.rb_torsions]
            xml_file.write('<dihedral_coeffs>\n')
            for params,idx in unique_dihedral_types.items():
                opls_coeffs = RB_to_OPLS(params[0],
                                         params[1],
                                         params[2],
                                         params[3],
                                         params[4],
                                         params[5])
                opls_coeffs /= ref_energy
                xml_file.write('{}\t{:.5f}\t{:.5f}\t{:.5f}\t{:.5f}\n'.format(idx,*opls_coeffs))
            xml_file.write('</dihedral_coeffs>\n')
            xml_file.write('<dihedral>\n')
            for idx,dihedral in enumerate(dihedrals):
                xml_file.write('{}\t{}\t{}\t{}\t{}\n'.format(dihedral_types[idx],
                                                             *dihedral))
            xml_file.write('</dihedral>\n')

        if rigid_bodies is not None:
            xml_file.write('<body>\n')
            for body in rigid_bodies:
                xml_file.write('{}\n'.format(int(body)))
            xml_file.write('</body>\n')

        xml_file.write('</configuration>\n')
        xml_file.write('</hoomd_xml>')


text:
import sys, os, time
from sqpyte.interpreter import Sqlite3DB, Sqlite3Query, SQPyteException
from rpython.rlib import jit
from sqpyte.capi import CConfig
from rpython.rtyper.lltypesystem import rffi

jitdriver = jit.JitDriver(
    greens=['printRes', 'query', 'queryRes'],
    reds=['rc'],
    )
    # get_printable_location=get_printable_location)

def run(query, queryRes, printRes):
    try:
        query.reset_query()

        if queryRes != "" and printRes:
            print 'Query result:'

        rc = query.mainloop()
        while rc == CConfig.SQLITE_ROW:
            jitdriver.jit_merge_point(query=query, queryRes=queryRes, printRes=printRes, rc=rc)
            if printRes:
                print "|".join([
                    rffi.charpsize2str(rffi.cast(rffi.CCHARP, query.column_text(i)), query.column_bytes(i))
                        for i in range(query.data_count())])
            rc = query.mainloop()

        if queryRes != "" and printRes:
            print '\nExpected result:\n%s' % queryRes

    except SQPyteException:
        raise

def entry_point(argv):
    usageMsg = """\n
  Usage:
  For testing:      ./target-c -t db_file query_file [query_results_file]
  For benchmarking: ./target-c -b [warm_up] db_file query_file
    """
    disabled_opcodes = ""
    try:
        flag = argv[1]
        if flag == '--jit':
            jit.set_user_param(None, argv[2])
            flag = argv[3]
            argv = [argv[0]] + argv[3:]
        if flag == '--disable-opcodes':
            disabled_opcodes = argv[2]
            flag = argv[3]
            argv = [argv[0]] + argv[3:]
        if flag == '-t':
            testingFlag = True
            warmup = 0
            testdb = argv[2]
            queryPath = argv[3]
        elif flag == '-b':
            testingFlag = False
            warmup = 3
            if len(argv) > 4:
                try:
                    warmup = int(argv[2])
                except ValueError:
                    print "Error: '%s' is not a valid number for warm_up argument.%s" % (argv[2], usageMsg)
                    return 1
                testdb = argv[3]
                queryPath = argv[4]
            else:
                testdb = argv[2]
                queryPath = argv[3]
        else:
            print "Error: Unknown flag '%s'.%s" % (flag, usageMsg)
            return 1
    except IndexError:
        print "Error: Not enough arguments.%s" % usageMsg
        return 1

    if testdb != ':memory:':
        try:
            fp = os.open(testdb, os.O_RDONLY, 0777)
            os.close(fp)
        except OSError:
            print "Error: Can't open '%s' file provided for db_file argument.%s" % (testdb, usageMsg)
            return 1

    try:
        fp = os.open(queryPath, os.O_RDONLY, 0777)
        queryStr = ""
        while True:
            read = os.read(fp, 4096)
            if len(read) == 0:
                break
            queryStr += read
        os.close(fp)
    except OSError:
        print "Error: Can't open '%s' file provided for query_file argument.%s" % (queryPath, usageMsg)
        return 1

    queryRes = ""
    if flag == '-t' and len(argv) > 4:
        queryResPath = argv[4]
        try:
            fp = os.open(queryResPath, os.O_RDONLY, 0777)
            while True:
                read = os.read(fp, 4096)
                if len(read) == 0:
                    break
                queryRes += read
            os.close(fp)
        except OSError:
            print "Error: Can't open '%s' file provided for query_results_file argument.%s" % (queryResPath, usageMsg)
            return 1

    db = Sqlite3DB(testdb)
    query = db.execute(queryStr, use_flag_cache=not disabled_opcodes)
    if disabled_opcodes:
        query.use_translated.disable_from_cmdline(disabled_opcodes)

    if testingFlag:
        run(query, queryRes, True)
    else:
        for i in range(warmup):
            run(query, "", False)
        t1 = time.time()
        run(query, queryRes, False)
        t2 = time.time()
        print "%s" % (t2 - t1)
    return 0

def target(*args):
    return entry_point, None

if __name__ == "__main__":
    entry_point(sys.argv)


text:
__author__ = 'fantomen'
import csv
from difflib import SequenceMatcher
import urllib
import datetime
import numpy as np

class fbDataParser:

    LEAGUES = [
        'http://www.football-data.co.uk/mmz4281/1718/E0.csv',
        'http://www.football-data.co.uk/mmz4281/1718/E1.csv',
        'http://www.football-data.co.uk/mmz4281/1718/I1.csv',
        'http://www.football-data.co.uk/mmz4281/1718/SP1.csv',
        'http://www.football-data.co.uk/mmz4281/1718/D1.csv',
        'https://s3-eu-west-1.amazonaws.com/tipset/Allsvenskan2017.csv',
        'https://s3-eu-west-1.amazonaws.com/tipset/Superettan2017.csv',
        'https://s3-eu-west-1.amazonaws.com/tipset/tippeligaen2017.csv',
        'https://s3-eu-west-1.amazonaws.com/tipset/Veikkausliiga2017.csv',
        'https://s3-eu-west-1.amazonaws.com/tipset/danska-superligan2017.csv'
    ]

    games = []

    def parse_date(self, d):
        try:
            d['Date'] = datetime.datetime.strptime(d['Date'], "%d/%m/%y").date()
        except ValueError:
            d['Date'] = datetime.datetime.strptime("01/01/70", "%d/%m/%y").date()
        return d

    def read_urls(self, urls):
        for u in urls:
            try:
                url = u
            except KeyError:
                self.games = []
                continue
            remote_file = urllib.urlopen(url)
            reader = csv.DictReader(remote_file.readlines())
            self.games += reader

    def __init__(self, url=None, urls=None, silent=False):
        self.silent = silent
        self.games = []
        if url:
            remote_file = urllib.urlopen(url)
            reader = csv.DictReader(remote_file.readlines())
            self.games = reader
        elif urls:
            self.read_urls(urls)
        else:
            self.read_urls(self.LEAGUES)

        self.games = map(lambda g: self.parse_date(g), self.games)

        print "parsed %s games" % len(self.games)

    def __del__(self):
        self.games = None

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.games = None

    def __enter__(self):
        return self

    def get_stats_for_game(self, home_team_name, visiting_team_name, game_date):
        """Get full stats row for a single game. The stats returned are described here: http://www.football-data.co.uk/notes.txt
        :param home_team_name: Name of home team
        :param visiting_team_name: Name of away team
        :param game_date: Date of the game as datetime
        :returns Game stats as Dict
        """
        game = []
        try:
            game = filter(lambda g: g['Date'] == game_date and (
                SequenceMatcher(None, home_team_name, g['HomeTeam']).ratio() > 0.8 or SequenceMatcher(None,
                                                                                visiting_team_name,
                                                                                g[
                                                                                'AwayTeam']).ratio() > 0.8),
                          self.games)[0]
        except IndexError, ValueError:
            print "could not find game %s - %s at %s" % (home_team_name, visiting_team_name, game_date)
        return game

    def get_field(self, team_name, row, field, place, inverse):
        r = None

        if SequenceMatcher(None, team_name, row["HomeTeam"]).ratio() > 0.8:
            if place == "away": return
            if inverse:
                key = "A" + field
            else:
                key = "H" + field
        else:
            if place == "home": return
            if inverse:
                key = "H" + field
            else:
                key = "A" + field

        try:
            r = row[key]
        except KeyError:
            if not self.silent:
                print "could not find key %s for %s" % (key, team_name)
            r = 0
        try:
            r = int(r)
        except ValueError:
            r = 0
        return r

    def get_historical_data_for_team(self, team_name, from_date, field="S", place="both", depth=10, inverse=False):
        """Get historic data of a single field for a team starting at a certain date. Available fields are described here: http://www.football-data.co.uk/notes.txt
        :param team_name: Name of team
        :param from_date: Date as datetime
        :param place; wether to include home, away games or both
        :param field: Which field to return, Ie S for shots or ST for shots on target
        :param depth: How many games to return history for
        :param inverse: Get opposing stats instead
        :returns List with the field in reversed order, Newest last.
        """
        try:
            games = map(lambda fg: self.get_field(team_name, fg, field, place, inverse), sorted(filter(
                lambda g: g['Date'] < from_date and (
                    SequenceMatcher(None, team_name, g['HomeTeam']).ratio() > 0.8 or SequenceMatcher(None, team_name, g[
                        'AwayTeam']).ratio() > 0.8), self.games), key=lambda g: g["Date"], reverse=True)[
                                                                                :int(depth * 2.5)])
        except IndexError:
            print "could not find games for %s from %s" % (team_name, from_date)
        l = list(reversed([x for x in games if x is not None]))

        ret = []

        if len(l) >= depth:
            ret = l[-depth:]
        else:
            a = np.zeros(depth, dtype=np.int)
            a = np.insert(l, 0, a).tolist()
            ret = a[-depth:]

        if ret.count(0) > depth / 2:
            if not self.silent:
                print "WARNING: Data may not have been found for: " + team_name
        return ret

if __name__ == '__main__':
    # Example usage:
    with fbDataParser() as parser:
        #print parser.get_stats_for_game("Liverpool", "AstonVilla",
        #                                datetime.datetime.strptime("2014-09-13", "%Y-%m-%d").date())
        print parser.get_historical_data_for_team("Bröndby IF",
                                                  datetime.datetime.strptime("2017-09-01", "%Y-%m-%d").date(), depth=20)

        print parser.get_historical_data_for_team("Arsenal",
                                                  datetime.datetime.strptime("2017-09-01", "%Y-%m-%d").date(),
                                                  inverse=True, depth=3)


text:
<!DOCTYPE html>

 <meta charset="UTF-8">
 <title>Contacts Builder</title>


text:
package com.greengrowapps.ggaforms.fields;

import com.greengrowapps.ggaforms.listeners.OnInputChangedListener;
import com.greengrowapps.ggaforms.validation.errors.ValidationError;

public abstract class BaseFormInput<T> implements FormInput<T> {

    private final Class<T> clazz;
    private OnInputChangedListener listener;
    private T value;
    private ValidationError error;

    public BaseFormInput(Class<T> clazz){
        this.clazz = clazz;
    }

    @Override
    public void setOnInputChangedListener(OnInputChangedListener listener) {
        this.listener = listener;
    }

    protected void onFieldChanged(T value){
        if(listener!=null){
            listener.onFieldChanged(this);
        }
    }

    @Override
    public void setValue(T value){
        if(!isEqual(this.value,value)){
            updateValue(value);
        }
    }

    protected boolean isEqual(T value1, T value2){
        if(value1==null){
            return value2==null;
        }
        else{
            return value1.equals(value2);
        }
    }

    private void updateValue(T value){
        this.value = value;
        onFieldChanged(value);
    }

    @Override
    public T getValue() {
        return value;
    }

    @Override
    public Class<T> getType() {
        return clazz;
    }

    @Override
    public void setError(ValidationError error) {
        this.error = error;
    }

    @Override
    public ValidationError getError() {
        return error;
    }
}


text: PageRank based on MapReduce


text:
package io.citrine.lolo.bags

import breeze.linalg.{norm, DenseMatrix, DenseVector}
import io.citrine.lolo.api.{PredictionResult, RegressionResult}
import org.slf4j.{Logger, LoggerFactory}

/**
  * Interface defining the return value of a [[BaggedModel]].
  *
  * This allows the implementation to depend on the number of simultaneous predictions,
  * which has performance implications.
  *
  * For background on the uncertainty calculation, see Wager, S.; Hastie, T and Efron, B. Confidence Intervals for
  * Random Forests: The Jackknife and Infinitesimal Jackknife. Journal of Machine Learning Research 15 (2014).
  */
trait BaggedPrediction[+T] extends PredictionResult[T] {

  /** The number of input rows that have been predicted on (NOT the number of bagged models). */
  def numPredictions: Int

  /** The predictions made by each of the bagged models in the ensemble. */
  def ensemblePredictions: Seq[PredictionResult[T]]

  /**
    * Average the gradients from the models in the ensemble
    *
    * @return the gradient of each prediction as a vector of doubles
    */
  override lazy val gradient: Option[Seq[Vector[Double]]] = if (ensemblePredictions.head.gradient.isEmpty) {
    /* If the underlying model has no gradient, return None */
    None
  } else {
    val gradientsByPrediction: Seq[Seq[Vector[Double]]] = ensemblePredictions.map(_.gradient.get)
    val gradientsByInput: Seq[Seq[Vector[Double]]] = gradientsByPrediction.transpose
    Some(
      gradientsByInput.map { r => r.toVector.transpose.map(_.sum / ensemblePredictions.size) }
    )
  }
}

/** Interface for [[BaggedPrediction]]s for regression tasks with task-specific methods. */
sealed trait BaggedRegressionPrediction extends BaggedPrediction[Double] with RegressionResult

/**
  * Container with model-wise predictions at a single input point.
  *
  * Assuming a single input allows for performance optimizations and more readable code.
  * See [[MultiPointBaggedPrediction]] for a generic implementation.
  *
  * @param ensemblePredictions for each constituent model
  * @param NibIn               the sample matrix as (N_models x N_training)
  * @param pointBias           bias model prediction at the single prediction point
  */
case class SinglePointBaggedPrediction(
    ensemblePredictions: Seq[PredictionResult[Double]],
    NibIn: Vector[Vector[Int]],
    pointBias: Option[Double] = None,
    rescaleRatio: Double = 1.0,
    disableBootstrap: Boolean = false
) extends BaggedRegressionPrediction {

  override def numPredictions: Int = 1

  override def expected: Seq[Double] = Seq(rawExpected + pointBias.getOrElse(0.0))

  override def bias: Option[Seq[Double]] = pointBias.map(Seq(_))

  override def uncertainty(observational: Boolean): Option[Seq[Double]] = {
    if (observational) {
      stdDevObs
    } else {
      stdDevMean
    }
  }

  /**
    * The importances are computed as an average of bias-corrected jackknife-after-bootstrap
    * and infinitesimal jackknife methods
    *
    * @return training row scores of each prediction
    */
  override def importanceScores: Option[Seq[Seq[Double]]] = Some(Seq(singleScores))

  override lazy val stdDevMean: Option[Seq[Double]] = {
    if (disableBootstrap) {
      // If bootstrap is disabled, rescale is unity and treeVariance is our only option for UQ.
      // Since it's not recalibrated, it's best considered to be a confidence interval of the underlying weak learner.
      assert(rescaleRatio == 1.0)
      Some(Seq(math.sqrt(treeVariance)))
    } else {
      Some(
        Seq(math.sqrt(BaggedPrediction.rectifyEstimatedVariance(singleScores)))
      )
    }
  }

  override lazy val stdDevObs: Option[Seq[Double]] = Option.when(!disableBootstrap) {
    val std = (rescaleRatio * math.sqrt(treeVariance)) ensuring (_ >= 0.0)
    Seq(std)
  }

  private lazy val treePredictions = ensemblePredictions.map(_.expected.head).toArray
  private lazy val rawExpected = treePredictions.sum / treePredictions.length
  private lazy val treeVariance = {
    assert(treePredictions.length > 1, "Bootstrap variance undefined for fewer than 2 bootstrap samples.")
    treePredictions.map(x => math.pow(x - rawExpected, 2.0)).sum / (treePredictions.length - 1)
  }

  private lazy val singleScores: Vector[Double] = {
    // This will be more convenient later
    val nMat = NibIn.transpose

    // Compute the Bessel-uncorrected variance of the ensemble of predicted values, then multiply by (n - 1) / (n * B)
    // We later sum over the training data, introducing a factor of n and leaving us with the expected correction term
    val correction = treeVariance * (treePredictions.length - 1.0) * (nMat.size - 1) /
      (treePredictions.length * treePredictions.length * nMat.size)

    // Loop over each of the training instances, computing its contribution to the uncertainty
    val trainingContributions = nMat.indices.toVector.map { idx =>
      // Pull the vector of the number of times this instance was used to train each tree
      val vecN = nMat(idx).toArray

      // Loop over the trees, computing the covariance for the IJ estimate and the predicted value of
      // the out-of-bag trees for the J(ackknife) estimate
      // The loops are merged for performance reasons
      var cov: Double = 0.0
      var tNot: Double = 0.0
      var tNotCount: Int = 0
      vecN.indices.foreach { jdx =>
        cov = cov + (vecN(jdx) - 1) * (treePredictions(jdx) - rawExpected)

        if (vecN(jdx) == 0) {
          tNot = tNot + treePredictions(jdx)
          tNotCount = tNotCount + 1
        }
      }
      // Compute the infinitesimal jackknife estimate
      val varIJ = math.pow(cov / vecN.length, 2.0)

      if (tNotCount > 0) {
        // Compute the Jackknife after bootstrap estimate
        val varJ = math.pow(tNot / tNotCount - rawExpected, 2.0) * (nMat.size - 1) / nMat.size
        // Averaged the corrected IJ and J estimates
        0.5 * (varJ + varIJ - math.E * correction)
      } else {
        // We can't compute the Jackknife after bootstrap estimate, so just correct the IJ estimate
        varIJ - correction
      }
    }
    // The uncertainty must be positive, so anything smaller than zero is noise.  Make sure that no estimated
    // uncertainty is below that noise level
    trainingContributions
  }
}

/**
  * Container with model-wise predictions and logic to compute variances and training row scores
  *
  * These calculations are implemented using matrix arithmetic to make them more performant when the number
  * of predictions is large.  This obfuscates the algorithm significantly, however.  To see what is being computed,
  * look at [[SinglePointBaggedPrediction]], which is more clear.  These two implementations are tested for consistency.
  *
  * @param ensemblePredictions for each constituent model
  * @param NibIn       the sample matrix as (N_models x N_training)
  * @param bias        bias model predictions at all of the prediction points
  */
case class MultiPointBaggedPrediction(
    ensemblePredictions: Seq[PredictionResult[Double]],
    NibIn: Vector[Vector[Int]],
    override val bias: Option[Seq[Double]] = None,
    rescaleRatio: Double = 1.0,
    disableBootstrap: Boolean = false
) extends BaggedRegressionPrediction {

  override def numPredictions: Int = expectedMatrix.length

  override def expected: Seq[Double] = rawExpected.zip(biasCorrection).map(x => x._1 + x._2)

  override def uncertainty(observational: Boolean): Option[Seq[Any]] = {
    if (observational) {
      stdDevObs
    } else {
      stdDevMean
    }
  }

  override def influenceScores(actuals: Seq[Any]): Option[Seq[Seq[Double]]] = {
    Some(
      influences(
        expected.toVector,
        actuals.toVector.asInstanceOf[Vector[Double]],
        expectedMatrix,
        NibJMat,
        NibIJMat
      )
    )
  }

  override def importanceScores: Option[Seq[Seq[Double]]] = Some(scores)

  override lazy val stdDevObs: Option[Seq[Double]] = Option.when(!disableBootstrap)(varObs.map(math.sqrt))

  override lazy val stdDevMean: Option[Seq[Double]] = Option
    .when(disableBootstrap) {
      // If bootstrap is disabled, rescale is unity and treeVariance is our only option for UQ.
      // Since it's not recalibrated, it's best considered to be a confidence interval of the underlying weak learner.
      assert(rescaleRatio == 1.0)
      varObs.map(math.sqrt)
    }
    .orElse {
      val std = variance(rawExpected.toVector, expectedMatrix, NibJMat, NibIJMat).map(math.sqrt)
      Some(std)
    }

  /* transpose to be (# training) x (# models) */
  private lazy val Nib: Vector[Vector[Int]] = NibIn.transpose

  /* Make a matrix of the tree-wise predictions */
  private lazy val expectedMatrix: Seq[Seq[Double]] = ensemblePredictions.map(p => p.expected).transpose

  /* Extract the prediction by averaging over trees and adding the bias correction. */
  private lazy val biasCorrection: Seq[Double] = bias.getOrElse(Seq.fill(expectedMatrix.length)(0))
  private lazy val rawExpected: Seq[Double] = expectedMatrix.map(ps => ps.sum / ps.size)

  private lazy val NibJMat: DenseMatrix[Double] = BaggedPrediction.getJackknifeAfterBootstrapMatrix(Nib)

  private lazy val NibIJMat: DenseMatrix[Double] = BaggedPrediction.getInfinitesimalJackknifeMatrix(Nib)

  /* This estimates the variance of predictive distribution. */
  private lazy val varObs: Seq[Double] = expectedMatrix.zip(rawExpected).map {
    case (b, y) =>
      assert(Nib.size > 1, "Bootstrap variance undefined for fewer than 2 bootstrap samples.")
      b.map { x => rescaleRatio * rescaleRatio * math.pow(x - y, 2.0) }.sum / (b.size - 1)
  }

  /* Compute the scores one prediction at a time */
  private lazy val scores: Seq[Vector[Double]] = scores(expected.toVector, expectedMatrix, NibJMat, NibIJMat)
    // make sure the variance is non-negative after the stochastic correction
    .map(BaggedPrediction.rectifyImportanceScores)
    .map(_.map(math.sqrt))

  /**
    * Compute the variance of a prediction as the average of bias corrected IJ and J variance estimates
    *
    * @param meanPrediction   over the models
    * @param modelPredictions prediction of each model
    * @param NibJ             sampling matrix for the jackknife-after-bootstrap estimate
    * @param NibIJ            sampling matrix for the infinitesimal jackknife estimate
    * @return the estimated variance
    */
  def variance(
      meanPrediction: Vector[Double],
      modelPredictions: Seq[Seq[Double]],
      NibJ: DenseMatrix[Double],
      NibIJ: DenseMatrix[Double]
  ): Seq[Double] = {
    scores(meanPrediction, modelPredictions, NibJ, NibIJ).map { BaggedPrediction.rectifyEstimatedVariance }
  }

  /**
    * Compute the IJ training row scores for a prediction
    *
    * @param meanPrediction   over the models
    * @param modelPredictions prediction of each model
    * @param NibJ             sampling matrix for the jackknife-after-bootstrap estimate
    * @param NibIJ            sampling matrix for the infinitesimal jackknife estimate
    * @return the score of each training row as a vector of doubles
    */
  def scores(
      meanPrediction: Vector[Double],
      modelPredictions: Seq[Seq[Double]],
      NibJ: DenseMatrix[Double],
      NibIJ: DenseMatrix[Double]
  ): Seq[Vector[Double]] = {
    /* Stick the predictions in a breeze matrix */
    val predMat =
      new DenseMatrix[Double](modelPredictions.head.size, modelPredictions.size, modelPredictions.flatten.toArray)

    /* These operations are pulled out of the loop and extra-verbose for performance */
    val JMat = NibJ.t * predMat
    val JMat2 = JMat *:* JMat * ((Nib.size - 1.0) / Nib.size)
    val IJMat = NibIJ.t * predMat
    val IJMat2 = IJMat *:* IJMat
    val arg = IJMat2 + JMat2

    /* Avoid division in the loop, calculate (n - 1) / (n * B^2) */
    val prefactor = 1.0 / math.pow(modelPredictions.head.size, 2.0) * (Nib.size - 1) / Nib.size

    modelPredictions.indices
      .map { i =>
        /* Compute the first order bias correction for the variance estimators */
        val correction = prefactor * math.pow(norm(predMat(::, i) - meanPrediction(i)), 2)

        /* The correction is prediction dependent, so we need to operate on vectors */
        0.5 * (arg(::, i) - math.E * correction)
      }
      .map(_.toScalaVector)
  }

  /**
    * Compute the IJ training row scores for a prediction
    *
    * @param meanPrediction   over the models
    * @param modelPredictions prediction of each model
    * @param NibJ             sampling matrix for the jackknife-after-bootstrap estimate
    * @param NibIJ            sampling matrix for the infinitesimal jackknife estimate
    * @return the score of each training row as a vector of doubles
    */
  def influences(
      meanPrediction: Vector[Double],
      actualPrediction: Vector[Double],
      modelPredictions: Seq[Seq[Double]],
      NibJ: DenseMatrix[Double],
      NibIJ: DenseMatrix[Double]
  ): Seq[Vector[Double]] = {
    /* Stick the predictions in a breeze matrix */
    val predMat =
      new DenseMatrix[Double](modelPredictions.head.size, modelPredictions.size, modelPredictions.flatten.toArray)

    /* These operations are pulled out of the loop and extra-verbose for performance */
    val JMat = NibJ.t * predMat
    val IJMat = NibIJ.t * predMat
    val arg = IJMat + JMat

    /* Avoid division in the loop */
    val inverseSize = 1.0 / modelPredictions.head.size

    modelPredictions.indices
      .map { i =>
        /* Compute the first order bias correction for the variance estimators */
        val correction = inverseSize * norm(predMat(::, i) - meanPrediction(i))

        /* The correction is prediction dependent, so we need to operate on vectors */
        val influencePerRow: DenseVector[Double] =
          math.signum(actualPrediction(i) - meanPrediction(i)) * 0.5 * (arg(::, i) - math.E * correction)

        /* Impose a floor in case any of the variances are negative (hacked to work in breeze) */
        // val floor: Double = math.min(0, -min(variancePerRow))
        // val rezero: DenseVector[Double] = variancePerRow - floor
        // 0.5 * (rezero + abs(rezero)) + floor
        influencePerRow
      }
      .map(_.toScalaVector)
  }
}

case class BaggedClassificationPrediction[T](ensemblePredictions: Seq[PredictionResult[T]])
    extends BaggedPrediction[T] {

  override def numPredictions: Int = expectedMatrix.length

  override def uncertainty(includeNoise: Boolean = true): Option[Seq[Map[T, Double]]] = Some(predictionUncertainties)

  override lazy val expected: Seq[T] = expectedMatrix.map(ps => ps.groupBy(identity).maxBy(_._2.size)._1)

  private lazy val expectedMatrix: Seq[Seq[T]] = ensemblePredictions.map(p => p.expected).transpose

  private lazy val predictionUncertainties: Seq[Map[T, Double]] =
    expectedMatrix.map(ps => ps.groupBy(identity).view.mapValues(_.size.toDouble / ps.size).toMap)
}

object BaggedPrediction {

  val logger: Logger = LoggerFactory.getLogger(getClass)

  /**
    * Generate a matrix that is useful for computing (co)variance via jackknife after bootstrap (JaB).
    * The central term of the JaB calculation (Wager et. al. 2014, equation 6) is the difference between the
    * out-of-bag prediction on a point and the mean prediction on that point. If this is written as a single sum over bags,
    * then each point has a weight -1/B when it is in-bag and weight 1/|{N_{bi}=0}| - 1/B when it is out-of-bag (B is the number of bags).
    * This matrix encodes those weights, so when it is multiplied by the (# bags) x (# predictions) prediction matrix
    * we have a matrix of the \Delta terms from equation 6.
    *
    * @param Nib The (# training) x (# bags) matrix indicating how many times each training point is used in each bag
    */
  def getJackknifeAfterBootstrapMatrix(Nib: Vector[Vector[Int]]): DenseMatrix[Double] = {
    new DenseMatrix[Double](
      Nib.head.size,
      Nib.size,
      Nib.flatMap { v =>
        val itot = 1.0 / v.size // 1/B
        val icount = 1.0 / v.count(_ == 0) // 1/|{N_{bi}=0}|
        v.map(n => if (n == 0) icount - itot else -itot)
      }.toArray
    )
  }

  /**
    * Generate a matrix that is useful for computing (co)variance via infinitesimal jackknife (IJ).
    * The central term of the IJ calculation (Wager et. al. 2014, equation 5) is the covariance between the number of
    * times a training point appears in a bag and the prediction made by that bag.
    * This matrix encodes (N - \bar{N})/B (B is the number of bags), so that when it is multiplied by the
    *  (# bags) x (# predictions) prediction matrix, we have a matrix of the covariance terms from equation 5.
    *
    * @param Nib The (# training) x (# bags) matrix indicating how many times each training point is used in each bag
    */
  def getInfinitesimalJackknifeMatrix(Nib: Vector[Vector[Int]]): DenseMatrix[Double] = {
    new DenseMatrix[Double](
      Nib.head.size,
      Nib.size,
      Nib.flatMap { v =>
        val itot = 1.0 / v.size // 1/B
        val vtot = v.sum.toDouble / (v.size * v.size) // \bar{N} / B
        v.map(n => n * itot - vtot)
      }.toArray
    )
  }

  /**
    * Make sure the variance is non-negative
    *
    * The monte carlo bias correction is itself stochastic, so let's make sure the result is positive
    *
    * If the sum is positive, then great!  We're done.
    *
    * If the sum is <= 0.0, then the actual variance is likely quite small.  We know the variance should be at
    * least as large as the largest importance, since at least one training point will be important.
    * Therefore, let's just take the maximum importance, which should be a reasonable lower-bound of the variance.
    * Note that we could also sum the non-negative scores, but that could be biased upwards.
    *
    * If all of the scores are negative (which happens infrequently for very small ensembles), then we just need a scale.
    * The largest scale is the largest magnitude score, which is the absolute value of the minimum score.  When this
    * happens, then a larger ensemble should really be used!
    *
    * If all of the treePredictions are zero, then this will return zero.
    *
    * @param scores the monte-carlo corrected importance scores
    * @return A non-negative estimate of the variance
    */
  def rectifyEstimatedVariance(scores: Seq[Double]): Double = {
    val rawSum = scores.sum
    lazy val maxEntry = scores.max

    if (rawSum > 0) {
      rawSum
    } else if (maxEntry > 0) {
      // If the sum is negative,
      logger.warn(
        s"Sum of scores was negative; using the largest score as an estimate for the variance.  Please consider increasing the ensemble size."
      )
      maxEntry
    } else {
      logger.warn(
        s"All scores were negative; using the magnitude of the smallest score as an estimate for the variance.  It is highly recommended to increase the ensemble size."
      )
      -scores.min // equivalent to math.abs(scores.min)
    }
  } ensuring (_ >= 0.0)

  /**
    * Make sure the scores are each non-negative
    *
    * The monte carlo bias correction is itself stochastic, so let's make sure the result is positive.
    * If the score was statistically consistent with zero, then we might subtract off the entire bias correction,
    * which results in the negative value.  Therefore, we can use the magnitude of the minimum as an estimate of the noise
    * level, and can simply set that as a floor.
    *
    * If all of the treePredictions are zero, then this will return a vector of zero
    *
    * @param scores the monte-carlo corrected importance scores
    * @return a vector of non-negative bias corrected scores
    */
  def rectifyImportanceScores(scores: Vector[Double]): Vector[Double] = {
    // this is a lower-bound on the noise level; note that it is strictly smaller than the correction
    val floor = math.abs(scores.min)
    if (floor < 0.0) {
      logger.warn(s"Some importance scores were negative; rectifying.  Please consider increasing the ensemble size.")
    }
    scores.map(math.max(floor, _))
  } ensuring (vec => vec.forall(_ >= 0.0))
}


text:
using LoT.IService;
using LoT.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LoT.Service
{
    public partial class ArticleTagService : BaseService<ArticleTag>, IArticleTagService
    {
        /// <summary>
        /// 给父类指派一个ArticleTagDal对象
        /// </summary>
        /// <returns></returns>
        protected override IDal.IBaseDal<ArticleTag> GetModelDal()
        {
            return dbSession.ArticleTagDal;
        }
    }
}


text:
CodeGenerator
=============

Generate code based on the module that you have created


text:
drop database dojodb;
use mysql;
delete from user where user='dojodbusr';


text:
CGFloat FBDistanceBetweenPoints(NSPoint point1, NSPoint point2);
CGFloat FBDistancePointToLine(NSPoint point, NSPoint lineStartPoint, NSPoint lineEndPoint);
NSPoint FBLineNormal(NSPoint lineStart, NSPoint lineEnd);
NSPoint FBLineMidpoint(NSPoint lineStart, NSPoint lineEnd);

NSPoint FBAddPoint(NSPoint point1, NSPoint point2);
NSPoint FBScalePoint(NSPoint point, CGFloat scale);
NSPoint FBUnitScalePoint(NSPoint point, CGFloat scale);
NSPoint FBSubtractPoint(NSPoint point1, NSPoint point2);
CGFloat FBDotMultiplyPoint(NSPoint point1, NSPoint point2);
CGFloat FBPointLength(NSPoint point);
CGFloat FBPointSquaredLength(NSPoint point);
NSPoint FBNormalizePoint(NSPoint point);
NSPoint FBNegatePoint(NSPoint point);
NSPoint FBRoundPoint(NSPoint point);

NSPoint FBRectGetTopLeft(NSRect rect);
NSPoint FBRectGetTopRight(NSRect rect);
NSPoint FBRectGetBottomLeft(NSRect rect);
NSPoint FBRectGetBottomRight(NSRect rect);

void FBExpandBoundsByPoint(NSPoint *topLeft, NSPoint *bottomRight, NSPoint point);
NSRect FBUnionRect(NSRect rect1, NSRect rect2);

BOOL FBArePointsClose(NSPoint point1, NSPoint point2);
BOOL FBArePointsCloseWithOptions(NSPoint point1, NSPoint point2, CGFloat threshold);
BOOL FBAreValuesClose(CGFloat value1, CGFloat value2);
BOOL FBAreValuesCloseWithOptions(CGFloat value1, CGFloat value2, CGFloat threshold);

//////////////////////////////////////////////////////////////////////////
// Angle Range structure provides a simple way to store angle ranges
//  and determine if a specific angle falls within.
//
typedef struct FBAngleRange {
    CGFloat minimum;
    CGFloat maximum;
} FBAngleRange;

FBAngleRange FBAngleRangeMake(CGFloat minimum, CGFloat maximum);
BOOL FBAngleRangeContainsAngle(FBAngleRange range, CGFloat angle);

CGFloat NormalizeAngle(CGFloat value);
CGFloat PolarAngle(NSPoint point);

//////////////////////////////////////////////////////////////////////////////////
// Parameter ranges
//

// FBRange is a range of parameter (t)
typedef struct FBRange {
    CGFloat minimum;
    CGFloat maximum;
} FBRange;

extern FBRange FBRangeMake(CGFloat minimum, CGFloat maximum);
extern BOOL FBRangeHasConverged(FBRange range, NSUInteger places);
extern CGFloat FBRangeGetSize(FBRange range);
extern CGFloat FBRangeAverage(FBRange range);
extern CGFloat FBRangeScaleNormalizedValue(FBRange range, CGFloat value);

extern BOOL FBTangentsCross(NSPoint edge1Tangents[2], NSPoint edge2Tangents[2]);


text:
<?php require_once("../includes/initialize.php"); ?>

<?php

	if ($_POST['undo_vote'] == 1) {
		Photo::undo_vote($_POST['photo_id']);
	} else {
		Photo::undo_vote($_POST['photo_id']);
		Photo::vote($_POST['photo_id'], $_POST['vote']);
	}

	// This new score is received in the Ajax callback of voting.
	// The callback uses the $new_score to update the front-end.
	$new_score = Photo::get_votes($_POST['photo_id']);
	echo $new_score;

?>


text:
/// @file

#ifndef _WX_CHARTS_WXBUBBLECHARTOPTIONS_H_
#define _WX_CHARTS_WXBUBBLECHARTOPTIONS_H_

#include "wxcharts_export.h"

#include "wxchartoptions.h"
#include "wxchartsgridoptions.h"
#include <wx/sharedptr.h>

/// The options for the wxBubbleChartCtrl control.

/// \ingroup chartclasses
class WXCHARTS_EXPORT wxBubbleChartOptions : public wxChartOptions
{
public:
    /// Smart pointer typedef.
    typedef wxSharedPtr<wxBubbleChartOptions> ptr;

    /// Constructs a wxBubbleChartOptions instance.
    wxBubbleChartOptions();

    /// Gets the options for the grid.
    /// @return The options for the grid.
    const wxChartsGridOptions& GetGridOptions() const;

private:
    wxChartsGridOptions m_gridOptions;
};

#endif


text:
private var isOver : boolean = false;

function GameOver () {
	GetComponent.<GUIText>().enabled = true;
	isOver = true;
	StartCoroutine("Blink");
}

function Blink() {
	yield WaitForSeconds(1);
	GetComponent.<GUIText>().enabled = !GetComponent.<GUIText>().enabled;
	StartCoroutine("Blink");
}

function Update() {
	if(!isOver) return;
	if(Input.GetKeyUp(KeyCode.Space)) StartCoroutine("StartNewGame");
}

function StartNewGame() {
	Game.objects.camWhiter.WhiteOut();
	yield WaitForEndOfFrame();
	Application.LoadLevel(1);
}


text:
namespace em = enterprise_management;

using testing::Mock;

namespace policy {

namespace {

const char kTestExtension[] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
const char kTestExtension2[] = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
const char kTestDownload[] = "http://example.com/getpolicy?id=123";
const char kTestDownload2[] = "http://example.com/getpolicy?id=456";

const char kTestPolicy[] =
    "{"
    "  \"Name\": {"
    "    \"Value\": \"disabled\""
    "  },"
    "  \"Second\": {"
    "    \"Value\": \"maybe\","
    "    \"Level\": \"Recommended\""
    "  }"
    "}";

const char kTestSchema[] =
    "{"
    "  \"type\": \"object\","
    "  \"properties\": {"
    "    \"Name\": { \"type\": \"string\" },"
    "    \"Second\": { \"type\": \"string\" }"
    "  }"
    "}";

class MockComponentCloudPolicyDelegate
    : public ComponentCloudPolicyService::Delegate {
 public:
  virtual ~MockComponentCloudPolicyDelegate() {}

  MOCK_METHOD0(OnComponentCloudPolicyRefreshNeeded, void());
  MOCK_METHOD0(OnComponentCloudPolicyUpdated, void());
};

class TestURLRequestContextGetter : public net::URLRequestContextGetter {
 public:
  explicit TestURLRequestContextGetter(
      scoped_refptr<base::SingleThreadTaskRunner> task_runner)
      : task_runner_(task_runner) {}
  virtual net::URLRequestContext* GetURLRequestContext() OVERRIDE {
    return NULL;
  }
  virtual scoped_refptr<base::SingleThreadTaskRunner>
      GetNetworkTaskRunner() const OVERRIDE {
    return task_runner_;
  }

 private:
  virtual ~TestURLRequestContextGetter() {}

  scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
};

}  // namespace

class ComponentCloudPolicyServiceTest : public testing::Test {
 protected:
  ComponentCloudPolicyServiceTest() {}

  virtual void SetUp() OVERRIDE {
    ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
    cache_ = new ResourceCache(temp_dir_.path(), loop_.message_loop_proxy());
    service_.reset(new ComponentCloudPolicyService(
        &delegate_,
        &store_,
        make_scoped_ptr(cache_),
        loop_.message_loop_proxy(),
        loop_.message_loop_proxy()));

    builder_.policy_data().set_policy_type(
        dm_protocol::kChromeExtensionPolicyType);
    builder_.policy_data().set_settings_entity_id(kTestExtension);
    builder_.payload().set_download_url(kTestDownload);
    builder_.payload().set_secure_hash(base::SHA1HashString(kTestPolicy));

    expected_policy_.Set("Name", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
                         base::Value::CreateStringValue("disabled"), NULL);
    expected_policy_.Set("Second", POLICY_LEVEL_RECOMMENDED, POLICY_SCOPE_USER,
                         base::Value::CreateStringValue("maybe"), NULL);

    // A NULL |request_context_| is enough to construct the updater, but
    // ComponentCloudPolicyService::Backend::LoadStore() tests the pointer when
    // Connect() is called before the store was loaded.
    request_context_ =
        new TestURLRequestContextGetter(loop_.message_loop_proxy());
  }

  virtual void TearDown() OVERRIDE {
    // The service cleans up its backend on the FILE thread.
    service_.reset();
    RunUntilIdle();
  }

  void RunUntilIdle() {
    base::RunLoop().RunUntilIdle();
  }

  void LoadStore() {
    EXPECT_FALSE(store_.is_initialized());
    EXPECT_FALSE(service_->is_initialized());

    em::PolicyData* data = new em::PolicyData();
    data->set_username(ComponentPolicyBuilder::kFakeUsername);
    data->set_request_token(ComponentPolicyBuilder::kFakeToken);
    store_.policy_.reset(data);

    EXPECT_CALL(delegate_, OnComponentCloudPolicyUpdated());
    store_.NotifyStoreLoaded();
    RunUntilIdle();
    Mock::VerifyAndClearExpectations(&delegate_);
    EXPECT_TRUE(service_->is_initialized());
  }

  void PopulateCache() {
    Pickle pickle;
    pickle.WriteString(kTestExtension);
    pickle.WriteString(kTestExtension2);
    std::string data(reinterpret_cast<const char*>(pickle.data()),
                     pickle.size());
    EXPECT_TRUE(
        cache_->Store(ComponentCloudPolicyService::kComponentNamespaceCache,
                      dm_protocol::kChromeExtensionPolicyType,
                      data));

    EXPECT_TRUE(cache_->Store(
        "extension-policy", kTestExtension, CreateSerializedResponse()));
    EXPECT_TRUE(
        cache_->Store("extension-policy-data", kTestExtension, kTestPolicy));

    builder_.policy_data().set_settings_entity_id(kTestExtension2);
    EXPECT_TRUE(cache_->Store(
        "extension-policy", kTestExtension2, CreateSerializedResponse()));
    EXPECT_TRUE(
        cache_->Store("extension-policy-data", kTestExtension2, kTestPolicy));

    EXPECT_TRUE(cache_->Store("unrelated", "stuff", "here"));
  }

  scoped_ptr<em::PolicyFetchResponse> CreateResponse() {
    builder_.Build();
    return make_scoped_ptr(new em::PolicyFetchResponse(builder_.policy()));
  }

  std::string CreateSerializedResponse() {
    builder_.Build();
    return builder_.GetBlob();
  }

  Schema CreateTestSchema() {
    std::string error;
    Schema schema = Schema::Parse(kTestSchema, &error);
    EXPECT_TRUE(schema.valid()) << error;
    return schema;
  }

  base::MessageLoop loop_;
  base::ScopedTempDir temp_dir_;
  scoped_refptr<TestURLRequestContextGetter> request_context_;
  net::TestURLFetcherFactory fetcher_factory_;
  MockComponentCloudPolicyDelegate delegate_;
  // |cache_| is owned by the |service_| and is invalid once the |service_|
  // is destroyed.
  ResourceCache* cache_;
  MockCloudPolicyClient client_;
  MockCloudPolicyStore store_;
  scoped_ptr<ComponentCloudPolicyService> service_;
  ComponentPolicyBuilder builder_;
  PolicyMap expected_policy_;
};

TEST_F(ComponentCloudPolicyServiceTest, InitializeWithoutCredentials) {
  EXPECT_FALSE(service_->is_initialized());
  // Run the background task to initialize the backend.
  RunUntilIdle();
  // Still waiting for the |store_|.
  EXPECT_FALSE(service_->is_initialized());

  // Initialize with a store without credentials.
  EXPECT_CALL(delegate_, OnComponentCloudPolicyUpdated());
  store_.NotifyStoreLoaded();
  RunUntilIdle();
  EXPECT_TRUE(service_->is_initialized());
  Mock::VerifyAndClearExpectations(&delegate_);
  const PolicyBundle empty_bundle;
  EXPECT_TRUE(service_->policy().Equals(empty_bundle));
}

TEST_F(ComponentCloudPolicyServiceTest, InitializationWithCachedComponents) {
  // Store a previous list of components.
  Pickle pickle;
  pickle.WriteString("aa");
  pickle.WriteString("bb");
  pickle.WriteString("cc");
  std::string data(reinterpret_cast<const char*>(pickle.data()), pickle.size());
  EXPECT_TRUE(
      cache_->Store(ComponentCloudPolicyService::kComponentNamespaceCache,
                    dm_protocol::kChromeExtensionPolicyType,
                    data));
  // Store some garbage in another domain; it won't be fetched.
  EXPECT_TRUE(cache_->Store(
      ComponentCloudPolicyService::kComponentNamespaceCache, "garbage", data));

  // Connect a client before initialization is complete.
  service_->Connect(&client_, request_context_);
  EXPECT_TRUE(client_.namespaces_to_fetch_.empty());

  // Now load the backend.
  LoadStore();

  // The cached namespaces were added to the client.
  std::set<PolicyNamespaceKey> set;
  set.insert(PolicyNamespaceKey(dm_protocol::kChromeExtensionPolicyType, "aa"));
  set.insert(PolicyNamespaceKey(dm_protocol::kChromeExtensionPolicyType, "bb"));
  set.insert(PolicyNamespaceKey(dm_protocol::kChromeExtensionPolicyType, "cc"));
  EXPECT_EQ(set, client_.namespaces_to_fetch_);

  // And the bad components were wiped from the cache.
  std::map<std::string, std::string> contents;
  cache_->LoadAllSubkeys(ComponentCloudPolicyService::kComponentNamespaceCache,
                         &contents);
  ASSERT_EQ(1u, contents.size());
  EXPECT_EQ(std::string(dm_protocol::kChromeExtensionPolicyType),
            contents.begin()->first);
}

TEST_F(ComponentCloudPolicyServiceTest, ConnectAfterRegister) {
  // Add some components.
  scoped_refptr<PolicyDomainDescriptor> descriptor = new PolicyDomainDescriptor(
      POLICY_DOMAIN_EXTENSIONS);
  descriptor->RegisterComponent(kTestExtension, CreateTestSchema());
  descriptor->RegisterComponent(kTestExtension2, CreateTestSchema());
  service_->RegisterPolicyDomain(descriptor);

  // Now connect the client.
  EXPECT_TRUE(client_.namespaces_to_fetch_.empty());
  service_->Connect(&client_, request_context_);
  EXPECT_TRUE(client_.namespaces_to_fetch_.empty());

  // It receives the namespaces once the backend is initialized.
  LoadStore();
  std::set<PolicyNamespaceKey> set;
  set.insert(PolicyNamespaceKey(dm_protocol::kChromeExtensionPolicyType,
                                kTestExtension));
  set.insert(PolicyNamespaceKey(dm_protocol::kChromeExtensionPolicyType,
                                kTestExtension2));
  EXPECT_EQ(set, client_.namespaces_to_fetch_);

  // The current components were also persisted to the cache.
  std::map<std::string, std::string> contents;
  cache_->LoadAllSubkeys(ComponentCloudPolicyService::kComponentNamespaceCache,
                         &contents);
  ASSERT_EQ(1u, contents.size());
  EXPECT_EQ(std::string(dm_protocol::kChromeExtensionPolicyType),
            contents.begin()->first);
  const std::string data(contents.begin()->second);
  Pickle pickle(data.data(), data.size());
  PickleIterator pickit(pickle);
  std::string value0;
  std::string value1;
  std::string tmp;
  ASSERT_TRUE(pickit.ReadString(&value0));
  ASSERT_TRUE(pickit.ReadString(&value1));
  EXPECT_FALSE(pickit.ReadString(&tmp));
  std::set<std::string> unpickled;
  unpickled.insert(value0);
  unpickled.insert(value1);

  std::set<std::string> expected_components;
  expected_components.insert(kTestExtension);
  expected_components.insert(kTestExtension2);

  EXPECT_EQ(expected_components, unpickled);
}

TEST_F(ComponentCloudPolicyServiceTest, StoreReadyAfterConnectAndRegister) {
  // Add some previous data to the cache.
  PopulateCache();

  // Add some components.
  scoped_refptr<PolicyDomainDescriptor> descriptor = new PolicyDomainDescriptor(
      POLICY_DOMAIN_EXTENSIONS);
  descriptor->RegisterComponent(kTestExtension, CreateTestSchema());
  service_->RegisterPolicyDomain(descriptor);

  // And connect the client. Make the client have some policies, with a new
  // download_url.
  builder_.payload().set_download_url(kTestDownload2);
  client_.SetPolicy(PolicyNamespaceKey(dm_protocol::kChromeExtensionPolicyType,
                                       kTestExtension),
                    *CreateResponse());
  service_->Connect(&client_, request_context_);

  // Now make the store ready.
  LoadStore();

  // The components that were registed before have their caches purged.
  std::map<std::string, std::string> contents;
  cache_->LoadAllSubkeys("extension-policy", &contents);
  EXPECT_EQ(1u, contents.size());  // kTestExtension2 was purged.
  EXPECT_TRUE(ContainsKey(contents, kTestExtension));
  cache_->LoadAllSubkeys("unrelated", &contents);
  EXPECT_EQ(1u, contents.size());  // unrelated keys are not purged.
  EXPECT_TRUE(ContainsKey(contents, "stuff"));

  // The policy responses that the client already had start updating.
  net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0);
  ASSERT_TRUE(fetcher);
  // Expect the URL of the client's PolicyFetchResponse, not the cached URL.
  EXPECT_EQ(GURL(kTestDownload2), fetcher->GetOriginalURL());
}

TEST_F(ComponentCloudPolicyServiceTest, ConnectThenRegisterThenStoreReady) {
  // Connect right after creating the service.
  service_->Connect(&client_, request_context_);

  // Now register the current components, before the backend has been
  // initialized.
  EXPECT_TRUE(client_.namespaces_to_fetch_.empty());
  scoped_refptr<PolicyDomainDescriptor> descriptor = new PolicyDomainDescriptor(
      POLICY_DOMAIN_EXTENSIONS);
  descriptor->RegisterComponent(kTestExtension, CreateTestSchema());
  service_->RegisterPolicyDomain(descriptor);
  EXPECT_TRUE(client_.namespaces_to_fetch_.empty());

  // Now load the store. The client gets the namespaces.
  LoadStore();
  std::set<PolicyNamespaceKey> set;
  set.insert(PolicyNamespaceKey(dm_protocol::kChromeExtensionPolicyType,
                                kTestExtension));
  EXPECT_EQ(set, client_.namespaces_to_fetch_);
}

TEST_F(ComponentCloudPolicyServiceTest, FetchPolicy) {
  // Initialize the store and create the backend, and connect the client.
  LoadStore();
  // A refresh is not needed, because no components were found.
  EXPECT_CALL(delegate_, OnComponentCloudPolicyRefreshNeeded()).Times(0);
  service_->Connect(&client_, request_context_);
  Mock::VerifyAndClearExpectations(&delegate_);

  // Register the components to fetch.
  scoped_refptr<PolicyDomainDescriptor> descriptor = new PolicyDomainDescriptor(
      POLICY_DOMAIN_EXTENSIONS);
  descriptor->RegisterComponent(kTestExtension, CreateTestSchema());
  EXPECT_CALL(delegate_, OnComponentCloudPolicyRefreshNeeded());
  service_->RegisterPolicyDomain(descriptor);
  Mock::VerifyAndClearExpectations(&delegate_);

  // Send back a fake policy fetch response.
  client_.SetPolicy(PolicyNamespaceKey(dm_protocol::kChromeExtensionPolicyType,
                                       kTestExtension),
                    *CreateResponse());
  service_->OnPolicyFetched(&client_);
  RunUntilIdle();

  // That should have triggered the download fetch.
  net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0);
  ASSERT_TRUE(fetcher);
  EXPECT_EQ(GURL(kTestDownload), fetcher->GetOriginalURL());
  fetcher->set_response_code(200);
  fetcher->SetResponseString(kTestPolicy);
  fetcher->delegate()->OnURLFetchComplete(fetcher);

  EXPECT_CALL(delegate_, OnComponentCloudPolicyUpdated());
  RunUntilIdle();
  Mock::VerifyAndClearExpectations(&delegate_);

  // The policy is now being served.
  PolicyNamespace ns(POLICY_DOMAIN_EXTENSIONS, kTestExtension);
  PolicyBundle expected_bundle;
  expected_bundle.Get(ns).CopyFrom(expected_policy_);
  EXPECT_TRUE(service_->policy().Equals(expected_bundle));
}

TEST_F(ComponentCloudPolicyServiceTest, LoadAndPurgeCache) {
  // Insert data in the cache.
  PopulateCache();

  // Load the initial cache.
  LoadStore();

  EXPECT_CALL(delegate_, OnComponentCloudPolicyRefreshNeeded());
  service_->Connect(&client_, request_context_);
  Mock::VerifyAndClearExpectations(&delegate_);

  PolicyBundle expected_bundle;
  PolicyNamespace ns(POLICY_DOMAIN_EXTENSIONS, kTestExtension);
  expected_bundle.Get(ns).CopyFrom(expected_policy_);
  ns.component_id = kTestExtension2;
  expected_bundle.Get(ns).CopyFrom(expected_policy_);
  EXPECT_TRUE(service_->policy().Equals(expected_bundle));

  // Now purge one of the extensions.
  EXPECT_CALL(delegate_, OnComponentCloudPolicyUpdated());
  // The service will start updating the components that are registered, which
  // starts by fetching policy for them.
  scoped_refptr<PolicyDomainDescriptor> descriptor = new PolicyDomainDescriptor(
      POLICY_DOMAIN_EXTENSIONS);
  descriptor->RegisterComponent(kTestExtension2, CreateTestSchema());
  service_->RegisterPolicyDomain(descriptor);
  RunUntilIdle();
  Mock::VerifyAndClearExpectations(&delegate_);

  ns.component_id = kTestExtension;
  expected_bundle.Get(ns).Clear();
  EXPECT_TRUE(service_->policy().Equals(expected_bundle));

  std::map<std::string, std::string> contents;
  cache_->LoadAllSubkeys("extension-policy", &contents);
  EXPECT_EQ(1u, contents.size());
  EXPECT_TRUE(ContainsKey(contents, kTestExtension2));
  cache_->LoadAllSubkeys("unrelated", &contents);
  EXPECT_EQ(1u, contents.size());
  EXPECT_TRUE(ContainsKey(contents, "stuff"));
}

TEST_F(ComponentCloudPolicyServiceTest, UpdateCredentials) {
  // Do the same as LoadStore() but without the initial credentials.
  EXPECT_FALSE(store_.is_initialized());
  EXPECT_FALSE(service_->is_initialized());
  store_.policy_.reset(new em::PolicyData());  //  No credentials.
  EXPECT_CALL(delegate_, OnComponentCloudPolicyUpdated());
  store_.NotifyStoreLoaded();
  RunUntilIdle();
  Mock::VerifyAndClearExpectations(&delegate_);
  EXPECT_TRUE(service_->is_initialized());

  // Connect the client and register an extension.
  service_->Connect(&client_, request_context_);
  EXPECT_CALL(delegate_, OnComponentCloudPolicyRefreshNeeded());
  scoped_refptr<PolicyDomainDescriptor> descriptor = new PolicyDomainDescriptor(
      POLICY_DOMAIN_EXTENSIONS);
  descriptor->RegisterComponent(kTestExtension, CreateTestSchema());
  service_->RegisterPolicyDomain(descriptor);
  Mock::VerifyAndClearExpectations(&delegate_);

  // Send the response to the service. The response data will be rejected,
  // because the store doesn't have the updated credentials yet.
  client_.SetPolicy(PolicyNamespaceKey(dm_protocol::kChromeExtensionPolicyType,
                                       kTestExtension),
                    *CreateResponse());
  service_->OnPolicyFetched(&client_);
  RunUntilIdle();

  // The policy was not verified, and no download is started.
  net::TestURLFetcher* fetcher = fetcher_factory_.GetFetcherByID(0);
  EXPECT_FALSE(fetcher);

  // Now update the |store_| with the updated policy, which includes
  // credentials. The responses in the |client_| will be reloaded.
  em::PolicyData* data = new em::PolicyData();
  data->set_username(ComponentPolicyBuilder::kFakeUsername);
  data->set_request_token(ComponentPolicyBuilder::kFakeToken);
  store_.policy_.reset(data);
  store_.NotifyStoreLoaded();
  RunUntilIdle();

  // The extension policy was validated this time, and the download is started.
  fetcher = fetcher_factory_.GetFetcherByID(0);
  ASSERT_TRUE(fetcher);
  EXPECT_EQ(GURL(kTestDownload), fetcher->GetOriginalURL());
  fetcher->set_response_code(200);
  fetcher->SetResponseString(kTestPolicy);
  fetcher->delegate()->OnURLFetchComplete(fetcher);

  EXPECT_CALL(delegate_, OnComponentCloudPolicyUpdated());
  RunUntilIdle();
  Mock::VerifyAndClearExpectations(&delegate_);

  // The policy is now being served.
  PolicyNamespace ns(POLICY_DOMAIN_EXTENSIONS, kTestExtension);
  PolicyBundle expected_bundle;
  expected_bundle.Get(ns).CopyFrom(expected_policy_);
  EXPECT_TRUE(service_->policy().Equals(expected_bundle));
}

}  // namespace policy