text:
package armhybridcompute

import (
	"context"
	"errors"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
	armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
	"net/http"
	"net/url"
	"strings"
)

// PrivateLinkResourcesClient contains the methods for the PrivateLinkResources group.
// Don't use this type directly, use NewPrivateLinkResourcesClient() instead.
type PrivateLinkResourcesClient struct {
	host           string
	subscriptionID string
	pl             runtime.Pipeline
}

// NewPrivateLinkResourcesClient creates a new instance of PrivateLinkResourcesClient with the specified values.
// subscriptionID - The ID of the target subscription.
// credential - used to authorize requests. Usually a credential from azidentity.
// options - pass nil to accept the default values.
func NewPrivateLinkResourcesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*PrivateLinkResourcesClient, error) {
	if options == nil {
		options = &arm.ClientOptions{}
	}
	ep := cloud.AzurePublic.Services[cloud.ResourceManager].Endpoint
	if c, ok := options.Cloud.Services[cloud.ResourceManager]; ok {
		ep = c.Endpoint
	}
	pl, err := armruntime.NewPipeline(moduleName, moduleVersion, credential, runtime.PipelineOptions{}, options)
	if err != nil {
		return nil, err
	}
	client := &PrivateLinkResourcesClient{
		subscriptionID: subscriptionID,
		host:           ep,
		pl:             pl,
	}
	return client, nil
}

// Get - Gets the private link resources that need to be created for a Azure Monitor PrivateLinkScope.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-03-10
// resourceGroupName - The name of the resource group. The name is case insensitive.
// scopeName - The name of the Azure Arc PrivateLinkScope resource.
// groupName - The name of the private link resource.
// options - PrivateLinkResourcesClientGetOptions contains the optional parameters for the PrivateLinkResourcesClient.Get
// method.
func (client *PrivateLinkResourcesClient) Get(ctx context.Context, resourceGroupName string, scopeName string, groupName string, options *PrivateLinkResourcesClientGetOptions) (PrivateLinkResourcesClientGetResponse, error) {
	req, err := client.getCreateRequest(ctx, resourceGroupName, scopeName, groupName, options)
	if err != nil {
		return PrivateLinkResourcesClientGetResponse{}, err
	}
	resp, err := client.pl.Do(req)
	if err != nil {
		return PrivateLinkResourcesClientGetResponse{}, err
	}
	if !runtime.HasStatusCode(resp, http.StatusOK) {
		return PrivateLinkResourcesClientGetResponse{}, runtime.NewResponseError(resp)
	}
	return client.getHandleResponse(resp)
}

// getCreateRequest creates the Get request.
func (client *PrivateLinkResourcesClient) getCreateRequest(ctx context.Context, resourceGroupName string, scopeName string, groupName string, options *PrivateLinkResourcesClientGetOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HybridCompute/privateLinkScopes/{scopeName}/privateLinkResources/{groupName}"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if scopeName == "" {
		return nil, errors.New("parameter scopeName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{scopeName}", url.PathEscape(scopeName))
	if groupName == "" {
		return nil, errors.New("parameter groupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{groupName}", url.PathEscape(groupName))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-03-10")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// getHandleResponse handles the Get response.
func (client *PrivateLinkResourcesClient) getHandleResponse(resp *http.Response) (PrivateLinkResourcesClientGetResponse, error) {
	result := PrivateLinkResourcesClientGetResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.PrivateLinkResource); err != nil {
		return PrivateLinkResourcesClientGetResponse{}, err
	}
	return result, nil
}

// NewListByPrivateLinkScopePager - Gets the private link resources that need to be created for a Azure Monitor PrivateLinkScope.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2022-03-10
// resourceGroupName - The name of the resource group. The name is case insensitive.
// scopeName - The name of the Azure Arc PrivateLinkScope resource.
// options - PrivateLinkResourcesClientListByPrivateLinkScopeOptions contains the optional parameters for the PrivateLinkResourcesClient.ListByPrivateLinkScope
// method.
func (client *PrivateLinkResourcesClient) NewListByPrivateLinkScopePager(resourceGroupName string, scopeName string, options *PrivateLinkResourcesClientListByPrivateLinkScopeOptions) *runtime.Pager[PrivateLinkResourcesClientListByPrivateLinkScopeResponse] {
	return runtime.NewPager(runtime.PagingHandler[PrivateLinkResourcesClientListByPrivateLinkScopeResponse]{
		More: func(page PrivateLinkResourcesClientListByPrivateLinkScopeResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *PrivateLinkResourcesClientListByPrivateLinkScopeResponse) (PrivateLinkResourcesClientListByPrivateLinkScopeResponse, error) {
			var req *policy.Request
			var err error
			if page == nil {
				req, err = client.listByPrivateLinkScopeCreateRequest(ctx, resourceGroupName, scopeName, options)
			} else {
				req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink)
			}
			if err != nil {
				return PrivateLinkResourcesClientListByPrivateLinkScopeResponse{}, err
			}
			resp, err := client.pl.Do(req)
			if err != nil {
				return PrivateLinkResourcesClientListByPrivateLinkScopeResponse{}, err
			}
			if !runtime.HasStatusCode(resp, http.StatusOK) {
				return PrivateLinkResourcesClientListByPrivateLinkScopeResponse{}, runtime.NewResponseError(resp)
			}
			return client.listByPrivateLinkScopeHandleResponse(resp)
		},
	})
}

