text:
from django.db import connection, connections
from django.db.migrations.exceptions import (
    AmbiguityError, InconsistentMigrationHistory, NodeNotFoundError,
)
from django.db.migrations.loader import MigrationLoader
from django.db.migrations.recorder import MigrationRecorder
from django.test import TestCase, modify_settings, override_settings

class RecorderTests(TestCase):
    """
    Tests recording migrations as applied or not.
    """
    multi_db = True

    def test_apply(self):
        """
        Tests marking migrations as applied/unapplied.
        """
        recorder = MigrationRecorder(connection)
        self.assertEqual(
            {(x, y) for (x, y) in recorder.applied_migrations() if x == "myapp"},
            set(),
        )
        recorder.record_applied("myapp", "0432_ponies")
        self.assertEqual(
            {(x, y) for (x, y) in recorder.applied_migrations() if x == "myapp"},
            {("myapp", "0432_ponies")},
        )
        # That should not affect records of another database
        recorder_other = MigrationRecorder(connections['other'])
        self.assertEqual(
            {(x, y) for (x, y) in recorder_other.applied_migrations() if x == "myapp"},
            set(),
        )
        recorder.record_unapplied("myapp", "0432_ponies")
        self.assertEqual(
            {(x, y) for (x, y) in recorder.applied_migrations() if x == "myapp"},
            set(),
        )

class LoaderTests(TestCase):
    """
    Tests the disk and database loader, and running through migrations
    in memory.
    """

    @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
    @modify_settings(INSTALLED_APPS={'append': 'basic'})
    def test_load(self):
        """
        Makes sure the loader can load the migrations for the test apps,
        and then render them out to a new Apps.
        """
        # Load and test the plan
        migration_loader = MigrationLoader(connection)
        self.assertEqual(
            migration_loader.graph.forwards_plan(("migrations", "0002_second")),
            [
                ("migrations", "0001_initial"),
                ("migrations", "0002_second"),
            ],
        )
        # Now render it out!
        project_state = migration_loader.project_state(("migrations", "0002_second"))
        self.assertEqual(len(project_state.models), 2)

        author_state = project_state.models["migrations", "author"]
        self.assertEqual(
            [x for x, y in author_state.fields],
            ["id", "name", "slug", "age", "rating"]
        )

        book_state = project_state.models["migrations", "book"]
        self.assertEqual(
            [x for x, y in book_state.fields],
            ["id", "author"]
        )

        # Ensure we've included unmigrated apps in there too
        self.assertIn("basic", project_state.real_apps)

    @override_settings(MIGRATION_MODULES={
        'migrations': 'migrations.test_migrations',
        'migrations2': 'migrations2.test_migrations_2',
    })
    @modify_settings(INSTALLED_APPS={'append': 'migrations2'})
    def test_plan_handles_repeated_migrations(self):
        """
        _generate_plan() doesn't readd migrations already in the plan (#29180).
        """
        migration_loader = MigrationLoader(connection)
        nodes = [('migrations', '0002_second'), ('migrations2', '0001_initial')]
        self.assertEqual(
            migration_loader.graph._generate_plan(nodes, at_end=True),
            [('migrations', '0001_initial'), ('migrations', '0002_second'), ('migrations2', '0001_initial')]
        )

    @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_unmigdep"})
    def test_load_unmigrated_dependency(self):
        """
        Makes sure the loader can load migrations with a dependency on an unmigrated app.
        """
        # Load and test the plan
        migration_loader = MigrationLoader(connection)
        self.assertEqual(
            migration_loader.graph.forwards_plan(("migrations", "0001_initial")),
            [
                ('contenttypes', '0001_initial'),
                ('auth', '0001_initial'),
                ("migrations", "0001_initial"),
            ],
        )
        # Now render it out!
        project_state = migration_loader.project_state(("migrations", "0001_initial"))
        self.assertEqual(len([m for a, m in project_state.models if a == "migrations"]), 1)

        book_state = project_state.models["migrations", "book"]
        self.assertEqual(
            [x for x, y in book_state.fields],
            ["id", "user"]
        )

    @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_run_before"})
    def test_run_before(self):
        """
        Makes sure the loader uses Migration.run_before.
        """
        # Load and test the plan
        migration_loader = MigrationLoader(connection)
        self.assertEqual(
            migration_loader.graph.forwards_plan(("migrations", "0002_second")),
            [
                ("migrations", "0001_initial"),
                ("migrations", "0003_third"),
                ("migrations", "0002_second"),
            ],
        )

    @override_settings(MIGRATION_MODULES={
        "migrations": "migrations.test_migrations_first",
        "migrations2": "migrations2.test_migrations_2_first",
    })
    @modify_settings(INSTALLED_APPS={'append': 'migrations2'})
    def test_first(self):
        """
        Makes sure the '__first__' migrations build correctly.
        """
        migration_loader = MigrationLoader(connection)
        self.assertEqual(
            migration_loader.graph.forwards_plan(("migrations", "second")),
            [
                ("migrations", "thefirst"),
                ("migrations2", "0001_initial"),
                ("migrations2", "0002_second"),
                ("migrations", "second"),
            ],
        )

    @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"})
    def test_name_match(self):
        "Tests prefix name matching"
        migration_loader = MigrationLoader(connection)
        self.assertEqual(
            migration_loader.get_migration_by_prefix("migrations", "0001").name,
            "0001_initial",
        )
        with self.assertRaises(AmbiguityError):
            migration_loader.get_migration_by_prefix("migrations", "0")
        with self.assertRaises(KeyError):
            migration_loader.get_migration_by_prefix("migrations", "blarg")

    def test_load_import_error(self):
        with override_settings(MIGRATION_MODULES={"migrations": "import_error_package"}):
            with self.assertRaises(ImportError):
                MigrationLoader(connection)

    def test_load_module_file(self):
        with override_settings(MIGRATION_MODULES={"migrations": "migrations.faulty_migrations.file"}):
            loader = MigrationLoader(connection)
            self.assertIn(
                "migrations", loader.unmigrated_apps,
                "App with migrations module file not in unmigrated apps."
            )

    def test_load_empty_dir(self):
        with override_settings(MIGRATION_MODULES={"migrations": "migrations.faulty_migrations.namespace"}):
            loader = MigrationLoader(connection)
            self.assertIn(
                "migrations", loader.unmigrated_apps,
                "App missing __init__.py in migrations module not in unmigrated apps."
            )

    @override_settings(
        INSTALLED_APPS=['migrations.migrations_test_apps.migrated_app'],
    )
    def test_marked_as_migrated(self):
        """
        Undefined MIGRATION_MODULES implies default migration module.
        """
        migration_loader = MigrationLoader(connection)
        self.assertEqual(migration_loader.migrated_apps, {'migrated_app'})
        self.assertEqual(migration_loader.unmigrated_apps, set())

    @override_settings(
        INSTALLED_APPS=['migrations.migrations_test_apps.migrated_app'],
        MIGRATION_MODULES={"migrated_app": None},
    )
    def test_marked_as_unmigrated(self):
        """
        MIGRATION_MODULES allows disabling of migrations for a particular app.
        """
        migration_loader = MigrationLoader(connection)
        self.assertEqual(migration_loader.migrated_apps, set())
        self.assertEqual(migration_loader.unmigrated_apps, {'migrated_app'})

    @override_settings(
        INSTALLED_APPS=['migrations.migrations_test_apps.migrated_app'],
        MIGRATION_MODULES={'migrated_app': 'missing-module'},
    )
    def test_explicit_missing_module(self):
        """
        If a MIGRATION_MODULES override points to a missing module, the error
        raised during the importation attempt should be propagated unless
        `ignore_no_migrations=True`.
        """
        with self.assertRaisesMessage(ImportError, 'missing-module'):
            migration_loader = MigrationLoader(connection)
        migration_loader = MigrationLoader(connection, ignore_no_migrations=True)
        self.assertEqual(migration_loader.migrated_apps, set())
        self.assertEqual(migration_loader.unmigrated_apps, {'migrated_app'})

    @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"})
    def test_loading_squashed(self):
        "Tests loading a squashed migration"
        migration_loader = MigrationLoader(connection)
        recorder = MigrationRecorder(connection)
        self.addCleanup(recorder.flush)
        # Loading with nothing applied should just give us the one node
        self.assertEqual(
            len([x for x in migration_loader.graph.nodes if x[0] == "migrations"]),
            1,
        )
        # However, fake-apply one migration and it should now use the old two
        recorder.record_applied("migrations", "0001_initial")
        migration_loader.build_graph()
        self.assertEqual(
            len([x for x in migration_loader.graph.nodes if x[0] == "migrations"]),
            2,
        )

    @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed_complex"})
    def test_loading_squashed_complex(self):
        "Tests loading a complex set of squashed migrations"

        loader = MigrationLoader(connection)
        recorder = MigrationRecorder(connection)
        self.addCleanup(recorder.flush)

        def num_nodes():
            plan = set(loader.graph.forwards_plan(('migrations', '7_auto')))
            return len(plan - loader.applied_migrations)

        # Empty database: use squashed migration
        loader.build_graph()
        self.assertEqual(num_nodes(), 5)

        # Starting at 1 or 2 should use the squashed migration too
        recorder.record_applied("migrations", "1_auto")
        loader.build_graph()
        self.assertEqual(num_nodes(), 4)

        recorder.record_applied("migrations", "2_auto")
        loader.build_graph()
        self.assertEqual(num_nodes(), 3)

        # However, starting at 3 to 5 cannot use the squashed migration
        recorder.record_applied("migrations", "3_auto")
        loader.build_graph()
        self.assertEqual(num_nodes(), 4)

        recorder.record_applied("migrations", "4_auto")
        loader.build_graph()
        self.assertEqual(num_nodes(), 3)

        # Starting at 5 to 7 we are passed the squashed migrations
        recorder.record_applied("migrations", "5_auto")
        loader.build_graph()
        self.assertEqual(num_nodes(), 2)

        recorder.record_applied("migrations", "6_auto")
        loader.build_graph()
        self.assertEqual(num_nodes(), 1)

        recorder.record_applied("migrations", "7_auto")
        loader.build_graph()
        self.assertEqual(num_nodes(), 0)

    @override_settings(MIGRATION_MODULES={
        "app1": "migrations.test_migrations_squashed_complex_multi_apps.app1",
        "app2": "migrations.test_migrations_squashed_complex_multi_apps.app2",
    })
    @modify_settings(INSTALLED_APPS={'append': [
        "migrations.test_migrations_squashed_complex_multi_apps.app1",
        "migrations.test_migrations_squashed_complex_multi_apps.app2",
    ]})
    def test_loading_squashed_complex_multi_apps(self):
        loader = MigrationLoader(connection)
        loader.build_graph()

        plan = set(loader.graph.forwards_plan(('app1', '4_auto')))
        expected_plan = {
            ('app1', '1_auto'),
            ('app2', '1_squashed_2'),
            ('app1', '2_squashed_3'),
            ('app1', '4_auto'),
        }
        self.assertEqual(plan, expected_plan)

    @override_settings(MIGRATION_MODULES={
        "app1": "migrations.test_migrations_squashed_complex_multi_apps.app1",
        "app2": "migrations.test_migrations_squashed_complex_multi_apps.app2",
    })
    @modify_settings(INSTALLED_APPS={'append': [
        "migrations.test_migrations_squashed_complex_multi_apps.app1",
        "migrations.test_migrations_squashed_complex_multi_apps.app2",
    ]})
    def test_loading_squashed_complex_multi_apps_partially_applied(self):
        loader = MigrationLoader(connection)
        recorder = MigrationRecorder(connection)
        recorder.record_applied('app1', '1_auto')
        recorder.record_applied('app1', '2_auto')
        loader.build_graph()

        plan = set(loader.graph.forwards_plan(('app1', '4_auto')))
        plan = plan - loader.applied_migrations
        expected_plan = {
            ('app2', '1_squashed_2'),
            ('app1', '3_auto'),
            ('app1', '4_auto'),
        }

        self.assertEqual(plan, expected_plan)

    @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed_erroneous"})
    def test_loading_squashed_erroneous(self):
        "Tests loading a complex but erroneous set of squashed migrations"

        loader = MigrationLoader(connection)
        recorder = MigrationRecorder(connection)
        self.addCleanup(recorder.flush)

        def num_nodes():
            plan = set(loader.graph.forwards_plan(('migrations', '7_auto')))
            return len(plan - loader.applied_migrations)

        # Empty database: use squashed migration
        loader.build_graph()
        self.assertEqual(num_nodes(), 5)

        # Starting at 1 or 2 should use the squashed migration too
        recorder.record_applied("migrations", "1_auto")
        loader.build_graph()
        self.assertEqual(num_nodes(), 4)

        recorder.record_applied("migrations", "2_auto")
        loader.build_graph()
        self.assertEqual(num_nodes(), 3)

        # However, starting at 3 or 4, nonexistent migrations would be needed.
        msg = ("Migration migrations.6_auto depends on nonexistent node ('migrations', '5_auto'). "
               "Django tried to replace migration migrations.5_auto with any of "
               "[migrations.3_squashed_5] but wasn't able to because some of the replaced "
               "migrations are already applied.")

        recorder.record_applied("migrations", "3_auto")
        with self.assertRaisesMessage(NodeNotFoundError, msg):
            loader.build_graph()

        recorder.record_applied("migrations", "4_auto")
        with self.assertRaisesMessage(NodeNotFoundError, msg):
            loader.build_graph()

        # Starting at 5 to 7 we are passed the squashed migrations
        recorder.record_applied("migrations", "5_auto")
        loader.build_graph()
        self.assertEqual(num_nodes(), 2)

        recorder.record_applied("migrations", "6_auto")
        loader.build_graph()
        self.assertEqual(num_nodes(), 1)

        recorder.record_applied("migrations", "7_auto")
        loader.build_graph()
        self.assertEqual(num_nodes(), 0)

    @override_settings(
        MIGRATION_MODULES={'migrations': 'migrations.test_migrations'},
        INSTALLED_APPS=['migrations'],
    )
    def test_check_consistent_history(self):
        loader = MigrationLoader(connection=None)
        loader.check_consistent_history(connection)
        recorder = MigrationRecorder(connection)
        recorder.record_applied('migrations', '0002_second')
        msg = (
            "Migration migrations.0002_second is applied before its dependency "
            "migrations.0001_initial on database 'default'."
        )
        with self.assertRaisesMessage(InconsistentMigrationHistory, msg):
            loader.check_consistent_history(connection)

    @override_settings(
        MIGRATION_MODULES={'migrations': 'migrations.test_migrations_squashed_extra'},
        INSTALLED_APPS=['migrations'],
    )
    def test_check_consistent_history_squashed(self):
        """
        MigrationLoader.check_consistent_history() should ignore unapplied
        squashed migrations that have all of their `replaces` applied.
        """
        loader = MigrationLoader(connection=None)
        recorder = MigrationRecorder(connection)
        recorder.record_applied('migrations', '0001_initial')
        recorder.record_applied('migrations', '0002_second')
        loader.check_consistent_history(connection)
        recorder.record_applied('migrations', '0003_third')
        loader.check_consistent_history(connection)

    @override_settings(MIGRATION_MODULES={
        "app1": "migrations.test_migrations_squashed_ref_squashed.app1",
        "app2": "migrations.test_migrations_squashed_ref_squashed.app2",
    })
    @modify_settings(INSTALLED_APPS={'append': [
        "migrations.test_migrations_squashed_ref_squashed.app1",
        "migrations.test_migrations_squashed_ref_squashed.app2",
    ]})
    def test_loading_squashed_ref_squashed(self):
        "Tests loading a squashed migration with a new migration referencing it"
        r"""
        The sample migrations are structured like this:

        app_1       1 --> 2 ---------------------*--> 3        *--> 4
                     \                          /             /
                      *-------------------*----/--> 2_sq_3 --*
                       \                 /    /
        =============== \ ============= / == / ======================
        app_2            *--> 1_sq_2 --*    /
                          \                /
                           *--> 1 --> 2 --*

        Where 2_sq_3 is a replacing migration for 2 and 3 in app_1,
        as 1_sq_2 is a replacing migration for 1 and 2 in app_2.
        """

        loader = MigrationLoader(connection)
        recorder = MigrationRecorder(connection)
        self.addCleanup(recorder.flush)

        # Load with nothing applied: both migrations squashed.
        loader.build_graph()
        plan = set(loader.graph.forwards_plan(('app1', '4_auto')))
        plan = plan - loader.applied_migrations
        expected_plan = {
            ('app1', '1_auto'),
            ('app2', '1_squashed_2'),
            ('app1', '2_squashed_3'),
            ('app1', '4_auto'),
        }
        self.assertEqual(plan, expected_plan)

        # Fake-apply a few from app1: unsquashes migration in app1.
        recorder.record_applied('app1', '1_auto')
        recorder.record_applied('app1', '2_auto')
        loader.build_graph()
        plan = set(loader.graph.forwards_plan(('app1', '4_auto')))
        plan = plan - loader.applied_migrations
        expected_plan = {
            ('app2', '1_squashed_2'),
            ('app1', '3_auto'),
            ('app1', '4_auto'),
        }
        self.assertEqual(plan, expected_plan)

        # Fake-apply one from app2: unsquashes migration in app2 too.
        recorder.record_applied('app2', '1_auto')
        loader.build_graph()
        plan = set(loader.graph.forwards_plan(('app1', '4_auto')))
        plan = plan - loader.applied_migrations
        expected_plan = {
            ('app2', '2_auto'),
            ('app1', '3_auto'),
            ('app1', '4_auto'),
        }
        self.assertEqual(plan, expected_plan)


