text:
void onewire_init(uint8_t pin);

// Perform a 1-Wire reset cycle. Returns 1 if a device responds
// with a presence pulse.  Returns 0 if there is no device or the
// bus is shorted or otherwise held low for more than 250uS
uint8_t onewire_reset(uint8_t pin);

// Issue a 1-Wire rom select command, you do the reset first.
void onewire_select(uint8_t pin, const uint8_t rom[8]);

// Issue a 1-Wire rom skip command, to address all on bus.
void onewire_skip(uint8_t pin);

// Write a byte. If 'power' is one then the wire is held high at
// the end for parasitically powered devices. You are responsible
// for eventually depowering it by calling depower() or doing
// another read or write.
void onewire_write(uint8_t pin, uint8_t v, uint8_t power);

void onewire_write_bytes(uint8_t pin, const uint8_t *buf, uint16_t count, bool power);

// Read a byte.
uint8_t onewire_read(uint8_t pin);

void onewire_read_bytes(uint8_t pin, uint8_t *buf, uint16_t count);

// Write a bit. The bus is always left powered at the end, see
// note in write() about that.
static void onewire_write_bit(uint8_t pin, uint8_t v, uint8_t power);

// Read a bit.
static uint8_t onewire_read_bit(uint8_t pin);

// Stop forcing power onto the bus. You only need to do this if
// you used the 'power' flag to write() or used a write_bit() call
// and aren't about to do another read or write. You would rather
// not leave this powered if you don't have to, just in case
// someone shorts your bus.
void onewire_depower(uint8_t pin);

#if ONEWIRE_SEARCH
// Clear the search state so that if will start from the beginning again.
void onewire_reset_search(uint8_t pin);

// Setup the search to find the device type 'family_code' on the next call
// to search(*newAddr) if it is present.
void onewire_target_search(uint8_t pin, uint8_t family_code);

// Look for the next device. Returns 1 if a new address has been
// returned. A zero might mean that the bus is shorted, there are
// no devices, or you have already retrieved all of them.  It
// might be a good idea to check the CRC to make sure you didn't
// get garbage.  The order is deterministic. You will always get
// the same devices in the same order.
uint8_t onewire_search(uint8_t pin, uint8_t *newAddr);
#endif

#if ONEWIRE_CRC
// Compute a Dallas Semiconductor 8 bit CRC, these are used in the
// ROM and scratchpad registers.
uint8_t onewire_crc8(const uint8_t *addr, uint8_t len);

#if ONEWIRE_CRC16
// Compute the 1-Wire CRC16 and compare it against the received CRC.
// Example usage (reading a DS2408):
//    // Put everything in a buffer so we can compute the CRC easily.
//    uint8_t buf[13];
//    buf[0] = 0xF0;    // Read PIO Registers
//    buf[1] = 0x88;    // LSB address
//    buf[2] = 0x00;    // MSB address
//    WriteBytes(net, buf, 3);    // Write 3 cmd bytes
//    ReadBytes(net, buf+3, 10);  // Read 6 data bytes, 2 0xFF, 2 CRC16
//    if (!CheckCRC16(buf, 11, &buf[11])) {
//        // Handle error.
//    }
//
// @param input - Array of bytes to checksum.
// @param len - How many bytes to use.
// @param inverted_crc - The two CRC16 bytes in the received data.
//                       This should just point into the received data,
//                       *not* at a 16-bit integer.
// @param crc - The crc starting value (optional)
// @return True, iff the CRC matches.
bool onewire_check_crc16(const uint8_t* input, uint16_t len, const uint8_t* inverted_crc, uint16_t crc);

// Compute a Dallas Semiconductor 16 bit CRC.  This is required to check
// the integrity of data received from many 1-Wire devices.  Note that the
// CRC computed here is *not* what you'll get from the 1-Wire network,
// for two reasons:
//   1) The CRC is transmitted bitwise inverted.
//   2) Depending on the endian-ness of your processor, the binary
//      representation of the two-byte return value may have a different
//      byte order than the two bytes you get from 1-Wire.
// @param input - Array of bytes to checksum.
// @param len - How many bytes to use.
// @param crc - The crc starting value (optional)
// @return The CRC16, as defined by Dallas Semiconductor.
uint16_t onewire_crc16(const uint8_t* input, uint16_t len, uint16_t crc);
#endif
#endif

#endif


text:
var DEFAULTS = {
    duration: 400,
    easing: "easeInOut"
};

module.exports = function flip (t, params) {
    var target;

    params = t.processParams(params, DEFAULTS);

    if (t.isIntro) {
        target = t.getStyle("transform");
        t.setStyle("transform", "rotateY(-180deg)");
    } else {
        target = "rotateY(180deg)";
    }

    t.setStyle({
        backfaceVisibility: "hidden",
        WebKitBackfaceVisibility: "hidden"
    });

    t.animateStyle("transform", target, params).then(t.complete);
};

redpajama_set_name: RedPajamaGithub


text:
namespace page_load_metrics {
namespace test {

// WeakMockTimer is a MockTimer that allows clients to keep WeakPtr<>s to it.
class WeakMockTimer : public base::MockOneShotTimer,
                      public base::SupportsWeakPtr<WeakMockTimer> {
 public:
  WeakMockTimer();

  WeakMockTimer(const WeakMockTimer&) = delete;
  WeakMockTimer& operator=(const WeakMockTimer&) = delete;
};

// WeakMockTimerProvider is a testing helper class that test classes can inherit
// from to provide basic MockTimer tracking capabilities.
class WeakMockTimerProvider {
 public:
  WeakMockTimerProvider();

  WeakMockTimerProvider(const WeakMockTimerProvider&) = delete;
  WeakMockTimerProvider& operator=(const WeakMockTimerProvider&) = delete;

  virtual ~WeakMockTimerProvider();

  base::MockOneShotTimer* GetMockTimer() const;
  void SetMockTimer(base::WeakPtr<WeakMockTimer> timer);

 private:
  base::WeakPtr<WeakMockTimer> timer_;
};

}  // namespace test
}  // namespace page_load_metrics

#endif  // COMPONENTS_PAGE_LOAD_METRICS_COMMON_TEST_WEAK_MOCK_TIMER_H_


text:
package com.rackspacecloud.client.service_registry.objects;

public class ConfigurationValue implements HasId {
    private String id;
    private String value;

    public ConfigurationValue(String id, String value) {
        this.id = id;
        this.value = value;
    }

    public String getId() {
        return id;
    }

    public String getValue() {
        return value;
    }

    @Override
    public String toString() {
        return String.format("[ConfigurationValue id=%s, value=%s]", this.getId(), this.getValue());
    }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using Cake.Core.Configuration.Parser;
using Cake.Core.Tests.Properties;
using Xunit;

namespace Cake.Core.Tests.Unit.Configuration.Parser
{
    public sealed class ConfigurationTokenizerTests
    {
        public sealed class TheTokenizeMethod
        {
            [Fact]
            public void Should_Tokenize_Comment()
            {
                // Given, When
                var result = ConfigurationTokenizer.Tokenize("; Hello World");

                // Then
                Assert.Empty(result);
            }

            [Fact]
            public void Should_Tokenize_Section()
            {
                // Given, When
                var result = ConfigurationTokenizer.Tokenize("[TheSection]");

                // Then
                Assert.Single(result);
                Assert.Equal(ConfigurationTokenKind.Section, result[0].Kind);
                Assert.Equal("TheSection", result[0].Value);
            }

            [Theory]
            [InlineData("[TheSection")]
            [InlineData("[TheSection\nHello=World")]
            public void Should_Throw_If_Section_Is_Malformed(string section)
            {
                // Given, When
                var result = Record.Exception(() => ConfigurationTokenizer.Tokenize(section));

                // Then
                AssertEx.IsExceptionWithMessage<InvalidOperationException>(result, "Encountered malformed section.");
            }

            [Fact]
            public void Should_Tokenize_Key_And_Value_Pair()
            {
                // Given, When
                var result = ConfigurationTokenizer.Tokenize("Hello=World");

                // Then
                Assert.Equal(3, result.Count);
                Assert.Equal("Hello", result[0].Value);
                Assert.Equal(ConfigurationTokenKind.Equals, result[1].Kind);
                Assert.Equal("World", result[2].Value);
            }

            [Fact]
            public void Should_Set_Missing_Value_As_Empty_String()
            {
                // Given, When
                var result = ConfigurationTokenizer.Tokenize("Hello=");

                // Then
                Assert.Equal(2, result.Count);
                Assert.Equal("Hello", result[0].Value);
                Assert.Equal(ConfigurationTokenKind.Equals, result[1].Kind);
            }

            [Fact]
            public void Should_Tokenize_Ini_File()
            {
                // Given, When
                var result = ConfigurationTokenizer.Tokenize(Resources.Ini_Configuration);

                // Then
                Assert.Equal(8, result.Count);
                Assert.Equal(ConfigurationTokenKind.Section, result[0].Kind);
                Assert.Equal("Section1", result[0].Value);
                Assert.Equal("Foo", result[1].Value);
                Assert.Equal(ConfigurationTokenKind.Equals, result[2].Kind);
                Assert.Equal("Bar", result[3].Value);
                Assert.Equal(ConfigurationTokenKind.Section, result[4].Kind);
                Assert.Equal("Section2", result[4].Value);
                Assert.Equal("Baz", result[5].Value);
                Assert.Equal(ConfigurationTokenKind.Equals, result[6].Kind);
                Assert.Equal("Qux", result[7].Value);
            }
        }
    }
}


text:
import * as fs from 'fs';
import * as path from 'path';

function* searchLocations(baseDir: string, resource: string): IterableIterator<string> {
  let next = baseDir;
  let prev = '';
  while (prev !== next && path.basename(next) !== 'node_modules') {
    yield path.join(next, resource);
    prev = next;
    next = path.join(next, '../');
  }
}

export default function resolve(baseDir: string, fileName: string): string | undefined {
  for (const location of searchLocations(baseDir, fileName)) {
    if (fs.existsSync(location)) {
      return location;
    }
  }
  return undefined;
}


text:
package edu.umass.cs.ciir.waltz.flow.impl;

import edu.umass.cs.ciir.waltz.flow.runtime.FlowSink;
import edu.umass.cs.ciir.waltz.flow.runtime.FlowSource;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;

/**
 * @author jfoley
 */
public class FlowCollectionSource<T extends Serializable> extends FlowSource<T> implements SerializableStateful<ArrayList<T>> {
  private ArrayList<T> items;

  public FlowCollectionSource() { }
  public FlowCollectionSource(Collection<? extends T> input) {
    this.items = new ArrayList<>(input);
  }

  @Override
  public void run(FlowSink<T> output) throws Exception {
    assert(items != null);
    output.process(items);
  }

  @Override
  public ArrayList<T> getState() {
    return items;
  }

  @Override
  public void setState(ArrayList<T> object) {
    this.items = object;
  }
}


text:
package org.elasticsearch.test.test;

import com.carrotsearch.randomizedtesting.annotations.Repeat;
import org.elasticsearch.test.ElasticsearchIntegrationTest;
import org.elasticsearch.test.TestCluster;
import org.junit.Test;

import java.io.IOException;

import static org.hamcrest.Matchers.equalTo;

/**
 * This test ensures that the cluster initializion for GLOBAL scope is not influencing
 * the tests random sequence due to initializtion using the same random instance.
 */
public class GlobalScopeClusterTests extends ElasticsearchIntegrationTest {
    private static int ITER = 0;
    private static long[] SEQUENCE = new long[100];
    private static Long CLUSTER_SEED = null;

    @Test
    @Repeat(iterations = 10, useConstantSeed = true)
    public void testReproducible() throws IOException {
        if (ITER++ == 0) {
            CLUSTER_SEED = cluster().seed();
            for (int i = 0; i < SEQUENCE.length; i++) {
                SEQUENCE[i] = randomLong();
            }
        } else {
            assertEquals(CLUSTER_SEED, new Long(cluster().seed()));
            for (int i = 0; i < SEQUENCE.length; i++) {
                assertThat(SEQUENCE[i], equalTo(randomLong()));
            }
        }
    }

