text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
						http://www.springframework.org/schema/beans/spring-beans.xsd
						http://www.springframework.org/schema/aop
						http://www.springframework.org/schema/aop/spring-aop.xsd
						http://www.springframework.org/schema/context
						http://www.springframework.org/schema/context/spring-context.xsd
						http://www.springframework.org/schema/tx
						http://www.springframework.org/schema/tx/spring-tx.xsd
	">

	<bean id="propertyConfigurer" class="com.gvtv.manage.projectname.spring.ConfigPropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
                 <value>/WEB-INF/classes/dbconfig.properties</value>
                 <value>/WEB-INF/classes/application.properties</value>
            </list>
        </property>
	</bean>

	<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
	    <!-- <property name="cacheSeconds" value="-1"/>  -->
	    <property name="cacheSeconds" value="5"/>
	    <property name="defaultEncoding" value ="utf-8" />
	    <property name="basenames">
	    	<list>
	    		<value>classpath:messages/message</value>
	    	</list>
	    </property>
	</bean>

	<!-- 阿里 druid数据库连接池 -->
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
         <!-- 数据库基本信息配置 -->
         <property name="url" value="${url}" />
         <property name="username" value="${username}" />
         <property name="password" value="${password}" />
         <property name="driverClassName" value="${driverClassName}" />
         <property name="filters" value="${filters}" />
   		 <!-- 最大并发连接数 -->
         <property name="maxActive" value="${maxActive}" />
         <!-- 初始化连接数量 -->
         <property name="initialSize" value="${initialSize}" />
         <!-- 配置获取连接等待超时的时间 -->
         <property name="maxWait" value="${maxWait}" />
         <!-- 最小空闲连接数 -->
         <property name="minIdle" value="${minIdle}" />
   		 <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
         <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}" />
         <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
         <property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}" />
         <property name="validationQuery" value="${validationQuery}" />
         <property name="testWhileIdle" value="${testWhileIdle}" />
         <property name="testOnBorrow" value="${testOnBorrow}" />
         <property name="testOnReturn" value="${testOnReturn}" />
         <property name="maxOpenPreparedStatements" value="${maxOpenPreparedStatements}" />
         <!-- 打开removeAbandoned功能 -->
         <property name="removeAbandoned" value="${removeAbandoned}" />
         <!-- 1800秒,也就是30分钟 -->
         <property name="removeAbandonedTimeout" value="${removeAbandonedTimeout}" />
         <!-- 关闭abanded连接时输出错误日志 -->
         <property name="logAbandoned" value="${logAbandoned}" />
	</bean>

	<!-- 配置mybatis -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    	<property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property>
        <property name="mapperLocations" value="classpath:mybatis/*/*.xml"></property><!-- mapper扫描 -->
    </bean>

    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg ref="sqlSessionFactory" />
	</bean>

	<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    	<property name="dataSource" ref="dataSource"></property>
 	</bean>

 	<tx:annotation-driven transaction-manager="transactionManager" />

	<!-- ================ Shiro start ================ -->
		<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
			<property name="realm" ref="ShiroRealm" />
		</bean>

		<!--Realm -->
		<bean id="ShiroRealm" class="com.gvtv.manage.base.interceptor.shiro.ShiroRealm" ></bean>

		<!-- rights -->
		<bean id="gvrts" class="com.gvtv.manage.base.filter.shiro.RightsFilter"></bean>

		<!-- Shiro Filter -->
		<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
			<property name="securityManager" ref="securityManager" />
			<property name="loginUrl" value="/" />
			<property name="successUrl" value="/main" />
			<property name="unauthorizedUrl" value="/login_toLogin" />
 			<property name="filters">
				<map>
					<entry key="gvrts" value-ref="gvrts" />
				</map>
			</property>
			<property name="filterChainDefinitions">
				<value>
				/static/** 		= anon
	           	/code 			= anon
	           	/login_login     	= anon
	           	/logout     	= anon
	           	/sys/index       = anon
	           	/user/unauthorized  = anon
	           	/user/editPwd  = anon
	           	/**					= gvrts
				</value>
			</property>
		</bean>
	<!-- ================ Shiro end ================ -->

</beans>


text:
Groovy Role Playing Game - Software educativo para aprender a programar de un modo simple, en español.

## Funcionamiento

Por el momento el proyecto está en etapa experimental, por lo que no hay un funcionamiento determinado. Se están probando los distintos conceptos posibles.

## Cómo colaborar

Simplemente hacer un fork del proyecto, realizar las modificaciones y efectuar un pull-request (el mecanismo de colaboración estándar de GitHub).
No necesitás hacer gran código para colaborar... aportando ideas, documentación o mejorando la legibilidad se puede llegar a incrementar el valor de la herramienta.

## Créditos (hasta el momento)

* [Lucas Videla](http://www.twitter.com/luke_ar)

redpajama_set_name: RedPajamaGithub


text:
package org.zaproxy.zap.extension.spider;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.httpclient.URI;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.zaproxy.zap.model.ScanController;
import org.zaproxy.zap.model.Target;
import org.zaproxy.zap.users.User;

/** @deprecated (2.12.0) See the spider add-on in zap-extensions instead. */
@Deprecated
public class SpiderScanController implements ScanController<SpiderScan> {

    private static final Logger log = LogManager.getLogger(SpiderScanController.class);

    private ExtensionSpider extension;

    /**
     * The {@code Lock} for exclusive access of instance variables related to multiple active scans.
     *
     * @see #spiderScanMap
     * @see #scanIdCounter
     */
    private final Lock spiderScansLock;

    /**
     * The counter used to give an unique ID to active scans.
     *
     *
Note: All accesses (both write and read) should be done while holding the
     * {@code Lock} {@code spiderScansLock}.
     *
     * @see #spiderScansLock
     * @see #startScan(String, Target, User, Object[])
     */
    private int scanIdCounter;

    /**
     * A map that contains all {@code SpiderScan}s created (and not yet removed). Used to control
     * (i.e. pause/resume and stop) the multiple active scans and get its results. The instance
     * variable is never {@code null}. The map key is the ID of the scan.
     *
     *
Note: All accesses (both write and read) should be done while holding the
     * {@code Lock} {@code spiderScansLock}.
     *
     * @see #spiderScansLock
     * @see #startScan(String, Target, User, Object[])
     * @see #scanIdCounter
     */
    private Map<Integer, SpiderScan> spiderScanMap;

    /**
     * An ordered list of all of the {@code SpiderScan}s created (and not yet removed). Used to get
     * provide the 'last' scan for client using the 'old' API that didn't support concurrent scans.
     */
    private List<SpiderScan> spiderScanList;

    public SpiderScanController(ExtensionSpider extension) {
        this.spiderScansLock = new ReentrantLock();
        this.extension = extension;
        this.spiderScanMap = new HashMap<>();
        this.spiderScanList = new ArrayList<>();
    }

    @Override
    public int startScan(String name, Target target, User user, Object[] contextSpecificObjects) {
        spiderScansLock.lock();
        try {
            int id = this.scanIdCounter++;

            org.zaproxy.zap.spider.SpiderParam spiderParams = extension.getSpiderParam();
            List<org.zaproxy.zap.spider.parser.SpiderParser> customSpiderParsers =
                    new ArrayList<>();
            List<org.zaproxy.zap.spider.filters.FetchFilter> customFetchFilters = new ArrayList<>();
            List<org.zaproxy.zap.spider.filters.ParseFilter> customParseFilters = new ArrayList<>();
            URI startUri = null;

            if (contextSpecificObjects != null) {
                for (Object obj : contextSpecificObjects) {
                    if (obj instanceof org.zaproxy.zap.spider.SpiderParam) {
                        log.debug("Setting custom spider params");
                        spiderParams = (org.zaproxy.zap.spider.SpiderParam) obj;
                    } else if (obj instanceof org.zaproxy.zap.spider.parser.SpiderParser) {
                        customSpiderParsers.add((org.zaproxy.zap.spider.parser.SpiderParser) obj);
                    } else if (obj instanceof org.zaproxy.zap.spider.filters.FetchFilter) {
                        customFetchFilters.add((org.zaproxy.zap.spider.filters.FetchFilter) obj);
                    } else if (obj instanceof org.zaproxy.zap.spider.filters.ParseFilter) {
                        customParseFilters.add((org.zaproxy.zap.spider.filters.ParseFilter) obj);
                    } else if (obj instanceof URI) {
                        startUri = (URI) obj;
                    } else {
                        log.error(
                                "Unexpected contextSpecificObject: {}",
                                obj.getClass().getCanonicalName());
                    }
                }
            }

            if (spiderParams.getMaxChildren() > 0) {
                // Add the filters to filter on maximum number of children
                org.zaproxy.zap.spider.filters.MaxChildrenFetchFilter maxChildrenFetchFilter =
                        new org.zaproxy.zap.spider.filters.MaxChildrenFetchFilter();
                maxChildrenFetchFilter.setMaxChildren(spiderParams.getMaxChildren());
                maxChildrenFetchFilter.setModel(extension.getModel());

                org.zaproxy.zap.spider.filters.MaxChildrenParseFilter maxChildrenParseFilter =
                        new org.zaproxy.zap.spider.filters.MaxChildrenParseFilter(
                                extension.getMessages());
                maxChildrenParseFilter.setMaxChildren(spiderParams.getMaxChildren());
                maxChildrenParseFilter.setModel(extension.getModel());

                customFetchFilters.add(maxChildrenFetchFilter);
                customParseFilters.add(maxChildrenParseFilter);
            }

            SpiderScan scan =
                    new SpiderScan(extension, spiderParams, target, startUri, user, id, name);
            scan.setCustomSpiderParsers(customSpiderParsers);
            scan.setCustomFetchFilters(customFetchFilters);
            scan.setCustomParseFilters(customParseFilters);

            this.spiderScanMap.put(id, scan);
            this.spiderScanList.add(scan);
            scan.start();

            return id;
        } finally {
            spiderScansLock.unlock();
        }
    }

    @Override
    public SpiderScan getScan(int id) {
        return this.spiderScanMap.get(id);
    }

    @Override
    public SpiderScan getLastScan() {
        spiderScansLock.lock();
        try {
            if (spiderScanList.isEmpty()) {
                return null;
            }
            return spiderScanList.get(spiderScanList.size() - 1);
        } finally {
            spiderScansLock.unlock();
        }
    }

    @Override
    public List<SpiderScan> getAllScans() {
        List<SpiderScan> list = new ArrayList<>();
        spiderScansLock.lock();
        try {
            for (SpiderScan scan : spiderScanList) {
                list.add(scan);
            }
            return list;
        } finally {
            spiderScansLock.unlock();
        }
    }