text:
package org.apache.giraph.block_app.library.algo;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Writable;

/**
 * Vertex-value class for DistributedIndependentSetBlockFactory
 */
public class DistributedIndependentSetVertexValue implements Writable {
  private IntWritable independentSetID;

  public IntWritable getIndependentSetID() {
    return independentSetID;
  }

  public void setIndependentSetID(IntWritable independentSetID) {
    this.independentSetID = independentSetID;
  }

  @Override
  public void write(DataOutput out) throws IOException {
    if (independentSetID == null) {
      independentSetID = new IntWritable();
    }
    out.writeInt(independentSetID.get());
  }

  @Override
  public void readFields(DataInput in) throws IOException {
    if (independentSetID == null) {
      independentSetID = new IntWritable();
    }
    independentSetID.set(in.readInt());
  }
}

redpajama_set_name: RedPajamaGithub


text:
package qiita

import (
	"context"
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestAddItemTagging(t *testing.T) {
	// 201
	func() {
		server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			w.WriteHeader(http.StatusCreated)
			http.ServeFile(w, r, "")
		}))
		c, _ := mockClient(server)
		ctx := context.TODO()
		err := c.AddItemTagging(ctx, "", Tagging{})
		if err != nil {
			t.Fatal(err)
		}
	}()

	// 400
	func() {
		server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			w.WriteHeader(http.StatusBadRequest)
			http.ServeFile(w, r, "")
		}))
		c, _ := mockClient(server)
		ctx := context.TODO()
		err := c.AddItemTagging(ctx, "", Tagging{})
		if err == nil {
			t.Fail()
		}
	}()
}

func TestDeleteItemTagging(t *testing.T) {
	// 204
	func() {
		server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			w.WriteHeader(http.StatusNoContent)
			http.ServeFile(w, r, "")
		}))
		c, _ := mockClient(server)
		ctx := context.TODO()
		err := c.DeleteItemTagging(ctx, "", "")
		if err != nil {
			t.Fatal(err)
		}
	}()

	// 400
	func() {
		server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			w.WriteHeader(http.StatusBadRequest)
			http.ServeFile(w, r, "")
		}))
		c, _ := mockClient(server)
		ctx := context.TODO()
		err := c.DeleteItemTagging(ctx, "", "")
		if err == nil {
			t.Fail()
		}
	}()
}


text:
layout: post
title:  "servlet中forword请求转发小结"
categories: java
tags: java
author: Init
---

* content
{:toc}

代码:两个servlet,由servlet1请求转发(req.getRequestDispatcher("/forword/s2").forward(req, resp);)到servlet2中,访问servlet1观察结果小结:
1)浏览器地址栏的路径没有发生改变。依然是servlet1的资源名称
2)只发送了一次请求
3)共享同一个请求,请求中共享数据。比如servlet1中有id参数,servlet2中也能接收到
4)最终页面响应输出由servlet2来控制。
5)req.getRequestDispatcher("/forword/s2").forward(req, resp)中不加斜线req.getRequestDispatcher("forword/s2").forward(req, resp)找的是相对路径。常用绝对路径。
6)只能访问当前应用中的资源,不能跨域跳转
7)浏览器不能直接访问WEB-INF中的资源,但是可以通过请求转发的方式访问。
请求用的servlet1的请求,响应用的servlet2的响应