    @Override
    protected TestCluster buildTestCluster(Scope scope, long seed) throws IOException {
        // produce some randomness
        int iters = between(1, 100);
        for (int i = 0; i < iters; i++) {
            randomLong();
        }
        return super.buildTestCluster(scope, seed);
    }
}


text:
package fswalker

import (
	"bytes"
	"os"
	"path/filepath"
	"strings"
	"testing"

	"github.com/google/fswalker"
	fspb "github.com/google/fswalker/proto/fswalker"

	"github.com/kopia/kopia/internal/testlogging"
)

func TestWalkChecker_GatherCompare(t *testing.T) {
	type fields struct {
		GlobalFilterMatchers []string
	}

	for _, tt := range []struct {
		name             string
		fields           fields
		fileTreeMaker    func(root string) error
		fileTreeModifier func(root string) error
		wantErr          bool
	}{
		{
			name: "empty directory, unchanged",
			fields: fields{
				GlobalFilterMatchers: nil,
			},
			fileTreeMaker:    func(rootDir string) error { return nil },
			fileTreeModifier: func(rootDir string) error { return nil },
			wantErr:          false,
		},
		{
			name: "subdirectory tree, unchanged",
			fields: fields{
				GlobalFilterMatchers: nil,
			},
			fileTreeMaker: func(rootDir string) error {
				return os.MkdirAll(filepath.Join(rootDir, "some", "path"), 0o700)
			},
			fileTreeModifier: func(rootDir string) error { return nil },
			wantErr:          false,
		},
		{
			name: "file in root, unchanged",
			fields: fields{
				GlobalFilterMatchers: nil,
			},
			fileTreeMaker: func(rootDir string) error {
				return os.WriteFile(filepath.Join(rootDir, "test-file"), []byte("some data"), 0o700)
			},
			fileTreeModifier: func(rootDir string) error { return nil },
			wantErr:          false,
		},
		{
			name: "file in root, contents modified",
			fields: fields{
				GlobalFilterMatchers: nil,
			},
			fileTreeMaker: func(rootDir string) error {
				return os.WriteFile(filepath.Join(rootDir, "test-file"), []byte("some data"), 0o700)
			},
			fileTreeModifier: func(rootDir string) error {
				os.WriteFile(filepath.Join(rootDir, "test-file"), []byte("some different data"), 0o700)
				return nil
			},
			wantErr: true,
		},
		{
			name: "file in deep subdirectory, contents modified",
			fields: fields{
				GlobalFilterMatchers: nil,
			},
			fileTreeMaker: func(rootDir string) error {
				subdir := filepath.Join(rootDir, "some", "really", "really", "very", "substantially", "deep", "directory", "tree")

				err := os.MkdirAll(subdir, 0o700)
				if err != nil {
					return err
				}

				return os.WriteFile(filepath.Join(subdir, "test-file"), []byte("some data"), 0o700)
			},
			fileTreeModifier: func(rootDir string) error {
				subdir := filepath.Join(rootDir, "some", "really", "really", "very", "substantially", "deep", "directory", "tree")
				return os.WriteFile(filepath.Join(subdir, "test-file"), []byte("some different data"), 0o700)
			},
			wantErr: true,
		},
		{
			name: "add a file",
			fields: fields{
				GlobalFilterMatchers: nil,
			},
			fileTreeMaker: func(rootDir string) error {
				return nil
			},
			fileTreeModifier: func(rootDir string) error {
				return os.WriteFile(filepath.Join(rootDir, "test-file"), []byte("some data"), 0o700)
			},
			wantErr: true,
		},
		{
			name: "delete a file",
			fields: fields{
				GlobalFilterMatchers: nil,
			},
			fileTreeMaker: func(rootDir string) error {
				return os.WriteFile(filepath.Join(rootDir, "test-file"), []byte("some data"), 0o700)
			},
			fileTreeModifier: func(rootDir string) error {
				return os.Remove(filepath.Join(rootDir, "test-file"))
			},
			wantErr: true,
		},
		{
			name: "get an error when walking",
			fields: fields{
				GlobalFilterMatchers: nil,
			},
			fileTreeMaker: func(rootDir string) error {
				return os.WriteFile(filepath.Join(rootDir, "test-file"), []byte("some data"), 0o700)
			},
			fileTreeModifier: func(rootDir string) error {
				return os.Chmod(filepath.Join(rootDir, "test-file"), 0o000)
			},
			wantErr: true,
		},
		{
			name: "add a directory",
			fields: fields{
				GlobalFilterMatchers: nil,
			},
			fileTreeMaker: func(rootDir string) error {
				subdir := filepath.Join(rootDir, "some", "really", "really", "very", "substantially", "deep", "directory", "tree")
				return os.MkdirAll(subdir, 0o700)
			},
			fileTreeModifier: func(rootDir string) error {
				subdir := filepath.Join(rootDir, "some", "other", "path")
				return os.MkdirAll(subdir, 0o700)
			},
			wantErr: true,
		},
		{
			name: "file in root, contents modified, filter just fingerprint (not size or mtime)",
			fields: fields{
				GlobalFilterMatchers: []string{
					"fingerprint:",
				},
			},
			fileTreeMaker: func(rootDir string) error {
				return os.WriteFile(filepath.Join(rootDir, "test-file"), []byte("some data"), 0o700)
			},
			fileTreeModifier: func(rootDir string) error {
				os.WriteFile(filepath.Join(rootDir, "test-file"), []byte("some different data"), 0o700)
				return nil
			},
			wantErr: true,
		},
		{
			name: "file in root, contents modified, filter fingerprint, size, and mtime",
			fields: fields{
				GlobalFilterMatchers: []string{
					"fingerprint:",
					"mtime:",
					"size",
				},
			},
			fileTreeMaker: func(rootDir string) error {
				return os.WriteFile(filepath.Join(rootDir, "test-file"), []byte("some data"), 0o700)
			},
			fileTreeModifier: func(rootDir string) error {
				os.WriteFile(filepath.Join(rootDir, "test-file"), []byte("some different data"), 0o700)
				return nil
			},
			wantErr: false,
		},
	} {
		t.Run(tt.name, func(t *testing.T) {
			matchers := tt.fields.GlobalFilterMatchers

			chk := &WalkCompare{
				GlobalFilterFuncs: []func(string, fswalker.ActionData) bool{
					func(inputStr string, _ fswalker.ActionData) bool {
						for _, filterStr := range matchers {
							if strings.Contains(inputStr, filterStr) {
								return true
							}
						}
						return false
					},
				},
			}

			tmpDir, err := os.MkdirTemp("", "")
			if err != nil {
				t.Fatal(err)
			}

			defer os.RemoveAll(tmpDir)

			err = tt.fileTreeMaker(tmpDir)
			if err != nil {
				t.Fatal(err)
			}

			ctx := testlogging.Context(t)

			walk, err := chk.Gather(ctx, tmpDir, nil)
			if err != nil {
				t.Fatal(err)
			}

			tt.fileTreeModifier(tmpDir)

			reportOut := &bytes.Buffer{}
			if err := chk.Compare(ctx, tmpDir, walk, reportOut, nil); (err != nil) != tt.wantErr {
				t.Errorf("Compare error = %v, wantErr %v", err, tt.wantErr)
				return
			}

			// If an error was thrown, expect a report to be written to the provided writer
			if (reportOut.Len() > 0) != tt.wantErr {
				t.Errorf("report length unexpected len = %v, expReport %v", reportOut.Len(), tt.wantErr)
			}
		})
	}
}

func TestWalkChecker_filterReportDiffs(t *testing.T) {
	type fields struct {
		GlobalFilterMatchers []string
	}

	for _, tt := range []struct {
		name        string
		fields      fields
		inputReport *fswalker.Report
		expModCount int
	}{
		{
			name: "No filters",
			fields: fields{
				GlobalFilterMatchers: nil,
			},
			inputReport: &fswalker.Report{
				Modified: []fswalker.ActionData{
					{
						Diff: "some difference",
					},
				},
			},
			expModCount: 1,
		},
		{
			name: "filter the only diff as prefix",
			fields: fields{
				GlobalFilterMatchers: []string{
					"some",
				},
			},
			inputReport: &fswalker.Report{
				Modified: []fswalker.ActionData{
					{
						Diff: "some difference",
					},
				},
			},
			expModCount: 0,
		},
		{
			name: "filter the only diff as substring",
			fields: fields{
				GlobalFilterMatchers: []string{
					"iff",
				},
			},
			inputReport: &fswalker.Report{
				Modified: []fswalker.ActionData{
					{
						Diff: "some difference",
					},
				},
			},
			expModCount: 0,
		},
		{
			name: "filter some but not all diffs",
			fields: fields{
				GlobalFilterMatchers: []string{
					"definitely",
				},
			},
			inputReport: &fswalker.Report{
				Modified: []fswalker.ActionData{
					{
						Diff: "this will not be filtered",
					},
					{
						Diff: "this will definitely be filtered",
					},
				},
			},
			expModCount: 1,
		},
		{
			name: "filter multiple diffs",
			fields: fields{
				GlobalFilterMatchers: []string{
					"definitely",
				},
			},
			inputReport: &fswalker.Report{
				Modified: []fswalker.ActionData{
					{
						Diff: "this will not be filtered",
					},
					{
						Diff: "this will definitely be filtered",
					},
					{
						Diff: "this will also definitely be filtered",
					},
				},
			},
			expModCount: 1,
		},
	} {
		t.Log(tt.name)

		matchers := tt.fields.GlobalFilterMatchers

		chk := &WalkCompare{
			GlobalFilterFuncs: []func(string, fswalker.ActionData) bool{
				func(inputStr string, _ fswalker.ActionData) bool {
					for _, filterStr := range matchers {
						if strings.Contains(inputStr, filterStr) {
							return true
						}
					}
					return false
				},
			},
		}

		chk.filterReportDiffs(tt.inputReport)

		if want, got := tt.expModCount, len(tt.inputReport.Modified); want != got {
			t.Errorf("Expected %v modifications after filter but got %v (%v)", want, got, tt.inputReport.Modified)
		}
	}
}

func Test_isRootDirectoryRename(t *testing.T) {
	type args struct {
		diffItem string
		mod      fswalker.ActionData
	}

	for _, tt := range []struct {
		name string
		args args
		want bool
	}{
		{
			name: "Check a root name change",
			args: args{
				diffItem: "name: \"fio-data-902268402\" => \"restore-snap-43720e98eaa9b40ec0be735e347bb853964221402\"",
				mod: fswalker.ActionData{
					Before: &fspb.File{
						Path: ".",
						Info: &fspb.FileInfo{
							IsDir: true,
						},
					},
				},
			},
			want: true,
		},
		{
			name: "Check path is \"./\", equivalent representation of root dir",
			args: args{
				diffItem: "name: \"fio-data-902268402\" => \"restore-snap-43720e98eaa9b40ec0be735e347bb853964221402\"",
				mod: fswalker.ActionData{
					Before: &fspb.File{
						Path: "./",
						Info: &fspb.FileInfo{
							IsDir: true,
						},
					},
				},
			},
			want: true,
		},
		{
			name: "Check path is \"./asdf/bsdf/../../\", equivalent representation of root dir",
			args: args{
				diffItem: "name: \"fio-data-902268402\" => \"restore-snap-43720e98eaa9b40ec0be735e347bb853964221402\"",
				mod: fswalker.ActionData{
					Before: &fspb.File{
						Path: "./asdf/bsdf/../../",
						Info: &fspb.FileInfo{
							IsDir: true,
						},
					},
				},
			},
			want: true,
		},
		{
			name: "Check a root name change",
			args: args{
				diffItem: "name: \"fio-data-902268402\" => \"restore-snap-43720e98eaa9b40ec0be735e347bb853964221402\"",
				mod: fswalker.ActionData{
					Before: &fspb.File{
						Path: "this_is_in_the_root",
						Info: &fspb.FileInfo{
							IsDir: true,
						},
					},
				},
			},
			want: false,
		},
		{
			name: "Check a non-root name change",
			args: args{
				diffItem: "name: \"fio-data-902268402\" => \"restore-snap-43720e98eaa9b40ec0be735e347bb853964221402\"",
				mod: fswalker.ActionData{
					Before: &fspb.File{
						Path: filepath.Join("this_is_restore_directory_root", "with", "more", "subdirectories"),
						Info: &fspb.FileInfo{
							IsDir: true,
						},
					},
				},
			},
			want: false,
		},
		{
			name: "Check empty path",
			args: args{
				diffItem: "name: \"fio-data-902268402\" => \"restore-snap-43720e98eaa9b40ec0be735e347bb853964221402\"",
				mod: fswalker.ActionData{
					Before: &fspb.File{
						Path: "",
						Info: &fspb.FileInfo{
							IsDir: true,
						},
					},
				},
			},
			want: true,
		},
		{
			name: "Check a non-name change diff item on root",
			args: args{
				diffItem: "ctime: 2020-02-06 00:30:41 UTC => 2020-02-06 00:30:47 UTC",
				mod: fswalker.ActionData{
					Before: &fspb.File{
						Path: "",
						Info: &fspb.FileInfo{
							IsDir: true,
						},
					},
				},
			},
			want: false,
		},
		{
			name: "Check a non-name change diff item in another directory",
			args: args{
				diffItem: "ctime: 2020-02-06 00:30:41 UTC => 2020-02-06 00:30:47 UTC",
				mod: fswalker.ActionData{
					Before: &fspb.File{
						Path: filepath.Join("some", "path"),
						Info: &fspb.FileInfo{
							IsDir: true,
						},
					},
				},
			},
			want: false,
		},
		{
			name: "Check not a directory",
			args: args{
				diffItem: "name: \"fio-data-902268402\" => \"restore-snap-43720e98eaa9b40ec0be735e347bb853964221402\"",
				mod: fswalker.ActionData{
					Before: &fspb.File{
						Path: "",
						Info: &fspb.FileInfo{
							IsDir: false,
						},
					},
				},
			},
			want: false,
		},
	} {
		t.Log(tt.name)

		if got := isRootDirectoryRename(tt.args.diffItem, tt.args.mod); got != tt.want {
			t.Errorf("isRootDirectoryRename() = %v, want %v", got, tt.want)
		}
	}
}

func Test_validateReport(t *testing.T) {
	type args struct {
		report *fswalker.Report
	}

	for _, tc := range []struct {
		name    string
		args    args
		wantErr bool
	}{
		{
			name: "no entries in the report",
			args: args{
				report: &fswalker.Report{
					Added:    nil,
					Deleted:  nil,
					Modified: nil,
					Errors:   nil,
				},
			},
			wantErr: false,
		},
		{
			name: "something was added",
			args: args{
				report: &fswalker.Report{
					Added:    []fswalker.ActionData{{}},
					Deleted:  nil,
					Modified: nil,
					Errors:   nil,
				},
			},
			wantErr: true,
		},
		{
			name: "something was deleted",
			args: args{
				report: &fswalker.Report{
					Added:    nil,
					Deleted:  []fswalker.ActionData{{}},
					Modified: nil,
					Errors:   nil,
				},
			},
			wantErr: true,
		},
		{
			name: "something was modified",
			args: args{
				report: &fswalker.Report{
					Added:    nil,
					Deleted:  nil,
					Modified: []fswalker.ActionData{{}},
					Errors:   nil,
				},
			},
			wantErr: true,
		},
		{
			name: "something hit an error",
			args: args{
				report: &fswalker.Report{
					Added:    nil,
					Deleted:  nil,
					Modified: nil,
					Errors:   []fswalker.ActionData{{}},
				},
			},
			wantErr: true,
		},
		{
			name: "multiple issues in report",
			args: args{
				report: &fswalker.Report{
					Added:    []fswalker.ActionData{{}},
					Deleted:  []fswalker.ActionData{{}},
					Modified: []fswalker.ActionData{{}},
					Errors:   []fswalker.ActionData{{}},
				},
			},
			wantErr: true,
		},
	} {
		t.Log(tc.name)

		if err := validateReport(tc.args.report); (err != nil) != tc.wantErr {
			t.Errorf("validateReport() error = %v, wantErr %v", err, tc.wantErr)
		}
	}
}

func Test_rerootWithCheckRename(t *testing.T) {
	for _, tt := range []struct {
		name     string
		file     *fspb.File
		newRoot  string
		diffItem string
		want     bool
	}{
		{
			name: "diff item refers to root dir",
			file: &fspb.File{
				Path: "/some/absolute/path/to/source",
				Info: &fspb.FileInfo{
					Name:  "source",
					IsDir: true,
				},
			},
			newRoot:  "/some/absolute/path/to/source",
			diffItem: "name: \"source\" => \"target\"",
			want:     true,
		},
		{
			name: "diff item refers to a subdir of root dir",
			file: &fspb.File{
				Path: "/some/absolute/path/to/source/subdir",
				Info: &fspb.FileInfo{
					Name:  "subdir",
					IsDir: true,
				},
			},
			newRoot:  "/some/absolute/path/to/source",
			diffItem: "name: \"subdir\" => \"some_unexpected_name\"",
			want:     false,
		},
	} {
		t.Log(tt.name)

		walk := &fspb.Walk{
			File: []*fspb.File{
				tt.file,
			},
		}

		err := rerootWalkDataPaths(walk, tt.newRoot)
		if err != nil {
			t.Errorf("rerootWalkDataPaths() error = %v", err)
		}

		if got := isRootDirectoryRename(tt.diffItem, fswalker.ActionData{Before: tt.file}); got != tt.want {
			t.Errorf("isRootDirectoryRename() got = %v, want %v", got, tt.want)
		}
	}
}


text:
package main.persistence.mongo;

import com.mongodb.client.MongoDatabase;

import main.domain.profession.ProfessionRepository;
import main.domain.profession.ProfessionRepositoryTest;

import org.bson.types.ObjectId;
import org.junit.Before;

public class MongoProfessionRepositoryTest extends ProfessionRepositoryTest {
    private MongoProfessionRepository repository;