    @Override
    public List<SpiderScan> getActiveScans() {
        List<SpiderScan> list = new ArrayList<>();
        spiderScansLock.lock();
        try {
            for (SpiderScan scan : spiderScanList) {
                if (!scan.isStopped()) {
                    list.add(scan);
                }
            }
            return list;
        } finally {
            spiderScansLock.unlock();
        }
    }

    @Override
    public SpiderScan removeScan(int id) {
        spiderScansLock.lock();

        try {
            SpiderScan ascan = this.spiderScanMap.get(id);
            if (!spiderScanMap.containsKey(id)) {
                // throw new IllegalArgumentException("Unknown id " + id);
                return null;
            }
            ascan.stopScan();
            ascan.clear();
            spiderScanMap.remove(id);
            spiderScanList.remove(ascan);
            return ascan;
        } finally {
            spiderScansLock.unlock();
        }
    }

    public int getTotalNumberScans() {
        return spiderScanMap.size();
    }

    @Override
    public void stopAllScans() {
        spiderScansLock.lock();
        try {
            for (SpiderScan scan : spiderScanMap.values()) {
                scan.stopScan();
            }
        } finally {
            spiderScansLock.unlock();
        }
    }

    @Override
    public void pauseAllScans() {
        spiderScansLock.lock();
        try {
            for (SpiderScan scan : spiderScanMap.values()) {
                scan.pauseScan();
            }
        } finally {
            spiderScansLock.unlock();
        }
    }

    @Override
    public void resumeAllScans() {
        spiderScansLock.lock();
        try {
            for (SpiderScan scan : spiderScanMap.values()) {
                scan.resumeScan();
            }
        } finally {
            spiderScansLock.unlock();
        }
    }

    @Override
    public int removeAllScans() {
        spiderScansLock.lock();
        try {
            int count = 0;
            for (Iterator<SpiderScan> it = spiderScanMap.values().iterator(); it.hasNext(); ) {
                SpiderScan ascan = it.next();
                ascan.stopScan();
                ascan.clear();
                it.remove();
                spiderScanList.remove(ascan);
                count++;
            }
            return count;
        } finally {
            spiderScansLock.unlock();
        }
    }

    @Override
    public int removeFinishedScans() {
        spiderScansLock.lock();
        try {
            int count = 0;
            for (Iterator<SpiderScan> it = spiderScanMap.values().iterator(); it.hasNext(); ) {
                SpiderScan scan = it.next();
                if (scan.isStopped()) {
                    scan.stopScan();
                    scan.clear();
                    it.remove();
                    spiderScanList.remove(scan);
                    count++;
                }
            }
            return count;
        } finally {
            spiderScansLock.unlock();
        }
    }

    @Override
    public void stopScan(int id) {
        spiderScansLock.lock();
        try {
            if (this.spiderScanMap.containsKey(id)) {
                this.spiderScanMap.get(id).stopScan();
            }
        } finally {
            spiderScansLock.unlock();
        }
    }

    @Override
    public void pauseScan(int id) {
        spiderScansLock.lock();
        try {
            if (this.spiderScanMap.containsKey(id)) {
                this.spiderScanMap.get(id).pauseScan();
            }
        } finally {
            spiderScansLock.unlock();
        }
    }

    @Override
    public void resumeScan(int id) {
        spiderScansLock.lock();
        try {
            if (this.spiderScanMap.containsKey(id)) {
                this.spiderScanMap.get(id).resumeScan();
            }
        } finally {
            spiderScansLock.unlock();
        }
    }