``` sh

@WebServlet("/forword/s1")
public class ForwordServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter out = resp.getWriter();
		System.out.println("servlet1 log ...");
		out.print("servlet1...web...before<br>");
		//请求转发
		req.getRequestDispatcher("/forword/s2").forward(req, resp);
		System.out.println("servlet 1 ... after");
		out.print("servlet1...web...after");
		out.print("<br> servlet1...forword...after");
	}
}

```

``` sh

@WebServlet("/forword/s2")
public class ForwordServlet2 extends HttpServlet{
	private static final long serialVersionUID = 1L;
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter out = resp.getWriter();
		System.out.println("servlet2 log ...");
		//请求转发
		out.print("servlet2...web...");
		out.print(req.getParameter("name"));
	}
}

```


text:
package fredboat.db.entity;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "user_config")
public class UConfig implements IEntity {

    @Id
    private String userId;
    private String bearer;
    private String refresh;
    private long bearerexpiration;

    public String getBearer() {
        return bearer;
    }

    public String getRefresh() {
        return refresh;
    }

    public String getUserId() {
        return userId;
    }

    public long getBearerExpiration() {
        return bearerexpiration;
    }

    public UConfig(String id) {
        this.userId = id;
    }

    @Override
    public void setId(String id) {
        this.userId = id;
    }

    public UConfig() {
    }

    public UConfig setBearer(String bearer) {
        this.bearer = bearer;
        return this;
    }

    public UConfig setRefresh(String refresh) {
        this.refresh = refresh;
        return this;
    }

    public UConfig setUserId(String userId) {
        this.userId = userId;
        return this;
    }