    protected ProfessionRepository getRepository() {
        return repository;
    }

    protected String getValidId() {
        return new ObjectId().toString();
    }

    protected String getInvalidId() {
        return "some text";
    }

    @Before
    public void setUp() throws Exception {
        setUpDatabase();
        repository = new MongoProfessionRepository();
        super.setUp();
    }

    private void setUpDatabase() {
    	MongoDatabase database = MongoConnection.getDatabase();
        database.getCollection("professions").drop();
    }
}


text:
package org.apache.ignite;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.DriverPropertyInfo;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;
import org.apache.ignite.cache.affinity.AffinityKey;
import org.apache.ignite.internal.jdbc.JdbcConnection;
import org.apache.ignite.logger.java.JavaLogger;

/**
 * JDBC driver implementation for In-Memory Data Grid.
 *

 * Driver allows to get distributed data from Ignite cache using standard
 * SQL queries and standard JDBC API. It will automatically get only fields that
 * you actually need from objects stored in cache.
 *
Limitations

 * Data in Ignite cache is usually distributed across several nodes,
 * so some queries may not work as expected since the query will be sent to each
 * individual node and results will then be collected and returned as JDBC result set.
 * Keep in mind following limitations (not applied if data is queried from one node only,
 * or data is fully co-located or fully replicated on multiple nodes):
 *

 *

 *         Joins will work correctly only if joined objects are stored in
 *         collocated mode. Refer to
 *         {@link AffinityKey}
 *         javadoc for more details.
 *

 *

 *         Note that if you are connected to local or replicated cache, all data will
 *         be queried only on one node, not depending on what caches participate in
 *         the query (some data from partitioned cache can be lost). And visa versa,
 *         if you are connected to partitioned cache, data from replicated caches
 *         will be duplicated.
 *

 *

 *
SQL Notice

 * Driver allows to query data from several caches. Cache that driver is connected to is
 * treated as default schema in this case. Other caches can be referenced by their names.
 *

 * Note that cache name is case sensitive and you have to always specify it in quotes.
 *
Dependencies

 * JDBC driver is located in main Ignite JAR and depends on all libraries located in
 * {@code IGNITE_HOME/libs} folder. So if you are using JDBC driver in any external tool,
 * you have to add main Ignite JAR will all dependencies to its classpath.
 *
Configuration

 *
 * JDBC driver can return two different types of connection: Ignite Java client based connection and
 * Ignite client node based connection. Java client best connection is deprecated and left only for
 * compatibility with previous version, so you should always use Ignite client node based mode.
 * It is also preferable because it has much better performance.
 *
 * The type of returned connection depends on provided JDBC connection URL.
 *
 *
Configuration of Ignite client node based connection

 *
 * JDBC connection URL has the following pattern: {@code jdbc:ignite:cfg://[<params>@]<config_url>}.

 *
 * {@code <config_url>} represents any valid URL which points to Ignite configuration file. It is required.

 *
 * {@code <params>} are optional and have the following format: {@code param1=value1:param2=value2:...:paramN=valueN}.

 *
 * The following parameters are supported:
 *

 *
{@code cache} - cache name. If it is not defined than default cache will be used.

 *

 *         {@code nodeId} - ID of node where query will be executed.
 *         It can be useful for querying through local caches.
 *         If node with provided ID doesn't exist, exception is thrown.
 *

 *

 *         {@code local} - query will be executed only on local node. Use this parameter with {@code nodeId} parameter.
 *         Default value is {@code false}.
 *

 *

 *          {@code collocated} - flag that used for optimization purposes. Whenever Ignite executes
 *          a distributed query, it sends sub-queries to individual cluster members.
 *          If you know in advance that the elements of your query selection are collocated
 *          together on the same node, usually based on some affinity-key, Ignite
 *          can make significant performance and network optimizations.
 *          Default value is {@code false}.
 *

 *

 *
 *
Configuration of Ignite Java client based connection

 *
 * All Ignite Java client configuration properties can be applied to JDBC connection of this type.
 *

 * JDBC connection URL has the following pattern:
 * {@code jdbc:ignite://<hostname>:<port>/<cache_name>?nodeId=<UUID>}

 * Note the following:
 *

 *
Hostname is required.

 *
If port is not defined, {@code 11211} is used (default for Ignite client).

 *
Leave {@code <cache_name>} empty if you are connecting to default cache.

 *

 *         Provide {@code nodeId} parameter if you want to specify node where to execute
 *         your queries. Note that local and replicated caches will be queried locally on
 *         this node while partitioned cache is queried distributively. If node ID is not
 *         provided, random node is used. If node with provided ID doesn't exist,
 *         exception is thrown.
 *

 *

 * Other properties can be defined in {@link Properties} object passed to
 * {@link DriverManager#getConnection(String, Properties)} method:
 *

 *

 *         Name
 *         Description
 *         Default
 *         Optional
 *

 *

 *         ignite.client.protocol
 *         Communication protocol ({@code TCP} or {@code HTTP}).
 *         {@code TCP}
 *         Yes
 *

 *

 *         ignite.client.connectTimeout
 *         Socket connection timeout.
 *         {@code 0} (infinite timeout)
 *         Yes
 *

 *

 *         ignite.client.tcp.noDelay
 *         Flag indicating whether TCP_NODELAY flag should be enabled for outgoing connections.
 *         {@code true}
 *         Yes
 *

 *

 *         ignite.client.ssl.enabled
 *         Flag indicating that {@code SSL} is needed for connection.
 *         {@code false}
 *         Yes
 *

 *

 *         ignite.client.ssl.protocol
 *         SSL protocol ({@code SSL} or {@code TLS}).
 *         {@code TLS}
 *         Yes
 *

 *

 *         ignite.client.ssl.key.algorithm
 *         Key manager algorithm.
 *         {@code SunX509}
 *         Yes
 *

 *

 *         ignite.client.ssl.keystore.location
 *         Key store to be used by client to connect with Ignite topology.
 *
 *         No (if {@code SSL} is enabled)
 *

 *

 *         ignite.client.ssl.keystore.password
 *         Key store password.
 *
 *         Yes
 *

 *

 *         ignite.client.ssl.keystore.type
 *         Key store type.
 *         {@code jks}
 *         Yes
 *

 *

 *         ignite.client.ssl.truststore.location
 *         Trust store to be used by client to connect with Ignite topology.
 *
 *         No (if {@code SSL} is enabled)
 *

 *

 *         ignite.client.ssl.truststore.password
 *         Trust store password.
 *
 *         Yes
 *

 *

 *         ignite.client.ssl.truststore.type
 *         Trust store type.
 *         {@code jks}
 *         Yes
 *

 *

 *         ignite.client.credentials
 *         Client credentials used in authentication process.
 *
 *         Yes
 *

 *

 *         ignite.client.cache.top
 *
 *             Flag indicating that topology is cached internally. Cache will be refreshed in
 *             the background with interval defined by {@code ignite.client.topology.refresh}
 *             property (see below).
 *
 *         {@code false}
 *         Yes
 *

 *

 *         ignite.client.topology.refresh
 *         Topology cache refresh frequency (ms).
 *         {@code 2000}
 *         Yes
 *

 *

 *         ignite.client.idleTimeout
 *         Maximum amount of time that connection can be idle before it is closed (ms).
 *         {@code 30000}
 *         Yes
 *

 *

 *
Example

 *

 * // Register JDBC driver.
 * Class.forName("org.apache.ignite.IgniteJdbcDriver");
 *
 * // Open JDBC connection.
 * Connection conn = DriverManager.getConnection("jdbc:ignite:cfg//cache=persons@file:///etc/configs/ignite-jdbc.xml");
 *
 * // Query persons' names
 * ResultSet rs = conn.createStatement().executeQuery("select name from Person");
 *
 * while (rs.next()) {
 *     String name = rs.getString(1);
 *
 *     ...
 * }
 *
 * // Query persons with specific age
 * PreparedStatement stmt = conn.prepareStatement("select name, age from Person where age = ?");
 *
 * stmt.setInt(1, 30);
 *
 * ResultSet rs = stmt.executeQuery();
 *
 * while (rs.next()) {
 *     String name = rs.getString("name");
 *     int age = rs.getInt("age");
 *
 *     ...
 * }
 *

 */
@SuppressWarnings("JavadocReference")
public class IgniteJdbcDriver implements Driver {
    /** Prefix for property names. */
    private static final String PROP_PREFIX = "ignite.jdbc.";

    /** Node ID parameter name. */
    private static final String PARAM_NODE_ID = "nodeId";

    /** Cache parameter name. */
    private static final String PARAM_CACHE = "cache";

    /** Local parameter name. */
    private static final String PARAM_LOCAL = "local";

    /** Collocated parameter name. */
    private static final String PARAM_COLLOCATED = "collocated";

    /** Hostname property name. */
    public static final String PROP_HOST = PROP_PREFIX + "host";

    /** Port number property name. */
    public static final String PROP_PORT = PROP_PREFIX + "port";

    /** Cache name property name. */
    public static final String PROP_CACHE = PROP_PREFIX + PARAM_CACHE;

    /** Node ID property name. */
    public static final String PROP_NODE_ID = PROP_PREFIX + PARAM_NODE_ID;

    /** Local property name. */
    public static final String PROP_LOCAL = PROP_PREFIX + PARAM_LOCAL;

    /** Collocated property name. */
    public static final String PROP_COLLOCATED = PROP_PREFIX + PARAM_COLLOCATED;