    public void reset() {
        this.removeAllScans();
        spiderScansLock.lock();
        try {
            this.scanIdCounter = 0;
        } finally {
            spiderScansLock.unlock();
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/ll_rootview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="75dip"
        android:gravity="center|left"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="1. 点击菜单项,使用showAsDropDown显示一个PopupWindow"
            android:textColor="@color/transparent_red"
            android:textSize="20sp"
            android:textStyle="bold" />
    </LinearLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="60dip"
        android:background="#ffffff">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_alignParentLeft="true"
            android:gravity="center"
            android:padding="10dp"
            android:text="返回"
            android:textColor="#50484b"
            android:textSize="22sp" />

        <TextView
            android:id="@+id/menu"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_alignParentRight="true"
            android:gravity="center"
            android:padding="10dp"
            android:text="菜单"
            android:textColor="#50484b"
            android:textSize="22sp" />
    </RelativeLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="75dip"
        android:gravity="center|left"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="2. 简单的使用showAsDropDown显示一个PopupWindow"
            android:textColor="@color/transparent_red"
            android:textSize="20sp"
            android:textStyle="bold" />
    </LinearLayout>

    <Button
        android:id="@+id/btn_show_popup"
        android:layout_width="match_parent"
        android:layout_height="45dip"
        android:layout_marginLeft="5dip"
        android:layout_marginRight="5dip"
        android:layout_marginTop="5dip"
        android:background="@drawable/button_selector"
        android:text="showAtLocation显示PopupWindow" />

</LinearLayout>


text:
import React from "react";
import { forceOnline } from "../../devices/must_be_online";
import { t } from "../../i18next_wrapper";
import { resendParameters } from "./export_menu";

export const SETTING_SYNC_TIMEOUT = 10000;

export interface SettingStatusState {
  inconsistent: boolean;
  syncing: boolean;
  timeout: NodeJS.Timeout | undefined;
}

export const initSettingStatusState = (): SettingStatusState => ({
  inconsistent: false,
  syncing: false,
  timeout: undefined,
});

export interface SettingStatusIndicatorProps {
  dispatch: Function | undefined;
  wasSyncing: boolean;
  isSyncing: boolean | undefined;
}

export const SettingStatusIndicator = (props: SettingStatusIndicatorProps) => {
  const { dispatch } = props;
  return <div className={"setting-status-indicator"}>
    {props.wasSyncing && dispatch &&
      <i className={`fa fa-${props.isSyncing ? "spinner fa-pulse" : "check"}`} />}
    {(!props.wasSyncing && props.isSyncing) && dispatch && !forceOnline() &&
      <i className={"fa fa-exclamation-triangle"}
        title={t("Save error. Click to retry.")}
        onClick={e => {
          e.stopPropagation();
          dispatch(resendParameters());
        }} />}
  </div>;
};


text:
using Robust.Shared.Serialization;

namespace Content.Shared.MobState
{
    [Serializable, NetSerializable]
    public enum DamageStateVisuals : byte
    {
        State
    }

    /// <summary>
    ///     Defines what state an <see cref="Robust.Shared.GameObjects.EntityUid"/> is in.
    ///
    ///     Ordered from most alive to least alive.
    ///     To enumerate them in this way see
    ///     <see cref="DamageStateHelpers.AliveToDead"/>.
    /// </summary>
    [Serializable, NetSerializable]
    public enum DamageState : byte
    {
        Invalid = 0,
        Alive = 1,
        Critical = 2,
        Dead = 3
    }
}


text:
A [Go](http://golang.org) client for the [NATS messaging system](https://nats.io).

[![License Apache 2][License-Image]][License-Url] [![Go Report Card][ReportCard-Image]][ReportCard-Url] [![Build Status][Build-Status-Image]][Build-Status-Url] [![GoDoc][GoDoc-Image]][GoDoc-Url] [![Coverage Status][Coverage-image]][Coverage-Url]

[License-Url]: https://www.apache.org/licenses/LICENSE-2.0
[License-Image]: https://img.shields.io/badge/License-Apache2-blue.svg
[ReportCard-Url]: https://goreportcard.com/report/github.com/nats-io/nats.go
[ReportCard-Image]: https://goreportcard.com/badge/github.com/nats-io/nats.go
[Build-Status-Url]: https://travis-ci.com/github/nats-io/nats.go
[Build-Status-Image]: https://travis-ci.com/nats-io/nats.go.svg?branch=main
[GoDoc-Url]: https://pkg.go.dev/github.com/nats-io/nats.go
[GoDoc-Image]: https://img.shields.io/badge/GoDoc-reference-007d9c
[Coverage-Url]: https://coveralls.io/r/nats-io/nats.go?branch=main
[Coverage-image]: https://coveralls.io/repos/github/nats-io/nats.go/badge.svg?branch=main

## Installation

```bash
# Go client
go get github.com/nats-io/nats.go/

# Server
go get github.com/nats-io/nats-server
```

When using or transitioning to Go modules support:

```bash
# Go client latest or explicit version
go get github.com/nats-io/nats.go/@latest
go get github.com/nats-io/nats.go/@v1.20.0

# For latest NATS Server, add /v2 at the end
go get github.com/nats-io/nats-server/v2

# NATS Server v1 is installed otherwise
# go get github.com/nats-io/nats-server
```

## Basic Usage

```go
import "github.com/nats-io/nats.go"

// Connect to a server
nc, _ := nats.Connect(nats.DefaultURL)

// Simple Publisher
nc.Publish("foo", []byte("Hello World"))

// Simple Async Subscriber
nc.Subscribe("foo", func(m *nats.Msg) {
    fmt.Printf("Received a message: %s\n", string(m.Data))
})

// Responding to a request message
nc.Subscribe("request", func(m *nats.Msg) {
    m.Respond([]byte("answer is 42"))
})

// Simple Sync Subscriber
sub, err := nc.SubscribeSync("foo")
m, err := sub.NextMsg(timeout)

// Channel Subscriber
ch := make(chan *nats.Msg, 64)
sub, err := nc.ChanSubscribe("foo", ch)
msg := <- ch

// Unsubscribe
sub.Unsubscribe()

// Drain
sub.Drain()

// Requests
msg, err := nc.Request("help", []byte("help me"), 10*time.Millisecond)

// Replies
nc.Subscribe("help", func(m *nats.Msg) {
    nc.Publish(m.Reply, []byte("I can help!"))
})

// Drain connection (Preferred for responders)
// Close() not needed if this is called.
nc.Drain()

// Close connection
nc.Close()
```

## JetStream Basic Usage

```go
import "github.com/nats-io/nats.go"

// Connect to NATS
nc, _ := nats.Connect(nats.DefaultURL)

// Create JetStream Context
js, _ := nc.JetStream(nats.PublishAsyncMaxPending(256))

// Simple Stream Publisher
js.Publish("ORDERS.scratch", []byte("hello"))

// Simple Async Stream Publisher
for i := 0; i < 500; i++ {
	js.PublishAsync("ORDERS.scratch", []byte("hello"))
}
select {
case <-js.PublishAsyncComplete():
case <-time.After(5 * time.Second):
	fmt.Println("Did not resolve in time")
}

// Simple Async Ephemeral Consumer
js.Subscribe("ORDERS.*", func(m *nats.Msg) {
	fmt.Printf("Received a JetStream message: %s\n", string(m.Data))
})

// Simple Sync Durable Consumer (optional SubOpts at the end)
sub, err := js.SubscribeSync("ORDERS.*", nats.Durable("MONITOR"), nats.MaxDeliver(3))
m, err := sub.NextMsg(timeout)

// Simple Pull Consumer
sub, err := js.PullSubscribe("ORDERS.*", "MONITOR")
msgs, err := sub.Fetch(10)

// Unsubscribe
sub.Unsubscribe()

// Drain
sub.Drain()
```

## JetStream Basic Management

```go
import "github.com/nats-io/nats.go"

// Connect to NATS
nc, _ := nats.Connect(nats.DefaultURL)

// Create JetStream Context
js, _ := nc.JetStream()

// Create a Stream
js.AddStream(&nats.StreamConfig{
	Name:     "ORDERS",
	Subjects: []string{"ORDERS.*"},
})

// Update a Stream
js.UpdateStream(&nats.StreamConfig{
	Name:     "ORDERS",
	MaxBytes: 8,
})

// Create a Consumer
js.AddConsumer("ORDERS", &nats.ConsumerConfig{
	Durable: "MONITOR",
})

// Delete Consumer
js.DeleteConsumer("ORDERS", "MONITOR")

// Delete Stream
js.DeleteStream("ORDERS")
```

## Encoded Connections

```go

nc, _ := nats.Connect(nats.DefaultURL)
c, _ := nats.NewEncodedConn(nc, nats.JSON_ENCODER)
defer c.Close()

// Simple Publisher
c.Publish("foo", "Hello World")

// Simple Async Subscriber
c.Subscribe("foo", func(s string) {
    fmt.Printf("Received a message: %s\n", s)
})

// EncodedConn can Publish any raw Go type using the registered Encoder
type person struct {
     Name     string
     Address  string
     Age      int
}

// Go type Subscriber
c.Subscribe("hello", func(p *person) {
    fmt.Printf("Received a person: %+v\n", p)
})

me := &person{Name: "derek", Age: 22, Address: "140 New Montgomery Street, San Francisco, CA"}

// Go type Publisher
c.Publish("hello", me)

// Unsubscribe
sub, err := c.Subscribe("foo", nil)
// ...
sub.Unsubscribe()

// Requests
var response string
err = c.Request("help", "help me", &response, 10*time.Millisecond)
if err != nil {
    fmt.Printf("Request failed: %v\n", err)
}

// Replying
c.Subscribe("help", func(subj, reply string, msg string) {
    c.Publish(reply, "I can help!")
})

// Close connection
c.Close();
```

## New Authentication (Nkeys and User Credentials)
This requires server with version >= 2.0.0

NATS servers have a new security and authentication mechanism to authenticate with user credentials and Nkeys.
The simplest form is to use the helper method UserCredentials(credsFilepath).
```go
nc, err := nats.Connect(url, nats.UserCredentials("user.creds"))
```

The helper methods creates two callback handlers to present the user JWT and sign the nonce challenge from the server.
The core client library never has direct access to your private key and simply performs the callback for signing the server challenge.
The helper will load and wipe and erase memory it uses for each connect or reconnect.

The helper also can take two entries, one for the JWT and one for the NKey seed file.
```go
nc, err := nats.Connect(url, nats.UserCredentials("user.jwt", "user.nk"))
```

You can also set the callback handlers directly and manage challenge signing directly.
```go
nc, err := nats.Connect(url, nats.UserJWT(jwtCB, sigCB))
```

Bare Nkeys are also supported. The nkey seed should be in a read only file, e.g. seed.txt
```bash
> cat seed.txt
# This is my seed nkey!
SUAGMJH5XLGZKQQWAWKRZJIGMOU4HPFUYLXJMXOO5NLFEO2OOQJ5LPRDPM
```

This is a helper function which will load and decode and do the proper signing for the server nonce.
It will clear memory in between invocations.
You can choose to use the low level option and provide the public key and a signature callback on your own.

```go
opt, err := nats.NkeyOptionFromSeed("seed.txt")
nc, err := nats.Connect(serverUrl, opt)

// Direct
nc, err := nats.Connect(serverUrl, nats.Nkey(pubNkey, sigCB))
```

## TLS

```go
// tls as a scheme will enable secure connections by default. This will also verify the server name.
nc, err := nats.Connect("tls://nats.demo.io:4443")

// If you are using a self-signed certificate, you need to have a tls.Config with RootCAs setup.
// We provide a helper method to make this case easier.
nc, err = nats.Connect("tls://localhost:4443", nats.RootCAs("./configs/certs/ca.pem"))

// If the server requires client certificate, there is an helper function for that too:
cert := nats.ClientCert("./configs/certs/client-cert.pem", "./configs/certs/client-key.pem")
nc, err = nats.Connect("tls://localhost:4443", cert)

// You can also supply a complete tls.Config

certFile := "./configs/certs/client-cert.pem"
keyFile := "./configs/certs/client-key.pem"
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
    t.Fatalf("error parsing X509 certificate/key pair: %v", err)
}

config := &tls.Config{
    ServerName: 	opts.Host,
    Certificates: 	[]tls.Certificate{cert},
    RootCAs:    	pool,
    MinVersion: 	tls.VersionTLS12,
}

nc, err = nats.Connect("nats://localhost:4443", nats.Secure(config))
if err != nil {
	t.Fatalf("Got an error on Connect with Secure Options: %+v\n", err)
}

```

## Using Go Channels (netchan)

```go
nc, _ := nats.Connect(nats.DefaultURL)
ec, _ := nats.NewEncodedConn(nc, nats.JSON_ENCODER)
defer ec.Close()

type person struct {
     Name     string
     Address  string
     Age      int
}

recvCh := make(chan *person)
ec.BindRecvChan("hello", recvCh)

sendCh := make(chan *person)
ec.BindSendChan("hello", sendCh)

me := &person{Name: "derek", Age: 22, Address: "140 New Montgomery Street"}

// Send via Go channels
sendCh <- me

// Receive via Go channels
who := <- recvCh
```

## Wildcard Subscriptions

```go

// "*" matches any token, at any level of the subject.
nc.Subscribe("foo.*.baz", func(m *Msg) {
    fmt.Printf("Msg received on [%s] : %s\n", m.Subject, string(m.Data));
})

nc.Subscribe("foo.bar.*", func(m *Msg) {
    fmt.Printf("Msg received on [%s] : %s\n", m.Subject, string(m.Data));
})

// ">" matches any length of the tail of a subject, and can only be the last token
// E.g. 'foo.>' will match 'foo.bar', 'foo.bar.baz', 'foo.foo.bar.bax.22'
nc.Subscribe("foo.>", func(m *Msg) {
    fmt.Printf("Msg received on [%s] : %s\n", m.Subject, string(m.Data));
})

// Matches all of the above
nc.Publish("foo.bar.baz", []byte("Hello World"))

```

## Queue Groups

```go
// All subscriptions with the same queue name will form a queue group.
// Each message will be delivered to only one subscriber per queue group,
// using queuing semantics. You can have as many queue groups as you wish.
// Normal subscribers will continue to work as expected.

nc.QueueSubscribe("foo", "job_workers", func(_ *Msg) {
  received += 1;
})
```

## Advanced Usage

```go

// Normally, the library will return an error when trying to connect and
// there is no server running. The RetryOnFailedConnect option will set
// the connection in reconnecting state if it failed to connect right away.
nc, err := nats.Connect(nats.DefaultURL,
    nats.RetryOnFailedConnect(true),
    nats.MaxReconnects(10),
    nats.ReconnectWait(time.Second),
    nats.ReconnectHandler(func(_ *nats.Conn) {
        // Note that this will be invoked for the first asynchronous connect.
    }))
if err != nil {
    // Should not return an error even if it can't connect, but you still
    // need to check in case there are some configuration errors.
}

// Flush connection to server, returns when all messages have been processed.
nc.Flush()
fmt.Println("All clear!")

// FlushTimeout specifies a timeout value as well.
err := nc.FlushTimeout(1*time.Second)
if err != nil {
    fmt.Println("All clear!")
} else {
    fmt.Println("Flushed timed out!")
}

// Auto-unsubscribe after MAX_WANTED messages received
const MAX_WANTED = 10
sub, err := nc.Subscribe("foo")
sub.AutoUnsubscribe(MAX_WANTED)

// Multiple connections
nc1 := nats.Connect("nats://host1:4222")
nc2 := nats.Connect("nats://host2:4222")

nc1.Subscribe("foo", func(m *Msg) {
    fmt.Printf("Received a message: %s\n", string(m.Data))
})

nc2.Publish("foo", []byte("Hello World!"));

```

## Clustered Usage

```go

var servers = "nats://localhost:1222, nats://localhost:1223, nats://localhost:1224"

nc, err := nats.Connect(servers)

// Optionally set ReconnectWait and MaxReconnect attempts.
// This example means 10 seconds total per backend.
nc, err = nats.Connect(servers, nats.MaxReconnects(5), nats.ReconnectWait(2 * time.Second))

// You can also add some jitter for the reconnection.
// This call will add up to 500 milliseconds for non TLS connections and 2 seconds for TLS connections.
// If not specified, the library defaults to 100 milliseconds and 1 second, respectively.
nc, err = nats.Connect(servers, nats.ReconnectJitter(500*time.Millisecond, 2*time.Second))

// You can also specify a custom reconnect delay handler. If set, the library will invoke it when it has tried
// all URLs in its list. The value returned will be used as the total sleep time, so add your own jitter.
// The library will pass the number of times it went through the whole list.
nc, err = nats.Connect(servers, nats.CustomReconnectDelay(func(attempts int) time.Duration {
    return someBackoffFunction(attempts)
}))

// Optionally disable randomization of the server pool
nc, err = nats.Connect(servers, nats.DontRandomize())

// Setup callbacks to be notified on disconnects, reconnects and connection closed.
nc, err = nats.Connect(servers,
	nats.DisconnectErrHandler(func(nc *nats.Conn, err error) {
		fmt.Printf("Got disconnected! Reason: %q\n", err)
	}),
	nats.ReconnectHandler(func(nc *nats.Conn) {
		fmt.Printf("Got reconnected to %v!\n", nc.ConnectedUrl())
	}),
	nats.ClosedHandler(func(nc *nats.Conn) {
		fmt.Printf("Connection closed. Reason: %q\n", nc.LastError())
	})
)

// When connecting to a mesh of servers with auto-discovery capabilities,
// you may need to provide a username/password or token in order to connect
// to any server in that mesh when authentication is required.
// Instead of providing the credentials in the initial URL, you will use
// new option setters:
nc, err = nats.Connect("nats://localhost:4222", nats.UserInfo("foo", "bar"))

// For token based authentication:
nc, err = nats.Connect("nats://localhost:4222", nats.Token("S3cretT0ken"))

// You can even pass the two at the same time in case one of the server
// in the mesh requires token instead of user name and password.
nc, err = nats.Connect("nats://localhost:4222",
    nats.UserInfo("foo", "bar"),
    nats.Token("S3cretT0ken"))

// Note that if credentials are specified in the initial URLs, they take
// precedence on the credentials specified through the options.
// For instance, in the connect call below, the client library will use
// the user "my" and password "pwd" to connect to localhost:4222, however,
// it will use username "foo" and password "bar" when (re)connecting to
// a different server URL that it got as part of the auto-discovery.
nc, err = nats.Connect("nats://my:pwd@localhost:4222", nats.UserInfo("foo", "bar"))

```

## Context support (+Go 1.7)

```go
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()

nc, err := nats.Connect(nats.DefaultURL)

// Request with context
msg, err := nc.RequestWithContext(ctx, "foo", []byte("bar"))

// Synchronous subscriber with context
sub, err := nc.SubscribeSync("foo")
msg, err := sub.NextMsgWithContext(ctx)

// Encoded Request with context
c, err := nats.NewEncodedConn(nc, nats.JSON_ENCODER)
type request struct {
	Message string `json:"message"`
}
type response struct {
	Code int `json:"code"`
}
req := &request{Message: "Hello"}
resp := &response{}
err := c.RequestWithContext(ctx, "foo", req, resp)
```

## License

Unless otherwise noted, the NATS source files are distributed
under the Apache Version 2.0 license found in the LICENSE file.

[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fnats-io%2Fgo-nats.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fnats-io%2Fgo-nats?ref=badge_large)


text:
<?php

namespace PhpSsrs\ReportingService2010;

class GetItemDataSourcesResponse
{

  /**
   *
   * @var DataSource[] $DataSources
   * @access public
   */
  public $DataSources = null;

  /**
   *
   * @param DataSource[] $DataSources
   * @access public
   */
  public function __construct($DataSources = null)
  {
    $this->DataSources = $DataSources;
  }

}


text:
testsuites.SSH.sshconnection.SSHConnection.client
=================================================

.. currentmodule:: testsuites.SSH.sshconnection

.. autoattribute:: SSHConnection.client


text:
namespace allocgc { namespace details { namespace collectors {

class pin_stack : private utils::noncopyable, private utils::nonmovable
{
public:
    pin_stack()
        : m_size(0)
    {}

    byte* top() const
    {
        assert(m_size > 0);
        return m_stack[m_size.load(std::memory_order_relaxed) - 1];
    }

    void push_pin(byte* ptr)
    {
        size_t size = m_size.load(std::memory_order_relaxed);
        m_stack[size] = ptr;
        m_size.store(size + 1, std::memory_order_relaxed);
    }

    void pop_pin()
    {
        size_t size = m_size.load(std::memory_order_relaxed);
        m_size.store(size - 1, std::memory_order_relaxed);
    }

    bool contains(byte* ptr) const
    {
        return std::find(begin(), end(), ptr) != end();
    }

    void trace(const gc_trace_pin_callback& cb) const
    {
        std::for_each(begin(), end(), cb);
    }

    size_t size() const
    {
        return m_size.load(std::memory_order_relaxed);
    }

    bool is_full() const
    {
        return size() == STACK_CAPACITY;
    }
private:
    static const size_t STACK_CAPACITY = 64;

    typedef std::array<byte*, STACK_CAPACITY> stack_t;

    stack_t::const_iterator begin() const
    {
        return m_stack.begin();
    }

    stack_t::const_iterator end() const
    {
        return std::next(m_stack.begin(), m_size.load(std::memory_order_relaxed));
    }

    stack_t m_stack;
    std::atomic<size_t> m_size;
};

}}}

#endif //ALLOCGC_PIN_STACK_HPP


text:
layout: resource
link: http://shop.oreilly.com/product/9780596805531.do
resourceid: definitiveguide
source: David Flanagan
title: "JavaScript: The Definitive Guide"
type: book
---


text:
require 'cucumber/gherkin/formatter/ansi_escapes'

module Cucumber
  module RbSupport
    # Defines the basic DSL methods availlable in all Cucumber step definitions.
    #
    # You can, and probably should, extend this DSL with your own methods that
    # make sense in your domain. For more on that, see {Cucumber::RbSupport::RbDsl#World}
    module RbWorld

      # @private
      AnsiEscapes = Cucumber::Gherkin::Formatter::AnsiEscapes

      # Call a Transform with a string from another Transform definition
      def Transform(arg)
        rb = @__cucumber_runtime.load_programming_language('rb')
        rb.execute_transforms([arg]).first
      end

      # @private
      attr_writer :__cucumber_runtime, :__natural_language

      # Run a single Gherkin step
      # @example Call another step
      #   step "I am logged in"
      # @example Call a step with quotes in the name
      #   step %{the user "Dave" is logged in}
      # @example Passing a table
      #   step "the following users exist:", table(%{
      #     | name  | email           |
      #     | Matt  | matt@matt.com   |
      #     | Aslak | aslak@aslak.com |
      #   })
      # @example Passing a multiline string
      #   step "the email should contain:", "Dear sir,\nYou've won a prize!\n"
      # @param [String] name The name of the step
      # @param [String,Cucumber::Ast::DocString,Cucumber::Ast::Table] multiline_argument
      def step(name, raw_multiline_arg=nil)
        location = Core::Ast::Location.of_caller
        @__cucumber_runtime.invoke_dynamic_step(name, MultilineArgument.from(raw_multiline_arg, location))
      end

      # Run a snippet of Gherkin
      # @example
      #   steps %{
      #     Given the user "Susan" exists
      #     And I am logged in as "Susan"
      #   }
      # @param [String] steps_text The Gherkin snippet to run
      def steps(steps_text)
        location = Core::Ast::Location.of_caller
        @__cucumber_runtime.invoke_dynamic_steps(steps_text, @__natural_language, location)
      end

      # Parse Gherkin into a {Cucumber::Ast::Table} object.
      #
      # Useful in conjunction with the #step method.
      # @example Create a table
      #   users = table(%{
      #     | name  | email           |
      #     | Matt  | matt@matt.com   |
      #     | Aslak | aslak@aslak.com |
      #   })
      # @param [String] text_or_table The Gherkin string that represents the table
      def table(text_or_table, file=nil, line_offset=0)
        @__cucumber_runtime.table(text_or_table, file, line_offset)
      end

      # Create an {Cucumber::Ast::DocString} object
      #
      # Useful in conjunction with the #step method, when
      # want to specify a content type.
      # @example Create a multiline string
      #   code = multiline_string(%{
      #     puts "this is ruby code"
      #   %}, 'ruby')
      def doc_string(string_without_triple_quotes, content_type='', line_offset=0)
        STDERR.puts AnsiEscapes.failed + "WARNING: #doc_string is deprecated. Just pass a regular String instead:" + caller[0] + AnsiEscapes.reset
        # TODO: rename this method to multiline_string
        @__cucumber_runtime.doc_string(string_without_triple_quotes, content_type, line_offset)
      end

      # @deprecated Use {#puts} instead.
      def announce(*messages)
        STDERR.puts AnsiEscapes.failed + "WARNING: #announce is deprecated. Use #puts instead:" + caller[0] + AnsiEscapes.reset
        puts(*messages)
      end

      # Print a message to the output.
      #
      # @note Cucumber might surprise you with the behaviour of this method. Instead
      #   of sending the output directly to STDOUT, Cucumber will intercept and cache
      #   the message until the current step has finished, and then display it.
      #
      #   If you'd prefer to see the message immediately, call {Kernel.puts} instead.
      def puts(*messages)
        @__cucumber_runtime.puts(*messages)
      end

      # Pause the tests and ask the operator for input
      def ask(question, timeout_seconds=60)
        @__cucumber_runtime.ask(question, timeout_seconds)
      end

      # Embed an image in the output
      def embed(file, mime_type, label='Screenshot')
        @__cucumber_runtime.embed(file, mime_type, label)
      end

      # Mark the matched step as pending.
      def pending(message = "TODO")
        if block_given?
          begin
            yield
          rescue Exception
            raise Pending, message
          end
          raise Pending, "Expected pending '#{message}' to fail. No Error was raised. No longer pending?"
        else
          raise Pending, message
        end
      end

      # Skips this step and the remaining steps in the scenario
      def skip_this_scenario(message = "Scenario skipped")
        raise Core::Test::Result::Skipped, message
      end

      # Prints the list of modules that are included in the World
      def inspect
        modules = [self.class]
        (class << self; self; end).instance_eval do
          modules += included_modules
        end
        sprintf("#<%s:0x%x>", modules.join('+'), self.object_id)
      end

      # see {#inspect}
      def to_s
        inspect
      end
    end
  end
end


text:
var _currentScale = 1;
var _scaleMin = 0.2;
var _scaleMax = 2;
var _zoom;

function zoominit()
{
	_zoom = d3.behavior.zoom()
    .scaleExtent([_scaleMin, _scaleMax])
    .on("zoom", _zoomed);

	d3.select("#fondo").call(_zoom);
}

function _zoomed()
{
	_Zoom(d3.event.scale);
}

function ZoomIn()
{
	_Zoom(Math.min(_scaleMax, _currentScale + 0.05));
	_zoom.scale(_currentScale);
}

function ZoomOut()
{
	_Zoom(Math.max(_scaleMin, _currentScale - 0.05));
	_zoom.scale(_currentScale);
}

function _Zoom(f)
{
	_currentScale = f;
	ApplyTransform();
}


text:
<?php

namespace Conekta;

use \Conekta\Conekta;
use \Conekta\Exceptions;
use \Exception;

class AuthenticationError extends Handler
{
}


text:
<?php
define('INCLUDE_CHECK',true);
include('hserun.php');
$main = new main();

if($main->init_site()){
    header('Location:https://hserun.ru/online-quest/end');
}

if(!$main->checkVk()){
    header('Location:https://hserun.ru/online-quest/');
}
?>
<!DOCTYPE html>

    <title>Карта - HSERUN</title>
    <link rel="stylesheet" type="text/css" href="//hserun.ru/online-quest/css/map.css">
    <link rel="icon" type="image/png" href="../img/compass.png" />
    <meta property="og:image" content="img/logo.png"/>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">

                    Для корректной работы сайта рекомендуется портретный режим

        Загрузка карты...

    <div class="window-block-img-profile" style="background-image: url(<?php echo $_SESSION['photo'];?>);">

            <button id="out" class="logout-button"> </button>
            <button domain="<?php echo $_SESSION['domain']; ?>" id="get_vk" class="vk-profile-button"> </button>
            <button id="closeprofile" class="close-block-logout-button"> </button>

            <?php echo strtoupper($_SESSION['firstname'].' '.$_SESSION['lastname']);?>

            БАЛЛЫ: <?php echo $_SESSION['score'];?>/100

        <div class="result-profile-img" style="background-image: url(<?php echo $_SESSION['photo'];?>);">

            <button id="out" class="logout-button"> </button>
            <button domain="<?php echo $_SESSION['domain']; ?>" id="get_vk" class="vk-profile-button"> </button>

Поздравляем, вы прошли онлайн-квест!

                        <?php echo 'Ваш счет: '.$_SESSION['score'].' баллов.'; ?>

                <button class="share-vk"> ПОДЕЛИТЬСЯ</button>

                <button class="restart-button" >Пройти заново</button>

<input type="button" class="user-id-link" value="<?php echo strtoupper($_SESSION['firstname'].' '.$_SESSION['lastname']);?>" />


text:
<?xml version="1.0" encoding="UTF-8" ?>
<updates version="1.0" xmlns="http://xmlns.oracle.com/jdeveloper/updatecenter">
  <update id="" xmlns="http://xmlns.oracle.com/jdeveloper/update">
    <name></name>
    <version></version>
    <category-id></category-id>
    <category></category>
    <author></author>
    <author-url></author-url>
    <description></description>
    <requirements>
      <requires-extension id=""/>
      <requires-agreement url=""/>
    </requirements>
    <bundle-url></bundle-url>
    <destination></destination>
    <post-startup-hook></post-startup-hook>
  </update>
</updates>


text:
namespace Nancy.JsonPatch.Core.Demo
{
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Configuration;
    using Nancy.Owin;

    public class Startup
    {
        public Startup(IHostingEnvironment env)
        {
        }

        public void Configure(IApplicationBuilder app)
        {
            app.UseOwin(x => x.UseNancy(opts => opts.Bootstrapper = new DemoBootstrapper()));
        }
    }
}


text: export * from './repo.query';


text:
require 'puppet/parameter/value'

# A collection of values and regular expressions, used for specifying allowed values
# in a given parameter.
# @note This class is considered part of the internal implementation of {Puppet::Parameter}, and
#   {Puppet::Property} and the functionality provided by this class should be used via their interfaces.
# @comment This class probably have several problems when trying to use it with a combination of
#   regular expressions and aliases as it finds an acceptable value holder vi "name" which may be
#   a regular expression...
#
# @api private
#
class Puppet::Parameter::ValueCollection

  # Aliases the given existing _other_ value with the additional given _name_.
  # @return [void]
  # @api private
  #
  def aliasvalue(name, other)
    other = other.to_sym
    unless value = match?(other)
      raise Puppet::DevError, "Cannot alias nonexistent value #{other}"
    end

    value.alias(name)
  end

  # Returns a doc string (enumerating the acceptable values) for all of the values in this parameter/property.
  # @return [String] a documentation string.
  # @api private
  #
  def doc
    unless defined?(@doc)
      @doc = ""
      unless values.empty?
        @doc << "Valid values are "
        @doc << @strings.collect do |value|
          if aliases = value.aliases and ! aliases.empty?
            "`#{value.name}` (also called `#{aliases.join(", ")}`)"
          else
            "`#{value.name}`"
          end
        end.join(", ") << ". "
      end

      unless regexes.empty?
        @doc << "Values can match `#{regexes.join("`, `")}`."
      end
    end

    @doc
  end

  # @return [Boolean] Returns whether the set of allowed values is empty or not.
  # @api private
  #
  def empty?
    @values.empty?
  end

  # @api private
  #
  def initialize
    # We often look values up by name, so a hash makes more sense.
    @values = {}

    # However, we want to retain the ability to match values in order,
    # but we always prefer directly equality (i.e., strings) over regex matches.
    @regexes = []
    @strings = []
  end

  # Checks if the given value is acceptable (matches one of the literal values or patterns) and returns
  # the "matcher" that matched.
  # Literal string matchers are tested first, if both a literal and a regexp match would match, the literal
  # match wins.
  #
  # @param test_value [Object] the value to test if it complies with the configured rules
  # @return [Puppet::Parameter::Value, nil] The instance of Puppet::Parameter::Value that matched the given value, or nil if there was no match.
  # @api private
  #
  def match?(test_value)
    # First look for normal values
    if value = @strings.find { |v| v.match?(test_value) }
      return value
    end

    # Then look for a regex match
    @regexes.find { |v| v.match?(test_value) }
  end

  # Munges the value if it is valid, else produces the same value.
  # @param value [Object] the value to munge
  # @return [Object] the munged value, or the given value
  # @todo This method does not seem to do any munging. It just returns the value if it matches the
  #   regexp, or the (most likely Symbolic) allowed value if it matches (which is more of a replacement
  #   of one instance with an equal one. Is the intent that this method should be specialized?
  # @api private
  #
  def munge(value)
    return value if empty?

    if instance = match?(value)
      if instance.regex?
        return value
      else
        return instance.name
      end
    else
      return value
    end
  end

  # Defines a new valid value for a {Puppet::Property}.
  # A valid value is specified as a literal (typically a Symbol), but can also be
  # specified with a regexp.
  #
  # @param name [Symbol, Regexp] a valid literal value, or a regexp that matches a value
  # @param options [Hash] a hash with options
  # @option options [Symbol] :event The event that should be emitted when this value is set.
  # @todo Option :event original comment says "event should be returned...", is "returned" the correct word
  #   to use?
  # @option options [Symbol] :call When to call any associated block. The default value is `:instead` which
  #   means that the block should be called instead of the provider. In earlier versions (before 20081031) it
  #   was possible to specify a value of `:before` or `:after` for the purpose of calling
  #   both the block and the provider. Use of these deprecated options will now raise an exception later
  #   in the process when the _is_ value is set (see Puppet::Property#set).
  # @option options [Symbol] :invalidate_refreshes True if a change on this property should invalidate and
  #   remove any scheduled refreshes (from notify or subscribe) targeted at the same resource. For example, if
  #   a change in this property takes into account any changes that a scheduled refresh would have performed,
  #   then the scheduled refresh would be deleted.
  # @option options [Object] _any_ Any other option is treated as a call to a setter having the given
  #   option name (e.g. `:required_features` calls `required_features=` with the option's value as an
  #   argument).
  # @api private
  #
  def newvalue(name, options = {}, &block)
    value = Puppet::Parameter::Value.new(name)
    @values[value.name] = value
    if value.regex?
      @regexes << value
    else
      @strings << value
    end

    options.each { |opt, arg| value.send(opt.to_s + "=", arg) }
    if block_given?
      value.block = block
    else
      value.call = options[:call] || :none
    end

    value.method ||= "set_#{value.name}" if block_given? and ! value.regex?

    value
  end

  # Defines one or more valid values (literal or regexp) for a parameter or property.
  # @return [void]
  # @dsl type
  # @api private
  #
  def newvalues(*names)
    names.each { |name| newvalue(name) }
  end

  # @return [Array<String>] An array of the regular expressions in string form, configured as matching valid values.
  # @api private
  #
  def regexes
    @regexes.collect { |r| r.name.inspect }
  end

  # Validates the given value against the set of valid literal values and regular expressions.
  # @raise [ArgumentError] if the value is not accepted
  # @return [void]
  # @api private
  #
  def validate(value)
    return if empty?

    unless @values.detect { |name, v| v.match?(value) }
      str = "Invalid value #{value.inspect}. "

      str += "Valid values are #{values.join(", ")}. " unless values.empty?

      str += "Valid values match #{regexes.join(", ")}." unless regexes.empty?

      raise ArgumentError, str
    end
  end

  # Returns a valid value matcher (a literal or regular expression)
  # @todo This looks odd, asking for an instance that matches a symbol, or an instance that has
  #   a regexp. What is the intention here? Marking as api private...
  #
  # @return [Puppet::Parameter::Value] a valid valud matcher
  # @api private
  #
  def value(name)
    @values[name]
  end

  # @return [Array<Symbol>] Returns a list of valid literal values.
  # @see regexes
  # @api private
  #
  def values
    @strings.collect { |s| s.name }
  end
end


text:
package edu.uw.easysrl.semantics;

import java.util.Map;

import edu.uw.easysrl.semantics.Variable.VariableNames;

/**
 * Steedman-style Generalized Skolem Term. sk(#x.p(x)) represents an entity x satisfying p. TODO proper treatment of
 * cardinality conditions
 *
 */
public class SkolemTerm extends Logic {
	private static final long serialVersionUID = 1L;

	private final String quantifier;
	private final LambdaExpression property;

	public SkolemTerm(final LambdaExpression property) {
		this(null, property);
	}

	private SkolemTerm(final String quantifier, final LambdaExpression property) {
		super();
		this.quantifier = quantifier;
		this.property = property;
	}

	@Override
	public Logic doSubstitution(final Substitution substitution) {
		return new SkolemTerm(quantifier, (LambdaExpression) property.doSubstitution(substitution));
	}

	@Override
	void toString(final StringBuilder result, final VariableNames varToName) {

		result.append("sk(");
		property.toString(result, varToName);
		if (quantifier != null) {
			result.append(";");
			result.append(quantifier);
		}
		result.append(")");
	}

	@Override
	public SemanticType getType() {
		return SemanticType.E;
	}

	@Override
	protected Logic alphaReduce(final Map<Variable, Variable> update) {
		return new SkolemTerm(quantifier, property.alphaReduce(update));
	}

	@Override
	public void accept(final LogicVisitor v) {
		v.visit(this);
	}

	public LambdaExpression getCondition() {
		return property;
	}
}


text:
/*global angular*/
(function () {
    angular
        .module('simplAdmin.localization')
        .factory('localizationService', localizationService);

    /* @ngInject */
    function localizationService($http) {
        var service = {
            getCultures: getCultures,
            getResources: getResources,
            updateResources: updateResources
        };
        return service;

        function getCultures() {
            return $http.get('api/localization/get-cultures');
        }

        function getResources(cultureId) {
            return $http.get('api/localization/get-resources?cultureId=' + cultureId);
        }

        function updateResources(cultureId, resources) {
            return $http.post('api/localization/update-resources?cultureId=' + cultureId, resources);
        }
    }
})();


text:
define(function(require) {
  /*
    DEPENDENCIES
   */

  var Locale = require('utils/locale');
  var Config = require('sunstone-config');
  var Sunstone = require('sunstone');
  var Humanize = require('utils/humanize');
  var Notifier = require('utils/notifier');
  var OpenNebulaVM = require('opennebula/vm');

  /*
    CONSTANTS
   */

  var TAB_ID = require('../tabId');
  var PANEL_ID = require('./snapshots/panelId');
  var SNAPSHOT_DIALOG_ID = require('../dialogs/snapshot/dialogId');
  var RESOURCE = "VM"
  var XML_ROOT = "VM"

  /*
    CONSTRUCTOR
   */

  function Panel(info) {
    this.panelId = PANEL_ID;
    this.title = Locale.tr("Snapshots");
    this.icon = "fa-laptop";

    this.element = info[XML_ROOT];

    return this;
  };

  Panel.PANEL_ID = PANEL_ID;
  Panel.prototype.html = _html;
  Panel.prototype.setup = _setup;

  return Panel;

  /*
    FUNCTION DEFINITIONS
   */

  function _html() {
    var that = this;
    var html = '<form id="snapshot_form" vmid="' + that.element.ID + '" >\

\

\

\

\

\
                ' + Locale.tr("ID") + '	\
                ' + Locale.tr("Name") + '	\
                ' + Locale.tr("Timestamp") + '	\
                ' + Locale.tr("Actions") + '	\
                '

    if (Config.isTabActionEnabled("vms-tab", "VM.snapshot_create")) {
      // If VM is not RUNNING, then we forget about the attach disk form.
      if (that.element.STATE == OpenNebulaVM.STATES.ACTIVE && that.element.LCM_STATE == OpenNebulaVM.LCM_STATES.RUNNING) {
        html += '\
           <button id="take_snapshot" class="button tiny success right radius" >' + Locale.tr("Take snapshot") + '</button>'
      } else {
        html += '\
           <button id="take_snapshot" class="button tiny success right radius" disabled="disabled">' + Locale.tr("Take snapshot") + '</button>'
      }
    }

    html +=  '	\

\

\

';

    var snapshots = []
    if ($.isArray(that.element.TEMPLATE.SNAPSHOT))
        snapshots = that.element.TEMPLATE.SNAPSHOT
    else if (!$.isEmptyObject(that.element.TEMPLATE.SNAPSHOT))
        snapshots = [that.element.TEMPLATE.SNAPSHOT]

    if (!snapshots.length) {
      html += '\

\
            '          + Locale.tr("No snapshots to show") + '	\

'        ;
    } else {

      for (var i = 0; i < snapshots.length; i++) {
        var snapshot = snapshots[i];

        if (
           (
            that.element.STATE == OpenNebulaVM.STATES.ACTIVE) &&
           (
            that.element.LCM_STATE == OpenNebulaVM.LCM_STATES.HOTPLUG_SNAPSHOT)) {
          actions = Locale.tr("snapshot in progress");
        } else {
          actions = '';

          if ((that.element.STATE == OpenNebulaVM.STATES.ACTIVE &&
               that.element.LCM_STATE == OpenNebulaVM.LCM_STATES.RUNNING)) {

            if (Config.isTabActionEnabled("vms-tab", "VM.snapshot_revert")) {
              actions += '' + Locale.tr("Revert") + '  '
            }

            if (Config.isTabActionEnabled("vms-tab", "VM.snapshot_delete")) {
              actions += '' + Locale.tr("Delete") + ''
            }
          }
        }

        html += '\

\
                '            + snapshot.SNAPSHOT_ID + '	\
                '            + snapshot.NAME + '	\
                '            + Humanize.prettyTime(snapshot.TIME) + '	\
                '            + actions + '	\

'        ;
      }
    }

    html += '\

\

\

\

\
      </form>';

    return html;
  }

  function _setup(context) {
    var that = this;

    if (Config.isTabActionEnabled("vms-tab", "VM.snapshot_create")) {
      context.off('click', '#take_snapshot');
      context.on('click', '#take_snapshot', function() {
        var dialog = Sunstone.getDialog(SNAPSHOT_DIALOG_ID);
        dialog.setElement(that.element);
        dialog.show();
        return false;
      });
    }

    if (Config.isTabActionEnabled("vms-tab", "VM.snapshot_revert")) {
      context.off('click', '.snapshot_revert');
      context.on('click', '.snapshot_revert', function() {
        var snapshot_id = $(this).parents('tr').attr('snapshot_id');
        Sunstone.runAction('VM.snapshot_revert', that.element.ID,  {"snapshot_id": snapshot_id});
        return false;
      });
    }

    if (Config.isTabActionEnabled("vms-tab", "VM.snapshot_delete")) {
      context.off('click', '.snapshot_delete');
      context.on('click', '.snapshot_delete', function() {
        var snapshot_id = $(this).parents('tr').attr('snapshot_id');
        Sunstone.runAction('VM.snapshot_delete', that.element.ID,  {"snapshot_id": snapshot_id});
        return false;
      });
    }
  }
});


text:
from __future__ import with_statement
import tempfile
import shutil
import os
import sys
from cStringIO import StringIO

from akara import commandline, read_config

class Config(object):
    def __init__(self, server_root):
        self.config_filename = os.path.join(server_root, "pid_test.ini")
        self.pid_filename = os.path.join(server_root, "pid.txt")
    def save_pid(self, text):
        f = open(self.pid_filename, "w")
        try:
            f.write(text)
        finally:
            f.close()

# 'akara stop' and 'akara restart' essentially just call get_pid()
# plus do one extra call. The os.kill calls are tested manually.

def tmpdir(func):
    def wrapper():
        dirname = tempfile.mkdtemp(prefix="akara_test_")
        try:
            func(dirname)
        finally:
            shutil.rmtree(dirname)
    wrapper.__name__ = func.__name__
    return wrapper

@tmpdir
def test_get_pid(server_root):
    config = Config(server_root)
    f = open(config.config_filename, "w")
    try:
        f.write("class Akara:\n  PidFile = %r\nMODULES=[]\n" % config.pid_filename)
    finally:
        f.close()
    try:
        commandline.get_pid(config)
        raise AssertionError("But the file does not exist!")
    except SystemExit, err:
        assert "Could not open Akara PID file" in str(err), err
        assert config.pid_filename in str(err), err

    config.save_pid("")
    try:
        commandline.get_pid(config)
    except SystemExit, err:
        assert "Empty Akara PID file" in str(err), err
        assert config.pid_filename in str(err), err

    config.save_pid("hello\n")
    try:
        commandline.get_pid(config)
    except SystemExit, err:
        assert "does not contain a PID" in str(err), err
        assert config.pid_filename in str(err), err

    config.save_pid("123\n")
    pid = commandline.get_pid(config)
    assert pid == 123

class CaptureStdout(object):
    def __init__(self):
        self.io = StringIO()
    def __enter__(self):
        self.io.reset()
        self.io.truncate()
        self.stdout = sys.stdout
        sys.stdout = self.io
    def __exit__(self, *args):
        sys.stdout = self.stdout
        self.content = self.io.getvalue()

@tmpdir
def test_status(server_root):
    config = Config(server_root)
    capture = CaptureStdout()
    with capture:
        try:
            commandline.status(config)
            raise AssertionError("should not get here")
        except SystemExit:
            pass
    assert "Could not open Akara configuration file" in capture.content
    assert config.config_filename in capture.content
    assert "Error log file" not in capture.content

    f = open(config.config_filename, "w")
    f.write("class Akara: PidFile = %r\n" % config.pid_filename)
    f.close()
    with capture:
        commandline.status(config)
    assert "PID file" in capture.content
    assert "PID file does not exist" in capture.content
    assert "Akara is not running" in capture.content
    assert "Cannot open PID file" not in capture.content

    config.save_pid("Scobby-doo!\n")
    with capture:
        try:
            commandline.status(config)
            raise AssertionError("where was the exit? %r" % capture.io.getvalue())
        except SystemExit:
            pass
    assert "Unable to parse the PID" in capture.content
    assert "Scobby-doo" in capture.content

    os.chmod(config.pid_filename, 0)
    with capture:
        try:
            commandline.status(config)
            raise AssertionError("where was the exit? %r" % capture.io.getvalue())
        except SystemExit:
            pass
    assert "*** Cannot open PID file" in capture.content

    os.chmod(config.pid_filename, 0644)
    my_pid = str(os.getpid())
    config.save_pid(my_pid)
    with capture:
        commandline.status(config)

    assert ("PID is %s and there is a process" % my_pid) in capture.content
    assert "Akara is running" in capture.content

    # I can't think of a good way to test for a PID which does not exist.
    # That test is done manually.

@tmpdir
def test_setup_config_file(server_root):
    config_file = os.path.join(server_root, "blah_subdir", "test_config.ini")

    assert not os.path.exists(config_file)

    capture = CaptureStdout()
    with capture:
        commandline._setup_config_file(config_file)
    assert "Copying reference configuration file" in capture.content
    assert "Creating directory" in capture.content
    assert "blah_subdir" in capture.content

    assert os.path.exists(config_file)
    s = open(config_file).read()
    assert "class Akara" in s
    assert " Listen" in s

    with capture:
        commandline._setup_config_file(config_file)
    assert "Configuration file already exists" in capture.content

@tmpdir
def test_setup(server_root):
    config = Config(server_root)
    capture = CaptureStdout()

    f = open(config.config_filename, "w")
    f.write("class Akara: ServerRoot = %r\n" % server_root)
    f.close()

    with capture:
        commandline.setup(config)

    assert "Created error log directory" in capture.content
    assert "Access log directory exists" in capture.content
    assert "PID file directory exists" in capture.content, capture.content
    assert "Created extension modules directory" in capture.content

    assert os.path.exists(os.path.join(server_root, "logs"))
    assert os.path.exists(os.path.join(server_root, "modules"))

@tmpdir
def test_log_rotate(server_root):
    config = Config(server_root)
    capture = CaptureStdout()
    error_log_filename = os.path.join(server_root, "testing.log")

    def find_backup_logs():
        return [name for name in os.listdir(server_root)
                   if name.startswith("testing.log.")]

    with open(config.config_filename, "w") as f:
        f.write("class Akara:\n  ServerRoot = %r\n  ErrorLog=%r\n" %
                (server_root, error_log_filename))

    # No log file present
    with capture:
        commandline.main(["akara", "-f", config.config_filename, "rotate"])
    assert "No log file"

    MESSAGE = "It was the best of times it was the worst of times.\n"
    with open(error_log_filename, "w") as f:
        f.write(MESSAGE)

    # Existing log file is present. Rotate
    with capture:
        commandline.main(["akara", "-f", config.config_filename, "rotate"])
    assert "testing.log.2" in capture.content, capture.content
    assert "Rotated log" in capture.content, capture.content

    filenames = find_backup_logs()
    assert len(filenames) == 1, ("should have one backup", filenames)

    # Check that the content rotated
    content = open(os.path.join(server_root, filenames[0])).read()
    assert content == MESSAGE, (content, MESSAGE)

    # The log file should not be present
    assert not os.path.exists(error_log_filename)
    MESSAGE = "When shall we three meet again?\n"
    with open(error_log_filename, "w") as f:
        f.write(MESSAGE)

    # And rotate again. Should now have two backups
    commandline.main(["akara", "-f", config.config_filename, "rotate"])
    filenames = find_backup_logs()
    assert len(filenames) == 2, ("should have two backups", filenames)

    assert not os.path.exists(error_log_filename)


text:
module RefsTypes(module RefsTypes,Pos(..),sameModuleName,noModule) where
import HsName(ModuleName,sameModuleName,noModule)
import HsLexerPos(Pos(..))
import SrcLoc1(SrcLoc)
{-+
The cross reference information was once written to files by #tstModules#
and then read by #hs2html#. That is why there were #Show# and #Read# instances,
and why the constructor names are short.
<p>
Since hs2html has been integrated into pfe now, these types are rather
obsolete...
-}

--data SP = T | V deriving (Read)
data T = V | Co Name {-Ref-} | Me Name {-Ref-} | Fi Name {-Ref-} | T | Cl deriving (Eq,Show,Read)
data R = DT | DL | DC | DI | DP | U | Ex | Im deriving ({-Show,Read,-}Eq)
type Module = ModuleName
type Name = String
--type Pos = (Int,Int) -- (line,column)
type SrcPos = (FilePath,Pos) -- better to keep SrcLoc?
type Global = (Module,Name)
type Local = SrcPos
type Ref = Either Global Local
type Orig = (Name,R,T,[(T,Ref)])
type Refs = [(Pos,Orig)]

isDef U = False
isDef DI = False
isDef Ex = False
isDef Im = False
isDef _ = True

isType Cl = True
isType T = True
isType _ = False

shPos p = show (line p)++":"++show (column p)
shPos' p = show (line p)++"."++show (column p)

-- Merge a sorted list of reference info with a list of lexical tokens
-- (Designed to be lazy in the reference list)
merge rs [] = []
merge rs tts@(t@(_,(tp,_)):ts) = (t,optref):merge rs' ts
  where
    (optref,rs') = findref rs

    findref [] = (Nothing,[])
    findref rrs@((rp,ref):rs) =
	  case compare rp tp of
	    LT -> findref rs
	    EQ -> (Just ref,rs)
	    GT -> (Nothing,rrs)

{-
-- Strict merge (only marginally faster, it seems):
merge' rs [] = []
merge' [] ts = map (flip (,) Nothing) ts
merge' rrs@(r@(rp,ref):rs) tts@(t@(_,(tp,_)):ts) =
  case compare rp tp of
    LT -> merge' rs tts
    EQ -> (t,Just ref):merge' rs ts
    GT -> (t,Nothing):merge' rrs ts
-}


text:
package org.apache.kerberos.kerb.codec.pac;

public class PacSidAttributes {

    private PacSid id;
    private int attributes;

    public PacSidAttributes(PacSid id, int attributes) {
        super();
        this.id = id;
        this.attributes = attributes;
    }

    public PacSid getId() {
        return id;
    }

    public int getAttributes() {
        return attributes;
    }

}


text:
function shortenToDate(longDate) {
  return longDate.split(',')[0];
}

console.log(shortenToDate("Friday May 2, 9am"), "Friday May 2");


text:
import logging

import dn

logger = logging.getLogger(__name__)

class Parser(object):
  def __init__(self, text):
    self._text = text

  def parse(self, output):
    with open(output, 'w') as csv:
      print >>csv, "Name, Given Name, Family Name, Name Prefix, " \
        "Phone 1 - Type, Phone 1 - Value, Phone 2 - Type, Phone 2 - Value, " \
        "Phone 3 - Type, Phone 3 - Value, Address 1 - Type, Address 1 - Formatted, " \
        "Email, Occupation"
      record = None
      for l in self._text:
        l = l.strip()
        if not l and record is not None:
          print >>csv, record.csv()
          record = None
          continue
        if l.startswith('#'): continue
        key, value = [x.strip() for x in l.split(':', 1)]
        if key == 'dn': record = dn.DN(value)
        elif key == 'cn': record.cn = value
        elif key == 'displayName': record.displayName = value
        elif key == 'givenName': record.givenName = value
        elif key == 'homePhone': record.homePhone = value
        elif key == 'homePostalAddress': record.homePostalAddress = value
        elif key == 'mail': record.mail = value
        elif key == 'mobile': record.mobile = value
        elif key == 'o': record.o = value
        elif key == 'objectClass': record.objectClass = value
        elif key == 'sn': record.sn = value
        elif key == 'telephoneNumber': record.telephoneNumber = value
        elif key == 'title': record.title = value
        else: logger.error('Key: %s value: %s not supported, ignoring', key, value)


text:
class Thing < ActiveRecord::Base; end unless SKIP_ACTIVE_RECORD

class Job < ActiveJob::Base
  def perform
    # Doing something here
  end
end

class BreadcrumbController < ApplicationController
  def active_record_event
    ActiveRecord::Base.connection.execute("SELECT '\x83ݔj'")
    Thing.create(name: "a thing")
    notice
  end

  def log_breadcrumb_event
    Rails.logger.info("test log event")
    notice
  end

  def active_job_event
    Job.perform_later
    notice
  end

  def cache_event
    Rails.cache.read("test read")
    notice
  end

  private

  def notice
    Honeybadger.notify(StandardError.new('test backend'))
    head 200
  end
end

Rails.application.routes.append do
  BreadcrumbController.action_methods.each do |action|
    get "/breadcrumbs/#{action}", to: "breadcrumb##{action}"
  end
end


text:
import os
import sys
import json
import traceback
import random
import math

import matplotlib
import matplotlib.pyplot as plt
import pprint

colors = {'red': '#cd7058', 'blue': '#599ad3', 'orange': '#f9a65a', 'green': '#66cc66', 'black': '#000000', 'purple': '#990066'}
numbering_subplots = ['a', 'b', 'c', 'd', 'e', 'f']

def compute_average(datapoints, has_shift):
    if len(datapoints) == 0:
        return 0, 0, 0
    num_freq = 0
    sum_metric = 0
    if not has_shift:
        minimum = 0
    else:
        minimum = None

    for key, value in datapoints.iteritems():
        occurrence = float(key)
        frequency = float(value)
        num_freq += frequency
        sum_metric += frequency * occurrence
        if has_shift:
            if minimum is None or occurrence < minimum:
                minimum = occurrence

    if num_freq <= 1:
        return 0, 0, 0

    mean = float(sum_metric) / float(num_freq)

    sum_metric_squared = 0
    for key, value in datapoints.iteritems():
        occurrence = float(key)
        frequency = float(value)
        sum_metric_squared += frequency * (occurrence - mean) * (occurrence - mean)

    variance = float(sum_metric_squared) / float(num_freq - 1)
    standard_deviation = math.sqrt(variance)
    return mean - minimum, variance, standard_deviation

def compute_median(datapoints, has_shift):
    # TODO: very inefficient, could optimize this method
    if len(datapoints) == 0:
        return 0, 0, 0
    values = []
    minimum = None
    for key, value in datapoints.iteritems():
        occurrence = float(key)
        frequency = float(value)
        for i in range(int(frequency)):
            values.append(occurrence)
        if has_shift:
            if minimum is None or occurrence < minimum:
                minimum = occurrence

    if not has_shift: minimum = 0
    values = sorted(values)
    median = values[len(values) / 2] - minimum
    perc95 = values[int(float(len(values)) * .95)] - minimum
    maximum = values[-1] - minimum
    return median, perc95, maximum

def aggregate_datapoints(dirpath_data, testcases, algorithms, shifts):
    print testcases, algorithms, shifts
    aggregate = {}
    for dirname, dirnames, filenames in os.walk(dirpath_data):
        for filename in filenames:
            basename, ext = os.path.splitext(filename)
            if ext.lower() != '.json': continue
            if '50000000' in filename: continue

            if testcases != 'all' and not any(filename.startswith(testcase) for testcase in testcases.split(',')):
                print 'skipping ' + filename
                continue

            if algorithms != 'all' and not any(algorithm in filename for algorithm in algorithms.split(',')):
                print 'skipping ' + filename
                continue

            try:
                filepath = os.path.join(dirname, filename)
                print "Reading file [%s]" % (filepath,)
                f = open(filepath, 'r')
                text = f.read()
                data_items = json.loads(text)
                f.close()
                has_shift = shifts and any(shift in filename for shift in shifts.split(','))
                if not isinstance(data_items, list):
                    data_items = [data_items]

                for data in data_items:
                    average, variance, stddev = compute_average(data['datapoints'], has_shift)
                    median, perc95, maximum = compute_median(data['datapoints'], has_shift)

                    ia = data['algorithm']
                    im = data['metric']
                    ib = data['parameters_hashmap_string']
                    ia = '%s-%s' % (ia, ib)

                    ii = data['instance']
                    ic = data['cycle']

                    it = data['testcase']
                    ip = data['parameters_testcase_string']
                    if '75' in ip:
                        print "before", ip
                        ip = ip.replace('lfm0.75', 'lfm0.80')
                        print "after", ip
                    it = '%s-%s' % (it, ip)
                    if im not in aggregate:
                        aggregate[im] = {}
                    if it not in aggregate[im]:
                        aggregate[im][it] = {}
                    if ia not in aggregate[im][it]:
                        aggregate[im][it][ia] = {}
                    if ic not in aggregate[im][it][ia]:
                        aggregate[im][it][ia][ic] = {}

                    for m in ['mean', 'median', 'perc95', 'standard_deviation', 'variance', 'maximum']:
                        if m not in aggregate[im][it][ia][ic]:
                            aggregate[im][it][ia][ic][m] = []

                    aggregate[im][it][ia][ic]['mean'].append(average)
                    aggregate[im][it][ia][ic]['standard_deviation'].append(stddev)
                    aggregate[im][it][ia][ic]['variance'].append(variance)
                    aggregate[im][it][ia][ic]['median'].append(median)
                    aggregate[im][it][ia][ic]['perc95'].append(perc95)
                    aggregate[im][it][ia][ic]['maximum'].append(maximum)
            except:
                print 'Crashed at file: [%s/%s]' % (dirname, filename)
                print traceback.print_exc()
                sys.exit(1)

    return aggregate

def randomized_paired_sample_t_test(reference, candidate, details):
    num_items = len(reference)
    random.seed(None)
    population = []
    print 'ref cand', reference, candidate

    diff = []
    for i in range(num_items):
        diff.append(reference[i] - candidate[i])

    num_population = 10240
    for k in range(num_population):
        diff_new = []
        for i in range(num_items):
            sign = -1 if random.random() < 0.5 else 1
            diff_new.append(diff[i] * sign)

        mean_new = float(sum(diff_new)) / float(num_items)
        population.append(mean_new)

    count_passed = 0
    mean = sum(diff) / num_items
    population = sorted(population)

    for mean_current in population:
        if (mean > 0 and mean <= mean_current) or (mean < 0 and mean < mean_currrent):
            break
        count_passed += 1

    if mean > 0:
        count_passed = num_population - count_passed

    if False and details:
        print "*" * 64
        print "*" * 64
        print "details"
        print "population", population[0], population[1], population[-2], population[-1]
        print "mean", mean
        print "count_passed: %f" % (float(count_passed),)
        print "num_pop %f" % (float(num_population), )

    p_value = float(count_passed) / float(num_population)
    print "passed: %f" % (p_value,)
    return p_value

def add_curve_to_plot(ax, aggregates, im, it, index_testcase, statistic, algorithms_ordering, filters, numbering_subplot, includes):
    names = []
    lines = []
    font = {'family' : 'normal',
            'weight' : 'normal',
            'size'   : 14}
    matplotlib.rc('font', **font)

    algorithms = [None] * 5
    for ia in aggregates[im][it].keys():
        for pattern in algorithms_ordering.keys():
            if pattern in ia:
                order = algorithms_ordering[pattern]['order']
                algorithms[order] = ia

    for ia in algorithms:
        if ia is None: continue
        print "Generating curve for: stats:%s | metric:%s | testcase:%s | algorithm:%s" % (statistic, im, it, ia)

        xs = []
        ys = []

        for cycle, stats in sorted(aggregates[im][it][ia].items()):
            if 'loading' in it:
                xs.append((cycle * 2.0) / 100.0)
            else:
                xs.append(cycle)
            ys.append(sum(stats[statistic]) / len(stats[statistic]))

        name = '[ERROR: unknown algorithm]'
        color = '#000000'
        linewidth = 3
        zorder = 1
        for k, v in filters.iteritems():
            if k in ia:
                name = filters[k]['name']
                color = filters[k]['color']
                linewidth = filters[k]['linewidth']
                style = '-'
                zorder = filters[k]['zorder']
                break

        if not any(pattern in ia for pattern in includes):
            continue

        line_current, = ax.plot(xs, ys, style, color=color, linewidth=linewidth, zorder=zorder)
        names.append(name)
        lines.append(line_current)

    if 'loading' in it:
        ax.set_xlabel('(%s) Load factor' % numbering_subplot)
    else:
        ax.set_xlabel('(%s) Iterations' % numbering_subplot)

    if statistic == 'mean':
        ax.set_ylabel('Mean %s' % im)
        if True or 'loading' not in it:
            x1,x2,y1,y2 = plt.axis()
            plt.axis((x1,x2,0,100))
    elif statistic == 'variance':
        ax.set_ylabel('Variance of %s' % im)
        if True or 'loading' not in it:
            x1,x2,y1,y2 = plt.axis()
            plt.axis((x1,x2,0,600))
    elif statistic == 'standard_deviation':
        ax.set_ylabel('Standard deviation of %s' % im)
    elif statistic == 'median':
        ax.set_ylabel('Median of %s' % im)
        if True or 'loading' not in it:
            x1,x2,y1,y2 = plt.axis()
            plt.axis((x1,x2,0,100))
    elif statistic == 'perc95':
        ax.set_ylabel('95th percentile of %s' % im)
        if True or 'loading' not in it:
            x1,x2,y1,y2 = plt.axis()
            plt.axis((x1,x2,0,100))
    elif statistic == 'maximum':
        ax.set_ylabel('Maximum %s' % im)
        if True or 'loading' not in it:
            x1,x2,y1,y2 = plt.axis()
            plt.axis((x1,x2,0,180))
    plt.title('Test case: %s' % (it.strip('-')))
    ax.grid(True)

    if any(metric in im for metric in ['blocks', 'aligned']) and statistic != 'variance':
        labels=['16 B', '32 B', '64 B', '128 B', '256 B', '512 B', '1 KB', '2 KB', '4 KB', '8 KB', '16 KB', '32 KB', '64 KB', '128 KB']
        plt.axis((x1,x2,4,4+len(labels)))
        ax.set_yticks(range(4,4+len(labels)))
        ax.set_yticklabels(labels)

    plt.legend(lines, names).set_visible(False)
    return names, lines

def plot_algorithms(aggregates):

    for index_stat, statistic in enumerate(['mean', 'median', 'perc95', 'maximum', 'variance']):
        for index_metric, im in enumerate(aggregates.keys()):
            fig = plt.figure((index_stat+1) * 10000 + (index_metric+1) * 100 + 1)
            legend = None
            for index_testcase, it in enumerate(sorted(aggregates[im].keys())):
                ax = fig.add_subplot(2, 2, index_testcase+1)
                lines = []
                names = []

                names_temp, lines_temp = add_curve_to_plot(
                                    ax=ax,
                                    aggregates=aggregates,
                                    im=im,
                                    it=it,
                                    index_testcase=index_testcase,
                                    statistic=statistic,
                                    algorithms_ordering = {
                                                            'linear': {'order': 0},
                                                            'backshift': {'order': 1},
                                                            'tombstone': {'order': 2},
                                                            'shadow': {'order': 3},
                                                            'bitmap': {'order': 4},
                                                          },
                                    filters = {
                                                'linear':    { 'color': colors['blue'],   'name': 'Linear probing',              'linewidth': 8,    'zorder': 1 },
                                                'backshift': { 'color': colors['orange'], 'name': 'Robin Hood (backward shift)', 'linewidth': 6,    'zorder': 2 },
                                                'tombstone': { 'color': colors['red'],    'name': 'Robin Hood (tombstone)',      'linewidth': 4.5,  'zorder': 3 },
                                                'shadow':    { 'color': colors['green'],  'name': 'Hopscotch (shadow)',          'linewidth': 3,    'zorder': 4 },
                                                'bitmap':    { 'color': colors['black'],  'name': 'Hopscotch (bitmap)',          'linewidth': 1.75, 'zorder': 5 },
                                              },
                                    numbering_subplot=numbering_subplots[index_testcase],
                                    includes=['10000-'],
                                 )

                names.extend(names_temp)
                lines.extend(lines_temp)

            legend = plt.legend(lines, names, prop={'size':12}, bbox_to_anchor=(0.2, -0.3))
            if not os.path.isdir('plots/algorithms'):
                os.mkdir('plots/algorithms')
            fig.set_size_inches(10, 7.5)
            plt.tight_layout()
            plt.savefig('plots/algorithms/%s_%s.png' % (im.lower(), statistic), dpi=72, bbox_extra_artists=(legend,), bbox_inches='tight')

def plot_robinhood(aggregates):
    for index_metric, im in enumerate(aggregates.keys()):
        fig = plt.figure((index_metric+1) * 100 + 1)
        for index_stat, statistic in enumerate(['mean', 'median', 'perc95', 'maximum', 'variance']):
            ax = fig.add_subplot(3, 2, index_stat+1)
            lines = []
            names = []
            for index_testcase, it in enumerate(sorted(aggregates[im].keys())):
                names_temp, lines_temp = add_curve_to_plot(
                                    ax=ax,
                                    aggregates=aggregates,
                                    im=im,
                                    it=it,
                                    index_testcase=index_testcase,
                                    statistic=statistic,
                                    algorithms_ordering = {
                                                            '10000-': {'order': 0},
                                                            '100000-': {'order': 1},
                                                            '1000000-': {'order': 2},
                                                            '10000000-': {'order': 3},
                                                            '50000000-': {'order': 4},
                                                          },
                                    filters = {
                                                '10000-':     { 'color': colors['blue'],   'name': 'Robin Hood (backward shift, 10k)',  'linewidth': 8, 'zorder': 1 },
                                                '100000-':    { 'color': colors['orange'], 'name': 'Robin Hood (backward shift, 100k)', 'linewidth': 6, 'zorder': 2 },
                                                '1000000-':   { 'color': colors['red'],    'name': 'Robin Hood (backward shift, 1M)',   'linewidth': 4.5, 'zorder': 3 },
                                                '10000000-':  { 'color': colors['green'],  'name': 'Robin Hood (backward shift, 10M)',  'linewidth': 3, 'zorder': 4 },
                                                '50000000-':  { 'color': colors['black'],   'name': 'Robin Hood (backward shift, 50M)', 'linewidth': 1.75, 'zorder': 5 },
                                                '100000000-': { 'color': colors['black'],  'name': 'Robin Hood (backward shift, 100M)', 'linewidth': 1.75, 'zorder': 5 },
                                              },
                                    numbering_subplot=numbering_subplots[index_stat],
                                    includes=['backshift'],
                                 )
                names.extend(names_temp)
                lines.extend(lines_temp)

        legend = plt.legend(lines, names, prop={'size':12}, bbox_to_anchor=(2.10, 0.75))
        fig.set_size_inches(10, 11.25)
        plt.tight_layout()
        if not os.path.isdir('plots/robinhood-backshift'):
            os.mkdir('plots/robinhood-backshift')
        plt.savefig('plots/robinhood-backshift/%s.png' % (im.lower()), dpi=72, bbox_extra_artists=(legend,), bbox_inches='tight')

if __name__=="__main__":
    shifts = ""
    if len(sys.argv) == 5:
        shifts = sys.argv[4]

    agg = aggregate_datapoints(dirpath_data=sys.argv[1],
                               testcases=sys.argv[2],
                               algorithms=sys.argv[3],
                               shifts=shifts)
    plot_algorithms(agg)
    plot_robinhood(agg)


text:
class System
  include Mongoid::Document
  include MultiLanguageText

  field :version, :type => String
  field :year, :type => String
  field :chop, :type => String
  field :icd, :type => String

  field :swissdrg_webgrouper_system_id, :type => String
  field :swissdrg_manual_link, :type => String
end