    public UConfig setBearerExpiration(long bearerExpiration) {
        this.bearerexpiration = bearerExpiration;
        return this;
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta name="viewport" content="width=device-width,initial-scale=1.0" />
<title>.Net Collections</title>
<link rel="stylesheet" type="text/css" href="../../style.css" />

static void

Main >

.Net >

Collections

Events

Globalization

Reflection

Security

Claims Security

Crypto+ signing

Serialization

Threading

Async

.Net Collections

Interfaces

The collection/list interfaces

IEnumerable (and IEnumerable<T>) Allows you to "foreach".

public IEnumerable GetEnumerator()

{

    foreach (ItemObject itemObject in _list)

        yield return itemObject;

}

In .net 1 you have to create a IEnumerator class (normally nested) with Current/MoveNext. In .net 2 generics you still need the nongeneric version.

ICollection inherits IEnumerable and adds Count and ability to lock SyncRoot

IList inherits ICollection and adds Add/Remove/Clear/Insert/Contains + IsFixedSize/IsReadOnly if needed

IDictionary inherits ICollection and is the name/value version of IList

The functional interfaces

IComparer - for sorting

IEnumerator - used for IEnumerable (but you can skip it with yield return)

Collections

Implement IList and/or IDictionary. For dictionaries (name/values):

foreach DictionaryEntry (in Generic versions, NameValuePair/ KeyValuePair)

Access by [index] as well as [key]: SortedList and OrderedDictionary (latter isn't sorted!)

By size: Hashtable (big), ListDictionary (small), HybridDictionary (both)

For strings, Hashtable and SortedList are case sensitive (Specialized.StringDictionary is insensitive). Use Specialized.CollectionsUtil.CreateCaseInsensitiveHashtable() or SortedList()

NB: collections ctors can take StringComparer.InvarientCulture

Specialized.StringDictionary and BaseDictionary for 1.1; now easier with generics

Specialized.NameValueCollection is like StringDictionary but has multiple keys (only thru .Add, not [indexer]- .Add("key1","a");.Add("key1","b"); adds two values. [indexer] returns CSV of all keys)

Generic dictionaries are simpler = Dictionary<T, V> (most things) and SortedList<T, V>.

SortedList and SortedDictionary are almost identical: the list one is more memory efficient and faster to initially load; dictionary is faster to insert/remove

Implementing interfaces

Sort: Implement IComparable (GetComparer static method, CompareTo instance method) and IComparer (which calls CompareTo on the instances, normally a nested class). Can pass in a generic delegate (a typed sort method can be passed in that matches the generic signature)

See my GenericComparer<T> using reflection

Duplicate objects- override .GetHashCode to return the unique property, AND override object.Equals
Or create an IEqualityComparer (which also has .GetHashCode and .Equals). You can't just hash all the properties, because if you change one, it's a "different" object.

BitArray is an array of booleans (doesn't dynamically resize- but you can reset .Length)

Specialized.BitVector32 is a structure to hide binary maths with a single Int32.

//1: lots of booleans. Use masks.

BitVector32 vector = new BitVector32(0);// All bit flags set to FALSE.

int mask1 = BitVector32.CreateMask();

int mask2 = BitVector32.CreateMask(mask1);

vector[mask2] = true; //masks allow you to flip booleans by indexer

You can also pack numbers into a single Int32.

//2: Pack numbers using CreateSection

BitVector32 packedVector = new BitVector32();

BitVector32.Section sec1 = BitVector32.CreateSection(20);

BitVector32.Section sec2 = BitVector32.CreateSection(300, sec1);

packedVector[sec1] = 6; //you have 2+ numbers stored in one 32bit int

packedVector[sec2] = 199;

Custom Collections

Inherit from Collection<T> and override InsertItem/SetItem and ClearItem. (Non generic use CollectionBase - my version)

Thread Safe

You can get a synchronised wrapper around a Stack: Stack mySyncdStack = Stack.Synchronized( myStack ) but for derived classes lock(myCollection.SyncRoot)

Lists with Delegates

Very useful functional programming.

List.Find(Predicate<T>)

List.FindAll(Predicate<T>)
items.Find(
delegate(DatedItem d) {
return (d.Id == key);
 });

List.Sort(Comparison<T>)
items.Sort(
delegate(DatedItem p1, DatedItem p2)
                {
 return p1.Name.CompareTo(p2.Name);
 });

List.ConvertAll<TOut>(Comparison<T, TOut>)
items.ConvertAll<Object>(
delegate(DatedItem p1)
                {
 return (Object)p1;
 });

Sorting

See SortableBindingList<T> (for Windows.Forms)

Copying to an array to sort with a delegate (here, sorting ListItems in asp DropDownList)

private void SortListControl(ListControl ddl)

{

    ListItemCollection c = ddl.Items;

    ListItem[] items = new ListItem[c.Count];

    c.CopyTo(items, 0);

    Array.Sort(items, delegate(ListItem a, ListItem b)

                          {

                              return a.Text.CompareTo(b.Text);

                          });

    ddl.Items.Clear();

    ddl.Items.AddRange(items);

}

Sorting with nullable properties has a slighly more involved delegate

private void SortList()

{

    //DeatedObject.Date is a nullable date

    List<DatedObject> olist = new List<DatedObject>();

    olist.Add(new DatedObject(DateTime.Now.AddDays(1)));

    olist.Add(new DatedObject(DateTime.Now));

    olist.Add(new DatedObject()); //null date

    olist.Sort(CompareDatedObjects); //IList does not have a Sort

    comboBox1.DataSource = olist;

    comboBox1.DisplayMember = "Date";

}

private static int CompareDatedObjects(DatedObject x, DatedObject y)

{

    if (x.Date == null)

        return (y.Date == null) ? 0 : -1; //If x is null and y is not null, y is greater.

    else // If x is not null...

    {

        if (y.Date == null)

            return 1; // y is null so x is greater.

        else

            return x.Date.Value.CompareTo(y.Date); // both non-null, compare the properties

    }

}

Nongeneric to generic ILists

When using an older style library in .net 2

/// <summary>

/// Converts nongeneric list to generic list.

/// Just a generic way of doing foreach (string s in untypedList) genericList.Add(s);

/// </summary>

/// <typeparam name="T">The type.

/// If any in the list aren't the type, throws an exception</typeparam>

/// <param name="list">The untyped list.</param>

/// <returns>A generic list</returns>

/// <example><code>IList&lt;string&gt; typedList = ConvertToGenericList&lt;string&gt;(untypedList);

/// </code></example>

/// <exception cref="InvalidCastException"/>

private static List<T> ConvertToGenericList<T>(ICollection list)

{

    //copy it into a concrete ArrayList

    ArrayList untypedList = new ArrayList(list);

    //then create the generic list from the arrayList's ToArray

    //with funky typeof/as [] casting

    return new List<T>(untypedList.ToArray(typeof (T)) as T[]);

}

Linq

//simple join

var simpleJoin = from category in categories

            //joins use "equals" not "=="

            join product in products on category.Id equals product.CategoryId

            orderby category.Id

            select new { category.CategoryName, product.ProductName };

//group join (hierarchical outer join)

var groupJoin = from category in categories

             join product in products on category.Id equals product.Id

                    //"into"

                    into productsForCategory

             select new { category.Id, Products = productsForCategory };

//groupby - products by category

var groups = from product in products

             group product by product.CategoryId;

Duplicates

//find duplicates

var dupes = from category in categories

            group category by category.Id

            into categoryGroup

            where categoryGroup.Count() > 1

            select categoryGroup.Key;

var noDupes = categories.Distinct(); //if you have IEqualityComparer

//or without a comparer

var noDupes2 = from category in categories

               //join to a distinct list of ids

               join id in categories.Select(x => x.Id).Distinct()

                    on category.Id equals id

               select category;

var noDupes3 = from category in categories

               //group them and just get the first

               group category by category.Id into categoryGroup

               select categoryGroup.First();

Set operations

var inBoth = list1.Intersect(list2);

Log("In both", inBoth);

var inList1Only = list1.Except(list2);

Log("Only in list 1", inList1Only);

var union = list1.Union(list2); //compare list1.Concat(list2)

Log("Both lists merged", union);

//.net 4 merge

var zip = list1.Zip(list2, (a, b) => a + " " + b);

Log("Zipped together", zip);

bool isInSameOrder = list1.SequenceEqual(list2);


text:
@class CLLocation, NSDictionary, NSString;

@protocol IPOILocationDisplayExt <NSObject>
- (void)onGetPOIDisplayName:(NSString *)arg1 ForLocation:(CLLocation *)arg2 Scene:(int)arg3 SrcDisplayName:(NSString *)arg4 extraInfo:(NSDictionary *)arg5 Error:(int)arg6;
@end


text:
cask "knotes" do
  version "2.11.0"
  sha256 "ddc1e1e30b1194adccab4dd32e5f40bb0e00ab0e6be39ee2f917c16a6f1f0b78"

  url "https://knotes2.s3-ap-northeast-1.amazonaws.com/download/mac/Knotes-#{version}.dmg",
      verified: "knotes2.s3-ap-northeast-1.amazonaws.com/"
  name "Knotes"
  desc "Reading notes management tool"
  homepage "https://knotesapp.com/"

  livecheck do
    url :homepage
    regex(%r{href=.*?/Knotes[._-]v?(\d+(?:\.\d+)+)\.dmg}i)
  end

  depends_on macos: ">= :yosemite"

  app "Knotes.app"

  zap trash: [
    "~/Library/Application Support/knotes",
    "~/Library/Logs/knotes",
    "~/Library/Preferences/com.knotesapp.knotes.helper.plist",
    "~/Library/Preferences/com.knotesapp.knotes.plist",
    "~/Library/Saved Application State/com.knotesapp.knotes.savedState",
  ]
end


text:
#ifndef __XILLYBUS_H
#define __XILLYBUS_H

#include <linux/list.h>
#include <linux/device.h>
#include <linux/dma-mapping.h>
#include <linux/interrupt.h>
#include <linux/sched.h>
#include <linux/cdev.h>
#include <linux/spinlock.h>
#include <linux/mutex.h>
#include <linux/workqueue.h>

struct xilly_endpoint_hardware;

struct xilly_page {
	struct list_head node;
	unsigned long addr;
	unsigned int order;
};

struct xilly_dma {
	struct list_head node;
	struct pci_dev *pdev;
	struct device *dev;
	dma_addr_t dma_addr;
	size_t size;
	int direction;
};

struct xilly_buffer {
	void *addr;
	dma_addr_t dma_addr;
	int end_offset; /* Counting elements, not bytes */
};

struct xilly_cleanup {
	struct list_head to_kfree;
	struct list_head to_pagefree;
	struct list_head to_unmap;
};

struct xilly_idt_handle {
	unsigned char *chandesc;
	unsigned char *idt;
	int entries;
};

/*
 * Read-write confusion: wr_* and rd_* notation sticks to FPGA view, so
 * wr_* buffers are those consumed by read(), since the FPGA writes to them
 * and vice versa.
 */

struct xilly_channel {
	struct xilly_endpoint *endpoint;
	int chan_num;
	int log2_element_size;
	int seekable;

	struct xilly_buffer **wr_buffers; /* FPGA writes, driver reads! */
	int num_wr_buffers;
	unsigned int wr_buf_size; /* In bytes */
	int wr_fpga_buf_idx;
	int wr_host_buf_idx;
	int wr_host_buf_pos;
	int wr_empty;
	int wr_ready; /* Significant only when wr_empty == 1 */
	int wr_sleepy;
	int wr_eof;
	int wr_hangup;
	spinlock_t wr_spinlock;
	struct mutex wr_mutex;
	wait_queue_head_t wr_wait;
	wait_queue_head_t wr_ready_wait;
	int wr_ref_count;
	int wr_synchronous;
	int wr_allow_partial;
	int wr_exclusive_open;
	int wr_supports_nonempty;

	struct xilly_buffer **rd_buffers; /* FPGA reads, driver writes! */
	int num_rd_buffers;
	unsigned int rd_buf_size; /* In bytes */
	int rd_fpga_buf_idx;
	int rd_host_buf_pos;
	int rd_host_buf_idx;
	int rd_full;
	spinlock_t rd_spinlock;
	struct mutex rd_mutex;
	wait_queue_head_t rd_wait;
	int rd_ref_count;
	int rd_allow_partial;
	int rd_synchronous;
	int rd_exclusive_open;
	struct delayed_work rd_workitem;
	unsigned char rd_leftovers[4];
};

struct xilly_endpoint {
	/*
	 * One of pdev and dev is always NULL, and the other is a valid
	 * pointer, depending on the type of device
	 */
	struct pci_dev *pdev;
	struct device *dev;
	struct resource res; /* OF devices only */
	struct xilly_endpoint_hardware *ephw;

	struct list_head ep_list;
	int dma_using_dac; /* =1 if 64-bit DMA is used, =0 otherwise. */
	__iomem u32 *registers;
	int fatal_error;

	struct mutex register_mutex;
	wait_queue_head_t ep_wait;

	/* List of memory allocations, to make release easy */
	struct xilly_cleanup cleanup;

	/* Channels and message handling */
	struct cdev cdev;

	int major;
	int lowest_minor; /* Highest minor = lowest_minor + num_channels - 1 */

	int num_channels; /* EXCLUDING message buffer */
	struct xilly_channel **channels;
	int msg_counter;
	int failed_messages;
	int idtlen;

	u32 *msgbuf_addr;
	dma_addr_t msgbuf_dma_addr;
	unsigned int msg_buf_size;
};

struct xilly_endpoint_hardware {
	struct module *owner;
	void (*hw_sync_sgl_for_cpu)(struct xilly_endpoint *,
				    dma_addr_t,
				    size_t,
				    int);
	void (*hw_sync_sgl_for_device)(struct xilly_endpoint *,
				       dma_addr_t,
				       size_t,
				       int);
	dma_addr_t (*map_single)(struct xilly_cleanup *,
				 struct xilly_endpoint *,
				 void *,
				 size_t,
				 int);
	void (*unmap_single)(struct xilly_dma *entry);
};

irqreturn_t xillybus_isr(int irq, void *data);

void xillybus_do_cleanup(struct xilly_cleanup *mem,
			 struct xilly_endpoint *endpoint);

struct xilly_endpoint *xillybus_init_endpoint(struct pci_dev *pdev,
					      struct device *dev,
					      struct xilly_endpoint_hardware
					      *ephw);

int xillybus_endpoint_discovery(struct xilly_endpoint *endpoint);

void xillybus_endpoint_remove(struct xilly_endpoint *endpoint);

#endif /* __XILLYBUS_H */


text:
module Bot

  MODULE_LOADED_BUFFER  = true
  MODULE_VERSION_BUFFER = 0.1

  class BufferManager < Hash

    def initialize
      Events.create :PART,    self, :on_part
      Events.create :PRIVMSG, self, :record_message
      Events.create :NOTICE,  self, :record_message

      super
    end

    def on_part msg
      return unless msg.me?
      self[msg.connection.name].delete msg.destination
    end

    def record_message msg
      return if msg.query?

      if msg.type == :PRIVMSG

        if msg.text =~ /\01ACTION (.+)\01/
          text = $1
          type = :ACTION
        else
          text = msg.text
          type = msg.type
        end

      else
        text = msg.text
        type = msg.type
      end

      self[msg.connection.name] ||= CanonizedHash.new(msg.connection)
      self[msg.connection.name][msg.destination] ||= []

      self[msg.connection.name][msg.destination] << {:type => type,
                                                     :text => text,
                                                     :nick => msg.nick}

      max = Conf[:modules][:buffer][:max_size] rescue 100

      # TODO: This is nasty. I am using a loop here because we might be
      # rehashed with a smaller value and have to shift it down to size. There
      # are better ways of doing this.
      while self[msg.connection.name][msg.destination].length > (Conf[:modules][:buffer][:max_size].to_i rescue 100)
        self[msg.connection.name][msg.destination].shift
      end
    end

  end

  Buffer ||= BufferManager.new

end
# vim: set tabstop=2 expandtab:


text:
package com.android.sample.test_utils;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import com.android.framework.R;
import com.android.libcore_ui.activity.BaseActivity;

/**
 * Description: utils测试类
 *
 * @author zzp(zhao_zepeng@hotmail.com)
 * @since 2015-07-31
 */
public class UtilsActivity extends BaseActivity implements View.OnClickListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initData();
    }

    protected void initView() {
        setContentView(R.layout.activity_test_utils);
        $(R.id.btn_test_file).setOnClickListener(this);
        $(R.id.btn_test_image).setOnClickListener(this);
        $(R.id.btn_test_common).setOnClickListener(this);
    }

    protected void initData() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_test_file:
                startActivity(new Intent(this, FileActivity.class));
                break;
            case R.id.btn_test_image:
                startActivity(new Intent(this, ImageActivity.class));
                break;
            case R.id.btn_test_common:
                startActivity(new Intent(this, CommonActivity.class));
                break;
        }
    }
}


text:
module Fog
  module Scaleway
    class Compute
      class Real
        def delete_user_data(server_id, key)
          delete("/servers/#{server_id}/user_data/#{key}")
        end
      end

      class Mock
        def delete_user_data(server_id, key)
          server = lookup(:servers, server_id)

          data[:user_data][server['id']].delete(key)

          response(status: 204)
        end
      end
    end
  end
end


text: angular.module('<%= package %>.<%= module %>', []);


text:
package org.nd4j.linalg.api.ops.impl.updaters;

import lombok.NonNull;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.DynamicCustomOp;

public class AdamUpdater extends DynamicCustomOp {

    public AdamUpdater() {
        //
    }

    public AdamUpdater(@NonNull INDArray gradients, @NonNull INDArray stateU, @NonNull INDArray stateM, double lr, double beta1, double beta2, double epsilon, int iteration) {
        this(gradients, stateU, stateM, gradients, stateU, stateM, lr, beta1, beta2, epsilon, iteration);
    }

    public AdamUpdater(@NonNull INDArray gradients, @NonNull INDArray stateU, @NonNull INDArray stateM, @NonNull INDArray updates, @NonNull INDArray updatedStateU, @NonNull INDArray updatedStateM, double lr, double beta1, double beta2, double epsilon, int iteration) {
        addInputArgument(gradients, stateU, stateM);
        addOutputArgument(updates, updatedStateU, updatedStateM);
        addTArgument(lr, beta1, beta2, epsilon);
        addIArgument(iteration);
    }

    @Override
    public String opName() {
        return "adam_updater";
    }
}