    /** Cache name property name. */
    public static final String PROP_CFG = PROP_PREFIX + "cfg";

    /** URL prefix. */
    public static final String URL_PREFIX = "jdbc:ignite://";

    /** Config URL prefix. */
    public static final String CFG_URL_PREFIX = "jdbc:ignite:cfg://";

    /** Default port. */
    public static final int DFLT_PORT = 11211;

    /** Major version. */
    private static final int MAJOR_VER = 1;

    /** Minor version. */
    private static final int MINOR_VER = 0;

    /** Logger. */
    private static final IgniteLogger LOG = new JavaLogger();

    /**
     * Register driver.
     */
    static {
        try {
            DriverManager.registerDriver(new IgniteJdbcDriver());
        }
        catch (SQLException e) {
            throw new RuntimeException("Failed to register Ignite JDBC driver.", e);
        }
    }

    /** {@inheritDoc} */
    @Override public Connection connect(String url, Properties props) throws SQLException {
        if (!parseUrl(url, props))
            throw new SQLException("URL is invalid: " + url);

        if (url.startsWith(URL_PREFIX)) {
            if (props.getProperty(PROP_CFG) != null)
                LOG.warning(PROP_CFG + " property is not applicable for this URL.");

            return new JdbcConnection(url, props);
        }
        else
            return new org.apache.ignite.internal.jdbc2.JdbcConnection(url, props);
    }

    /** {@inheritDoc} */
    @Override public boolean acceptsURL(String url) throws SQLException {
        return url.startsWith(URL_PREFIX) || url.startsWith(CFG_URL_PREFIX);
    }

    /** {@inheritDoc} */
    @Override public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException {
        if (!parseUrl(url, info))
            throw new SQLException("URL is invalid: " + url);

        List<DriverPropertyInfo> props = Arrays.<DriverPropertyInfo>asList(
            new PropertyInfo("Hostname", info.getProperty(PROP_HOST), ""),
            new PropertyInfo("Port number", info.getProperty(PROP_PORT), ""),
            new PropertyInfo("Cache name", info.getProperty(PROP_CACHE), ""),
            new PropertyInfo("Node ID", info.getProperty(PROP_NODE_ID), ""),
            new PropertyInfo("Local", info.getProperty(PROP_LOCAL), ""),
            new PropertyInfo("Collocated", info.getProperty(PROP_COLLOCATED), "")
        );

        if (info.getProperty(PROP_CFG) != null)
            props.add(new PropertyInfo("Configuration path", info.getProperty(PROP_CFG), ""));
        else
            props.addAll(Arrays.<DriverPropertyInfo>asList(
                new PropertyInfo("ignite.client.protocol",
                    info.getProperty("ignite.client.protocol", "TCP"),
                    "Communication protocol (TCP or HTTP)."),
                new PropertyInfo("ignite.client.connectTimeout",
                    info.getProperty("ignite.client.connectTimeout", "0"),
                    "Socket connection timeout."),
                new PropertyInfo("ignite.client.tcp.noDelay",
                    info.getProperty("ignite.client.tcp.noDelay", "true"),
                    "Flag indicating whether TCP_NODELAY flag should be enabled for outgoing connections."),
                new PropertyInfo("ignite.client.ssl.enabled",
                    info.getProperty("ignite.client.ssl.enabled", "false"),
                    "Flag indicating that SSL is needed for connection."),
                new PropertyInfo("ignite.client.ssl.protocol",
                    info.getProperty("ignite.client.ssl.protocol", "TLS"),
                    "SSL protocol."),
                new PropertyInfo("ignite.client.ssl.key.algorithm",
                    info.getProperty("ignite.client.ssl.key.algorithm", "SunX509"),
                    "Key manager algorithm."),
                new PropertyInfo("ignite.client.ssl.keystore.location",
                    info.getProperty("ignite.client.ssl.keystore.location", ""),
                    "Key store to be used by client to connect with Ignite topology."),
                new PropertyInfo("ignite.client.ssl.keystore.password",
                    info.getProperty("ignite.client.ssl.keystore.password", ""),
                    "Key store password."),
                new PropertyInfo("ignite.client.ssl.keystore.type",
                    info.getProperty("ignite.client.ssl.keystore.type", "jks"),
                    "Key store type."),
                new PropertyInfo("ignite.client.ssl.truststore.location",
                    info.getProperty("ignite.client.ssl.truststore.location", ""),
                    "Trust store to be used by client to connect with Ignite topology."),
                new PropertyInfo("ignite.client.ssl.keystore.password",
                    info.getProperty("ignite.client.ssl.truststore.password", ""),
                    "Trust store password."),
                new PropertyInfo("ignite.client.ssl.truststore.type",
                    info.getProperty("ignite.client.ssl.truststore.type", "jks"),
                    "Trust store type."),
                new PropertyInfo("ignite.client.credentials",
                    info.getProperty("ignite.client.credentials", ""),
                    "Client credentials used in authentication process."),
                new PropertyInfo("ignite.client.cache.top",
                    info.getProperty("ignite.client.cache.top", "false"),
                    "Flag indicating that topology is cached internally. Cache will be refreshed in the " +
                        "background with interval defined by topologyRefreshFrequency property (see below)."),
                new PropertyInfo("ignite.client.topology.refresh",
                    info.getProperty("ignite.client.topology.refresh", "2000"),
                    "Topology cache refresh frequency (ms)."),
                new PropertyInfo("ignite.client.idleTimeout",
                    info.getProperty("ignite.client.idleTimeout", "30000"),
                    "Maximum amount of time that connection can be idle before it is closed (ms).")
                )
            );

        return props.toArray(new DriverPropertyInfo[0]);
    }

    /** {@inheritDoc} */
    @Override public int getMajorVersion() {
        return MAJOR_VER;
    }

    /** {@inheritDoc} */
    @Override public int getMinorVersion() {
        return MINOR_VER;
    }

    /** {@inheritDoc} */
    @Override public boolean jdbcCompliant() {
        return false;
    }

    /** {@inheritDoc} */
    @Override public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        throw new SQLFeatureNotSupportedException("java.util.logging is not used.");
    }

    /**
     * Validates and parses connection URL.
     *
     * @param props Properties.
     * @param url URL.
     * @return Whether URL is valid.
     */
    private boolean parseUrl(String url, Properties props) {
        if (url == null)
            return false;

        if (url.startsWith(URL_PREFIX) && url.length() > URL_PREFIX.length())
            return parseJdbcUrl(url, props);
        else if (url.startsWith(CFG_URL_PREFIX) && url.length() >= CFG_URL_PREFIX.length())
            return parseJdbcConfigUrl(url, props);

        return false;
    }

    /**
     * @param url Url.
     * @param props Properties.
     */
    private boolean parseJdbcConfigUrl(String url, Properties props) {
        url = url.substring(CFG_URL_PREFIX.length());

        String[] parts = url.split("@");

        if (parts.length > 2)
            return false;

        if (parts.length == 2) {
            if (!parseParameters(parts[0], ":", props))
                return false;
        }

        props.setProperty(PROP_CFG, parts[parts.length - 1]);

        return true;
    }

    /**
     * @param url Url.
     * @param props Properties.
     */
    private boolean parseJdbcUrl(String url, Properties props) {
        url = url.substring(URL_PREFIX.length());

        String[] parts = url.split("\\?");

        if (parts.length > 2)
            return false;

        if (parts.length == 2)
            if (!parseParameters(parts[1], "&", props))
                return false;

        parts = parts[0].split("/");

        assert parts.length > 0;

        if (parts.length > 2)
            return false;

        if (parts.length == 2 && !parts[1].isEmpty())
            props.setProperty(PROP_CACHE, parts[1]);

        url = parts[0];

        parts = url.split(":");

        assert parts.length > 0;

        if (parts.length > 2)
            return false;

        props.setProperty(PROP_HOST, parts[0]);

        try {
            props.setProperty(PROP_PORT, String.valueOf(parts.length == 2 ? Integer.valueOf(parts[1]) : DFLT_PORT));
        }
        catch (NumberFormatException ignored) {
            return false;
        }

        return true;
    }

    /**
     * Validates and parses URL parameters.
     *
     * @param val Parameters string.
     * @param delim Delimiter.
     * @param props Properties.
     * @return Whether URL parameters string is valid.
     */
    private boolean parseParameters(String val, String delim, Properties props) {
        String[] params = val.split(delim);

        for (String param : params) {
            String[] pair = param.split("=");

            if (pair.length != 2 || pair[0].isEmpty() || pair[1].isEmpty())
                return false;

            props.setProperty(PROP_PREFIX + pair[0], pair[1]);
        }

        return true;
    }

    /**
     * Extension of {@link DriverPropertyInfo} that adds
     * convenient constructors.
     */
    private static class PropertyInfo extends DriverPropertyInfo {

        /**
         * @param name Name.
         * @param val Value.
         * @param desc Description.
         */
        private PropertyInfo(String name, String val, String desc) {
            super(name, val);

            description = desc;
        }
    }
}


text:
//
//  GTLWebmastersSitemapsListResponse.m
//

// ----------------------------------------------------------------------------
// NOTE: This file is generated from Google APIs Discovery Service.
// Service:
//   Webmaster Tools API (webmasters/v3)
// Description:
//   Lets you view Google Webmaster Tools data for your verified sites.
// Documentation:
//   https://developers.google.com/webmaster-tools/
// Classes:
//   GTLWebmastersSitemapsListResponse (0 custom class methods, 1 custom properties)

#import "GTLWebmastersSitemapsListResponse.h"

#import "GTLWebmastersWmxSitemap.h"

// ----------------------------------------------------------------------------
//
//   GTLWebmastersSitemapsListResponse
//

@implementation GTLWebmastersSitemapsListResponse
@dynamic sitemap;

+ (NSDictionary *)arrayPropertyToClassMap {
  NSDictionary *map = @{
    @"sitemap" : [GTLWebmastersWmxSitemap class]
  };
  return map;
}

@end


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

#include "status.h"

using namespace easynet;

void NetWorkStatus::add_send_packet(int32_t c) {
    send_packet_ += c;
    ++send_msg_;
}

void NetWorkStatus::add_receive_packet(int32_t c) {
    receive_packet_ += c;
    ++receive_msg_;
}

void NetWorkStatus::add_online_count() {
    ++online_count_;
}

void NetWorkStatus::del_online_count() {
    --online_count_;
}

void NetWorkStatus::print_status() {
    LOG(INFO) << "发送流量:" << send_packet_ << " 接收流量:" << receive_packet_
            << " 发送消息:" << send_msg_ << " 接收消息:" << receive_msg_
            << " 在线数量:" << online_count_;
}

uint64_t NetWorkStatus::send_packet_ = 0;
uint64_t NetWorkStatus::receive_packet_ = 0;
uint64_t NetWorkStatus::send_msg_ = 0;
uint64_t NetWorkStatus::receive_msg_ = 0;
uint64_t NetWorkStatus::online_count_ = 0;


text:
from distutils.core import setup

setup(
    name = "bh_oauth",
    version = "2.0.0",
    author = "Narūnas Krasauskas",
    author_email = "narun4sk@gmail.com",
    url = "https://github.com/narunask/BH_OAuth",
    download_url = "https://github.com/narunask/BH_OAuth/archive/master.zip",
    keywords = ["bullhorn", "rest", "client"],
    install_requires = ["requests>=2.9.1",],
    package_dir = {'': 'BH_OAuth_py2'},
    py_modules = ["bh_oauth",],
    data_files=[("", ["LICENSE"]),],
    classifiers = [
        "Programming Language :: Python",
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 2.7",
        "Development Status :: 4 - Beta",
        "Environment :: Other Environment",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: BSD License",
        "Operating System :: OS Independent",
        "Topic :: Software Development :: Libraries :: Python Modules",
        "Topic :: Internet :: WWW/HTTP",
        "Topic :: Internet :: WWW/HTTP :: Dynamic Content",
        ],
    description = "bullhorn.com REST API Client",
    long_description = """\
bullhorn.com REST API Client
----------------------------

*Dependencies*:

- `requests`_ - HTTP for Humans

*Quick Example*::

    auth = dict(
        client = "Bullhorn OAuth Client ID",
        secret = 'Bullhorn OAuth Client Secret',
        username = "Bullhorn Username",
        password = "Bullhorn Password")

    bhr = BHRest(**auth)
    bhr._auth_url = "https://auth9.bullhornstaffing.com/oauth"
    bhr._rest_url = "https://rest9.bullhornstaffing.com/rest-services"

    print bhr.access_token
    print bhr.find(query="+12345678")

*Features*:

- Automatically refresh `rest_token/url` if `access_token` has expired.
- Search the following entity types given a string containing search terms.

.. _requests: http://docs.python-requests.org/en/master/user/install/#install
"""
)


text:
package cloud

import (
	"errors"
	"strconv"
	"testing"
	"time"

	"github.com/quilt/quilt/cloud/acl"
	"github.com/quilt/quilt/db"
	"github.com/quilt/quilt/join"
	"github.com/stretchr/testify/assert"
)

var FakeAmazon db.Provider = "FakeAmazon"
var FakeVagrant db.Provider = "FakeVagrant"
var testRegion = "Fake region"