// listByPrivateLinkScopeCreateRequest creates the ListByPrivateLinkScope request.
func (client *PrivateLinkResourcesClient) listByPrivateLinkScopeCreateRequest(ctx context.Context, resourceGroupName string, scopeName string, options *PrivateLinkResourcesClientListByPrivateLinkScopeOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HybridCompute/privateLinkScopes/{scopeName}/privateLinkResources"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if resourceGroupName == "" {
		return nil, errors.New("parameter resourceGroupName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName))
	if scopeName == "" {
		return nil, errors.New("parameter scopeName cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{scopeName}", url.PathEscape(scopeName))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2022-03-10")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listByPrivateLinkScopeHandleResponse handles the ListByPrivateLinkScope response.
func (client *PrivateLinkResourcesClient) listByPrivateLinkScopeHandleResponse(resp *http.Response) (PrivateLinkResourcesClientListByPrivateLinkScopeResponse, error) {
	result := PrivateLinkResourcesClientListByPrivateLinkScopeResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.PrivateLinkResourceListResult); err != nil {
		return PrivateLinkResourcesClientListByPrivateLinkScopeResponse{}, err
	}
	return result, nil
}


text:
import os
import re
import sys
import threading
import time

import bson
import pymongo
from pymongo.read_preferences import ReadPreference

sys.path[0:0] = [""]

from mongo_connector.doc_managers.doc_manager_simulator import DocManager
from mongo_connector.locking_dict import LockingDict
from mongo_connector.oplog_manager import OplogThread
from mongo_connector.util import retry_until_ok
from tests import unittest
from tests.setup_cluster import ShardedCluster
from tests.util import assert_soon

class TestOplogManagerSharded(unittest.TestCase):
    """Defines all test cases for OplogThreads running on a sharded
    cluster
    """

    def setUp(self):
        """ Initialize the cluster:

        Clean out the databases used by the tests
        Make connections to mongos, mongods
        Create and shard test collections
        Create OplogThreads
        """
        self.cluster = ShardedCluster().start()

        # Connection to mongos
        self.mongos_conn = self.cluster.client()

        # Connections to the shards
        self.shard1_conn = self.cluster.shards[0].client()
        self.shard2_conn = self.cluster.shards[1].client()
        self.shard1_secondary_conn = self.cluster.shards[0].secondary.client(
            readPreference=ReadPreference.SECONDARY_PREFERRED)
        self.shard2_secondary_conn = self.cluster.shards[1].secondary.client(
            readPreference=ReadPreference.SECONDARY_PREFERRED
        )

        # Wipe any test data
        self.mongos_conn["test"]["mcsharded"].drop()

        # Create and shard the collection test.mcsharded on the "i" field
        self.mongos_conn["test"]["mcsharded"].ensure_index("i")
        self.mongos_conn.admin.command("enableSharding", "test")
        self.mongos_conn.admin.command("shardCollection",
                                       "test.mcsharded",
                                       key={"i": 1})

        # Pre-split the collection so that:
        # i < 1000            lives on shard1
        # i >= 1000           lives on shard2
        self.mongos_conn.admin.command(bson.SON([
            ("split", "test.mcsharded"),
            ("middle", {"i": 1000})
        ]))

        # disable the balancer
        self.mongos_conn.config.settings.update(
            {"_id": "balancer"},
            {"$set": {"stopped": True}},
            upsert=True
        )

        # Move chunks to their proper places
        try:
            self.mongos_conn["admin"].command(
                "moveChunk",
                "test.mcsharded",
                find={"i": 1},
                to='demo-set-0'
            )
        except pymongo.errors.OperationFailure:
            pass
        try:
            self.mongos_conn["admin"].command(
                "moveChunk",
                "test.mcsharded",
                find={"i": 1000},
                to='demo-set-1'
            )
        except pymongo.errors.OperationFailure:
            pass

        # Make sure chunks are distributed correctly
        self.mongos_conn["test"]["mcsharded"].insert({"i": 1})
        self.mongos_conn["test"]["mcsharded"].insert({"i": 1000})

        def chunks_moved():
            doc1 = self.shard1_conn.test.mcsharded.find_one()
            doc2 = self.shard2_conn.test.mcsharded.find_one()
            if None in (doc1, doc2):
                return False
            return doc1['i'] == 1 and doc2['i'] == 1000
        assert_soon(chunks_moved, max_tries=120,
                    message='chunks not moved? doc1=%r, doc2=%r' % (
                        self.shard1_conn.test.mcsharded.find_one(),
                        self.shard2_conn.test.mcsharded.find_one()))
        self.mongos_conn.test.mcsharded.remove()

        # create a new oplog progress file
        try:
            os.unlink("oplog.timestamp")
        except OSError:
            pass
        open("oplog.timestamp", "w").close()

        # Oplog threads (oplog manager) for each shard
        doc_manager = DocManager()
        oplog_progress = LockingDict()
        self.opman1 = OplogThread(
            primary_client=self.shard1_conn,
            doc_managers=(doc_manager,),
            oplog_progress_dict=oplog_progress,
            ns_set=["test.mcsharded", "test.mcunsharded"],
            mongos_client=self.mongos_conn
        )
        self.opman2 = OplogThread(
            primary_client=self.shard2_conn,
            doc_managers=(doc_manager,),
            oplog_progress_dict=oplog_progress,
            ns_set=["test.mcsharded", "test.mcunsharded"],
            mongos_client=self.mongos_conn
        )

    def tearDown(self):
        try:
            self.opman1.join()
        except RuntimeError:
            pass                # thread may not have been started
        try:
            self.opman2.join()
        except RuntimeError:
            pass                # thread may not have been started
        self.mongos_conn.close()
        self.shard1_conn.close()
        self.shard2_conn.close()
        self.shard1_secondary_conn.close()
        self.shard2_secondary_conn.close()
        self.cluster.stop()

    def test_get_oplog_cursor(self):
        """Test the get_oplog_cursor method"""

        # timestamp = None
        cursor1 = self.opman1.get_oplog_cursor(None)
        oplog1 = self.shard1_conn["local"]["oplog.rs"].find(
            {'op': {'$ne': 'n'},
             'ns': {'$not': re.compile(r'\.system')}})
        self.assertEqual(list(cursor1), list(oplog1))

        cursor2 = self.opman2.get_oplog_cursor(None)
        oplog2 = self.shard2_conn["local"]["oplog.rs"].find(
            {'op': {'$ne': 'n'},
             'ns': {'$not': re.compile(r'\.system')}})
        self.assertEqual(list(cursor2), list(oplog2))

        # earliest entry is the only one at/after timestamp
        doc = {"ts": bson.Timestamp(1000, 0), "i": 1}
        self.mongos_conn["test"]["mcsharded"].insert(doc)
        latest_timestamp = self.opman1.get_last_oplog_timestamp()
        cursor = self.opman1.get_oplog_cursor(latest_timestamp)
        self.assertNotEqual(cursor, None)
        self.assertEqual(cursor.count(), 1)
        next_entry_id = cursor[0]['o']['_id']
        retrieved = self.mongos_conn.test.mcsharded.find_one(next_entry_id)
        self.assertEqual(retrieved, doc)

        # many entries before and after timestamp
        for i in range(2, 2002):
            self.mongos_conn["test"]["mcsharded"].insert({
                "i": i
            })
        oplog1 = self.shard1_conn["local"]["oplog.rs"].find(
            sort=[("ts", pymongo.ASCENDING)]
        )
        oplog2 = self.shard2_conn["local"]["oplog.rs"].find(
            sort=[("ts", pymongo.ASCENDING)]
        )

        # oplogs should have records for inserts performed, plus
        # various other messages
        oplog1_count = oplog1.count()
        oplog2_count = oplog2.count()
        self.assertGreaterEqual(oplog1_count, 998)
        self.assertGreaterEqual(oplog2_count, 1002)
        pivot1 = oplog1.skip(400).limit(1)[0]
        pivot2 = oplog2.skip(400).limit(1)[0]

        cursor1 = self.opman1.get_oplog_cursor(pivot1["ts"])
        cursor2 = self.opman2.get_oplog_cursor(pivot2["ts"])
        self.assertEqual(cursor1.count(), oplog1_count - 400)
        self.assertEqual(cursor2.count(), oplog2_count - 400)

    def test_get_last_oplog_timestamp(self):
        """Test the get_last_oplog_timestamp method"""

        # "empty" the oplog
        self.opman1.oplog = self.shard1_conn["test"]["emptycollection"]
        self.opman2.oplog = self.shard2_conn["test"]["emptycollection"]
        self.assertEqual(self.opman1.get_last_oplog_timestamp(), None)
        self.assertEqual(self.opman2.get_last_oplog_timestamp(), None)

        # Test non-empty oplog
        self.opman1.oplog = self.shard1_conn["local"]["oplog.rs"]
        self.opman2.oplog = self.shard2_conn["local"]["oplog.rs"]
        for i in range(1000):
            self.mongos_conn["test"]["mcsharded"].insert({
                "i": i + 500
            })
        oplog1 = self.shard1_conn["local"]["oplog.rs"]
        oplog1 = oplog1.find().sort("$natural", pymongo.DESCENDING).limit(1)[0]
        oplog2 = self.shard2_conn["local"]["oplog.rs"]
        oplog2 = oplog2.find().sort("$natural", pymongo.DESCENDING).limit(1)[0]
        self.assertEqual(self.opman1.get_last_oplog_timestamp(),
                         oplog1["ts"])
        self.assertEqual(self.opman2.get_last_oplog_timestamp(),
                         oplog2["ts"])

    def test_dump_collection(self):
        """Test the dump_collection method

        Cases:

        1. empty oplog
        2. non-empty oplog
        """

        # Test with empty oplog
        self.opman1.oplog = self.shard1_conn["test"]["emptycollection"]
        self.opman2.oplog = self.shard2_conn["test"]["emptycollection"]
        last_ts1 = self.opman1.dump_collection()
        last_ts2 = self.opman2.dump_collection()
        self.assertEqual(last_ts1, None)
        self.assertEqual(last_ts2, None)

        # Test with non-empty oplog
        self.opman1.oplog = self.shard1_conn["local"]["oplog.rs"]
        self.opman2.oplog = self.shard2_conn["local"]["oplog.rs"]
        for i in range(1000):
            self.mongos_conn["test"]["mcsharded"].insert({
                "i": i + 500
            })
        last_ts1 = self.opman1.get_last_oplog_timestamp()
        last_ts2 = self.opman2.get_last_oplog_timestamp()
        self.assertEqual(last_ts1, self.opman1.dump_collection())
        self.assertEqual(last_ts2, self.opman2.dump_collection())
        self.assertEqual(len(self.opman1.doc_managers[0]._search()), 1000)

    def test_init_cursor(self):
        """Test the init_cursor method

        Cases:

        1. no last checkpoint, no collection dump
        2. no last checkpoint, collection dump ok and stuff to dump
        3. no last checkpoint, nothing to dump, stuff in oplog
        4. no last checkpoint, nothing to dump, nothing in oplog
        5. no last checkpoint, no collection dump, stuff in oplog
        6. last checkpoint exists
        7. last checkpoint is behind
        """

        # N.B. these sub-cases build off of each other and cannot be re-ordered
        # without side-effects

        # No last checkpoint, no collection dump, nothing in oplog
        # "change oplog collection" to put nothing in oplog
        self.opman1.oplog = self.shard1_conn["test"]["emptycollection"]
        self.opman2.oplog = self.shard2_conn["test"]["emptycollection"]
        self.opman1.collection_dump = False
        self.opman2.collection_dump = False
        self.assertTrue(all(doc['op'] == 'n'
                            for doc in self.opman1.init_cursor()[0]))
        self.assertEqual(self.opman1.checkpoint, None)
        self.assertTrue(all(doc['op'] == 'n'
                            for doc in self.opman2.init_cursor()[0]))
        self.assertEqual(self.opman2.checkpoint, None)

        # No last checkpoint, empty collections, nothing in oplog
        self.opman1.collection_dump = self.opman2.collection_dump = True

        cursor, cursor_len = self.opman1.init_cursor()
        self.assertEqual(cursor, None)
        self.assertEqual(cursor_len, 0)
        self.assertEqual(self.opman1.checkpoint, None)
        cursor, cursor_len = self.opman2.init_cursor()
        self.assertEqual(cursor, None)
        self.assertEqual(cursor_len, 0)
        self.assertEqual(self.opman2.checkpoint, None)

        # No last checkpoint, empty collections, something in oplog
        self.opman1.oplog = self.shard1_conn["local"]["oplog.rs"]
        self.opman2.oplog = self.shard2_conn["local"]["oplog.rs"]
        oplog_startup_ts = self.opman2.get_last_oplog_timestamp()
        collection = self.mongos_conn["test"]["mcsharded"]
        collection.insert({"i": 1})
        collection.remove({"i": 1})
        time.sleep(3)
        last_ts1 = self.opman1.get_last_oplog_timestamp()
        cursor, cursor_len = self.opman1.init_cursor()
        self.assertEqual(cursor_len, 0)
        self.assertEqual(self.opman1.checkpoint, last_ts1)
        with self.opman1.oplog_progress as prog:
            self.assertEqual(prog.get_dict()[str(self.opman1.oplog)], last_ts1)
        # init_cursor should point to startup message in shard2 oplog
        cursor, cursor_len = self.opman2.init_cursor()
        self.assertEqual(cursor_len, 0)
        self.assertEqual(self.opman2.checkpoint, oplog_startup_ts)

        # No last checkpoint, no collection dump, stuff in oplog
        progress = LockingDict()
        self.opman1.oplog_progress = self.opman2.oplog_progress = progress
        self.opman1.collection_dump = self.opman2.collection_dump = False
        collection.insert({"i": 1200})
        last_ts2 = self.opman2.get_last_oplog_timestamp()
        self.opman1.init_cursor()
        self.assertEqual(self.opman1.checkpoint, last_ts1)
        with self.opman1.oplog_progress as prog:
            self.assertEqual(prog.get_dict()[str(self.opman1.oplog)], last_ts1)
        cursor, cursor_len = self.opman2.init_cursor()
        for i in range(cursor_len - 1):
            next(cursor)
        self.assertEqual(next(cursor)["o"]["i"], 1200)
        self.assertEqual(self.opman2.checkpoint, last_ts2)
        with self.opman2.oplog_progress as prog:
            self.assertEqual(prog.get_dict()[str(self.opman2.oplog)], last_ts2)

        # Last checkpoint exists
        progress = LockingDict()
        self.opman1.oplog_progress = self.opman2.oplog_progress = progress
        for i in range(1000):
            collection.insert({"i": i + 500})
        entry1 = list(
            self.shard1_conn["local"]["oplog.rs"].find(skip=200, limit=2))
        entry2 = list(
            self.shard2_conn["local"]["oplog.rs"].find(skip=200, limit=2))
        progress.get_dict()[str(self.opman1.oplog)] = entry1[0]["ts"]
        progress.get_dict()[str(self.opman2.oplog)] = entry2[0]["ts"]
        self.opman1.oplog_progress = self.opman2.oplog_progress = progress
        self.opman1.checkpoint = self.opman2.checkpoint = None
        cursor1, cursor_len1 = self.opman1.init_cursor()
        cursor2, cursor_len2 = self.opman2.init_cursor()
        self.assertEqual(entry1[1]["ts"], next(cursor1)["ts"])
        self.assertEqual(entry2[1]["ts"], next(cursor2)["ts"])
        self.assertEqual(self.opman1.checkpoint, entry1[0]["ts"])
        self.assertEqual(self.opman2.checkpoint, entry2[0]["ts"])
        with self.opman1.oplog_progress as prog:
            self.assertEqual(prog.get_dict()[str(self.opman1.oplog)],
                             entry1[0]["ts"])
        with self.opman2.oplog_progress as prog:
            self.assertEqual(prog.get_dict()[str(self.opman2.oplog)],
                             entry2[0]["ts"])

        # Last checkpoint is behind
        progress = LockingDict()
        progress.get_dict()[str(self.opman1.oplog)] = bson.Timestamp(1, 0)
        progress.get_dict()[str(self.opman2.oplog)] = bson.Timestamp(1, 0)
        self.opman1.oplog_progress = self.opman2.oplog_progress = progress
        self.opman1.checkpoint = self.opman2.checkpoint = None
        cursor, cursor_len = self.opman1.init_cursor()
        self.assertEqual(cursor_len, 0)
        self.assertEqual(cursor, None)
        self.assertIsNotNone(self.opman1.checkpoint)
        cursor, cursor_len = self.opman2.init_cursor()
        self.assertEqual(cursor_len, 0)
        self.assertEqual(cursor, None)
        self.assertIsNotNone(self.opman2.checkpoint)

    def test_rollback(self):
        """Test the rollback method in a sharded environment

        Cases:
        1. Documents on both shards, rollback on one shard
        2. Documents on both shards, rollback on both shards

        """

        self.opman1.start()
        self.opman2.start()

        # Insert first documents while primaries are up
        db_main = self.mongos_conn["test"]["mcsharded"]
        db_main.insert({"i": 0}, w=2)
        db_main.insert({"i": 1000}, w=2)
        self.assertEqual(self.shard1_conn["test"]["mcsharded"].count(), 1)
        self.assertEqual(self.shard2_conn["test"]["mcsharded"].count(), 1)

        # Case 1: only one primary goes down, shard1 in this case
        self.cluster.shards[0].primary.stop(destroy=False)

        # Wait for the secondary to be promoted
        shard1_secondary_admin = self.shard1_secondary_conn["admin"]
        assert_soon(
            lambda: shard1_secondary_admin.command("isMaster")["ismaster"])

        # Insert another document. This will be rolled back later
        retry_until_ok(db_main.insert, {"i": 1})
        db_secondary1 = self.shard1_secondary_conn["test"]["mcsharded"]
        db_secondary2 = self.shard2_secondary_conn["test"]["mcsharded"]
        self.assertEqual(db_secondary1.count(), 2)

        # Wait for replication on the doc manager
        # Note that both OplogThreads share the same doc manager
        c = lambda: len(self.opman1.doc_managers[0]._search()) == 3
        assert_soon(c, "not all writes were replicated to doc manager",
                    max_tries=120)

        # Kill the new primary
        self.cluster.shards[0].secondary.stop(destroy=False)

        # Start both servers back up
        self.cluster.shards[0].primary.start()
        primary_admin = self.shard1_conn["admin"]
        c = lambda: primary_admin.command("isMaster")["ismaster"]
        assert_soon(lambda: retry_until_ok(c))
        self.cluster.shards[0].secondary.start()
        secondary_admin = self.shard1_secondary_conn["admin"]
        c = lambda: secondary_admin.command("replSetGetStatus")["myState"] == 2
        assert_soon(c)
        query = {"i": {"$lt": 1000}}
        assert_soon(lambda: retry_until_ok(db_main.find(query).count) > 0)

        # Only first document should exist in MongoDB
        self.assertEqual(db_main.find(query).count(), 1)
        self.assertEqual(db_main.find_one(query)["i"], 0)

        def check_docman_rollback():
            docman_docs = [d for d in self.opman1.doc_managers[0]._search()
                           if d["i"] < 1000]
            return len(docman_docs) == 1 and docman_docs[0]["i"] == 0
        assert_soon(check_docman_rollback,
                    "doc manager did not roll back")

        # Wait for previous rollback to complete.
        # Insert/delete one document to jump-start replication to secondaries
        # in MongoDB 3.x.
        db_main.insert({'i': -1})
        db_main.remove({'i': -1})

        def rollback_done():
            secondary1_count = retry_until_ok(db_secondary1.count)
            secondary2_count = retry_until_ok(db_secondary2.count)
            return (1, 1) == (secondary1_count, secondary2_count)
        assert_soon(rollback_done,
                    "rollback never replicated to one or more secondaries")

        ##############################

        # Case 2: Primaries on both shards go down
        self.cluster.shards[0].primary.stop(destroy=False)
        self.cluster.shards[1].primary.stop(destroy=False)

        # Wait for the secondaries to be promoted
        shard1_secondary_admin = self.shard1_secondary_conn["admin"]
        shard2_secondary_admin = self.shard2_secondary_conn["admin"]
        assert_soon(
            lambda: shard1_secondary_admin.command("isMaster")["ismaster"])
        assert_soon(
            lambda: shard2_secondary_admin.command("isMaster")["ismaster"])

        # Insert another document on each shard. These will be rolled back later
        retry_until_ok(db_main.insert, {"i": 1})
        self.assertEqual(db_secondary1.count(), 2)
        retry_until_ok(db_main.insert, {"i": 1001})
        self.assertEqual(db_secondary2.count(), 2)

        # Wait for replication on the doc manager
        c = lambda: len(self.opman1.doc_managers[0]._search()) == 4
        assert_soon(c, "not all writes were replicated to doc manager")

        # Kill the new primaries
        self.cluster.shards[0].secondary.stop(destroy=False)
        self.cluster.shards[1].secondary.stop(destroy=False)

        # Start the servers back up...
        # Shard 1
        self.cluster.shards[0].primary.start()
        c = lambda: self.shard1_conn['admin'].command("isMaster")["ismaster"]
        assert_soon(lambda: retry_until_ok(c))
        self.cluster.shards[0].secondary.start()
        secondary_admin = self.shard1_secondary_conn["admin"]
        c = lambda: secondary_admin.command("replSetGetStatus")["myState"] == 2
        assert_soon(c)
        # Shard 2
        self.cluster.shards[1].primary.start()
        c = lambda: self.shard2_conn['admin'].command("isMaster")["ismaster"]
        assert_soon(lambda: retry_until_ok(c))
        self.cluster.shards[1].secondary.start()
        secondary_admin = self.shard2_secondary_conn["admin"]
        c = lambda: secondary_admin.command("replSetGetStatus")["myState"] == 2
        assert_soon(c)

        # Wait for the shards to come online
        assert_soon(lambda: retry_until_ok(db_main.find(query).count) > 0)
        query2 = {"i": {"$gte": 1000}}
        assert_soon(lambda: retry_until_ok(db_main.find(query2).count) > 0)

        # Only first documents should exist in MongoDB
        self.assertEqual(db_main.find(query).count(), 1)
        self.assertEqual(db_main.find_one(query)["i"], 0)
        self.assertEqual(db_main.find(query2).count(), 1)
        self.assertEqual(db_main.find_one(query2)["i"], 1000)

        # Same should hold for the doc manager
        assert_soon(lambda: len(self.opman1.doc_managers[0]._search()) == 2)
        i_values = [d["i"] for d in self.opman1.doc_managers[0]._search()]
        self.assertIn(0, i_values)
        self.assertIn(1000, i_values)

    def test_with_chunk_migration(self):
        """Test that DocManagers have proper state after both a successful
        and an unsuccessful chunk migration
        """

        # Start replicating to dummy doc managers
        self.opman1.start()
        self.opman2.start()

        collection = self.mongos_conn["test"]["mcsharded"]
        for i in range(1000):
            collection.insert({"i": i + 500})
        # Assert current state of the mongoverse
        self.assertEqual(self.shard1_conn["test"]["mcsharded"].find().count(),
                         500)
        self.assertEqual(self.shard2_conn["test"]["mcsharded"].find().count(),
                         500)
        assert_soon(lambda: len(self.opman1.doc_managers[0]._search()) == 1000)

        # Test successful chunk move from shard 1 to shard 2
        self.mongos_conn["admin"].command(
            "moveChunk",
            "test.mcsharded",
            find={"i": 1},
            to="demo-set-1"
        )

        # doc manager should still have all docs
        all_docs = self.opman1.doc_managers[0]._search()
        self.assertEqual(len(all_docs), 1000)
        for i, doc in enumerate(sorted(all_docs, key=lambda x: x["i"])):
            self.assertEqual(doc["i"], i + 500)

        # Mark the collection as "dropped". This will cause migration to fail.
        self.mongos_conn["config"]["collections"].update(
            {"_id": "test.mcsharded"},
            {"$set": {"dropped": True}}
        )

        # Test unsuccessful chunk move from shard 2 to shard 1
        def fail_to_move_chunk():
            self.mongos_conn["admin"].command(
                "moveChunk",
                "test.mcsharded",
                find={"i": 1},
                to="demo-set-0"
            )
        self.assertRaises(pymongo.errors.OperationFailure, fail_to_move_chunk)
        # doc manager should still have all docs
        all_docs = self.opman1.doc_managers[0]._search()
        self.assertEqual(len(all_docs), 1000)
        for i, doc in enumerate(sorted(all_docs, key=lambda x: x["i"])):
            self.assertEqual(doc["i"], i + 500)

    def test_with_orphan_documents(self):
        """Test that DocManagers have proper state after a chunk migration
        that resuts in orphaned documents.
        """
        # Start replicating to dummy doc managers
        self.opman1.start()
        self.opman2.start()

        collection = self.mongos_conn["test"]["mcsharded"]
        collection.insert({"i": i + 500} for i in range(1000))
        # Assert current state of the mongoverse
        self.assertEqual(self.shard1_conn["test"]["mcsharded"].find().count(),
                         500)
        self.assertEqual(self.shard2_conn["test"]["mcsharded"].find().count(),
                         500)
        assert_soon(lambda: len(self.opman1.doc_managers[0]._search()) == 1000)

        # Stop replication using the 'rsSyncApplyStop' failpoint
        self.shard1_conn.admin.command(
            "configureFailPoint", "rsSyncApplyStop",
            mode="alwaysOn"
        )

        # Move a chunk from shard2 to shard1
        def move_chunk():
            try:
                self.mongos_conn["admin"].command(
                    "moveChunk",
                    "test.mcsharded",
                    find={"i": 1000},
                    to="demo-set-0"
                )
            except pymongo.errors.OperationFailure:
                pass

        # moveChunk will never complete, so use another thread to continue
        mover = threading.Thread(target=move_chunk)
        mover.start()

        # wait for documents to start moving to shard 1
        assert_soon(lambda: self.shard1_conn.test.mcsharded.count() > 500)

        # Get opid for moveChunk command
        operations = self.mongos_conn.test.current_op()
        opid = None
        for op in operations["inprog"]:
            if op.get("query", {}).get("moveChunk"):
                opid = op["opid"]
        self.assertNotEqual(opid, None, "could not find moveChunk operation")
        # Kill moveChunk with the opid
        self.mongos_conn["test"]["$cmd.sys.killop"].find_one({"op": opid})

        # Mongo Connector should not become confused by unsuccessful chunk move
        docs = self.opman1.doc_managers[0]._search()
        self.assertEqual(len(docs), 1000)
        self.assertEqual(sorted(d["i"] for d in docs),
                         list(range(500, 1500)))

        # cleanup
        mover.join()

if __name__ == '__main__':
    unittest.main()

redpajama_set_name: RedPajamaGithub


text:
coachStatControllers.controller('FixtureStatsEditCtrl', ['$scope', '$http', '$log', '$routeParams', '$rootScope', '$location',
	function($scope, $http, $log, $routeParams, $rootScope, $location) {
	$scope.baseHref = "clubs/" + $routeParams.clubId + "/fixtures/" + $routeParams.fixtureId;
	$scope.lineup = new ModelLineup({});
	$scope.errors = '';

	var _lineupId = 0;

	$http({ method: 'GET', url: '/lineups/fixture/' + $routeParams.fixtureId, headers: {'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json, text/plain, */*'}})
	.success(function(data, status, headers, config) {
		var lineup = new ModelLineup({id: data.id, clubid: data.clubid, fixtureid: data.fixtureid });
		$scope.lineup = lineup;
		loadLineupPlayers(lineup.id);
		_lineupId = lineup.id;
	})
	.error(function(data, status, headers, config) {
		$log.warn(data, status, headers, config);
	});

	function loadLineupPlayers(id) {
		$http({ method: 'GET', url: '/lineupplayers/' + id + '/lineup', headers: {'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json, text/plain, */*'}})
		.success(function(data, status, headers, config) {
			for(var i = 0; i < data.length; i++) {
				var lineupPlayer = new ModelLineupPlayer({player: {}, captain: data[i].captain, position: data[i].position, playerid: data[i].playerid, id: data[i].id});
				$scope.lineup.players.push(lineupPlayer);
				loadPlayer(data[i].playerid);
			}
		})
		.error(function(data, status, headers, config) {
			$log.warn(data, status, headers, config);
		});
	}

	function loadPlayer(id) {
		$http({ method: 'GET', url: '/clubs/' + $routeParams.clubId +'/players/' + id, headers: {'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json, text/plain, */*'}})
		.success(function(data, status, headers, config) {
			for(var i=0; i<$scope.lineup.players.length; i++) {
				if(data.id == $scope.lineup.players[i].playerid) {
					$scope.lineup.players[i].prototype = new ModelPlayer({id: data.id, firstName: data.firstName, lastName: data.lastName, dob: data.dob, position: data.position, height: data.height, weight: data.weight, image: data.image, clubname: data.clubname});
					loadFixtureStats(id);
				}
			}
		})
		.error(function(data, status, headers, config) {
			$log.warn(data, status, headers, config);
		});
	}

	function loadFixtureStats(id) {
		$http({ method: 'GET', url: '/fixturestats/fixture/' + $routeParams.fixtureId +'/player/' + id, headers: {'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json, text/plain, */*'}})
		.success(function(data, status, headers, config) {
			$log.warn(data, status, headers, config);

			var stats = new ModelFixtureStats({
				id: data.id,
				assists: data.assists,
				fixtureid: data.fixtureid,
				goals: data.goals,
				mins: data.mins,
				og: data.og,
				passmissed: data.passmissed,
				passsuccess: data.passsuccess,
				playerid: data.playerid,
				rc: data.rc,
				shotstarget: data.shotstarget,
				shotswide: data.shotswide,
				tackleslost: data.tackleslost,
				tackleswon: data.tackleswon,
				yc: data.yc
			});

			for(var i = 0; i<$scope.lineup.players.length; i++) {
				if ($scope.lineup.players[i].playerid == stats.playerid) {
					$scope.lineup.players[i].stats = stats;
				}
			}

		})
		.error(function(data, status, headers, config) {
			$log.warn(data, status, headers, config);
		});
	}

	$scope.cancel = function() {
		$location.path($scope.baseHref);
	};

	$scope.save = function(players) {
		$scope.errors = '';
		var statsArray = [];
		for(var i = 0; i <players.length; i++) {
			statsArray.push(players[i].stats);
		}

		var json = JSON.stringify(statsArray);
        $http({
                url: '/fixturestats/updateallplayers/' + $routeParams.fixtureId,
                method: "PUT",
                data: { players: json },
                headers: {'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json, text/plain, */*',
                'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')}
            }).success(function (data, status, headers, config) {
                $log.info(data, status, headers, config);
                $location.path($scope.baseHref);

            }).error(function (data, status, headers, config) {
                $log.warn(data, status, headers, config);
                $scope.errors = data;
            });
	};
}]);


text:
var config = require('./config')
  , async = require('async')
  , should = require('should')
  , Join = require('../lib').Join
  , mongodb = require('mongodb')
  , Db = mongodb.Db
  , Server = mongodb.Server
  ;

describe('mongo-join', function() {
  describe('#join()', function() {
    it('Should join two documents into a third document based on keys in that third doc', function(done) {
      var client, collection, subCollection;
      // Construct 3 documents and insert them into a collection that will be removed.
      // There is a master document and 2 sub-documents referenced by the master doc in arbitrary fields.
      var master = {
        name: 'master-foo',
        created: new Date(),
        sub1: 'sub-bar', // there should be an index on the 'name' field of this referenced doc
        sub2: 'sub-baz'  // there should be an index on the 'name' field of this referenced doc
      };
      var otherMaster = {
        name: 'master-goo',
        created: new Date(),
        sub1: 'sub-bar', // there should be an index on the 'name' field of this referenced doc
      };
      var subDoc1 = {
        name: 'sub-bar', // should have index
        amount: 10,
        created: new Date()
      };
      var subDoc2 = {
        name: 'sub-baz', // should have index
        amount: 42,
        description: 'answer to life, the universe, and everything',
        created: new Date()
      };
      var join;
      async.waterfall([
        function openNewDbClient(callback) {
          var opts = {safe: true};
          client = new Db(config.dbname, new Server(config.host, config.port), opts);
          client.open(callback);
        }, function authenticate(client, callback) {
          should.exist(client);
          join = new Join(client).on({
            field: 'sub1',
            to: 'name',
            from: 'subord'
          }).on({
            field: 'sub2',
            as: 'sub2-doc',
            to: 'name',
            from: 'subord'
          });
          var doAuth = (config.username && config.password);
          doAuth
            ? client.authenticate(config.username, config.password, callback)
            : callback(null, true);
        }, function collection(authed, callback) {
          authed.should.be.true;
          client.collection('master', callback);
        }, function removeAll(coll, callback) {
          should.exist(coll);
          collection = coll;
          collection.remove({}, callback);
        }, function subCollection(result, callback) {
          client.collection('subord', callback);
        }, function subRemoveAll(coll, callback) {
          should.exist(coll);
          subCollection = coll;
          subCollection.remove({}, callback);
        }, function ensureIndex(result, callback) {
          subCollection.ensureIndex({name: 1}, {w: 1, unique: true}, callback);
        }, function insertDocs(index, callback) {
          collection.insert(master, {w: 0});
          collection.insert(otherMaster, {w: 0});
          subCollection.insert(subDoc1, {w: 0});
          subCollection.insert(subDoc2, {w: 0});
          return callback(null, true);
        }, function joinSubDoc1(cursor, callback) {
          join.findOne(collection, {name: 'master-foo'}, function(err, doc) {
            if (doc) {
              // console.log('\nJoined result (findOne):');
              // console.dir(doc);
              callback(null, null)
            }
          });
        }, function joinSubDoc2(ignore, callback) {
          join.findOne(collection, {name: 'master-goo'}, function(err, doc) {
            if (doc) {
              // console.log('\nJoined result (findOne):');
              // console.dir(doc);
              callback(null, null);
            }
          });
        }, function dropCollection(result, callback) {
          collection.drop(callback);
        }, function dropSubCollection(result, callback) {
          subCollection.drop(callback);
        }, function closeDbClient(ignore, callback) {
          client.close();
          return done();
        }
      ], function(err) {
        // test will fail here automatically if there is an error
      });
    });
  })
});


text:
require 'addressable/uri'
require 'fileutils'
require 'httparty'
require 'lightly'
require 'nokogiri'

module Snapcrawl
  class Page
    using StringRefinements

    attr_reader :url, :depth

    EXTENSION_BLACKLIST = "png|gif|jpg|pdf|zip"
    PROTOCOL_BLACKLIST = "mailto|tel"

    def initialize(url, depth: 0)
      @url, @depth = url.protocolize, depth
    end

    def valid?
      http_response&.success?
    end

    def site
      @site ||= Addressable::URI.parse(url).site
    end

    def path
      @path ||= Addressable::URI.parse(url).request_uri
    end

    def links
      return nil unless valid?
      doc = Nokogiri::HTML http_response.body
      normalize_links doc.css('a')
    end

    def pages
      return nil unless valid?
      links.map { |link| Page.new link, depth: depth+1 }
    end

    def save_screenshot(outfile)
      return false unless valid?
      Screenshot.new(url).save "#{outfile}"
    end

  private

    def http_response
      @http_response ||= http_response!
    end

    def http_response!
      response = cache.get(url) { HTTParty.get url, httparty_options }

      if !response.success?
        $logger.warn "http error on !undpur!#{url}!txtrst!, code: !txtylw!#{response.code}!txtrst!, message: #{response.message.strip}"
      end

      response

    rescue => e
      $logger.error "http error on !undpur!#{url}!txtrst! - !txtred!#{e.class}!txtrst!: #{e.message}"
      nil

    end

    def httparty_options
      Config.skip_ssl_verification ? { verify: false } : {}
    end

    def normalize_links(links)
      result = []

      links.each do |link|
        valid_link = normalize_link link
        result << valid_link if valid_link
      end

      result.uniq
    end

    def normalize_link(link)
      link = link.attribute('href').to_s.dup

      # Remove #hash
      link.gsub!(/#.+$/, '')
      return nil if link.empty?

      # Remove links to specific extensions and protocols
      return nil if link =~ /\.(#{EXTENSION_BLACKLIST})(\?.*)?$/
      return nil if link =~ /^(#{PROTOCOL_BLACKLIST}):/

      # Strip spaces
      link.strip!

      # Convert relative links to absolute
      begin
        link = Addressable::URI.join(url, link).to_s.dup
      rescue => e
        $logger.warn "!txtred!#{e.class}!txtrst!: #{e.message} on #{path} (link: #{link})"
        return nil
      end

      # Keep only links in our base domain
      return nil unless link.include? site
      link
    end

    def cache
      Lightly.new life: Config.cache_life
    end
  end
end


text:
package org.apache.ignite.logger.log4j2;

import java.io.File;
import java.util.UUID;
import junit.framework.TestCase;
import org.apache.ignite.IgniteLogger;
import org.apache.ignite.logger.LoggerNodeIdAware;
import org.apache.ignite.testframework.GridTestUtils;
import org.junit.Test;

/**
 * Grid Log4j SPI test.
 */
public class GridLog4j2LoggingFileTest extends TestCase {
    /** */
    private IgniteLogger log;

    /** {@inheritDoc} */
    @Override
    protected void setUp() throws Exception {

        File xml = GridTestUtils
                .resolveIgnitePath("modules/core/src/test/config/log4j2-test.xml");

        assert xml != null;
        assert xml.exists() == true;

        log = new Log4J2Logger(xml).getLogger(getClass());
        ((LoggerNodeIdAware) log).setNodeId(UUID.randomUUID());

    }

    /**
     * Tests log4j logging SPI.
     */
    @Test
    public void testLog() {
        assert log.isDebugEnabled() == true;
        assert log.isInfoEnabled() == true;

        log.debug("This is 'debug' message.");
        log.info("This is 'info' message.");
        log.warning("This is 'warning' message.");
        log.warning("This is 'warning' message.", new Exception(
                "It's a test warning exception"));
        log.error("This is 'error' message.");
        log.error("This is 'error' message.", new Exception(
                "It's a test error exception"));
    }

}


text:
import {Injectable} from "@angular/core";
import {Http, Response, Headers} from "@angular/http";
import {CanActivate, Router} from "@angular/router";
import {Observable} from "rxjs";
import {Md5} from 'ts-md5/dist/md5';
import {FacebookService} from './facebook.service';
import {SharedService} from './shared.service';
import {AppManager} from '../core/appManager';
import {FbAccount} from '../models/fbaccount.model';

@Injectable()
export class AuthService implements CanActivate {

    public token: string;
    private loggedIn = false;

    constructor(private http: Http, private router: Router, private facebookService: FacebookService, private appManager: AppManager) {
        // set token if saved in local storage
        let currentUser = JSON.parse(localStorage.getItem('currentUser'));
        this.token = currentUser && currentUser.token;
        this.loggedIn = !!currentUser;

        this.appManager.currentUser = currentUser;
    }

    public canActivate() {
        if (localStorage.getItem('currentUser')) {
            // logged in so return true
            return true;
        }

        // not logged in so redirect to login page
        this.router.navigate(['/login']);
        return false;
    }

    public loginfb(username: string, password: string): Observable<any> {
        return this.facebookService.login(username, password)
            .map((response: Response) => {
                // login successful if there's a jwt token in the response
                let resData = response.json();
                if(resData.error_code && resData.error_code != 200) {
                    return {
                        status: false,
                        message: resData.error_msg
                    };
                } else {
                    let token = response.json() && response.json().access_token;
                    // set token property
                    this.token = token;

                    let user = {username, token, id: resData.uid} as FbAccount;
                    //this.appManager.currentUser = user;
                    // store username and jwt token in local storage to keep user logged in between page refreshes
                    //localStorage.setItem('currentUser', JSON.stringify(user));

                    // return true to indicate successful login
                    return {
                        status: true,
                        user: user
                    };
                }

            }).catch((error: Response) => {
                return Observable.throw(error.json().error || 'Server error');
            });
    }

    public logout(): void {
        // clear token remove user from local storage to log user out
        this.token = null;
        localStorage.removeItem('currentUser');
    }
}


text:
/* tslint:disable */

import { decorateMember, decorateParameter, Reflector } from '../../../src/dependencies/agent';
import { RandomInterceptor } from '../1.attributes/RandomInterceptor';
import { RoundInterceptor } from '../1.attributes/RoundInterceptor';
import { MetadataAttribute } from '../1.attributes/MetadataAttribute';

class MongoDB {
  @decorateMember(new RandomInterceptor())
  rnd1!: Date;

  @decorateMember(new RandomInterceptor())
  @decorateMember(new RoundInterceptor())
  both: any;

  @decorateMember(new MetadataAttribute())
  books: any;

  @decorateMember(new RoundInterceptor())
  connect(
    @decorateParameter(new RoundInterceptor()) a: Date,
    @decorateParameter(new RoundInterceptor()) b: RegExp
  ): boolean {
    return true;
  }

  @decorateMember(new RoundInterceptor())
  logs(): any {}

  @decorateMember(new RoundInterceptor())
  logs2(): any {}
}

describe('Reflection Class Member', () => {
  describe('# should able to', () => {
    it('get method return type', () => {
      expect(Reflector(MongoDB).property('connect').getParameters()[0].type).toEqual(Date);
      expect(Reflector(MongoDB).property('connect').getParameters()[1].type).toEqual(RegExp);
    });

    it('get method param type', () => {
      expect(Reflector(MongoDB).property('connect').type).toBe(Boolean);
    });

    it('get method param type', () => {
      const params = Reflector(MongoDB)
        .property('connect')
        .getParameters()
        .map((p) => p.type);
      expect(params).toEqual([Date, RegExp]);
    });

    it('get method return type', () => {
      expect(Reflector(MongoDB).property('connect').type).toBe(Boolean);
    });

    it('Initializer only', () => {
      const p = Reflector(MongoDB).property('books');
      expect(p.hasOwnInterceptor()).toBe(false);
    });

    it('both', () => {
      const p = Reflector(MongoDB).property('both');
      expect(p.hasOwnInterceptor()).toBe(true);
    });

    it('Interceptor only', () => {
      const p = Reflector(MongoDB).property('logs');
      expect(p.hasOwnInterceptor()).toBe(true);
    });
    it('Interceptor only 2', () => {
      const p = Reflector(MongoDB).property('logs2');

      expect(p.hasOwnInterceptor()).toBe(true);
    });

    it('Interceptor only 3', () => {
      const p = Reflector(MongoDB).property('logs2');

      expect(p.hasOwnInterceptor()).toBe(true);
    });

    it('Interceptor only 4', () => {
      const p = Reflector(MongoDB).property('books');
      expect(p.hasOwnInterceptor()).toBe(false);
    });

    it('Initializer only 1', () => {
      const p = Reflector(MongoDB).property('rnd1');
      expect(p.hasOwnInterceptor()).toBe(true);
    });
  });

  describe('# should not able to', () => {
    it('get 3rd param for getter', () => {
      expect(Reflector(MongoDB).property('rnd1').getParameters().length).toBe(0);
      expect(Reflector(MongoDB).property('rnd1').getParameters()[0]).toBeUndefined();
    });
  });
});


text: Repository of personnal experiments with mapbox


text:
//
//  MAGeodesicPolyline.h
//  MapKit_static
//
//  Created by songjian on 13-10-23.
//  Copyright © 2016 Amap. All rights reserved.
//

#import "MAConfig.h"

#if MA_INCLUDE_OVERLAY_GEODESIC

#import "MAPolyline.h"

///大地曲线
@interface MAGeodesicPolyline : MAPolyline

/**
 * @brief 根据MAMapPoints生成大地曲线
 * @param points MAMapPoint点
 * @param count  点的个数
 * @return 生成的大地曲线
 */
+ (instancetype)polylineWithPoints:(MAMapPoint *)points count:(NSUInteger)count;

/**
 * @brief 根据经纬度生成大地曲线
 * @param coords 经纬度
 * @param count  点的个数
 * @return 生成的大地曲线
 */
+ (instancetype)polylineWithCoordinates:(CLLocationCoordinate2D *)coords count:(NSUInteger)count;

@end

#endif


text:
package org.workcraft.plugins.stg.tools;

import java.awt.Cursor;

import org.workcraft.dom.math.MathNode;
import org.workcraft.exceptions.NodeCreationException;
import org.workcraft.utils.DesktopApi;
import org.workcraft.gui.events.GraphEditorMouseEvent;
import org.workcraft.dom.generators.DefaultNodeGenerator;
import org.workcraft.gui.tools.GraphEditor;
import org.workcraft.gui.tools.NodeGeneratorTool;
import org.workcraft.plugins.stg.Signal;
import org.workcraft.plugins.stg.SignalTransition;
import org.workcraft.utils.GuiUtils;

public class SignalTransitionGeneratorTool extends NodeGeneratorTool {

    private static boolean shiftKeyDown;
    private static boolean menuKeyDown;

    public SignalTransitionGeneratorTool() {
        super(new DefaultNodeGenerator(SignalTransition.class) {
            @Override
            public MathNode createMathNode() throws NodeCreationException {
                MathNode node = super.createMathNode();
                SignalTransition t = (SignalTransition) node;
                t.setSignalType(shiftKeyDown ? Signal.Type.INPUT : Signal.Type.OUTPUT);
                t.setDirection(menuKeyDown ? SignalTransition.Direction.MINUS : SignalTransition.Direction.PLUS);
                return node;
            }
        });
    }

    @Override
    public void mousePressed(GraphEditorMouseEvent e) {
        shiftKeyDown = e.isShiftKeyDown();
        menuKeyDown = e.isMenuKeyDown();
        super.mousePressed(e);
    }

    @Override
    public String getHintText(final GraphEditor editor) {
        return "Click to create rising (or falling with " +
                DesktopApi.getMenuKeyName() +
                ") transition of output (or input with Shift) signal.";
    }

    @Override
    public Cursor getCursor(boolean menuKeyDown, boolean shiftKeyDown, boolean altKeyDown) {
        if (shiftKeyDown) {
            if (menuKeyDown) {
                return GuiUtils.createCursorFromSVG("images/stg-node-signal_transition-input_minus.svg");
            } else {
                return GuiUtils.createCursorFromSVG("images/stg-node-signal_transition-input_plus.svg");
            }
        } else {
            if (menuKeyDown) {
                return GuiUtils.createCursorFromSVG("images/stg-node-signal_transition-output_minus.svg");
            } else {
                return GuiUtils.createCursorFromSVG("images/stg-node-signal_transition-output_plus.svg");
            }
        }
    }

}


text:
"""
Django settings for legal_accord project.

Generated by 'django-admin startproject' using Django 2.1.2.

For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""

import os
from typing import List

# Basic configuration

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
# This is directory containing the project and app directories.

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

DEBUG = True if os.getenv('DJANGO_DEBUG') == 'True' else False

ALLOWED_HOSTS = os.getenv('DJANGO_ALLOWED_HOSTS', '').split(',')  # type: List[str]

INTERNAL_IPS = os.getenv('DJANGO_INTERNAL_IPS', '').split(',')  # type: List[str]

SECRET_KEY = os.getenv('DJANGO_SECRET_KEY')

ROOT_URLCONF = 'legal_accord.urls'

WSGI_APPLICATION = 'legal_accord.wsgi.application'

AUTH_USER_MODEL = 'unravel.User'

# Applications
# https://docs.djangoproject.com/en/2.1/ref/applications/

INSTALLED_APPS = [
    'django_celery_beat',
    'django_celery_results',
    'django.contrib.admindocs',
    'django.contrib.humanize',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'unravel',
]

if DEBUG:
    INSTALLED_APPS.append('debug_toolbar')
    INSTALLED_APPS.append('django_extensions')

# Middleware
# https://docs.djangoproject.com/en/2.1/topics/http/middleware/

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

if DEBUG:
    csrf_index = MIDDLEWARE.index('django.middleware.csrf.CsrfViewMiddleware')
    MIDDLEWARE.insert(csrf_index + 1, 'debug_toolbar.middleware.DebugToolbarMiddleware')

# Templates
# https://docs.djangoproject.com/en/2.1/ref/settings/#std:setting-TEMPLATES

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, 'templates')
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

# Cookies
# NOTE: change the name to match the app name, as the port is not included in the SESSION_COOKIE_DOMAIN

SESSION_COOKIE_NAME = 'unravel_session_id'

CSRF_COOKIE_NAME = 'unravel_csrftoken'

# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': os.getenv('DJANGO_DATABASE_NAME'),
        'USER': os.getenv('DJANGO_DATABASE_USER'),
        'PASSWORD': os.getenv('DJANGO_DATABASE_PASSWORD'),
        'HOST': os.getenv('DJANGO_DATABASE_HOST', 'localhost'),
        'PORT': int(os.getenv('DJANGO_DATABASE_PORT', '5432')),
    }
}

# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

LANGUAGE_CODE = 'en-au'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

LANGUAGE_COOKIE_NAME = 'unravel_django_language'

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = os.getenv('DJANGO_STATIC_URL')
STATIC_ROOT = os.getenv('DJANGO_STATIC_ROOT')
STATICFILES_STORAGE = os.getenv('DJANGO_STATICFILES_STORAGE')

MEDIA_URL = os.getenv('DJANGO_MEDIA_URL')
MEDIA_ROOT = os.getenv('DJANGO_MEDIA_ROOT')

# Cache
# https://docs.djangoproject.com/en/2.1/ref/settings/#caches

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
        'LOCATION': os.getenv('DJANGO_CACHE_LOCATION'),
    }
}

# Security and HTTPS and CSRF
# https://docs.djangoproject.com/en/2.1/ref/middleware/#http-strict-transport-security
# https://docs.djangoproject.com/en/2.1/ref/csrf/
# https://docs.djangoproject.com/en/2.1/ref/clickjacking/

# SECURE_HSTS_SECONDS: If your entire site is
# served only over SSL, you may want to consider setting a value and enabling HTTP Strict Transport Security. Be sure
# to read the documentation first; enabling HSTS carelessly can cause serious, irreversible problems.
SECURE_HSTS_SECONDS = int(os.getenv('DJANGO_SECURE_HSTS_SECONDS', 0))

# SECURE_CONTENT_TYPE_NOSNIFF: When false, your pages will not be served with
# an 'x-content-type-options: nosniff' header. You should consider enabling this header to prevent the browser from
# identifying content types incorrectly.
SECURE_CONTENT_TYPE_NOSNIFF = True if os.getenv('DJANGO_SECURE_CONTENT_TYPE_NOSNIFF', 'False') == 'True' else False

# SECURE_BROWSER_XSS_FILTER: When false, your pages will not be served with an 'x-xss-protection: 1; mode=block' header.
# You should consider enabling this header to activate the browser's XSS filtering and help prevent XSS attacks.
SECURE_BROWSER_XSS_FILTER = True if os.getenv('DJANGO_SECURE_BROWSER_XSS_FILTER', 'False') == 'True' else False

# SECURE_SSL_REDIRECT: Unless your site should be available over
# both SSL and non-SSL connections, you may want to either set this setting True or configure a load balancer or
# reverse-proxy server to redirect all connections to HTTPS.
SECURE_SSL_REDIRECT = True if os.getenv('DJANGO_SECURE_SSL_REDIRECT', 'False') == 'True' else False

# SESSION_COOKIE_SECURE: Using a secure-only session cookie makes it more difficult
# for network traffic sniffers to hijack user sessions.
SESSION_COOKIE_SECURE = True if os.getenv('DJANGO_SESSION_COOKIE_SECURE', 'False') == 'True' else False

# CSRF_COOKIE_SECURE: Using a secure-only CSRF cookie makes it more difficult for network traffic sniffers
# to steal the CSRF token.
CSRF_COOKIE_SECURE = True if os.getenv('DJANGO_CSRF_COOKIE_SECURE', 'False') == 'True' else False

# CSRF_COOKIE_HTTPONLY: Using an HttpOnly CSRF cookie makes it more difficult for cross-site scripting
# attacks to steal the CSRF token.
CSRF_COOKIE_HTTPONLY = True if os.getenv('DJANGO_CSRF_COOKIE_HTTPONLY', 'False') == 'True' else False

# CSRF_HEADER_NAME: The name of the request header used for CSRF authentication.
CSRF_HEADER_NAME = os.getenv('DJANGO_CSRF_HEADER_NAME', 'HTTP_X_CSRFTOKEN')

# X_FRAME_OPTIONS: Could be set to 'DENY'. The default is 'SAMEORIGIN', but unless there is a good reason for your
# site to serve other parts of itself in a frame, you should change it to 'DENY'.
X_FRAME_OPTIONS = os.getenv('DJANGO_X_FRAME_OPTIONS', 'DENY')

# Logging
# https://docs.djangoproject.com/en/2.1/topics/logging

LOGGING_DIR = os.getenv('DJANGO_LOG_DIR')
LOGGING_LEVEL = os.getenv('DJANGO_LOG_LEVEL')

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '[%(asctime)s] [%(levelname)8s] - %(name)s - %(message)s [%(process)d:%(processName)s %(thread)d:%(threadName)s] (%(filename)s:%(lineno)s)'
        },
        'standard': {
            'format': '[%(asctime)s] [%(levelname)8s] - %(message)s'
        },
    },
    'handlers': {
        'app_log': {
            'level': LOGGING_LEVEL,
            'class': 'logging.FileHandler',
            'filename': os.path.join(LOGGING_DIR, 'app.log'),
            'formatter': 'standard'
        },
        'django_fallback_log': {
            'level': LOGGING_LEVEL,
            'class': 'logging.FileHandler',
            'filename': os.path.join(LOGGING_DIR, 'django_framework.log'),
            'formatter': 'verbose'
        },
        'django_request_log': {
            'level': LOGGING_LEVEL,
            'class': 'logging.FileHandler',
            'filename': os.path.join(LOGGING_DIR, 'django_request.log'),
            'formatter': 'standard'
        },
        'django_security_log': {
            'level': LOGGING_LEVEL,
            'class': 'logging.FileHandler',
            'filename': os.path.join(LOGGING_DIR, 'django_security.log'),
            'formatter': 'standard'
        },
        'django_template_log': {
            'level': LOGGING_LEVEL,
            'class': 'logging.FileHandler',
            'filename': os.path.join(LOGGING_DIR, 'django_template.log'),
            'formatter': 'standard'
        },
        'django_db_log': {
            'level': LOGGING_LEVEL,
            'class': 'logging.FileHandler',
            'filename': os.path.join(LOGGING_DIR, 'django_db.log'),
            'formatter': 'standard'
        }
    },
    'loggers': {
        'unravel': {
            'handlers': ['app_log'],
            'level': LOGGING_LEVEL,
            'propagate': True,
        },
        '': {
            'handlers': ['django_fallback_log'],
            'level': LOGGING_LEVEL,
            'propagate': True
        },
        'django': {
            'handlers': ['django_fallback_log'],
            'level': LOGGING_LEVEL,
            'propagate': False
        },
        'django.request': {
            'handlers': ['django_request_log'],
            'level': LOGGING_LEVEL,
            'propagate': False
        },
        'django.template': {
            'handlers': ['django_template_log'],
            'level': LOGGING_LEVEL,
            'propagate': False
        },
        'django.db': {
            'handlers': ['django_db_log'],
            'level': LOGGING_LEVEL,
            'propagate': False
        },
        'django.security': {
            'handlers': ['django_security_log'],
            'level': LOGGING_LEVEL,
            'propagate': False
        }
    }
}

# Celery
# http://docs.celeryproject.org/en/latest/userguide/configuration.html

CELERY_RESULT_BACKEND = 'django-db'
CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler'


text:
package io.quarkus.resteasy.mutiny.test.annotations;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ ElementType.PARAMETER, ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Async {
    // Marker annotation
}


text:
package com.zhou.android.bluetooth;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.zhou.android.R;
import com.zhou.android.common.BaseActivity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

/**
 * Bluetooth 蓝牙主页列表测试用
 * Created by ZhOu on 2017/6/14.
 */

public class BluetoothMainActivity extends BaseActivity {

    private final static String TAG = "zhou";
    private final static int RequestBluetoothCode = 10001;

    private BluetoothChatService bluetoothChatService;

    private BluetoothAdapter bluetoothAdapter;
    private List<BluetoothDevice> bondedDevices = new ArrayList<>();
    private Set<BluetoothDevice> foundDevices = Collections.synchronizedSet(new LinkedHashSet<BluetoothDevice>());

    private TextView tv_detail;

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_bluetooth_main);
    }

    @Override
    protected void init() {
        tv_detail = (TextView) findViewById(R.id.tv_detail);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null) {
            Toast.makeText(this, "Your device do not support Bluetooth.", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!bluetoothAdapter.isEnabled()) {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, RequestBluetoothCode);
        } else {
            Set<BluetoothDevice> set = bluetoothAdapter.getBondedDevices();
            for (BluetoothDevice device : set) {
                bondedDevices.add(device);
                String text = device.getName() + " address: " + device.getAddress() + " type: " + device.getType() + "\n";
                tv_detail.append(text);
            }
        }

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        registerReceiver(bluetoothReceiver, intentFilter);

        bluetoothChatService = new BluetoothChatService(this, handler);
        bluetoothChatService.start();
    }

    @Override
    protected void addListener() {
        findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bondedDevices.size() == 0)
                    return;
                bluetoothChatService.connect(bondedDevices.get(0));
            }
        });
        findViewById(R.id.btn_send).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bluetoothChatService != null) {
                    bluetoothChatService.write("123".getBytes());
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(bluetoothReceiver);
        if (bluetoothChatService != null) {
            bluetoothChatService.initiativeStop();
            bluetoothChatService = null;
        }
    }

    private void deviceDiscoverable() {
        if (bluetoothAdapter.getScanMode() !=
                BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(intent);
        }
    }

    private void discoverDevice() {
        tv_detail.append("扫描设备:" + bluetoothAdapter.isEnabled() + "\n");
        if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) {
            if (bluetoothAdapter.isDiscovering())
                bluetoothAdapter.cancelDiscovery();
            foundDevices.clear();
            bluetoothAdapter.startDiscovery();
        }
    }

    private void loadDiscoverDevices() {
        tv_detail.append("发现设备:\n");
        if (foundDevices.size() > 0) {
            for (BluetoothDevice device : foundDevices) {
                String text = device.getName() + " address: " + device.getAddress() + " type: " + device.getType() + "\n";
                tv_detail.append(text);
            }
        }
    }

    private BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
                int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
                if (BluetoothAdapter.STATE_OFF == state) {
                    Log.d(TAG, "state: " + state);
                } else if (BluetoothAdapter.STATE_ON == state) {
                    Log.d(TAG, "state: " + state);
                    discoverDevice();
                }
            } else if (action.equals(BluetoothDevice.ACTION_FOUND)) {
                Log.d(TAG, "found");
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                foundDevices.add(device);
            } else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
                loadDiscoverDevices();
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == RequestBluetoothCode) {
            if (resultCode == RESULT_OK) {
                Set<BluetoothDevice> set = bluetoothAdapter.getBondedDevices();
                bondedDevices.clear();
                for (BluetoothDevice device : set) {
                    bondedDevices.add(device);
                    String text = device.getName() + " address: " + device.getAddress() + " type: " + device.getType() + "\n";
                    tv_detail.append(text);
                }
            } else
                Toast.makeText(this, "Open Bluetooth is failed,please open in Setting.", Toast.LENGTH_SHORT).show();
        } else
            super.onActivityResult(requestCode, resultCode, data);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Object o = msg.obj;
            String v;
            if (o instanceof Integer)
                v = String.valueOf(o);
            else if (o instanceof String)
                v = (String) o;
            else
                v = new String((byte[]) o);
            if (msg.what == MessageType.MESSAGE_READ) {
                Toast.makeText(BluetoothMainActivity.this, v, Toast.LENGTH_SHORT).show();
                if (v.equals(MessageType.MESSAGE_DISCONNECT_DEVICE)) {
                    Log.d(TAG, "断开连接");
                }
            } else if (msg.what == MessageType.MESSAGE_WRITE) {
                Toast.makeText(BluetoothMainActivity.this, v, Toast.LENGTH_SHORT).show();
                if (v.equals(MessageType.MESSAGE_DISCONNECT_DEVICE)) {
                    Log.d(TAG, "断开连接");
                }
            }
            Log.d(TAG, msg.what + " : " + v);
        }
    };
}


text:
sux
===

Python 2 compatibility layer for Python 3

For those times when you really need to use a
non-python-3-compliant module but don't
want to downgrade your whole system to python 2.

Are you crazy?
--------------
Yes, a little, but this actually works!

How could this possibly work?
-----------------------------
Simply install your python2 packages as you would normally, in a python2 (virtual)
environment. Then, in your python3 space, you will install and invoke `sux`, and it
will provide a "tunnel" through to python2, relaying your interactions between the
two environments.

Quickstart
----------
In a python3 (virtual) env:

    pip3 install sux

Create your python2 virtualenv and install the
naughty package(s):

    export PY2_VIRTUAL_ENV="/tmp/sux-to-use-python2"
    virtualenv -ppython2 "$PY2_VIRTUAL_ENV"
    "$PY2_VIRTUAL_ENV"/bin/pip install boto

Now, with `PY2_VIRTUAL_ENV` still set, fire up python3
and get to work:

    import sux
    connection = sux.to_use('boto.s3.connection')
    conn = connection.S3Connection('abc', '123')
    conn.create_bucket("foo")

The final command will attempt to connect to S3, and will raise
sux.exceptions.S3ResponseError.

Note that the `to_use` operator expects a package name to be passed.
e.g. with the pyxero package, you might choose to do the following:

    PublicCredentials = sux.to_use('xero.auth').PublicCredentials
    Xero = sux.to_use('xero').Xero

where in a native python2 environment you would have instead used:

    from xero.auth import PublicCredentials
    from xero import Xero

Tell me More!
=============
![CI status](https://travis-ci.org/nicois/sux.svg?branch=master)

What works?
-----------
* Importing a python2 package
* Accessing attributes in that package (recursively)
* Invoking functions and methods on the python2 objects
* Handling exceptions
* Garbage collection

What doesn't (yet) work?
------------------
* Simultaneous operations from multiple threads.
* Passing python3 objects to python2 space. (e.g. registering a 'hook' function with a python2 object)
* Accessing the special class methods starting with  double-underscore.

Is it thread-safe?
------------------
Yes. However, only one thread can be operating on a python2 object
at a time. So if you make a long-running call via sux, if another
thread attempts to use a python2 object, it will block.

How are exceptions handled?
---------------------------
Any exception raised in the python2 environment
will cause an exception of the same name (to be raised in the python3
space. See tests.test_boto for an example.

I want to control the environment of the python2 instance!
----------------------------------------------------------
OK:

    bf = sux.to_use('bioformats', env=os.environ)

or, if you are not afraid of accessing private attributes:

    bf = sux.to_use('bioformats', env=os.environ.__dict__['_data'])

Is this fast?
-------------
Every interaction between python2 and python3 uses `pickle` for
transport and is not optimised for speed. Then again, the python2 instance
runs in a separate process, with a separate GIL.


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('restaurant', '0030_kitchen_usertable'),
    ]

    operations = [
        migrations.AlterField(
            model_name='kitchen',
            name='menu_item',
            field=models.CharField(max_length=200),
        ),
    ]


text:
using NBi.Core.Scalar.Resolver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NBi.Core.Variable
{
    public class InstanceVariable : ILoadtimeVariable
    {
        private object Value { get; }

        public InstanceVariable(object value)
            => Value = value;

        public object GetValue() => Value;

        public bool IsEvaluated() => true;
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Continental</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">

    <link href="css/grayscale.css" rel="stylesheet">
    <link href="css/main.css" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">

                </button>

                    Home

                        About

                        Tour

                        Music

                        Contact

CONTINENTAL

About

Known mostly for his time as founding guitarist of The Dropkick Murphys, Boston based rocker Rick Barton has spent the last five years fronting his current band and labor of love "Continental." Continental's sound is soulful Rock n Roll, plain and simple. While often compared to a variety of different bands, they like to summarize their style as "Paul Westerberg writing songs for The Rolling Stones," a compliment they received and have remembered for years. "I wear my heart on my sleeve and prefer to sing about what's inside, rather than fast cars and shaking booty" says Rick.

upcoming shows

                            ContinentalBand Tour Dates

Watch

Listen

Contact

Booking

USA - Jim@bucketcity.com

EU - booking@8ballconcerts.com

Press

Ralph.Knuckles@gmail.com

Management

twistedricco@gmail.com

Copyright © Continental 2016


text:
require 'bundler/gem_helper'
Bundler::GemHelper.install_tasks