text:
import React from 'react';
import LoginPage from '../Auth/Login/LoginPage';

class HomePage extends React.Component {
  render() {
    return (
      <div>
        <LoginPage />
      </div>
    );
  }
}

export default HomePage;


text:
import os
from urlparse import urlparse

import pyauto_functional  # Must be imported before pyauto
import pyauto
import test_utils
from webdriver_pages import settings

class PasswordTest(pyauto.PyUITest):
  """Tests that passwords work correctly."""

  INFOBAR_TYPE = 'password_infobar'
  URL = 'https://accounts.google.com/ServiceLogin'
  URL_HTTPS = 'https://accounts.google.com/Login'
  URL_LOGOUT = 'https://accounts.google.com/Logout'
  HOSTNAME = 'https://' + urlparse(URL).netloc + '/'
  USERNAME_ELEM = 'Email'
  PASSWORD_ELEM = 'Passwd'
  USERNAME = 'test@google.com'
  PASSWORD = 'test.password'

  def Debug(self):
    """Test method for experimentation.

    This method will not run automatically.
    """
    while True:
      raw_input('Interact with the browser and hit <enter> to dump passwords. ')
      print '*' * 20
      self.pprint(self.GetSavedPasswords())

  def setUp(self):
    pyauto.PyUITest.setUp(self)
    self.assertFalse(self.GetSavedPasswords())

  def _AssertWithinOneSecond(self, time1, time2):
    self.assertTrue(abs(time1 - time2) < 1.0,
                    'Times not within an acceptable range. '
                    'First was %lf, second was %lf' % (time1, time2))

  def _ConstructPasswordDictionary(self, username_value, password_value,
                                   signon_realm, origin_url, username_element,
                                   password_element, action_target,
                                   time=1279650942.0, submit_element='submit',
                                   blacklist=False):
    """Construct a password dictionary with all the required fields."""
    return {'username_value': username_value,
            'password_value': password_value,
            'signon_realm': signon_realm,
            'time': time,
            'origin_url': origin_url,
            'username_element': username_element,
            'password_element': password_element,
            'submit_element': submit_element,
            'action_target': action_target,
            'blacklist': blacklist}

  def _ClickOnLoginPage(self, window_index, tab_index):
    # In some cases (such as on Windows) the current page displays an account
    # name and e-mail, rather than an e-mail and password.  Clicking on a
    # particular DOM element causes the e-mail and password to be displayed.
    click_js = """
      var elements = document.getElementsByClassName("accounts");
      if (elements && elements.length > 0) {
        elements = elements[0].getElementsByTagName("p");
        if (elements && elements.length > 0)
          elements[0].onclick();
      }
      window.domAutomationController.send("done");
    """
    self.ExecuteJavascript(click_js, tab_index, window_index)

    # Wait until username/password is filled by the Password manager on the
    # login page.
    js_template = """
      var value = "";
      var element = document.getElementById("%s");
      if (element)
        value = element.value;
      window.domAutomationController.send(value);
    """
    self.assertTrue(self.WaitUntil(
        lambda: self.ExecuteJavascript(js_template % self.USERNAME_ELEM,
                                      tab_index, window_index) != '' and
                self.ExecuteJavascript(js_template % self.PASSWORD_ELEM,
                                      tab_index, window_index) != ''))

  def testSavePassword(self):
    """Test saving a password and getting saved passwords."""
    password1 = self._ConstructPasswordDictionary(
        'user@example.com', 'test.password',
        'https://www.example.com/', 'https://www.example.com/login',
        'username', 'password', 'https://www.example.com/login/')
    self.assertTrue(self.AddSavedPassword(password1))
    self.assertEqual(self.GetSavedPasswords(), [password1])

  def testRemovePasswords(self):
    """Verify that saved passwords can be removed."""
    password1 = self._ConstructPasswordDictionary(
        'user1@example.com', 'test1.password',
        'https://www.example.com/', 'https://www.example.com/login',
        'username1', 'password', 'https://www.example.com/login/')
    password2 = self._ConstructPasswordDictionary(
        'user2@example.com', 'test2.password',
        'https://www.example.com/', 'https://www.example.com/login',
        'username2', 'password2', 'https://www.example.com/login/')
    self.AddSavedPassword(password1)
    self.AddSavedPassword(password2)
    self.assertEquals(2, len(self.GetSavedPasswords()))
    self.assertEquals([password1, password2], self.GetSavedPasswords())
    self.RemoveSavedPassword(password1)
    self.assertEquals(1, len(self.GetSavedPasswords()))
    self.assertEquals([password2], self.GetSavedPasswords())
    self.RemoveSavedPassword(password2)
    # TODO: GetSavedPasswords() doesn't return anything when empty.
    # http://crbug.com/64603
    # self.assertFalse(self.GetSavedPasswords())

  def testDisplayAndSavePasswordInfobar(self):
    """Verify password infobar displays and able to save password."""
    test_utils.ClearPasswords(self)
    creds = self.GetPrivateInfo()['test_google_account']
    username = creds['username']
    password = creds['password']
    # Disable one-click login infobar for sync.
    self.SetPrefs(pyauto.kReverseAutologinEnabled, False)
    test_utils.GoogleAccountsLogin(self, username, password)
    # Wait until page completes loading.
    self.WaitUntil(
        lambda: self.GetDOMValue('document.readyState'),
        expect_retval='complete')
    self.PerformActionOnInfobar(
        'accept', infobar_index=test_utils.WaitForInfobarTypeAndGetIndex(
            self, self.INFOBAR_TYPE))
    self.NavigateToURL(self.URL_LOGOUT)
    self.NavigateToURL(self.URL_HTTPS)
    self._ClickOnLoginPage(0, 0)
    test_utils.VerifyGoogleAccountCredsFilled(self, username, password,
                                              tab_index=0, windex=0)
    test_utils.ClearPasswords(self)

  def testNeverSavePasswords(self):
    """Verify passwords not saved/deleted when 'never for this site' chosen."""
    creds1 = self.GetPrivateInfo()['test_google_account']
    # Disable one-click login infobar for sync.
    self.SetPrefs(pyauto.kReverseAutologinEnabled, False)
    test_utils.GoogleAccountsLogin(
        self, creds1['username'], creds1['password'])
    self.PerformActionOnInfobar(
        'accept', infobar_index=test_utils.WaitForInfobarTypeAndGetIndex(
            self, self.INFOBAR_TYPE))
    self.assertEquals(1, len(self.GetSavedPasswords()))
    self.AppendTab(pyauto.GURL(creds1['logout_url']))
    creds2 = self.GetPrivateInfo()['test_google_account_2']
    test_utils.GoogleAccountsLogin(
        self, creds2['username'], creds2['password'], tab_index=1)
    # Selecting 'Never for this site' option on password infobar.
    self.PerformActionOnInfobar(
        'cancel', infobar_index=test_utils.WaitForInfobarTypeAndGetIndex(
            self, self.INFOBAR_TYPE, tab_index=1), tab_index=1)

    # TODO: GetSavedPasswords() doesn't return anything when empty.
    # http://crbug.com/64603
    # self.assertFalse(self.GetSavedPasswords())
    # TODO: Check the exceptions list

  def testSavedPasswordInTabsAndWindows(self):
    """Verify saved username/password shows in window and tab."""
    creds = self.GetPrivateInfo()['test_google_account']
    username = creds['username']
    password = creds['password']
    # Disable one-click login infobar for sync.
    self.SetPrefs(pyauto.kReverseAutologinEnabled, False)
    # Login to Google a/c
    test_utils.GoogleAccountsLogin(self, username, password)
    self.PerformActionOnInfobar(
        'accept', infobar_index=test_utils.WaitForInfobarTypeAndGetIndex(
            self, self.INFOBAR_TYPE))
    self.NavigateToURL(self.URL_LOGOUT)
    self.NavigateToURL(self.URL)
    self._ClickOnLoginPage(0, 0)
    test_utils.VerifyGoogleAccountCredsFilled(self, username, password,
        tab_index=0, windex=0)
    self.AppendTab(pyauto.GURL(self.URL))
    self._ClickOnLoginPage(0, 1)
    test_utils.VerifyGoogleAccountCredsFilled(self, username, password,
        tab_index=1, windex=0)
    test_utils.ClearPasswords(self)

  def testLoginCredsNotShownInIncognito(self):
    """Verify login creds are not shown in Incognito mode."""
    creds = self.GetPrivateInfo()['test_google_account']
    username = creds['username']
    password = creds['password']
    # Disable one-click login infobar for sync.
    self.SetPrefs(pyauto.kReverseAutologinEnabled, False)
    # Login to Google account.
    test_utils.GoogleAccountsLogin(self, username, password)
    self.PerformActionOnInfobar(
        'accept', infobar_index=test_utils.WaitForInfobarTypeAndGetIndex(
            self, self.INFOBAR_TYPE))
    self.NavigateToURL(self.URL_LOGOUT)
    self.RunCommand(pyauto.IDC_NEW_INCOGNITO_WINDOW)
    self.NavigateToURL(self.URL, 1, 0)
    email_value = self.GetDOMValue('document.getElementById("Email").value',
                                   tab_index=0, windex=1)
    passwd_value = self.GetDOMValue('document.getElementById("Passwd").value',
                                    tab_index=0, windex=1)
    self.assertEqual(email_value, '',
                    msg='Email creds displayed %s.' % email_value)
    self.assertEqual(passwd_value, '', msg='Password creds displayed.')

  def testPasswordAutofilledInIncognito(self):
    """Verify saved password is autofilled in Incognito mode.

    Saved passwords should be autofilled once the username is entered in
    incognito mode.
    """
    action_target = self.HOSTNAME

    driver = self.NewWebDriver()
    password_dict = self._ConstructPasswordDictionary(
        self.USERNAME, self.PASSWORD, self.HOSTNAME, self.URL,
        self.USERNAME_ELEM, self.PASSWORD_ELEM, action_target)
    self.AddSavedPassword(password_dict)
    self.RunCommand(pyauto.IDC_NEW_INCOGNITO_WINDOW)
    self.NavigateToURL(self.URL, 1, 0)
    # Switch to window 1.
    driver.switch_to_window(driver.window_handles[1])
    driver.find_element_by_id(
        self.USERNAME_ELEM).send_keys(self.USERNAME + '\t')
    incognito_passwd = self.GetDOMValue(
        'document.getElementById("Passwd").value', tab_index=0, windex=1)
    self.assertEqual(incognito_passwd, self.PASSWORD,
                     msg='Password creds did not autofill in incognito mode.')

  def testInfoBarDisappearByNavigatingPage(self):
    """Test password infobar is dismissed when navigating to different page."""
    creds = self.GetPrivateInfo()['test_google_account']
    # Disable one-click login infobar for sync.
    self.SetPrefs(pyauto.kReverseAutologinEnabled, False)
    # Login to Google account.
    test_utils.GoogleAccountsLogin(self, creds['username'], creds['password'])
    self.PerformActionOnInfobar(
        'accept', infobar_index=test_utils.WaitForInfobarTypeAndGetIndex(
            self, self.INFOBAR_TYPE))
    self.NavigateToURL('chrome://version')
    self.assertTrue(self.WaitForInfobarCount(0))
    # To make sure user is navigated to Version page.
    self.assertEqual('About Version', self.GetActiveTabTitle())
    test_utils.AssertInfobarTypeDoesNotAppear(self, self.INFOBAR_TYPE)

  def testInfoBarDisappearByReload(self):
    """Test that Password infobar disappears by the page reload."""
    creds = self.GetPrivateInfo()['test_google_account']
    # Disable one-click login infobar for sync.
    self.SetPrefs(pyauto.kReverseAutologinEnabled, False)
    # Login to Google a/c
    test_utils.GoogleAccountsLogin(self, creds['username'], creds['password'])
    self.PerformActionOnInfobar(
        'accept', infobar_index=test_utils.WaitForInfobarTypeAndGetIndex(
            self, self.INFOBAR_TYPE))
    self.GetBrowserWindow(0).GetTab(0).Reload()
    test_utils.AssertInfobarTypeDoesNotAppear(self, self.INFOBAR_TYPE)

  def testPasswdInfoNotStoredWhenAutocompleteOff(self):
    """Verify that password infobar does not appear when autocomplete is off.

    If the password field has autocomplete turned off, then the password infobar
    should not offer to save the password info.
    """
    password_info = {'Email': self.USERNAME,
                     'Passwd': self.PASSWORD}

    # Disable one-click login infobar for sync.
    self.SetPrefs(pyauto.kReverseAutologinEnabled, False)
    url = self.GetHttpURLForDataPath(
        os.path.join('password', 'password_autocomplete_off_test.html'))
    self.NavigateToURL(url)
    for key, value in password_info.iteritems():
      script = ('document.getElementById("%s").value = "%s"; '
                'window.domAutomationController.send("done");') % (key, value)
      self.ExecuteJavascript(script, 0, 0)
    self.assertTrue(self.SubmitForm('loginform'))
    test_utils.AssertInfobarTypeDoesNotAppear(self, self.INFOBAR_TYPE)

  def _SendCharToPopulateField(self, char, tab_index=0, windex=0):
    """Simulate a char being typed into a field.

    Args:
      char: the char value to be typed into the field.
      tab_index: tab index to work on. Defaults to 0 (first tab).
      windex: window index to work on. Defaults to 0 (first window).
    """
    CHAR_KEYPRESS = ord((char).upper())  # ASCII char key press.
    KEY_DOWN_TYPE = 0  # kRawKeyDownType
    KEY_UP_TYPE = 3  # kKeyUpType

    self.SendWebkitKeyEvent(KEY_DOWN_TYPE, CHAR_KEYPRESS, tab_index, windex)
    self.SendWebkitCharEvent(char, tab_index, windex)
    self.SendWebkitKeyEvent(KEY_UP_TYPE, CHAR_KEYPRESS, tab_index, windex)

  def testClearFetchedCredForNewUserName(self):
    """Verify that the fetched credentials are cleared for a new username.

    This test requires sending key events rather than pasting a new username
    into the Email field.
    """
    creds = self.GetPrivateInfo()['test_google_account']
    username = creds['username']
    password = creds['password']
    # Disable one-click login infobar for sync.
    self.SetPrefs(pyauto.kReverseAutologinEnabled, False)
    # Login to Google a/c
    test_utils.GoogleAccountsLogin(self, username, password)
    self.PerformActionOnInfobar(
        'accept', infobar_index=test_utils.WaitForInfobarTypeAndGetIndex(
            self, self.INFOBAR_TYPE))
    self.NavigateToURL(self.URL_LOGOUT)
    self.NavigateToURL(self.URL)
    self._ClickOnLoginPage(0, 0)
    test_utils.VerifyGoogleAccountCredsFilled(self, username, password,
        tab_index=0, windex=0)
    clear_username_field = (
        'document.getElementById("Email").value = ""; '
        'window.domAutomationController.send("done");')
    set_focus = (
        'document.getElementById("Email").focus(); '
        'window.domAutomationController.send("done");')
    self.ExecuteJavascript(clear_username_field, 0, 0)
    self.ExecuteJavascript(set_focus, 0, 0)
    self._SendCharToPopulateField('t', tab_index=0, windex=0)
    passwd_value = self.GetDOMValue('document.getElementById("Passwd").value')
    self.assertFalse(passwd_value,
                     msg='Password field not empty for new username.')
    test_utils.ClearPasswords(self)

  def testPasswordInfobarShowsForBlockedDomain(self):
    """Verify that password infobar shows when cookies are blocked.

    Password infobar should be shown if cookies are blocked for Google
    accounts domain.
    """
    creds = self.GetPrivateInfo()['test_google_account']
    username = creds['username']
    password = creds['password']
    # Block cookies for Google accounts domain.
    self.SetPrefs(pyauto.kContentSettingsPatternPairs,
                  {'https://accounts.google.com/': {'cookies': 2}})
    test_utils.GoogleAccountsLogin(self, username, password)
    test_utils.WaitForInfobarTypeAndGetIndex(self, self.INFOBAR_TYPE)