type fakeProvider struct {
	namespace   string
	machines    map[string]db.Machine
	roles       map[string]db.Role
	idCounter   int
	cloudConfig string

	bootRequests []db.Machine
	stopRequests []string
	updatedIPs   []db.Machine
	aclRequests  []acl.ACL

	listError error
}

func fakeValidRegions(p db.Provider) []string {
	return []string{testRegion}
}

func (p *fakeProvider) clearLogs() {
	p.bootRequests = nil
	p.stopRequests = nil
	p.aclRequests = nil
	p.updatedIPs = nil
}

func (p *fakeProvider) List() ([]db.Machine, error) {
	if p.listError != nil {
		return nil, p.listError
	}

	var machines []db.Machine
	for _, machine := range p.machines {
		machines = append(machines, machine)
	}
	return machines, nil
}

func (p *fakeProvider) Boot(bootSet []db.Machine) error {
	for _, toBoot := range bootSet {
		// Record the boot request before we mutate it with implementation
		// details of our fakeProvider.
		p.bootRequests = append(p.bootRequests, toBoot)

		p.idCounter++
		idStr := strconv.Itoa(p.idCounter)
		toBoot.CloudID = idStr
		toBoot.PublicIP = idStr

		// A machine's role is `None` until the minion boots, at which
		// `getMachineRoles` will populate this field with the correct role.
		// We simulate this by setting the role of the machine returned by
		// `List()` to be None, and only return the correct role in
		// `getMachineRole`.
		p.roles[toBoot.PublicIP] = toBoot.Role
		toBoot.Role = db.None

		p.machines[idStr] = toBoot
	}

	return nil
}

func (p *fakeProvider) Stop(machines []db.Machine) error {
	for _, machine := range machines {
		delete(p.machines, machine.CloudID)
		p.stopRequests = append(p.stopRequests, machine.CloudID)
	}
	return nil
}

func (p *fakeProvider) SetACLs(acls []acl.ACL) error {
	p.aclRequests = acls
	return nil
}

func (p *fakeProvider) UpdateFloatingIPs(machines []db.Machine) error {
	for _, desired := range machines {
		curr := p.machines[desired.CloudID]
		curr.FloatingIP = desired.FloatingIP
		p.machines[desired.CloudID] = curr
	}
	p.updatedIPs = append(p.updatedIPs, machines...)
	return nil
}

func newTestCloud(namespace string) *cloud {
	sleep = func(t time.Duration) {}
	mock()
	return newCloud(db.New(), namespace)
}

func TestPanicBadProvider(t *testing.T) {
	temp := allProviders
	defer func() {
		r := recover()
		assert.NotNil(t, r)
		allProviders = temp
	}()
	allProviders = []db.Provider{FakeAmazon}
	conn := db.New()
	newCloud(conn, "test")
}

func TestSyncDB(t *testing.T) {
	checkSyncDB := func(cloudMachines []joinMachine,
		databaseMachines []db.Machine, expected syncDBResult) syncDBResult {
		dbRes := syncDB(cloudMachines, databaseMachines)

		assert.Equal(t, expected.boot, dbRes.boot, "boot")
		assert.Equal(t, expected.stop, dbRes.stop, "stop")
		assert.Equal(t, expected.updateIPs, dbRes.updateIPs, "updateIPs")

		return dbRes
	}

	var noMachines []joinMachine
	dbNoSize := db.Machine{Provider: FakeAmazon, Region: testRegion}
	cmNoSize := joinMachine{provider: FakeAmazon, region: testRegion}
	dbLarge := db.Machine{Provider: FakeAmazon, Size: "m4.large", Region: testRegion}
	cmLarge := joinMachine{
		provider: FakeAmazon,
		region:   testRegion,
		Machine:  db.Machine{Size: "m4.large"},
	}

	dbMaster := db.Machine{Provider: FakeAmazon, Role: db.Master}
	cmMasterList := joinMachine{provider: FakeAmazon, role: db.Master}
	dbWorker := db.Machine{Provider: FakeAmazon, Role: db.Worker}
	cmWorkerList := joinMachine{provider: FakeAmazon, role: db.Worker}

	cmNoIP := joinMachine{provider: FakeAmazon, Machine: db.Machine{CloudID: "id"}}
	cmWithIP := joinMachine{
		provider: FakeAmazon,
		Machine:  db.Machine{CloudID: "id", FloatingIP: "ip"},
	}
	dbNoIP := db.Machine{Provider: FakeAmazon, CloudID: "id"}
	dbWithIP := db.Machine{Provider: FakeAmazon, CloudID: "id", FloatingIP: "ip"}

	// Test boot with no size
	checkSyncDB(noMachines, []db.Machine{dbNoSize, dbNoSize}, syncDBResult{
		boot: []db.Machine{dbNoSize, dbNoSize},
	})

	// Test boot with size
	checkSyncDB(noMachines, []db.Machine{dbLarge, dbLarge}, syncDBResult{
		boot: []db.Machine{dbLarge, dbLarge},
	})

	// Test mixed boot
	checkSyncDB(noMachines, []db.Machine{dbNoSize, dbLarge}, syncDBResult{
		boot: []db.Machine{dbNoSize, dbLarge},
	})

	// Test partial boot
	checkSyncDB([]joinMachine{cmNoSize}, []db.Machine{dbNoSize, dbLarge},
		syncDBResult{
			boot: []db.Machine{dbLarge},
		},
	)

	// Test stop
	checkSyncDB([]joinMachine{cmNoSize, cmNoSize}, []db.Machine{}, syncDBResult{
		stop: []joinMachine{cmNoSize, cmNoSize},
	})

	// Test partial stop
	checkSyncDB([]joinMachine{cmNoSize, cmLarge}, []db.Machine{}, syncDBResult{
		stop: []joinMachine{cmNoSize, cmLarge},
	})

	// Test assign Floating IP
	checkSyncDB([]joinMachine{cmNoIP}, []db.Machine{dbWithIP}, syncDBResult{
		updateIPs: []joinMachine{cmWithIP},
	})

	// Test remove Floating IP
	checkSyncDB([]joinMachine{cmWithIP}, []db.Machine{dbNoIP}, syncDBResult{
		updateIPs: []joinMachine{cmNoIP},
	})

	// Test replace Floating IP
	cNewIP := joinMachine{
		provider: FakeAmazon,
		Machine:  db.Machine{CloudID: "id", FloatingIP: "ip^"},
	}
	checkSyncDB([]joinMachine{cNewIP}, []db.Machine{dbWithIP}, syncDBResult{
		updateIPs: []joinMachine{cmWithIP},
	})

	// Test bad disk size
	checkSyncDB([]joinMachine{{Machine: db.Machine{DiskSize: 3}}},
		[]db.Machine{{DiskSize: 4}},
		syncDBResult{
			stop: []joinMachine{{Machine: db.Machine{DiskSize: 3}}},
			boot: []db.Machine{{DiskSize: 4}},
		})

	// Test different roles
	checkSyncDB([]joinMachine{cmWorkerList}, []db.Machine{dbMaster}, syncDBResult{
		boot: []db.Machine{dbMaster},
		stop: []joinMachine{cmWorkerList},
	})

	checkSyncDB([]joinMachine{cmMasterList}, []db.Machine{dbWorker}, syncDBResult{
		boot: []db.Machine{dbWorker},
		stop: []joinMachine{cmMasterList},
	})

	// Test reserved instances.
	checkSyncDB([]joinMachine{{Machine: db.Machine{Preemptible: true}}},
		[]db.Machine{{Preemptible: false}},
		syncDBResult{
			boot: []db.Machine{{Preemptible: false}},
			stop: []joinMachine{
				{Machine: db.Machine{Preemptible: true}},
			},
		})

	// Test matching role as priority over PublicIP
	dbMaster.PublicIP = "worker"
	cmMasterList.PublicIP = "master"
	dbWorker.PublicIP = "master"
	cmWorkerList.PublicIP = "worker"

	checkSyncDB([]joinMachine{cmMasterList, cmWorkerList},
		[]db.Machine{dbMaster, dbWorker},
		syncDBResult{})

	// Test shuffling roles before CloudID is assigned
	dbw1 := db.Machine{Provider: FakeAmazon, Role: db.Worker, PublicIP: "w1"}
	dbw2 := db.Machine{Provider: FakeAmazon, Role: db.Worker, PublicIP: "w2"}
	dbw3 := db.Machine{Provider: FakeAmazon, Role: db.Worker, PublicIP: "w3"}

	mw1 := joinMachine{provider: FakeAmazon, role: db.Worker,
		Machine: db.Machine{CloudID: "mw1", PublicIP: "w1"}}
	mw2 := joinMachine{provider: FakeAmazon, role: db.Worker,
		Machine: db.Machine{CloudID: "mw2", PublicIP: "w2"}}
	mw3 := joinMachine{provider: FakeAmazon, role: db.Worker,
		Machine: db.Machine{CloudID: "mw3", PublicIP: "w3"}}

	pair1 := join.Pair{L: dbw1, R: mw1}
	pair2 := join.Pair{L: dbw2, R: mw2}
	pair3 := join.Pair{L: dbw3, R: mw3}

	exp := []join.Pair{
		pair1,
		pair2,
		pair3,
	}

	pairs := checkSyncDB([]joinMachine{mw1, mw2, mw3},
		[]db.Machine{dbw1, dbw2, dbw3},
		syncDBResult{})

	assert.Equal(t, exp, pairs.pairs)

	// Test FloatingIP without role
	dbf1 := db.Machine{Provider: FakeAmazon, Role: db.Master, PublicIP: "master"}
	dbf2 := db.Machine{Provider: FakeAmazon, Role: db.Worker, PublicIP: "worker",
		FloatingIP: "float"}

	cmf1 := joinMachine{provider: FakeAmazon,
		Machine: db.Machine{PublicIP: "worker", CloudID: "worker"}}
	cmf2 := joinMachine{provider: FakeAmazon,
		Machine: db.Machine{PublicIP: "master", CloudID: "master"}}

	// No roles, CloudIDs not assigned, so nothing should happen
	checkSyncDB([]joinMachine{cmf1, cmf2},
		[]db.Machine{dbf1, dbf2},
		syncDBResult{})

	cmf1.role = db.Worker

	// One role assigned, so one CloudID to be assigned after
	checkSyncDB([]joinMachine{cmf1, cmf2},
		[]db.Machine{dbf1, dbf2},
		syncDBResult{})

	dbf2.CloudID = cmf1.CloudID
	cmf2.role = db.Master

	// Now that CloudID of machine with FloatingIP has been assigned,
	// FloatingIP should also be assigned
	checkSyncDB([]joinMachine{cmf1, cmf2},
		[]db.Machine{dbf1, dbf2},
		syncDBResult{
			updateIPs: []joinMachine{
				{
					provider: FakeAmazon,
					role:     db.Worker,
					Machine: db.Machine{
						PublicIP:   "worker",
						CloudID:    "worker",
						FloatingIP: "float",
					},
				},
			},
		})

	// Test FloatingIP role shuffling
	dbm2 := db.Machine{Provider: FakeAmazon, Role: db.Master, PublicIP: "mIP"}
	dbm3 := db.Machine{Provider: FakeAmazon, Role: db.Worker, PublicIP: "wIP1",
		FloatingIP: "flip1"}
	dbm4 := db.Machine{Provider: FakeAmazon, Role: db.Worker, PublicIP: "wIP2",
		FloatingIP: "flip2"}

	m2 := joinMachine{provider: FakeAmazon,
		Machine: db.Machine{PublicIP: "mIP", CloudID: "m2"}}
	m3 := joinMachine{provider: FakeAmazon,
		Machine: db.Machine{PublicIP: "wIP1", CloudID: "m3"}}
	m4 := joinMachine{provider: FakeAmazon,
		Machine: db.Machine{PublicIP: "wIP2", CloudID: "m4"}}

	m2.role = db.Worker
	m3.role = db.Master
	m4.role = db.Worker

	// CloudIDs not assigned to db machines yet, so shouldn't update anything.
	checkSyncDB([]joinMachine{m2, m3, m4},
		[]db.Machine{dbm2, dbm3, dbm4},
		syncDBResult{})

	dbm2.CloudID = m3.CloudID
	dbm3.CloudID = m2.CloudID
	dbm4.CloudID = m4.CloudID

	// CloudIDs are now assigned, so time to update floating IPs
	checkSyncDB([]joinMachine{m2, m3, m4},
		[]db.Machine{dbm2, dbm3, dbm4},
		syncDBResult{
			updateIPs: []joinMachine{
				{
					provider: FakeAmazon,
					role:     db.Worker,
					Machine: db.Machine{
						PublicIP:   "mIP",
						CloudID:    "m2",
						FloatingIP: "flip1",
					},
				},
				{
					provider: FakeAmazon,
					role:     db.Worker,
					Machine: db.Machine{
						PublicIP:   "wIP2",
						CloudID:    "m4",
						FloatingIP: "flip2",
					},
				},
			},
		})

}