if __name__ == '__main__':
  pyauto_functional.Main()


text:
                      <button type="button" class="close" data-dismiss="modal">×</button>

     <form class="form-group" ng-submit="formSubmit()">

      <input type="text" class="validate" ng-model="username" placeholder="Email">

      <input type="password" class="validate" ng-model="password" placeholder="Password">

     {{ success }}
         {{ error }}
     <button class="btn btn success pull-right" type="submit" href="#!" class="modal-action modal-close waves-effect waves-green btn-flat">Login</button>
     </form>

                      <button type="button" class="close" data-dismiss="modal">×</button>

     <form class="form-group" ng-submit="formSignup()">

      <input type="text" class="validate" ng-model="username" placeholder="Email">

      <input type="password" class="validate" ng-model="password" placeholder="Password">

      <input type="number" class="validate" placeholder="Contact No">

     <button class="btn btn success pull-right" type="submit" href="#!" class="modal-action modal-close waves-effect waves-green btn-flat">Sign Up</button>
     </form>


text:
#include "xenia/vfs/devices/disc_image_file.h"

#include <algorithm>

#include "xenia/vfs/devices/disc_image_entry.h"

namespace xe {
namespace vfs {

DiscImageFile::DiscImageFile(kernel::KernelState* kernel_state,
                             uint32_t file_access, DiscImageEntry* entry)
    : XFile(kernel_state, file_access, entry), entry_(entry) {}

DiscImageFile::~DiscImageFile() = default;

X_STATUS DiscImageFile::ReadSync(void* buffer, size_t buffer_length,
                                 size_t byte_offset, size_t* out_bytes_read) {
  if (byte_offset >= entry_->size()) {
    return X_STATUS_END_OF_FILE;
  }
  size_t real_offset = entry_->data_offset() + byte_offset;
  size_t real_length =
      std::min(buffer_length, entry_->data_size() - byte_offset);
  std::memcpy(buffer, entry_->mmap()->data() + real_offset, real_length);
  *out_bytes_read = real_length;
  return X_STATUS_SUCCESS;
}

}  // namespace vfs
}  // namespace xe


text:
'convert from [stackoverflow-specific] CSV to VW format'

import sys, csv, re

def get_label( status ):
	statuses = ['not a real question', 'not constructive', 'off topic', 'open', 'too localized']
	label = statuses.index( status ) + 1
	return label

input_file = sys.argv[1]
output_file = sys.argv[2]

reader = csv.reader( open( input_file ))
o = open( output_file, 'wb' )

counter = 0
for line in reader:

	counter += 1

	post_id = line[0]
	status = line[1]
	reputation = line[2]
	good_posts = line[3]
	words = line[4]
	tags = line[5:10]
	tags = " ".join( tags ).strip()

	body = line[10]

	if status != '0':
		label = get_label( status )
	else:
		label = status		# test set

	output_line = "%s %s %s" % ( label, 1, post_id ) 	# weight is 1
	output_line += "|n %s %s" % ( reputation, good_posts )
	output_line += "|w %s |t %s |b %s" % ( words, tags, body )
	output_line += "\n"

	o.write( output_line )

	if counter % 100000 == 0:
		print counter


text:
import _ from 'lodash';
import LocalCounter from './counter';

export default class LocalBackend {
  _counterValues: any;
  _counterTags: any;
  _timerValues: any;
  _timerTags: any;
  _gaugeValues: any;
  _gaugeTags: any;

  constructor() {
    this.reset();
  }

  static counterEquals(counter: LocalCounter, value: number): boolean {
    let valueEqual = counter._backend._counterValues[counter._name] === value;
    let tagsEqual = _.isEqual(counter._backend._counterTags[counter._name], counter._tags);
    return valueEqual && tagsEqual;
  }

  static counterValue(counter: LocalCounter): number {
    return counter._backend._counterValues[counter._name];
  }

  reset() {
    this._counterValues = {};
    this._counterTags = {};
    this._timerValues = {};
    this._timerTags = {};
    this._gaugeValues = {};
    this._gaugeTags = {};
  }

  increment(name: string, delta: number, tags: any): void {
    if (this._counterValues[name] === undefined) {
      this._counterValues[name] = 0;
    }
    this._counterValues[name] += delta;
    this._counterTags[name] = tags;
  }

  record(name: string, value: number, tags: any): void {
    this._timerValues[name] = value;
    this._timerTags[name] = tags;
  }

  gauge(name: string, value: number, tags: any): void {
    this._gaugeValues[name] = value;
    this._gaugeTags[name] = tags;
  }
}


text:
package org.jfrog.artifactory.client.model.impl;

import org.jfrog.artifactory.client.model.Item;

import java.io.File;
import java.util.Date;

/**
 * @author jbaruch
 * @since 29/07/12
 */

public class ItemImpl implements Item {
    private String uri;
    private String repo;
    private String path;
    private boolean folder;
    private String metadataUri;
    private Date lastModified;
    private String modifiedBy;
    private Date lastUpdated;

    ItemImpl(boolean folder, String uri, String metadataUri, Date lastModified, String modifiedBy, Date lastUpdated) {
        this.folder = folder;
        this.uri = uri;
        this.metadataUri = metadataUri;
        this.lastModified = lastModified;
        this.modifiedBy = modifiedBy;
        this.lastUpdated = lastUpdated;
    }

    protected ItemImpl() {
    }

    public String getPath() {
        return path;
    }

    private void setPath(String path) {
        this.path = path;
    }

    public String getRepo() {
        return repo;
    }

    private void setRepo(String repo) {
        this.repo = repo;
    }

    @Override
    public boolean isFolder() {
        return folder;
    }

    private void setFolder(boolean folder) {
        this.folder = folder;
    }

    @Override
    public String getName() {
        return new File(uri).getName();
    }

    @Override
    public String getUri() {
        return uri;
    }

    private void setUri(String uri) {
        this.uri = uri;
    }

    @Override
    public String getMetadataUri() {
        return metadataUri;
    }

    private void setMetadataUri(String metadataUri) {
        this.metadataUri = metadataUri;
    }

    @Override
    public Date getLastModified() {
        return lastModified;
    }

    private void setLastModified(Date lastModified) {
        this.lastModified = lastModified;
    }

    @Override
    public String getModifiedBy() {
        return modifiedBy;
    }

    private void setModifiedBy(String modifiedBy) {
        this.modifiedBy = modifiedBy;
    }

    @Override
    public Date getLastUpdated() {
        return lastUpdated;
    }

    private void setLastUpdated(Date lastUpdated) {
        this.lastUpdated = lastUpdated;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof ItemImpl)) {
            return false;
        }

        ItemImpl item = (ItemImpl) o;

        if (!uri.equals(item.uri)) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        return uri.hashCode();
    }
}


text:
package org.caseinsensitive.folksent.model

import scala.collection.mutable

abstract class InMemoryFolksonomy[T <: Document] extends Folksonomy[T] {

  def authors(): Seq[Author] = {
    _authors.keySet.toSeq
  }

  def documents(): Seq[T] = {
    _documents.toSeq
  }

  def topics(): Seq[Topic] = {
    _topics.keySet.toSeq
  }

  def documents(author: Author): Seq[T] = {
    _authors.getOrElse(author, Set.empty[T]).toSeq
  }

  def documents(topic: Topic): Seq[T] = {
    _topics.getOrElse(topic, Set.empty[T]).toSeq
  }

  def add(document: T): Unit = {
    if (!_documents.add(document)) {
      return
    }

    _authors(author(document)) += document
    topics(document).foreach(topic => _topics(topic) += document)
  }

  // main document store
  private val _documents = new mutable.HashSet[T]

  // reverse lookups for authors and topics
  private class DocumentReverseLookup[TLookup <: Entity] extends mutable.HashMap[TLookup, mutable.Set[T]] {
    override def default(key: TLookup): mutable.Set[T] = {
      new mutable.HashSet[T]
    }
  }

  private val _authors = new DocumentReverseLookup[Author]()
  private val _topics  = new DocumentReverseLookup[Topic]()
}


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