func TestSync(t *testing.T) {
	type ipRequest struct {
		id string
		ip string
	}

	type assertion struct {
		boot      []db.Machine
		stop      []string
		updateIPs []ipRequest
	}

	checkSync := func(clst *cloud, provider db.Provider, region string,
		expected assertion) {

		clst.runOnce()
		inst := launchLoc{provider, region}
		providerInst := clst.providers[inst].(*fakeProvider)

		assert.Equal(t, expected.boot, providerInst.bootRequests, "bootRequests")

		assert.Equal(t, expected.stop, providerInst.stopRequests, "stopRequests")

		var updatedIPs []ipRequest
		for _, m := range providerInst.updatedIPs {
			updatedIPs = append(updatedIPs,
				ipRequest{id: m.CloudID, ip: m.FloatingIP})
		}
		assert.Equal(t, expected.updateIPs, updatedIPs, "updateIPs")

		providerInst.clearLogs()
	}

	// Test initial boot
	clst := newTestCloud("ns")
	setNamespace(clst.conn, "ns")
	clst.conn.Txn(db.AllTables...).Run(func(view db.Database) error {
		m := view.InsertMachine()
		m.Role = db.Master
		m.Provider = FakeAmazon
		m.Region = testRegion
		m.Size = "m4.large"
		view.Commit(m)

		return nil
	})
	checkSync(clst, FakeAmazon, testRegion,
		assertion{boot: []db.Machine{
			{Size: "m4.large", Role: db.Master},
		}})

	// Test adding a machine with the same provider
	clst.conn.Txn(db.AllTables...).Run(func(view db.Database) error {
		m := view.InsertMachine()
		m.Role = db.Master
		m.Provider = FakeAmazon
		m.Region = testRegion
		m.Size = "m4.xlarge"
		view.Commit(m)

		return nil
	})
	checkSync(clst, FakeAmazon, testRegion,
		assertion{boot: []db.Machine{
			{Size: "m4.xlarge", Role: db.Master},
		}})

	// Test adding a machine with a different provider
	clst.conn.Txn(db.AllTables...).Run(func(view db.Database) error {
		m := view.InsertMachine()
		m.Role = db.Master
		m.Provider = FakeVagrant
		m.Region = testRegion
		m.Size = "vagrant.large"
		view.Commit(m)

		return nil
	})
	checkSync(clst, FakeVagrant, testRegion,
		assertion{boot: []db.Machine{
			{Size: "vagrant.large", Role: db.Master},
		}})

	// Test removing a machine
	var toRemove db.Machine
	clst.conn.Txn(db.AllTables...).Run(func(view db.Database) error {
		toRemove = view.SelectFromMachine(func(m db.Machine) bool {
			return m.Provider == FakeAmazon && m.Size == "m4.xlarge"
		})[0]
		view.Remove(toRemove)

		return nil
	})
	checkSync(clst, FakeAmazon, testRegion,
		assertion{stop: []string{toRemove.CloudID}})

	// Test booting a machine with floating IP - shouldn't update FloatingIP yet
	clst.conn.Txn(db.AllTables...).Run(func(view db.Database) error {
		m := view.InsertMachine()
		m.Role = db.Master
		m.Provider = FakeAmazon
		m.Size = "m4.large"
		m.Region = testRegion
		m.FloatingIP = "ip"
		view.Commit(m)

		return nil
	})
	checkSync(clst, FakeAmazon, testRegion, assertion{
		boot: []db.Machine{
			{Size: "m4.large", Role: db.Master},
		},
	})

	// The bootRequest from the previous test is done now, and a CloudID has
	// been assigned, so we should also receive the ipRequest from before
	checkSync(clst, FakeAmazon, testRegion, assertion{
		updateIPs: []ipRequest{{id: "3", ip: "ip"}},
	})

	// Test assigning a floating IP to an existing machine
	clst.conn.Txn(db.AllTables...).Run(func(view db.Database) error {
		toAssign := view.SelectFromMachine(func(m db.Machine) bool {
			return m.Provider == FakeAmazon &&
				m.Size == "m4.large" &&
				m.FloatingIP == ""
		})[0]
		toAssign.FloatingIP = "another.ip"
		view.Commit(toAssign)

		return nil
	})
	checkSync(clst, FakeAmazon, testRegion, assertion{
		updateIPs: []ipRequest{
			{
				id: "1",
				ip: "another.ip",
			},
		},
	})

	// Test removing a floating IP
	clst.conn.Txn(db.AllTables...).Run(func(view db.Database) error {
		toUpdate := view.SelectFromMachine(func(m db.Machine) bool {
			return m.Provider == FakeAmazon &&
				m.Size == "m4.large" &&
				m.FloatingIP == "ip"
		})[0]
		toUpdate.FloatingIP = ""
		view.Commit(toUpdate)

		return nil
	})
	checkSync(clst, FakeAmazon, testRegion, assertion{
		updateIPs: []ipRequest{{
			id: "3",
			ip: "",
		}},
	})

	// Test removing and adding a machine
	clst.conn.Txn(db.AllTables...).Run(func(view db.Database) error {
		toRemove = view.SelectFromMachine(func(m db.Machine) bool {
			return m.Provider == FakeAmazon && m.Size == "m4.large"
		})[0]
		view.Remove(toRemove)

		m := view.InsertMachine()
		m.Role = db.Worker
		m.Provider = FakeAmazon
		m.Size = "m4.xlarge"
		m.Region = testRegion
		view.Commit(m)

		return nil
	})
	checkSync(clst, FakeAmazon, testRegion, assertion{
		boot: []db.Machine{
			{Size: "m4.xlarge", Role: db.Worker},
		},
		stop: []string{toRemove.CloudID},
	})

	// Test adding machine with different role
	clst.conn.Txn(db.AllTables...).Run(func(view db.Database) error {
		m := view.InsertMachine()
		m.Role = db.Master
		m.Provider = FakeAmazon
		m.Size = "m4.xlarge"
		m.Region = testRegion
		view.Commit(m)

		return nil
	})

	checkSync(clst, FakeAmazon, testRegion, assertion{
		boot: []db.Machine{
			{Size: "m4.xlarge", Role: db.Master},
		},
	})

	clst.conn.Txn(db.AllTables...).Run(func(view db.Database) error {
		toRemove = view.SelectFromMachine(func(m db.Machine) bool {
			return m.Role == db.Master && m.Size == "m4.xlarge" &&
				m.Provider == FakeAmazon
		})[0]
		view.Remove(toRemove)
		m := view.InsertMachine()
		m.Role = db.Worker
		m.Provider = FakeAmazon
		m.Size = "m4.xlarge"
		m.Region = testRegion
		view.Commit(m)

		return nil
	})

	checkSync(clst, FakeAmazon, testRegion, assertion{
		boot: []db.Machine{
			{Size: "m4.xlarge", Role: db.Worker},
		},
		stop: []string{toRemove.CloudID},
	})
}

func TestACLs(t *testing.T) {
	myIP = func() (string, error) {
		return "5.6.7.8", nil
	}

	clst := newTestCloud("ns")
	clst.syncACLs([]string{"admin"},
		[]db.PortRange{
			{
				MinPort: 80,
				MaxPort: 80,
			},
		},
		[]db.Machine{
			{
				Provider: FakeAmazon,
				PublicIP: "8.8.8.8",
				Region:   testRegion,
			},
			{},
		},
	)

	exp := []acl.ACL{
		{
			CidrIP:  "admin",
			MinPort: 1,
			MaxPort: 65535,
		},
		{
			CidrIP:  "5.6.7.8/32",
			MinPort: 1,
			MaxPort: 65535,
		},
		{
			CidrIP:  "0.0.0.0/0",
			MinPort: 80,
			MaxPort: 80,
		},
		{
			CidrIP:  "8.8.8.8/32",
			MinPort: 1,
			MaxPort: 65535,
		},
	}
	inst := launchLoc{FakeAmazon, testRegion}
	actual := clst.providers[inst].(*fakeProvider).aclRequests
	assert.Equal(t, exp, actual)
}

func TestUpdateCloud(t *testing.T) {
	conn := db.New()

	clst := updateCloud(conn, nil, nil)
	assert.Nil(t, clst)

	setNamespace(conn, "ns1")
	clst = updateCloud(conn, clst, nil)
	assert.NotNil(t, clst)
	assert.Equal(t, "ns1", clst.namespace)

	inst := launchLoc{FakeAmazon, testRegion}
	amzn := clst.providers[inst].(*fakeProvider)
	assert.Empty(t, amzn.bootRequests)
	assert.Empty(t, amzn.stopRequests)
	assert.Equal(t, "ns1", amzn.namespace)

	conn.Txn(db.AllTables...).Run(func(view db.Database) error {
		m := view.InsertMachine()
		m.Provider = FakeAmazon
		m.Size = "size1"
		m.Region = testRegion
		view.Commit(m)
		return nil
	})

	oldClst := clst
	oldAmzn := amzn

	clst = updateCloud(conn, clst, nil)
	assert.NotNil(t, clst)

	// Pointers shouldn't have changed
	amzn = clst.providers[inst].(*fakeProvider)
	assert.True(t, oldClst == clst)
	assert.True(t, oldAmzn == amzn)

	assert.Empty(t, amzn.stopRequests)
	assert.Equal(t, []db.Machine{{
		Size: "size1",
	}}, amzn.bootRequests)
	assert.Equal(t, "ns1", amzn.namespace)
	amzn.clearLogs()

	conn.Txn(db.AllTables...).Run(func(view db.Database) error {
		dbms := view.SelectFromMachine(nil)
		dbms[0].Size = "size2"
		view.Commit(dbms[0])
		return nil
	})

	oldClst = clst
	oldAmzn = amzn
	setNamespace(conn, "ns2")
	clst = updateCloud(conn, clst, nil)
	assert.NotNil(t, clst)

	// Pointers should have changed
	amzn = clst.providers[inst].(*fakeProvider)
	assert.True(t, oldClst != clst)
	assert.True(t, oldAmzn != amzn)

	assert.Equal(t, "ns1", oldAmzn.namespace)
	assert.Empty(t, oldAmzn.bootRequests)
	assert.Empty(t, oldAmzn.stopRequests)

	assert.Equal(t, "ns2", amzn.namespace)
	assert.Equal(t, []db.Machine{{
		Size: "size2",
	}}, amzn.bootRequests)
	assert.Empty(t, amzn.stopRequests)
}

func TestMultiRegionDeploy(t *testing.T) {
	clst := newTestCloud("ns")
	clst.conn.Txn(db.MachineTable,
		db.BlueprintTable).Run(func(view db.Database) error {

		for _, p := range allProviders {
			for _, r := range validRegions(p) {
				m := view.InsertMachine()
				m.Provider = p
				m.Region = r
				m.Size = "size1"
				view.Commit(m)
			}
		}

		c := view.InsertBlueprint()
		c.Namespace = "ns"
		view.Commit(c)
		return nil
	})

	for i := 0; i < 2; i++ {
		clst.runOnce()
		cloudMachines, err := clst.get()
		assert.NoError(t, err)
		dbMachines := clst.conn.SelectFromMachine(nil)
		joinResult := syncDB(cloudMachines, dbMachines)

		// All machines should be booted
		assert.Empty(t, joinResult.boot)
		assert.Empty(t, joinResult.stop)
		assert.Len(t, joinResult.pairs, len(dbMachines))
	}

	clst.conn.Txn(db.MachineTable).Run(func(view db.Database) error {
		m := view.SelectFromMachine(func(m db.Machine) bool {
			return m.Provider == FakeAmazon &&
				m.Region == validRegions(FakeAmazon)[0]
		})

		assert.Len(t, m, 1)
		view.Remove(m[0])
		return nil
	})

	clst.runOnce()
	machinesRemaining, err := clst.get()
	assert.NoError(t, err)

	assert.NotContains(t, machinesRemaining, joinMachine{
		provider: FakeAmazon,
		region:   validRegions(FakeAmazon)[0],
		Machine:  db.Machine{Size: "size1"},
	})
	cloudMachines, err := clst.get()
	assert.NoError(t, err)
	dbMachines := clst.conn.SelectFromMachine(nil)
	joinResult := syncDB(cloudMachines, dbMachines)

	assert.Empty(t, joinResult.boot)
	assert.Empty(t, joinResult.stop)
	assert.Len(t, joinResult.pairs, len(dbMachines))
}

func TestGetError(t *testing.T) {
	t.Parallel()

	_, err := cloud{
		providers: map[launchLoc]provider{
			{db.Amazon, "us-west-1"}: &fakeProvider{
				listError: errors.New("err"),
			},
		},
	}.get()
	assert.EqualError(t, err, "list Amazon-us-west-1: err")

	_, err = cloud{
		providers: map[launchLoc]provider{
			{provider: db.Vagrant}: &fakeProvider{
				listError: errors.New("err"),
			},
		},
	}.get()
	assert.EqualError(t, err, "list Vagrant: err")
}

func setNamespace(conn db.Conn, ns string) {
	conn.Txn(db.AllTables...).Run(func(view db.Database) error {
		bp, err := view.GetBlueprint()
		if err != nil {
			bp = view.InsertBlueprint()
		}

		bp.Namespace = ns
		view.Commit(bp)
		return nil
	})
}