<title>DVConstraint.FormulaPair (POI API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.poi.hssf.usermodel

Class DVConstraint.FormulaPair

java.lang.Object

org.apache.poi.hssf.usermodel.DVConstraint.FormulaPair

Enclosing class:

DVConstraint

public static final class DVConstraint.FormulaPair
extends java.lang.Object

Constructor Summary

Constructors

Constructor and Description

DVConstraint.FormulaPair(Ptg[] formula1,
                        Ptg[] formula2)

Method Summary

Methods

Modifier and Type
Method and Description

Ptg[]
getFormula1()

Ptg[]
getFormula2()

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

DVConstraint.FormulaPair

public DVConstraint.FormulaPair(Ptg[] formula1,
                        Ptg[] formula2)

Method Detail

getFormula1

public Ptg[] getFormula1()

getFormula2

public Ptg[] getFormula2()

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

                Copyright 2015 The Apache Software Foundation or
        its licensors, as applicable.


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;

using wojilu.Serialization;
using wojilu.Web.Mvc;
using wojilu.Web.Utils;
using wojilu.Web.Mvc.Attr;

using wojilu.Apps.Forum.Domain;
using wojilu.Apps.Forum.Interface;
using wojilu.Apps.Forum.Service;
using wojilu.Members.Users.Domain;

namespace wojilu.Web.Controller.Forum {

    [App( typeof( ForumApp ) )]
    public class UploaderController : ControllerBase {

        public IAttachmentService attachService { get; set; }
        public IForumTopicService topicService { get; set; }

        public UploaderController() {
            topicService = new ForumTopicService();
            attachService = new AttachmentService();
        }

        public void UploadForm() {
            target( SaveUpload );

            set( "uploadLink", to( SaveUpload ) );
            set( "authCookieName", ctx.web.CookieAuthName() );
            set( "authCookieValue", ctx.web.CookieAuthValue() );
        }

        public void SaveUpload() {

            HttpFile postedFile = ctx.GetFileSingle();

            Result result = Uploader.SaveFileOrImage( postedFile );

            if (result.HasErrors) {
                errors.Join( result );
                run( UploadForm );
                return;
            }

            AttachmentTemp uploadFile = savePostData( postedFile, result );

            // 返回数据给主页面
            set( "objFile", SimpleJsonString.ConvertObject( uploadFile ) );
            set( "deleteLink", to( DeleteTempAttachment ) );

        }

        private AttachmentTemp savePostData( HttpFile postedFile, Result result ) {
            // 将附件存入数据库
            AttachmentTemp uploadFile = new AttachmentTemp();
            uploadFile.FileSize = postedFile.ContentLength;
            uploadFile.Type = postedFile.ContentType;
            uploadFile.Name = result.Info.ToString();
            uploadFile.Description = ctx.Post( "FileDescription" );
            uploadFile.ReadPermission = ctx.PostInt( "FileReadPermission" );
            uploadFile.Price = ctx.PostInt( "FilePrice" );
            uploadFile.AppId = ctx.app.Id;

            attachService.CreateTemp( uploadFile, (User)ctx.viewer.obj, ctx.owner.obj );
            return uploadFile;
        }

        public void SaveFlashUpload() {

            HttpFile postedFile = ctx.GetFileSingle();

            Result result = Uploader.SaveFileOrImage( postedFile );

            if (result.HasErrors) {
                errors.Join( result );
                echoError();
                return;
            }

            AttachmentTemp uploadFile = savePostData( postedFile, result );

            // 返回json给主页面
            String json = "{deleteLink:'" + to( DeleteTempAttachment ) + "', photo:" + SimpleJsonString.ConvertObject( uploadFile ) + "}";
            echoText( json );

        }

        public void DeleteTempAttachment() {
            int id = ctx.PostInt( "Id" );
            attachService.DeleteTempAttachment( id );
            echoAjaxOk();
        }

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

        //private void saveAttachment( ForumTopic topic ) {
        //    ForumPost post = topicService.GetPostByTopic( topic.Id );
        //    int attachmentCount = 0;

        //    string[] des = ctx.context.getFormValues( "FileDescription" );
        //    string[] rdPer = ctx.context.getFormValues( "FileReadPermission" );
        //    string[] prices = ctx.context.getFormValues( "FilePrice" );

        //    int uploadMaxUnit = 3;
        //    int uploadMax = 1024 * 1024 * uploadMaxUnit;

        //    for (int i = 0; i < ctx.getFiles().Count; i++) {

        //        if (des == null || rdPer == null || prices == null) continue;

        //        HttpPostedFile postedFile = ctx.getFiles()[i];

        //        // 检查文件大小
        //        if (postedFile.ContentLength <= 1 || postedFile.ContentLength > uploadMax) continue;

        //        // 检查文件格式
        //        if (Uploader.isAllowType( postedFile ) == false) {
        //            errors.Add( "文件类型不允许:" + postedFile.FileName + "/" + postedFile.ContentType );
        //            continue;
        //        }

        //        Result result;
        //        if (Uploader.IsImage( postedFile ))
        //            result = Uploader.SaveImg( postedFile );
        //        else
        //            result = Uploader.SaveFile( postedFile );
        //        if (result.HasErrors) continue;

        //        Attachment uploadFile = new Attachment();
        //        uploadFile.FileSize = postedFile.ContentLength;
        //        uploadFile.Type = postedFile.ContentType;
        //        uploadFile.Name = result.Info.ToString();

        //        uploadFile.Description = des[i];
        //        uploadFile.ReadPermission = cvt.ToInt( rdPer[i] );
        //        uploadFile.Price = cvt.ToInt( prices[i] );

        //        uploadFile.AppId = ctx.app.Id;
        //        uploadFile.TopicId = topic.Id;
        //        uploadFile.PostId = post.Id;
        //        attachService.Create( uploadFile, (User)ctx.viewer.obj, ctx.owner.obj );
        //        attachmentCount++;
        //    }
        //    topicService.UpdateAttachments( topic, attachmentCount );
        //}

    }

}


text:
import { RootSchemaElement, SchemaElement, Type } from "./schema";

export const prettyPrintData = (schema: RootSchemaElement, data: object, selection: any): string => {
	const out = new PrintWriter();
	printData(schema, data, out, 0, selection);
	return out.toString();
};

export const prettyPrintSchema = (schema: RootSchemaElement, selection: SchemaElement): string => {
	const out = new PrintWriter();
	printObject(schema, out, 0, selection);
	return out.toString();
};

export const prettyPrint = (object: object, selection: object): string => {
	const out = new PrintWriter();
	if (Array.isArray(object)) {
		printArray(object, out, 0, selection);
	} else {
		printObject(object, out, 0, selection);
	}
	return out.toString();
};

const printData = (schema: SchemaElement, data: any, out: PrintWriter, idt: number, selection): void => {
	switch (schema.type) {
		case Type.TObject:
			out.print('{');
			out.newLine();
			let keys = Object.keys(data);
			let getSchema = (key) => {
				if (schema.properties) {
					return schema.properties[key];
				} else {
					return schema.patternProperties!['.+'];
				}
			};
			for (let i = 0; i < keys.length; i++) {
				let key = keys[i];
				if (selection === data[key]) {
					out.printSelectionStart();
				}
				out.indent(idt + 1);
				out.printKey(key);
				out.print(':');
				out.space();
				printData(getSchema(key), data[key], out, idt + 1, selection);
				if (i < keys.length - 1) {
					out.print(',');
				}
				out.newLine();
			}
			out.indent(idt);
			out.print('}');
			break;
		case Type.TArray:
			out.print('[');
			out.newLine();
			if (schema.items) {
				for (let i = 0; i < data.length; i++) {
					if (selection === data[i]) {
						out.printSelectionStart();
					}
					out.indent(idt + 1);
					printData(schema.items, data[i], out, idt + 1, selection);
					if (i < data.length - 1) {
						out.print(',');
					}
					out.newLine();
				}
			}
			out.indent(idt);
			out.print(']');
			break;
		case Type.TString:
			out.printString(data as string);
			break;
		case Type.TBoolean:
			out.printBoolean(data as boolean);
			break;
	}
	if (selection === data) {
		out.printSelectionEndAtNewLine = true;
	}
};

const printObject = (object: any, out: PrintWriter, idt: number, selection): void => {
	out.print('{');
	out.newLine();
	let keys = Object.keys(object);
	for (let i = 0; i < keys.length; i++) {
		const key = keys[i];
		const value = object[key];
		if (selection === value) {
			out.printSelectionStart();
		}
		out.indent(idt + 1);
		out.printKey(key);
		out.print(':');
		out.space();
		switch (typeof value) {
			case 'number':
				out.printNumber(value);
				break;
			case 'boolean':
				out.printBoolean(value);
				break;
			case 'string':
				out.printString(value);
				break;
			case 'object':
				if (Array.isArray(value)) {
					printArray(value as any[], out, idt + 1, selection);
				} else {
					printObject(value as object, out, idt + 1, selection);
				}
				break;
		}
		if (i < keys.length - 1) {
			out.print(',');
		}
		out.newLine();
	}
	out.indent(idt);
	out.print('}');
	if (selection === object) {
		out.printSelectionEndAtNewLine = true;
	}
};

const printArray = (array: any[], out: PrintWriter, idt: number, selection): void => {
	out.print('[');
	out.newLine();
	for (let i = 0; i < array.length; i++) {
		const value = array[i];
		if (selection === value) {
			out.printSelectionStart();
		}
		out.indent(idt + 1);
		switch (typeof value) {
			case 'number':
				out.printNumber(value);
				break;
			case 'boolean':
				out.printBoolean(value);
				break;
			case 'string':
				out.printString(value);
				break;
			case 'object':
				printObject(value as object, out, idt + 1, selection);
				break;
		}
		if (i < array.length - 1) {
			out.print(',');
		}
		out.newLine();
	}
	out.indent(idt);
	out.print(']');
	if (selection === array) {
		out.printSelectionEndAtNewLine = true;
	}
};

class PrintWriter {
	buffer: string[];
	printSelectionEndAtNewLine: boolean = false;

	constructor() {
		this.buffer = [];
	}

	print(str) {
		this.buffer.push(str);
	}

	newLine() {
		if (this.printSelectionEndAtNewLine) {
			this.printSelectionEnd();
			this.printSelectionEndAtNewLine = false;
		} else {
			this.buffer.push('<br>');
		}
	}

	space() {
		this.buffer.push(' ');
	}

	indent(len: number) {
		if (len > 0) {
			let res = '';
			for (let i = 0; i < len; i++) {
				res += '  ';
			}
			this.buffer.push(res);
		}
	}

	printKey(key: string) {
		this.buffer.push('\"');
		this.buffer.push(`<span class="json-key">${key}</span>`);
		this.buffer.push('\"');
	}

	printString(value: string) {
		this.buffer.push('\"');
		this.buffer.push(`<span class="json-string">${value}</span>`);
		this.buffer.push('\"');
	}

	printBoolean(value: boolean) {
		this.buffer.push(`<span class="json-boolean">${value}</span>`);
	}
	printNumber(value: number) {
		this.buffer.push(`<span class="json-number">${value}</span>`);
	}

	printSelectionStart() {
		this.buffer.push(`<div class="selected">`);
	}

	printSelectionEnd() {
		this.buffer.push(`</div>`);
	}

	toString() {
		return this.buffer.join('');
	}
}


text:
<!DOCTYPE html>

<link rel="stylesheet" href="stylesheets/my-berkshire-stylesheet.css">

        BERKSHIRE HATHAWAY INC.

        3555 Farnam Street
        Omaha, NE 68131

Official Home Page

A Message From Warren E. Buffett

Annual & Interim Reports

 Updated November 6, 2015

Special Letters From Warren & Charlie RE:Past, Present and Future

Link to SEC Filings

Links to Berkshire Subsidiary Companies

Corporate Governance

Owner's Manual

Letters from Warren E. Buffett Regarding Pledges to Make Gifts of Berkshire Stock

News Releases

Updated January 29, 2016

Warren Buffet's Letters to Berkshire Shareholders

Updated February 28, 2015

Charlie Munger's Letters to Wesco Shareholders

Annual Meeting Information

Celebrating 50 Years of a Profitable Partnership

(A commemorative book first sold at the 2015 Annual Meeting and now for sale on eBay.)

Comparative Rights & Relative Prices of Class A and B Stock

Berkshire Activewear

FOR A FREE CAR INSURANCE RATE QUOTE THAT COULD SAVE YOU SUBSTANTIAL MONEY

 WWW.GEICO.COM OR CALL 1-888-395-6349, 24 HOURS A DAY

If you have any comments about our WEB page, you can either write us at the address shown above or e-mail us at berkshire@berkshirehathaway.com. However, due to the limited number of personnel in
        our corporate office, we are unable to provide a direct response.

Legal Disclaimer

Copyright © 1978-2015 Berkshire Hathaway Inc.


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Parmelia reterimulosa J. Steiner & Zahlbr.

### Remarks
null


text:
<?php

namespace Omnipay\IPay88\Message;

use Omnipay\Common\Message\AbstractResponse;

class PurchaseResponse extends AbstractResponse
{
    protected $endpoint = 'https://www.mobile88.com/ePayment/entry.asp';

    public function getTransactionId()
    {
        return $this->data['RefNo'];
    }

    public function isTransparentRedirect()
    {
        return true;
    }

    public function isRedirect()
    {
        return true;
    }

    public function isSuccessful()
    {
        return false;
    }

    public function getRedirectUrl()
    {
        return $this->endpoint;
    }

    public function getRedirectMethod()
    {
        return 'POST';
    }

    public function getRedirectData()
    {
        return $this->data;
    }

}


text:
{% extends "layout.html" %}

{% block page_title %}
  Single travel payment
{% endblock %}

{% block content %}

        BETA
        This is a new service – your feedback will help us to improve it.

Your one off travel claim details

            <fieldset>
              <legend class="form-label-bold">Date of travel</legend>

                  Day
                  <input type="text" class="form-control" id="dob-day" maxlength="2" name="dob-day">

                  Month
                  <input type="text" class="form-control" id="dob-month" maxlength="2" name="dob-month">

                  Year
                  <input type="text" class="form-control" id="dob-year" maxlength="4" name="dob-year">

            </fieldset>

                Reason for travel

              <textarea class="form-control" id="reasons" name="reasons"></textarea>

              Total number of journeys

List all journeys made on the date given above.

              <input type="text" class="form-control" id="email">

              Total cost of travel

Total cost of all journeys made on the date given above.

              <input type="text" class="form-control" id="email">

 Continue

{% endblock %}


text:
from mapofinnovation.tests import *

class TestSearchapiController(TestController):

    def test_index(self):
        response = self.app.get(url(controller='searchapi', action='index'))
        # Test response...


text:
<?php

namespace CodesWholesale\DataStore;

use CodesWholesale\Resource\Resource;

interface InternalDataStore extends DataStore
{

    public function create($parentHref, Resource $resource, $returnType, array $options = array());

    public function save(Resource $resource, $returnType = null);

    public function delete(Resource $resource);

}


text:
using System;
using System.Data;
using Csla;

namespace Invoices.DataAccess
{
    /// <summary>
    /// DAL Interface for CustomerEdit type
    /// </summary>
    public partial interface ICustomerEditDal
    {
        /// <summary>
        /// Loads a CustomerEdit object from the database.
        /// </summary>
        /// <param name="customerId">The Customer Id.</param>
        /// <returns>A data reader to the CustomerEdit.</returns>
        IDataReader Fetch(string customerId);

        /// <summary>
        /// Inserts a new CustomerEdit object in the database.
        /// </summary>
        /// <param name="customerId">The Customer Id.</param>
        /// <param name="name">The Name.</param>
        /// <param name="fiscalNumber">The Fiscal Number.</param>
        /// <param name="addressLine1">The Address Line1.</param>
        /// <param name="addressLine2">The Address Line2.</param>
        /// <param name="zipCode">The Zip Code.</param>
        /// <param name="state">The State.</param>
        /// <param name="country">The Country.</param>
        void Insert(string customerId, string name, string fiscalNumber, string addressLine1, string addressLine2, string zipCode, string state, byte? country);

        /// <summary>
        /// Updates in the database all changes made to the CustomerEdit object.
        /// </summary>
        /// <param name="customerId">The Customer Id.</param>
        /// <param name="name">The Name.</param>
        /// <param name="fiscalNumber">The Fiscal Number.</param>
        /// <param name="addressLine1">The Address Line1.</param>
        /// <param name="addressLine2">The Address Line2.</param>
        /// <param name="zipCode">The Zip Code.</param>
        /// <param name="state">The State.</param>
        /// <param name="country">The Country.</param>
        void Update(string customerId, string name, string fiscalNumber, string addressLine1, string addressLine2, string zipCode, string state, byte? country);

        /// <summary>
        /// Deletes the CustomerEdit object from database.
        /// </summary>
        /// <param name="customerId">The Customer Id.</param>
        void Delete(string customerId);
    }
}