func mock() {
	var instantiatedProviders []fakeProvider
	newProvider = func(p db.Provider, namespace, region string) (provider, error) {
		ret := fakeProvider{
			namespace: namespace,
			machines:  make(map[string]db.Machine),
			roles:     make(map[string]db.Role),
		}
		ret.clearLogs()

		instantiatedProviders = append(instantiatedProviders, ret)
		return &ret, nil
	}

	validRegions = fakeValidRegions
	allProviders = []db.Provider{FakeAmazon, FakeVagrant}
	getMachineRole = func(ip string) db.Role {
		for _, prvdr := range instantiatedProviders {
			if role, ok := prvdr.roles[ip]; ok {
				return role
			}
		}
		return db.None
	}
}


text:
select sod.SalesPersonID pracId, concat(per.LastName,',',per.FirstName) as "Nazwisko, imiê", avg(TotalDue) as "Œrednia sprzeda¿",
DENSE_RANK() OVER (ORDER BY avg(TotalDue) desc) as Ranking,
case
	when NTILE(2) OVER(ORDER BY avg(TotalDue) DESC) =1 then 'Wyró¿niony'
	when NTILE(2) OVER(ORDER BY avg(TotalDue) DESC) =2 then 'Do weryfikacji'
end AS Grupa
from Sales.SalesOrderHeader sod,Person.Person per
where sod.SalesPersonID=per.BusinessEntityID
group by sod.SalesPersonID,per.LastName ,per.FirstName


text:
struct RendererData
{
	vec3 defaultColor;
	PointLight *pointLights;
	size_t numPointLights;
	AreaLight *areaLights;
	size_t numAreaLights;
	Ray* rays;
	Sphere *spheres;
	size_t numSpheres;
	Triangle *triangles;
	size_t numTriangles;
	Material* materials;
	curandState* curandStates;
};

/// <summary>
/// A struct containing all the data to be used by the entire program.
/// </summary>
struct ProgramData
{
	RendererData renderData;			//all necessary data for main render loop
	Camera camera;						//The camera
	uint3 *totalPixelColors;			//A running total of the color in all pixels.  Used to average the results of ray tracing
	cudaEvent_t start, stop;			//For measuring timing
	int lastResetTick;					//The last tick since the tracing was "reset"
	unsigned int maxIterations = 15;	//The maximum number of bounces a ray can perform
	bool resetTicksThisFrame;			//If true, the tracing must be reset this frame
	bool usePathTracer = true;			//If true, then the path tracing algorithm is running.  If false, simple ray tracing is used instead
};

void generateFrame(uchar4 *pixels, void*, int ticks);
void Key(unsigned char key, int x, int y);
bool moveCamera(Camera& camera, unsigned char key);
void saveScreenshot(char filename[160], int x, int y);

__device__
Ray computeEyeRay(int x, int y, const Camera& camera, curandState& state);

__device__
vec3 shade(const RendererData& data, const SurfaceElement& surfel, const Material& material, curandState& state);

__device__
vec3 getAreaLightPoint(const AreaLight& light, Triangle* triangles, curandState& state);

__device__
bool lineOfSight(const RendererData& data, const vec3& normal, const vec3& point0, const vec3& point1, vec3& w_i, float& distance2);

__device__
vec3 computeIndirectRadianceAndScatter(Ray& ray, const SurfaceElement& surfel, const Material& material, float cosI, const float distance, const bool inside, curandState& localState);

__device__
float computeFresnelForReflectance(const float cosI, const float sinT2, const float n1, const float n2, const float n);

__device__
void computeSinT2AndRefractiveIndexes(const float refrIndex, float& cosI, float& sinT2, float& n1, float& n2, float& n);

__device__
void reflRay(Ray& ray, const vec3& point, const vec3& normal);

__device__
void reflRay(Ray& ray, const SurfaceElement& surfel, const float cosI);

__device__
void refrRay(Ray& ray, const SurfaceElement& surfel, const float cosI, const float sinT2, const float n);

__device__
vec3 randomDirectionLambert(vec3 const& normal, curandState& state);

__device__
vec3 randomDirectionPhong(const vec3& w_o, float exponent, curandState& state);

__device__
vec3 randomDirectionBeckmann(vec3 const& normal, float roughness, curandState& state);

__device__
const quat rotateVectorToVector(const vec3& source, const vec3& target);

struct ray_is_active
{
	__host__ __device__
	bool operator()(const Ray &ray)
	{
		return ray.active;
	}
};


text:
import * as vscode from 'vscode';
import { Node, HtmlNode, Rule, Property, Stylesheet } from 'EmmetFlatNode';
import { getEmmetHelper, getFlatNode, getHtmlFlatNode, getMappingForIncludedLanguages, validate, getEmmetConfiguration, isStyleSheet, getEmmetMode, parsePartialStylesheet, isStyleAttribute, getEmbeddedCssNodeIfAny, allowedMimeTypesInScriptTag, toLSTextDocument, isOffsetInsideOpenOrCloseTag } from './util';
import { getRootNode as parseDocument } from './parseDocument';

const trimRegex = /[\u00a0]*[\d#\-\*\u2022]+\.?/;
const hexColorRegex = /^#[\da-fA-F]{0,6}$/;

interface ExpandAbbreviationInput {
	syntax: string;
	abbreviation: string;
	rangeToReplace: vscode.Range;
	textToWrap?: string[];
	filter?: string;
	indent?: string;
	baseIndent?: string;
}

interface PreviewRangesWithContent {
	previewRange: vscode.Range;
	originalRange: vscode.Range;
	originalContent: string;
	textToWrapInPreview: string[];
	baseIndent: string;
}

export async function wrapWithAbbreviation(args: any): Promise<boolean> {
	if (!validate(false)) {
		return false;
	}

	const editor = vscode.window.activeTextEditor!;
	const document = editor.document;

	args = args || {};
	if (!args['language']) {
		args['language'] = document.languageId;
	}
	// we know it's not stylesheet due to the validate(false) call above
	const syntax = getSyntaxFromArgs(args) || 'html';
	const rootNode = parseDocument(document, true);

	const helper = getEmmetHelper();

	const operationRanges = Array.from(editor.selections).sort((a, b) => a.start.compareTo(b.start)).map(selection => {
		let rangeToReplace: vscode.Range = selection;
		// wrap around the node if the selection falls inside its open or close tag
		{
			let { start, end } = rangeToReplace;

			const startOffset = document.offsetAt(start);
			const documentText = document.getText();
			const startNode = getHtmlFlatNode(documentText, rootNode, startOffset, true);
			if (startNode && isOffsetInsideOpenOrCloseTag(startNode, startOffset)) {
				start = document.positionAt(startNode.start);
				const nodeEndPosition = document.positionAt(startNode.end);
				end = nodeEndPosition.isAfter(end) ? nodeEndPosition : end;
			}

			const endOffset = document.offsetAt(end);
			const endNode = getHtmlFlatNode(documentText, rootNode, endOffset, true);
			if (endNode && isOffsetInsideOpenOrCloseTag(endNode, endOffset)) {
				const nodeStartPosition = document.positionAt(endNode.start);
				start = nodeStartPosition.isBefore(start) ? nodeStartPosition : start;
				const nodeEndPosition = document.positionAt(endNode.end);
				end = nodeEndPosition.isAfter(end) ? nodeEndPosition : end;
			}

			rangeToReplace = new vscode.Range(start, end);
		}
		// in case of multi-line, exclude last empty line from rangeToReplace
		if (!rangeToReplace.isSingleLine && rangeToReplace.end.character === 0) {
			const previousLine = rangeToReplace.end.line - 1;
			rangeToReplace = new vscode.Range(rangeToReplace.start, document.lineAt(previousLine).range.end);
		}
		// wrap line the cursor is on
		if (rangeToReplace.isEmpty) {
			rangeToReplace = document.lineAt(rangeToReplace.start).range;
		}

		// ignore whitespace on the first line
		const firstLineOfRange = document.lineAt(rangeToReplace.start);
		if (!firstLineOfRange.isEmptyOrWhitespace && firstLineOfRange.firstNonWhitespaceCharacterIndex > rangeToReplace.start.character) {
			rangeToReplace = rangeToReplace.with(new vscode.Position(rangeToReplace.start.line, firstLineOfRange.firstNonWhitespaceCharacterIndex));
		}

		return rangeToReplace;
	}).reduce((mergedRanges, range) => {
		// Merge overlapping ranges
		if (mergedRanges.length > 0 && range.intersection(mergedRanges[mergedRanges.length - 1])) {
			mergedRanges.push(range.union(mergedRanges.pop()!));
		} else {
			mergedRanges.push(range);
		}
		return mergedRanges;
	}, [] as vscode.Range[]);

	// Backup orginal selections and update selections
	// Also helps with https://github.com/microsoft/vscode/issues/113930 by avoiding `editor.linkedEditing`
	// execution if selection is inside an open or close tag
	const oldSelections = editor.selections;
	editor.selections = operationRanges.map(range => new vscode.Selection(range.start, range.end));

	// Fetch general information for the succesive expansions. i.e. the ranges to replace and its contents
	const rangesToReplace: PreviewRangesWithContent[] = operationRanges.map(rangeToReplace => {
		let textToWrapInPreview: string[];
		const textToReplace = document.getText(rangeToReplace);

		// the following assumes all the lines are indented the same way as the first
		// this assumption helps with applyPreview later
		const wholeFirstLine = document.lineAt(rangeToReplace.start).text;
		const otherMatches = wholeFirstLine.match(/^(\s*)/);
		const baseIndent = otherMatches ? otherMatches[1] : '';
		textToWrapInPreview = rangeToReplace.isSingleLine ?
			[textToReplace] :
			textToReplace.split('\n' + baseIndent).map(x => x.trimEnd());

		// escape $ characters, fixes #52640
		textToWrapInPreview = textToWrapInPreview.map(e => e.replace(/(\$\d)/g, '\\$1'));

		return {
			previewRange: rangeToReplace,
			originalRange: rangeToReplace,
			originalContent: textToReplace,
			textToWrapInPreview,
			baseIndent
		};
	});

	const { tabSize, insertSpaces } = editor.options;
	const indent = insertSpaces ? ' '.repeat(tabSize as number) : '\t';

	function revertPreview(): Thenable<boolean> {
		return editor.edit(builder => {
			for (const rangeToReplace of rangesToReplace) {
				builder.replace(rangeToReplace.previewRange, rangeToReplace.originalContent);
				rangeToReplace.previewRange = rangeToReplace.originalRange;
			}
		}, { undoStopBefore: false, undoStopAfter: false });
	}

	function applyPreview(expandAbbrList: ExpandAbbreviationInput[]): Thenable<boolean> {
		let lastOldPreviewRange = new vscode.Range(0, 0, 0, 0);
		let lastNewPreviewRange = new vscode.Range(0, 0, 0, 0);
		let totalNewLinesInserted = 0;

		return editor.edit(builder => {
			// the edits are applied in order top-down
			for (let i = 0; i < rangesToReplace.length; i++) {
				const expandedText = expandAbbr(expandAbbrList[i]) || '';
				if (!expandedText) {
					// Failed to expand text. We already showed an error inside expandAbbr.
					break;
				}

				// get the current preview range, format the new wrapped text, and then replace
				// the text in the preview range with that new text
				const oldPreviewRange = rangesToReplace[i].previewRange;
				const newText = expandedText
					.replace(/\$\{[\d]*\}/g, '|') // Removing Tabstops
					.replace(/\$\{[\d]*:([^}]*)\}/g, (_, placeholder) => placeholder) // Replacing Placeholders
					.replace(/\\\$/g, '$'); // Remove backslashes before $
				builder.replace(oldPreviewRange, newText);

				// calculate the new preview range to use for future previews
				// we also have to take into account that the previous expansions could:
				// - cause new lines to appear
				// - be on the same line as other expansions
				const expandedTextLines = newText.split('\n');
				const oldPreviewLines = oldPreviewRange.end.line - oldPreviewRange.start.line + 1;
				const newLinesInserted = expandedTextLines.length - oldPreviewLines;

				const newPreviewLineStart = oldPreviewRange.start.line + totalNewLinesInserted;
				let newPreviewStart = oldPreviewRange.start.character;
				const newPreviewLineEnd = oldPreviewRange.end.line + totalNewLinesInserted + newLinesInserted;
				let newPreviewEnd = expandedTextLines[expandedTextLines.length - 1].length;
				if (i > 0 && newPreviewLineEnd === lastNewPreviewRange.end.line) {
					// If newPreviewLineEnd is equal to the previous expandedText lineEnd,
					// set newPreviewStart to the length of the previous expandedText in that line
					// plus the number of characters between both selections.
					newPreviewStart = lastNewPreviewRange.end.character + (oldPreviewRange.start.character - lastOldPreviewRange.end.character);
					newPreviewEnd += newPreviewStart;
				} else if (i > 0 && newPreviewLineStart === lastNewPreviewRange.end.line) {
					// Same as above but expandedTextLines.length > 1 so newPreviewEnd keeps its value.
					newPreviewStart = lastNewPreviewRange.end.character + (oldPreviewRange.start.character - lastOldPreviewRange.end.character);
				} else if (expandedTextLines.length === 1) {
					// If the expandedText is single line, add the length of preceeding text as it will not be included in line length.
					newPreviewEnd += oldPreviewRange.start.character;
				}

				lastOldPreviewRange = rangesToReplace[i].previewRange;
				lastNewPreviewRange = new vscode.Range(newPreviewLineStart, newPreviewStart, newPreviewLineEnd, newPreviewEnd);
				rangesToReplace[i].previewRange = lastNewPreviewRange;
				totalNewLinesInserted += newLinesInserted;
			}
		}, { undoStopBefore: false, undoStopAfter: false });
	}

	let inPreviewMode = false;
	async function makeChanges(inputAbbreviation: string | undefined, previewChanges: boolean): Promise<boolean> {
		const isAbbreviationValid = !!inputAbbreviation && !!inputAbbreviation.trim() && helper.isAbbreviationValid(syntax, inputAbbreviation);
		const extractedResults = isAbbreviationValid ? helper.extractAbbreviationFromText(inputAbbreviation!, syntax) : undefined;
		if (!extractedResults) {
			if (inPreviewMode) {
				inPreviewMode = false;
				await revertPreview();
			}
			return false;
		}

		const { abbreviation, filter } = extractedResults;
		if (abbreviation !== inputAbbreviation) {
			// Not clear what should we do in this case. Warn the user? How?
		}

		if (previewChanges) {
			const expandAbbrList: ExpandAbbreviationInput[] = rangesToReplace.map(rangesAndContent =>
				({ syntax, abbreviation, rangeToReplace: rangesAndContent.originalRange, textToWrap: rangesAndContent.textToWrapInPreview, filter, indent, baseIndent: rangesAndContent.baseIndent })
			);

			inPreviewMode = true;
			return applyPreview(expandAbbrList);
		}

		const expandAbbrList: ExpandAbbreviationInput[] = rangesToReplace.map(rangesAndContent =>
			({ syntax, abbreviation, rangeToReplace: rangesAndContent.originalRange, textToWrap: rangesAndContent.textToWrapInPreview, filter, indent })
		);

		if (inPreviewMode) {
			inPreviewMode = false;
			await revertPreview();
		}

		return expandAbbreviationInRange(editor, expandAbbrList, false);
	}

	let currentValue = '';
	function inputChanged(value: string): string {
		if (value !== currentValue) {
			currentValue = value;
			makeChanges(value, true);
		}
		return '';
	}

	const prompt = vscode.l10n.t("Enter Abbreviation");
	const inputAbbreviation = (args && args['abbreviation'])
		? (args['abbreviation'] as string)
		: await vscode.window.showInputBox({ prompt, validateInput: inputChanged });

	const changesWereMade = await makeChanges(inputAbbreviation, false);
	if (!changesWereMade) {
		editor.selections = oldSelections;
	}

	return changesWereMade;
}

export function expandEmmetAbbreviation(args: any): Thenable<boolean | undefined> {
	if (!validate() || !vscode.window.activeTextEditor) {
		return fallbackTab();
	}

	/**
	 * Short circuit the parsing. If previous character is space, do not expand.
	 */
	if (vscode.window.activeTextEditor.selections.length === 1 &&
		vscode.window.activeTextEditor.selection.isEmpty
	) {
		const anchor = vscode.window.activeTextEditor.selection.anchor;
		if (anchor.character === 0) {
			return fallbackTab();
		}

		const prevPositionAnchor = anchor.translate(0, -1);
		const prevText = vscode.window.activeTextEditor.document.getText(new vscode.Range(prevPositionAnchor, anchor));
		if (prevText === ' ' || prevText === '\t') {
			return fallbackTab();
		}
	}

	args = args || {};
	if (!args['language']) {
		args['language'] = vscode.window.activeTextEditor.document.languageId;
	} else {
		const excludedLanguages = vscode.workspace.getConfiguration('emmet')['excludeLanguages'] ? vscode.workspace.getConfiguration('emmet')['excludeLanguages'] : [];
		if (excludedLanguages.indexOf(vscode.window.activeTextEditor.document.languageId) > -1) {
			return fallbackTab();
		}
	}
	const syntax = getSyntaxFromArgs(args);
	if (!syntax) {
		return fallbackTab();
	}

	const editor = vscode.window.activeTextEditor;

	// When tabbed on a non empty selection, do not treat it as an emmet abbreviation, and fallback to tab instead
	if (vscode.workspace.getConfiguration('emmet')['triggerExpansionOnTab'] === true && editor.selections.find(x => !x.isEmpty)) {
		return fallbackTab();
	}

	const abbreviationList: ExpandAbbreviationInput[] = [];
	let firstAbbreviation: string;
	let allAbbreviationsSame: boolean = true;
	const helper = getEmmetHelper();

	const getAbbreviation = (document: vscode.TextDocument, selection: vscode.Selection, position: vscode.Position, syntax: string): [vscode.Range | null, string, string | undefined] => {
		position = document.validatePosition(position);
		let rangeToReplace: vscode.Range = selection;
		let abbr = document.getText(rangeToReplace);
		if (!rangeToReplace.isEmpty) {
			const extractedResults = helper.extractAbbreviationFromText(abbr, syntax);
			if (extractedResults) {
				return [rangeToReplace, extractedResults.abbreviation, extractedResults.filter];
			}
			return [null, '', ''];
		}

		const currentLine = editor.document.lineAt(position.line).text;
		const textTillPosition = currentLine.substr(0, position.character);

		// Expand cases like <div to

 explicitly
		// else we will end up with <

		if (syntax === 'html') {
			const matches = textTillPosition.match(/<(\w+)$/);
			if (matches) {
				abbr = matches[1];
				rangeToReplace = new vscode.Range(position.translate(0, -(abbr.length + 1)), position);
				return [rangeToReplace, abbr, ''];
			}
		}
		const extractedResults = helper.extractAbbreviation(toLSTextDocument(editor.document), position, { lookAhead: false });
		if (!extractedResults) {
			return [null, '', ''];
		}

		const { abbreviationRange, abbreviation, filter } = extractedResults;
		return [new vscode.Range(abbreviationRange.start.line, abbreviationRange.start.character, abbreviationRange.end.line, abbreviationRange.end.character), abbreviation, filter];
	};

	const selectionsInReverseOrder = editor.selections.slice(0);
	selectionsInReverseOrder.sort((a, b) => {
		const posA = a.isReversed ? a.anchor : a.active;
		const posB = b.isReversed ? b.anchor : b.active;
		return posA.compareTo(posB) * -1;
	});

	let rootNode: Node | undefined;
	function getRootNode() {
		if (rootNode) {
			return rootNode;
		}

		const usePartialParsing = vscode.workspace.getConfiguration('emmet')['optimizeStylesheetParsing'] === true;
		if (editor.selections.length === 1 && isStyleSheet(editor.document.languageId) && usePartialParsing && editor.document.lineCount > 1000) {
			rootNode = parsePartialStylesheet(editor.document, editor.selection.isReversed ? editor.selection.anchor : editor.selection.active);
		} else {
			rootNode = parseDocument(editor.document, true);
		}

		return rootNode;
	}

	selectionsInReverseOrder.forEach(selection => {
		const position = selection.isReversed ? selection.anchor : selection.active;
		const [rangeToReplace, abbreviation, filter] = getAbbreviation(editor.document, selection, position, syntax);
		if (!rangeToReplace) {
			return;
		}
		if (!helper.isAbbreviationValid(syntax, abbreviation)) {
			return;
		}
		if (isStyleSheet(syntax) && abbreviation.endsWith(':')) {
			// Fix for https://github.com/Microsoft/vscode/issues/1623
			return;
		}

		const offset = editor.document.offsetAt(position);
		let currentNode = getFlatNode(getRootNode(), offset, true);
		let validateLocation = true;
		let syntaxToUse = syntax;

		if (editor.document.languageId === 'html') {
			if (isStyleAttribute(currentNode, offset)) {
				syntaxToUse = 'css';
				validateLocation = false;
			} else {
				const embeddedCssNode = getEmbeddedCssNodeIfAny(editor.document, currentNode, position);
				if (embeddedCssNode) {
					currentNode = getFlatNode(embeddedCssNode, offset, true);
					syntaxToUse = 'css';
				}
			}
		}

		if (validateLocation && !isValidLocationForEmmetAbbreviation(editor.document, getRootNode(), currentNode, syntaxToUse, offset, rangeToReplace)) {
			return;
		}

		if (!firstAbbreviation) {
			firstAbbreviation = abbreviation;
		} else if (allAbbreviationsSame && firstAbbreviation !== abbreviation) {
			allAbbreviationsSame = false;
		}

		abbreviationList.push({ syntax: syntaxToUse, abbreviation, rangeToReplace, filter });
	});

	return expandAbbreviationInRange(editor, abbreviationList, allAbbreviationsSame).then(success => {
		return success ? Promise.resolve(undefined) : fallbackTab();
	});
}

function fallbackTab(): Thenable<boolean | undefined> {
	if (vscode.workspace.getConfiguration('emmet')['triggerExpansionOnTab'] === true) {
		return vscode.commands.executeCommand('tab');
	}
	return Promise.resolve(true);
}
/**
 * Checks if given position is a valid location to expand emmet abbreviation.
 * Works only on html and css/less/scss syntax
 * @param document current Text Document
 * @param rootNode parsed document
 * @param currentNode current node in the parsed document
 * @param syntax syntax of the abbreviation
 * @param position position to validate
 * @param abbreviationRange The range of the abbreviation for which given position is being validated
 */
export function isValidLocationForEmmetAbbreviation(document: vscode.TextDocument, rootNode: Node | undefined, currentNode: Node | undefined, syntax: string, offset: number, abbreviationRange: vscode.Range): boolean {
	if (isStyleSheet(syntax)) {
		const stylesheet =


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>"tscmd/dev/compose-testdata" | mailer</title>
	<meta name="description" content="Documentation for mailer">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="../assets/css/main.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					mailer

						Options

								All

Public

Public/Protected

All

							<input type="checkbox" id="tsd-filter-inherited" checked />
							Inherited
							<input type="checkbox" id="tsd-filter-externals" checked />
							Externals
							<input type="checkbox" id="tsd-filter-only-exported" />
							Only exported

					Menu

					Globals

					"tscmd/dev/compose-testdata"

Module "tscmd/dev/compose-testdata"

Index

Functions

create<wbr>Notice<wbr>Main

Functions

Const create<wbr>Notice<wbr>Main

create<wbr>Notice<wbr>Main(): Promise<void>

Defined in tscmd/dev/compose-testdata.ts:11

Returns Promise<void>

						Globals

						"tscmd/dev/compose-<wbr>testdata"

Legend

Object literal

Variable

Function

Type alias

Enumeration

Interface

Class

Generated using TypeDoc


text:
<?php
namespace api\modules\v1\models;
use \yii\db\ActiveRecord;
/**
 * User Model
 *
 * @author Budi Irawan <deerawan@gmail.com>
 */
class User extends ActiveRecord
{
	/**
	 * @inheritdoc
	 */
	public static function tableName()
	{
		return 'user';
	}

    /**
     * @inheritdoc
     */
    public static function primaryKey()
    {
        return ['id'];
    }

    /**
     * Define rules for validation
     */
    public function rules()
    {
        return [
            [['id'], 'required']
        ];
    }
}


text:
<ProxyEndpoint name="userinfo">
  <Description/>
  <HTTPProxyConnection>
    <BasePath>/apijam-oidc/userinfo</BasePath>
    <VirtualHost>secure</VirtualHost>
  </HTTPProxyConnection>
  <Flows>
    <Flow name="CORS-preflight">
      <Request>
        <Step>
          <Condition>(request.header.Access-Control-Request-Method = null) OR (request.header.origin = null)</Condition>
          <Name>RF-Bad-CORS-Request</Name>
        </Step>
      </Request>
      <Response>
        <Step>
          <Name>AM-CORS-Preflight</Name>
        </Step>
      </Response>
      <Condition>request.verb = "OPTIONS"</Condition>
    </Flow>

    <Flow name="Userinfo">
      <Request>
        <Step>
          <Name>Verify-Access-Token</Name>
        </Step>
      </Request>
      <Response>
        <Step>
          <Name>JS-BuildUserInfoResponse</Name>
        </Step>
        <Step>
          <Name>AM-UserInfo-Response</Name>
        </Step>
      </Response>
    </Flow>
  </Flows>

  <PostFlow name="PostFlow">
    <Request/>
    <Response/>
  </PostFlow>
  <RouteRule name="noroute"/>
</ProxyEndpoint>


text:
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Example</title>
  <script src="../../dist/modular/js/core.js" type="text/javascript"></script>
  <link href="../../dist/modular/css/core.css" rel="stylesheet" type="text/css">
  <link href="../../dist/modular/css/dropdown.css" rel="stylesheet" type="text/css">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" type="text/css">
  <script src="../../dist/modular/js/dropdown.js"></script>
</head>
<body style="padding: 8px;">
 <button class="gj-button-md" onclick="dropdown.destroy()">Destroy</button>
 <select id="dropdown" width="200">
     <option value="1">One</option>
     <option value="2" selected>Two</option>
     <option value="3">Three</option>
 </select>
 <script>
     var dropdown = $('#dropdown').dropdown();
 </script>
</body>
</html>