text:
package main_test

import "lib"

func _() {
	// This reference should be found by the ref-method query.
	_ = (lib.Type).Method // ref from external test package
}


text:
function utils_FocusInputForModal(elementId) {
    // We need to wait for the modal to appear first.
    setTimeout(function() {
        // Trick to set focus on the field.
        $("#" + elementId).focus().val($("#" + elementId).val());
    }, 500);
}

function utils_SelectInputForModal(elementId) {
    // We need to wait for the modal to appear first.
    setTimeout(function() {
        // Trick to set focus on the field.
        $("#" + elementId).focus().val($("#" + elementId).val());
        // Then select the input.
        $("#" + elementId).select();
    }, 500);
}

function utils_FocusTextAreaForModal(elementId) {
    var el = $("#" + elementId);

    if (typeof el.selectionStart == "number") {
        el.selectionStart = el.selectionEnd = el.value.length;
    } else if (typeof el.createTextRange != "undefined") {
        el.focus();
        var range = el.createTextRange();
        range.collapse(false);
        range.select();
    }
}

function utils_SuggestPaths(elementId) {
    var input = $("#" + elementId);
    input.autocomplete({ source: [] });

    input.keypress(function(){
        var val = input.val();
        $.get("/internals/get/path-suggestion?path=" + encodeURIComponent(val), function(data) {
            var newSources = JSON.parse(data);
            input.autocomplete("option", "source", newSources.paths);
        });
    });
}

/********************************************************************************/
/**************************Common table operations ******************************/
/********************************************************************************/

utilMutiSelectTable = function() {
    var clearRows = function(rows) {
        rows.removeClass('table-highlight');
    }

    var toggleRow = function(cell) {
        cell.classList.toggle('table-highlight');
    }

    var highlightRow = function(cell) {
        cell.classList.add('table-highlight');
    }

    var setSelectedRow = function(tableId, index) {
        var rows = $("#" + tableId).find("td");
        if (index < 0 || index > rows.length) {
            return;
        }

        console.log(rows[index]);
        rows[index].classList.add('table-highlight');
    }

    var onClick = function(e, tableId, rows, cell, row, col) {
        if (e.ctrlKey) {
            toggleRow(cell);
            return;
        }
        if (e.shiftKey) {
            var firstIndex = firstSelected(tableId);
            if (firstIndex == -1) {
                firstIndex = 0;
            }
            var low = Math.min(firstIndex, row);
            var high = Math.max(firstIndex, row);
            if (low == high) {
                return;
            }

            for (var i = low; i <= high; i++) {
                rows[i].classList.add('table-highlight');
            }
            return;
        }

        clearRows(rows);
        var isSelected = cell.classList.contains('table-highlight');
        if (!isSelected) {
            highlightRow(cell);
        }
    }

    var register = function(tableId) {
        var rows = $("#" + tableId).find("td");
        var table = document.getElementById(tableId);
        if (table == null) {
            return;
        }

        for (var i = 1; i < table.rows.length; i++) {
            for (var j = 0; j < table.rows[i].cells.length; j++)
            table.rows[i].cells[j].onclick = function(cell, i, j) {
                return function(e) {
                    // Minus one so that row index starts from 0.
                    onClick(e, tableId, rows, cell, i - 1, j);
                };
            }(table.rows[i].cells[j], i, j);
        }
    }

    var firstSelected = function(tableId) {
        var rows = $("#" + tableId).find("td");
        for (var i = 0; i < rows.length; i++) {
            if (rows[i].classList.contains('table-highlight')) {
                return i;
            }
        }
        return -1;
    }

    var lastSelected = function(tableId) {
        var rows = $("#" + tableId).find("td");
        for (var i = rows.length - 1; i >= 0; i--) {
            if (rows[i].classList.contains('table-highlight')) {
                return i;
            }
        }
        return -1;
    }

    var allSelected = function(tableId) {
        var rows = $("#" + tableId).find("td");
        var selectedIndices = [];
        for (var i = rows.length - 1; i >= 0; i--) {
            if (rows[i].classList.contains('table-highlight')) {
                selectedIndices.push(i);
            }
        }
        return selectedIndices;
    }

    return {
        register: register,
        firstSelected: firstSelected,
        lastSelected: lastSelected,
        allSelected: allSelected,
        setSelectedRow: setSelectedRow,
    }
}()

function utils_TableHighlight(tableId) {
    /* Get all rows from your 'table' but not the first one
    * that includes headers. */
    var rows = $("#" + tableId).find("tr").not(":first");

    /* Create 'click' event handler for rows */
    rows.click(function(e) {
        /* Get current row */
        var row = $(this);

        /* Otherwise just highlight one row and clean others */
        rows.removeClass('table-highlight');
        row.addClass('table-highlight');
    });
}

// onClickFunc takes in a cell element, a row index and a column index.
// Row index and column index start from 0.
function utils_TableOnclick(tableId, onClickFunc) {
    var table = document.getElementById(tableId);

    // Start from row = 1 since row = 0 is the headings.
    for (var i = 1; i < table.rows.length; i++) {
        for (var j = 0; j < table.rows[i].cells.length; j++)
        table.rows[i].cells[j].onclick = function(cell, i, j) {
            return function() {
                // Minus one so that row index starts from 0.
                onClickFunc(cell, i - 1, j);
            };
        }(table.rows[i].cells[j], i, j);
    }
}

function utils_SetTableSelectedIndex(tableId, index) {
    var rows = $("#" + tableId).find("tr").not(":first");
    if (index < 0) {
        index = 0;
    }
    if (index >= rows.length) {
        index = rows.length - 1;
    }

    rows.each(function(i) {
        if (index == i) {
            rows.removeClass('table-highlight');
            $(this).addClass('table-highlight');
            return false;
        }
    });
}

// Returns -1 if nothing is selected.
function utils_GetTableSelectedRowIndex(tableId) {
    var rows = $("#" + tableId).find("tr").not(":first");
    var index = -1;
    rows.each(function(i) {
        if ($(this).hasClass("table-highlight")) {
            index = i;
            return false;
        }
    });

    return index;
}

// Returns null if nothing is selected.
function utils_GetTableSelectedRow(tableId) {
    var rows = $("#" + tableId).find("tr").not(":first");
    var index = utils_GetTableSelectedRowIndex(tableId);
    if (index == -1) {
        return null;
    }
    return rows[index];
}

redpajama_set_name: RedPajamaGithub


text:
title = 'Pmw.MessageBar demonstration'

# Import Pmw from this directory tree.
import sys
sys.path[:0] = ['../../..']

import Tkinter
import Pmw

class Demo:
    def __init__(self, parent):
	# Create and pack the MessageBar.
	self._messagebar = Pmw.MessageBar(parent,
		entry_width = 40,
		entry_relief='groove',
		labelpos = 'w',
		label_text = 'Status:')
	self._messagebar.pack(side = 'bottom', fill = 'x',
		expand = 1, padx = 10, pady = 10)

	# Create and pack the ScrolledListBox to change the MessageBar.
	self.box = Pmw.ScrolledListBox(parent,
		listbox_selectmode='single',
		items=('state', 'help', 'userevent', 'systemevent',
			'usererror', 'systemerror', 'busy',),
		label_text='Message type',
		labelpos='n',
		selectioncommand=self.selectionCommand)
	self.box.pack(fill = 'both', expand = 'yes', padx = 10, pady = 10)

	self._index = 0
	self._stateCounter = 0

    def selectionCommand(self):
	sels = self.box.getcurselection()
	if len(sels) > 0:
	    self._index = self._index + 1
	    messagetype = sels[0]
	    if messagetype == 'state':
		self._stateCounter = (self._stateCounter + 1) % 3
		text = stateMessages[self._stateCounter]
		if text != '':
		    text = text + ' (' + messagetype + ')'
		self._messagebar.message('state', text)
	    else:
		text = messages[messagetype]
		text = text + ' (' + messagetype + ')'
		self._messagebar.message(messagetype, text)
		if messagetype == 'busy':
		    Pmw.showbusycursor()
		    self.box.after(2000)
		    Pmw.hidebusycursor()
		    self._messagebar.resetmessages('busy')
		    text = 'All files successfully removed'
		    text = text + ' (userevent)'
		    self._messagebar.message('userevent', text)

messages = {
    'help': 'Save current file',
    'userevent': 'Saving file "foo"',
    'busy': 'Busy deleting all files from file system ...',
    'systemevent': 'File "foo" saved',
    'usererror': 'Invalid file name "foo/bar"',
    'systemerror': 'Failed to save file: file system full',
}

stateMessages = {
    0: '',
    1: 'Database is down',
    2: 'Waiting for reply from database',
}

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

# Create demo in root window for testing.
if __name__ == '__main__':
    root = Tkinter.Tk()
    Pmw.initialise(root)
    root.title(title)

    exitButton = Tkinter.Button(root, text = 'Exit', command = root.destroy)
    exitButton.pack(side = 'bottom')
    widget = Demo(root)
    root.mainloop()


text:
import React from 'react';
import Footer from '../../../components/Footer';
import Navbar from '../../../components/Navbar';
import { ThemeProvider } from '@material-ui/core';
import theme from '../../../theme';
import withRoot from '../../../withRoot';
import WorkshopPageHeader from '../../../components/WorkshopPageHeader';
import GridOfContents from './GridOfContents';
import image from './../../../assets/img/general/header-bai-2021.png';
import Loader from '../../../loader';

function BAI2021() {
    return (
        <ThemeProvider theme={theme}>
            <Loader />
            <Navbar />
            <WorkshopPageHeader src={image}/>
            <GridOfContents/>
            <Footer />
        </ThemeProvider>
    );
}

export default withRoot(BAI2021);


text:
@interface LZMyPreferenceCell ()

/// 方便懒加载控件
@property (nonatomic,strong) UISwitch *lzSwitch;

/// 方便懒加载控件
@property (nonatomic,strong) UIButton *lzTaskBtn;

@end

@implementation LZMyPreferenceCell

/// 重写模型的 set 方法赋值
/// @param model 模型
- (void)setModel:(LZMyPreferenceModel *)model{

    _model = model;

    //设置文字和图片
    if (![model.icon isEqual: @""]) {

        self.imageView.image = [UIImage imageNamed:model.icon];
    }
    self.textLabel.text = model.title;

    //设置显示箭头还是开关
    if ([model isKindOfClass:[LZMyPreferenceArrow class]]) {

        self.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }else if([model isKindOfClass:[LZMyPreferenceSwitch class]]){

        //取消行选中状态
        self.selectionStyle = UITableViewCellSelectionStyleNone;

        //记录按钮状态
        self.lzSwitch.on = [[NSUserDefaults standardUserDefaults] boolForKey:model.title];

        //设置附件
        self.accessoryView = self.lzSwitch;
    }else if([model isKindOfClass:[LZMyPreferenceLabel class]]){

        self.accessoryView = self.lzTaskBtn;

        //获取内容
        NSInteger taskStatus = [[NSUserDefaults standardUserDefaults] integerForKey:model.title];

        NSString *taskContent;

        if ( taskStatus == 0){

           taskContent = @"点我进行";
        }else {

            taskContent = @"进行中";
        }

        //设置按钮
        [self.lzTaskBtn setTitle:taskContent forState:UIControlStateNormal];
        [self.lzTaskBtn sizeToFit];
    }
}

/// 懒加载,方便 cell 重用
/// @return  switch 开关
- (UIButton *)lzTaskBtn{

    if( _lzTaskBtn == nil ){

        _lzTaskBtn = [UIButton buttonWithType:UIButtonTypeCustom];

        [_lzTaskBtn setTitleColor:kMainColor forState:UIControlStateNormal];

        [_lzTaskBtn addTarget:self action:@selector(taskBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _lzTaskBtn;
}

- (void)taskBtnClick:(UIButton *)btn{

    NSInteger taskStatus = [[NSUserDefaults standardUserDefaults] integerForKey:self.model.title];

    //点击按钮,让任务正在进行
    if (taskStatus == 0) {
        [[NSUserDefaults standardUserDefaults]  setInteger:1 forKey:self.model.title];
        [[NSUserDefaults standardUserDefaults] synchronize];

        //让控制器刷新数据
        if([self.delegate respondsToSelector:@selector(MyPreferenceCellAskToRefreshTableView:)]){

            [self.delegate MyPreferenceCellAskToRefreshTableView:self];
        }
    }

}

/// 懒加载,方便 cell 重用
/// @return  switch 开关
- (UISwitch *)lzSwitch{

    if( _lzSwitch == nil ){

        _lzSwitch = [UISwitch new];

        _lzSwitch.on = YES;

        [_lzSwitch addTarget:self action:@selector(valueChanges:) forControlEvents:UIControlEventValueChanged];
    }
    return _lzSwitch;
}

/// 记录开关的状态
/// @param lzSwitch 用户点击的开关
- (void)valueChanges:(UISwitch *)lzSwitch{

    //记录当前的值
    [[NSUserDefaults standardUserDefaults]setBool:lzSwitch.isOn forKey:self.model.title];

    //同步
    [[NSUserDefaults standardUserDefaults] synchronize];
}

@end


text:
@echo off
pushd %~dp0
"%VS120COMNTOOLS%..\IDE\mstest" /test:Microsoft.Protocols.TestSuites.MS_LISTSWS.S01_OperationOnList.MSLISTSWS_S01_TC16_GetListAndView_InvalidViewName /testcontainer:..\..\MS-LISTSWS\TestSuite\bin\Debug\MS-LISTSWS_TestSuite.dll /runconfig:..\..\MS-LISTSWS\MS-LISTSWS.testsettings /unique
pause


text:
"""Tests for TPUClusterResolver."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os

import six
from six.moves.urllib.error import URLError

from tensorflow.python import framework
from tensorflow.python.client import session
from tensorflow.python.distribute.cluster_resolver import tpu_cluster_resolver as resolver
from tensorflow.python.eager.context import LogicalDevice
from tensorflow.python.framework import errors
from tensorflow.python.framework import test_util
from tensorflow.python.platform import test
from tensorflow.python.training import server_lib
from tensorflow.python.util import compat

mock = test.mock

class MockRequestClass(object):

  def __init__(self, name, tpu_map):
    self._name = name
    self._tpu_map = tpu_map

  def execute(self):
    if self._name in self._tpu_map:
      return self._tpu_map[self._name]
    else:
      raise KeyError('Resource %s was not found' % self._name)

class MockNodeClass(object):

  def __init__(self, tpu_map):
    self._tpu_map = tpu_map

  def get(self, name):
    return MockRequestClass(name, self._tpu_map)

def mock_request_compute_metadata(cls, *args, **kwargs):
  del cls, kwargs  # Unused.
  if args[0] == 'project/project-id':
    return 'test-project'
  elif args[0] == 'instance/zone':
    return 'projects/test-project/locations/us-central1-c'
  elif args[0] == 'instance/network-interfaces/0/ip':
    return '10.128.1.2'
  return ''

def mock_is_running_in_gce():
  return True

def mock_is_not_running_in_gce():
  return False

def mock_running_in_gce_urlopen(cls, *args, **kwargs):
  del cls, args, kwargs  # Unused.
  mock_response = mock.MagicMock()
  mock_response.info.return_value = {'Metadata-Flavor': 'Google'}
  return mock_response

def mock_not_running_in_gce_urlopen(cls, *args, **kwargs):
  del cls, args, kwargs  # Unused.
  raise URLError(reason='Host does not exist.')

@test_util.run_all_in_graph_and_eager_modes
class TPUClusterResolverTest(test.TestCase):

  def _verifyClusterSpecEquality(self, cluster_spec, expected_proto):
    """Verifies that the ClusterSpec generates the correct proto.

    We are testing this four different ways to ensure that the ClusterSpec
    returned by the TPUClusterResolver behaves identically to a normal
    ClusterSpec when passed into the generic ClusterSpec libraries.

    Args:
      cluster_spec: ClusterSpec returned by the TPUClusterResolver
      expected_proto: Expected protobuf
    """
    self.assertProtoEquals(expected_proto, cluster_spec.as_cluster_def())
    self.assertProtoEquals(
        expected_proto,
        server_lib.ClusterSpec(cluster_spec).as_cluster_def())
    self.assertProtoEquals(expected_proto,
                           server_lib.ClusterSpec(
                               cluster_spec.as_cluster_def()).as_cluster_def())
    self.assertProtoEquals(expected_proto,
                           server_lib.ClusterSpec(
                               cluster_spec.as_dict()).as_cluster_def())

  def mock_service_client(self, tpu_map=None):

    if tpu_map is None:
      tpu_map = {}

    mock_locations = mock.MagicMock()
    mock_locations.nodes.return_value = MockNodeClass(tpu_map)

    mock_project = mock.MagicMock()
    mock_project.locations.return_value = mock_locations

    mock_client = mock.MagicMock()
    mock_client.projects.return_value = mock_project

    return mock_client

  @mock.patch.object(resolver, 'is_running_in_gce',
                     mock_is_running_in_gce)
  def testCheckRunningInGceWithNoTpuName(self):
    with self.assertRaisesRegexp(RuntimeError, '.*Google Cloud.*'):
      resolver.TPUClusterResolver(tpu='')

  @mock.patch.object(six.moves.urllib.request,
                     'urlopen',
                     mock_running_in_gce_urlopen)
  def testIsRunningInGce(self):
    self.assertTrue(resolver.is_running_in_gce())

  @mock.patch.object(six.moves.urllib.request,
                     'urlopen',
                     mock_not_running_in_gce_urlopen)
  def testIsNotRunningInGce(self):
    self.assertFalse(resolver.is_running_in_gce())

  @mock.patch.object(resolver.TPUClusterResolver,
                     '_request_compute_metadata', mock_request_compute_metadata)
  def testRetrieveProjectAndZoneFromMetadata(self):
    tpu_map = {
        'projects/test-project/locations/us-central1-c/nodes/test-tpu-1': {
            'ipAddress': '10.1.2.3',
            'port': '8470',
            'health': 'HEALTHY'
        }
    }

    cluster_resolver = resolver.TPUClusterResolver(
        project=None,
        zone=None,
        tpu=['test-tpu-1'],
        credentials=None,
        service=self.mock_service_client(tpu_map=tpu_map),
        coordinator_name='coordinator')

    actual_cluster_spec = cluster_resolver.cluster_spec()
    expected_proto = """
    job {
      name: 'coordinator'
      tasks { key: 0 value: '10.128.1.2:%s' }
    }
    job {
      name: 'worker'
      tasks { key: 0 value: '10.1.2.3:8470' }
    }
    """ % cluster_resolver._coordinator_port
    self._verifyClusterSpecEquality(actual_cluster_spec, str(expected_proto))
    self.assertEqual(cluster_resolver.master(), 'grpc://10.1.2.3:8470')

  @mock.patch.object(resolver.TPUClusterResolver,
                     '_request_compute_metadata', mock_request_compute_metadata)
  def testRetrieveProjectAndZoneFromMetadataNoCoordinator(self):
    tpu_map = {
        'projects/test-project/locations/us-central1-c/nodes/test-tpu-1': {
            'ipAddress': '10.1.2.3',
            'port': '8470',
            'health': 'HEALTHY'
        }
    }

    cluster_resolver = resolver.TPUClusterResolver(
        project=None,
        zone=None,
        tpu=['test-tpu-1'],
        coordinator_name=None,
        credentials=None,
        service=self.mock_service_client(tpu_map=tpu_map))

    actual_cluster_spec = cluster_resolver.cluster_spec()
    expected_proto = """
    job { name: 'worker' tasks { key: 0 value: '10.1.2.3:8470' } }
    """
    self._verifyClusterSpecEquality(actual_cluster_spec, expected_proto)
    self.assertEqual(cluster_resolver.master(), 'grpc://10.1.2.3:8470')

  @mock.patch.object(resolver.TPUClusterResolver,
                     '_request_compute_metadata', mock_request_compute_metadata)
  def testNotReadyCloudTpu(self):
    tpu_map = {
        'projects/test-project/locations/us-central1-c/nodes/test-tpu-1': {
            'ipAddress': '10.1.2.3',
            'port': '8470',
            'state': 'CREATING'
        }
    }

    cluster_resolver = resolver.TPUClusterResolver(
        project=None,
        zone=None,
        tpu='test-tpu-1',
        coordinator_name=None,
        credentials=None,
        service=self.mock_service_client(tpu_map=tpu_map))

    with self.assertRaises(RuntimeError):
      cluster_resolver.cluster_spec()

  def testSimpleSuccessfulRetrieval(self):
    tpu_map = {
        'projects/test-project/locations/us-central1-c/nodes/test-tpu-1': {
            'ipAddress': '10.1.2.3',
            'port': '8470',
            'health': 'HEALTHY'
        }
    }

    cluster_resolver = resolver.TPUClusterResolver(
        project='test-project',
        zone='us-central1-c',
        tpu=['test-tpu-1'],
        coordinator_name='coordinator',
        coordinator_address='10.128.1.5:10203',
        credentials=None,
        service=self.mock_service_client(tpu_map=tpu_map))

    actual_cluster_spec = cluster_resolver.cluster_spec()
    expected_proto = """
    job { name: 'coordinator' tasks { key: 0 value: '10.128.1.5:10203' } }
    job { name: 'worker' tasks { key: 0 value: '10.1.2.3:8470' } }
    """
    self._verifyClusterSpecEquality(actual_cluster_spec, expected_proto)
    self.assertEqual(cluster_resolver.master(), 'grpc://10.1.2.3:8470')

  def testFailedMetadata(self):
    tpu_map = {
        'projects/test-project/locations/us-central1-c/nodes/test-tpu-1': {
            'ipAddress': '10.1.2.3',
            'port': '8470',
            'health': 'HEALTHY'
        }
    }

    cluster_resolver = resolver.TPUClusterResolver(
        project='test-project',
        zone='us-central1-c',
        tpu='nonexistent-tpu',
        coordinator_name='coordinator',
        coordinator_address='10.128.1.5:10203',
        credentials=None,
        service=self.mock_service_client(tpu_map=tpu_map))

    with self.assertRaises(ValueError) as context:
      cluster_resolver.cluster_spec()

    self.assertIn('Could not lookup TPU metadata', str(context.exception))

  def testNewNetworkEndpointFormat(self):
    tpu_map = {
        'projects/test-project/locations/us-central1-c/nodes/test-tpu-1': {
            'health': 'HEALTHY',
            'networkEndpoints': [{
                'ipAddress': '10.2.3.4',
                'port': 8470,
            }]
        }
    }

    cluster_resolver = resolver.TPUClusterResolver(
        project='test-project',
        zone='us-central1-c',
        tpu='test-tpu-1',
        coordinator_name='coordinator',
        coordinator_address='10.128.1.5:10203',
        credentials=None,
        service=self.mock_service_client(tpu_map=tpu_map))

    actual_cluster_spec = cluster_resolver.cluster_spec()
    expected_proto = """
    job { name: 'coordinator' tasks { key: 0 value: '10.128.1.5:10203' } }
    job { name: 'worker' tasks { key: 0 value: '10.2.3.4:8470' } }
    """
    self._verifyClusterSpecEquality(actual_cluster_spec, expected_proto)
    self.assertEqual('grpc://10.2.3.4:8470', cluster_resolver.master())

  @mock.patch.object(resolver.TPUClusterResolver,
                     '_request_compute_metadata', mock_request_compute_metadata)
  def testPodResolution(self):
    tpu_map = {
        'projects/test-project/locations/us-central1-c/nodes/test-tpu-1': {
            'health':
                'HEALTHY',
            'networkEndpoints': [
                {
                    'ipAddress': '10.2.3.4',
                    'port': 8470,
                },
                {
                    'ipAddress': '10.2.3.5',
                    'port': 8470,
                },
                {
                    'ipAddress': '10.2.3.6',
                    'port': 8470,
                },
                {
                    'ipAddress': '10.2.3.7',
                    'port': 8470,
                },
            ]
        }
    }

    cluster_resolver = resolver.TPUClusterResolver(
        tpu='test-tpu-1',
        credentials=None,
        service=self.mock_service_client(tpu_map=tpu_map),
        coordinator_name='coordinator')

    actual_cluster_spec = cluster_resolver.cluster_spec()
    expected_proto = """
    job {
      name: 'coordinator',
      tasks { key: 0 value: '10.128.1.2:%s'}
    }
    job {
      name: 'worker'
      tasks { key: 0 value: '10.2.3.4:8470' }
      tasks { key: 1 value: '10.2.3.5:8470' }
      tasks { key: 2 value: '10.2.3.6:8470' }
      tasks { key: 3 value: '10.2.3.7:8470' }
    }
    """ % cluster_resolver._coordinator_port
    self._verifyClusterSpecEquality(actual_cluster_spec, str(expected_proto))
    self.assertEqual(cluster_resolver.master(), 'grpc://10.2.3.4:8470')

  def testPodResolutionNoCoordinator(self):
    tpu_map = {
        'projects/test-project/locations/us-central1-c/nodes/test-tpu-1': {
            'health':
                'HEALTHY',
            'networkEndpoints': [
                {
                    'ipAddress': '10.2.3.4',
                    'port': 8470,
                },
                {
                    'ipAddress': '10.2.3.5',
                    'port': 8470,
                },
                {
                    'ipAddress': '10.2.3.6',
                    'port': 8470,
                },
                {
                    'ipAddress': '10.2.3.7',
                    'port': 8470,
                },
            ]
        }
    }

    cluster_resolver = resolver.TPUClusterResolver(
        project='test-project',
        zone='us-central1-c',
        tpu='test-tpu-1',
        coordinator_name=None,
        credentials=None,
        service=self.mock_service_client(tpu_map=tpu_map))

    actual_cluster_spec = cluster_resolver.cluster_spec()
    expected_proto = """
    job {
      name: 'worker'
      tasks { key: 0 value: '10.2.3.4:8470' }
      tasks { key: 1 value: '10.2.3.5:8470' }
      tasks { key: 2 value: '10.2.3.6:8470' }
      tasks { key: 3 value: '10.2.3.7:8470' }
    }
    """
    self._verifyClusterSpecEquality(actual_cluster_spec, expected_proto)
    self.assertEqual(cluster_resolver.master(), 'grpc://10.2.3.4:8470')

  def testGetMasterNoEntries(self):
    tpu_map = {}

    with self.assertRaises(ValueError):
      resolver.TPUClusterResolver(
          project='test-project',
          zone='us-central1-c',
          tpu=[],
          coordinator_name=None,
          credentials=None,
          service=self.mock_service_client(tpu_map=tpu_map))

  # TODO(saeta): Convert to parameterized test when included in OSS TF.
  def verifyShouldResolve(self, tpu, should_resolve):
    cluster_resolver = resolver.TPUClusterResolver(
        project='test-project',
        zone='us-central1-c',
        tpu=tpu,
        coordinator_name=None,
        credentials=None,
        service=self.mock_service_client(tpu_map={}))
    self.assertEqual(should_resolve, cluster_resolver._should_resolve(),
                     "TPU: '%s'" % tpu)

  @mock.patch.object(resolver, 'is_running_in_gce',
                     mock_is_not_running_in_gce)
  def testShouldResolveNoName(self):
    self.verifyShouldResolve('', False)

  def testShouldResolveLocal(self):
    self.verifyShouldResolve('local', False)

  def testShouldResolveGrpc(self):
    self.verifyShouldResolve('grpc://10.1.2.3:8470', False)

  def testShouldResolveName(self):
    self.verifyShouldResolve('mytpu', True)

  def testShouldResolveList(self):
    self.verifyShouldResolve(['myothertpu'], True)

  def testShouldResolveGrpcPrefix(self):
    self.verifyShouldResolve('grpctpu', True)

  def testNoCallComputeMetadata(self):
    cluster_resolver = resolver.TPUClusterResolver(tpu='grpc://10.1.2.3:8470')
    self.assertEqual('grpc://10.1.2.3:8470', cluster_resolver.master())
    self.assertEqual(
        server_lib.ClusterSpec({
            'worker': ['10.1.2.3:8470']
        }).as_dict(),
        cluster_resolver.cluster_spec().as_dict())

  def testGkeEnvironmentForDonut(self):
    os.environ['KUBE_GOOGLE_CLOUD_TPU_ENDPOINTS'] = 'grpc://10.120.27.5:8470'

    self.assertIn('KUBE_GOOGLE_CLOUD_TPU_ENDPOINTS', os.environ)
    self.assertTrue(resolver.TPUClusterResolver._in_gke())
    self.assertEqual(
        compat.as_bytes('grpc://10.120.27.5:8470'),
        compat.as_bytes(
            resolver.TPUClusterResolver._gke_endpoints()))

    cluster_resolver = resolver.TPUClusterResolver()
    self.assertEqual(
        compat.as_bytes('grpc://10.120.27.5:8470'),
        compat.as_bytes(cluster_resolver.master()))
    actual_cluster_spec = cluster_resolver.cluster_spec()
    expected_proto = """
    job {
      name: 'worker'
      tasks { key: 0 value: '10.120.27.5:8470' }
    }
    """
    self._verifyClusterSpecEquality(actual_cluster_spec, expected_proto)

    del os.environ['KUBE_GOOGLE_CLOUD_TPU_ENDPOINTS']

  def testGkeEnvironmentForPod(self):
    os.environ['KUBE_GOOGLE_CLOUD_TPU_ENDPOINTS'] = ('grpc://10.120.27.5:8470,'
                                                     'grpc://10.120.27.6:8470,'
                                                     'grpc://10.120.27.7:8470,'
                                                     'grpc://10.120.27.8:8470')

    self.assertIn('KUBE_GOOGLE_CLOUD_TPU_ENDPOINTS', os.environ)
    self.assertTrue(resolver.TPUClusterResolver._in_gke())
    self.assertEqual(
        compat.as_bytes('grpc://10.120.27.5:8470,'
                        'grpc://10.120.27.6:8470,'
                        'grpc://10.120.27.7:8470,'
                        'grpc://10.120.27.8:8470'),
        compat.as_bytes(
            resolver.TPUClusterResolver._gke_endpoints()))

    cluster_resolver = resolver.TPUClusterResolver()
    self.assertEqual(
        compat.as_bytes('grpc://10.120.27.5:8470'),
        compat.as_bytes(cluster_resolver.master()))
    actual_cluster_spec = cluster_resolver.cluster_spec()
    expected_proto = """
    job {
      name: 'worker'
      tasks { key: 0 value: '10.120.27.5:8470' }
      tasks { key: 1 value: '10.120.27.6:8470' }
      tasks { key: 2 value: '10.120.27.7:8470' }
      tasks { key: 3 value: '10.120.27.8:8470' }
    }
    """
    self._verifyClusterSpecEquality(actual_cluster_spec, expected_proto)

    del os.environ['KUBE_GOOGLE_CLOUD_TPU_ENDPOINTS']

  def testEnvironmentDiscoveryUrl(self):
    os.environ['TPU_API_DISCOVERY_URL'] = 'https://{api}.internal/{apiVersion}'
    self.assertEqual(
        'https://{api}.internal/{apiVersion}',
        (resolver.TPUClusterResolver._environment_discovery_url()))

  def testEnvironmentAndRpcDetectionForGrpcString(self):
    cluster_resolver = resolver.TPUClusterResolver(
        tpu='grpc://10.1.2.3:8470')
    self.assertEqual(cluster_resolver.environment, '')
    self.assertEqual(cluster_resolver.rpc_layer, 'grpc')
    self.assertEqual(cluster_resolver.master(), 'grpc://10.1.2.3:8470')

  def testOverrideTaskTypeAndIndexAndGetMaster(self):
    tpu_map = {
        'projects/test-project/locations/us-central1-c/nodes/test-tpu-1': {
            'health':
                'HEALTHY',
            'networkEndpoints': [
                {
                    'ipAddress': '10.2.3.4',
                    'port': 8470,
                },
                {
                    'ipAddress': '10.2.3.5',
                    'port': 8470,
                },
                {
                    'ipAddress': '10.2.3.6',
                    'port': 8470,
                },
                {
                    'ipAddress': '10.2.3.7',
                    'port': 8470,
                },
            ]
        }
    }

    cluster_resolver = resolver.TPUClusterResolver(
        project='test-project',
        zone='us-central1-c',
        tpu='test-tpu-1',
        coordinator_name=None,
        credentials=None,
        service=self.mock_service_client(tpu_map=tpu_map))

    self.assertEqual(cluster_resolver.master(), 'grpc://10.2.3.4:8470')

    cluster_resolver.task_type = 'worker'
    cluster_resolver.task_id = 3
    self.assertEqual(cluster_resolver.master(), 'grpc://10.2.3.7:8470')

    self.assertEqual(
        cluster_resolver.master(
            task_type='worker', task_id=2, rpc_layer='test'),
        'test://10.2.3.6:8470')

  def testGetDeviceDictAndCoresWithTPUs(self):
    device_names = [
        '/job:tpu_worker/task:0/device:TPU:0',
        '/job:tpu_worker/task:1/device:TPU:1',
        '/job:tpu_worker/task:2/device:TPU:0',
        '/job:tpu_worker/task:3/device:TPU:1',
        '/job:tpu_worker/task:0/device:TPU:4',
        '/job:tpu_worker/task:1/device:TPU:5',
        '/job:tpu_worker/task:2/device:TPU:4',
        '/job:tpu_worker/task:3/device:TPU:5',
    ]
    device_list = [
        session._DeviceAttributes(
            name, 'TPU', 1024, 0) for name in device_names
    ]

    device_details = resolver.TPUClusterResolver._get_device_dict_and_cores(
        device_list)
    self.assertEqual(device_details.total_cores, 8)
    self.assertEqual(device_details.device_map,
                     {'0': ['0', '4'],
                      '1': ['1', '5'],
                      '2': ['0', '4'],
                      '3': ['1', '5']})

  def testGetDeviceDictAndCoresWithCPUsAndGPUs(self):
    device_names = [
        '/job:tpu_worker/task:0/device:CPU:0',
        '/job:tpu_worker/task:1/device:CPU:0',
        '/job:tpu_worker/task:2/device:CPU:0',
        '/job:tpu_worker/task:3/device:CPU:0',
        '/job:tpu_worker/task:0/device:GPU:1',
        '/job:tpu_worker/task:1/device:GPU:1',
        '/job:tpu_worker/task:2/device:GPU:1',
        '/job:tpu_worker/task:3/device:GPU:1',
    ]
    device_list = [
        session._DeviceAttributes(
            name, 'XLA', 1024, 0) for name in device_names
    ]

    device_dict, num_cores =\
        resolver.TPUClusterResolver._get_device_dict_and_cores(device_list)
    self.assertEqual(num_cores, 0)
    self.assertEqual(device_dict, {})

  def testVerifySameCoreCount(self):
    self.assertEqual(
        resolver.TPUClusterResolver
        ._verify_and_return_same_core_count({0: [0, 1, 2, 3, 4, 5, 6, 7]}), 8)
    self.assertEqual(
        resolver.TPUClusterResolver
        ._verify_and_return_same_core_count({
            0: [0, 1],
            1: [2, 3]
        }), 2)
    with self.assertRaises(RuntimeError):
      resolver.TPUClusterResolver._verify_and_return_same_core_count(
          {
              0: [0],
              1: [1, 2]
          })

  @mock.patch.object(framework.config, 'list_logical_devices')
  @mock.patch.object(session.BaseSession, 'list_devices')
  @mock.patch.object(resolver, 'is_running_in_gce',
                     mock_is_not_running_in_gce)
  def testNumAcceleratorsSuccess(self, mock_list_devices,
                                 mock_eager_list_devices):
    devices = [
        LogicalDevice('/job:tpu_worker/task:0/device:TPU:0', 'TPU'),
        LogicalDevice('/job:tpu_worker/task:1/device:TPU:1', 'TPU'),
        LogicalDevice('/job:tpu_worker/task:2/device:TPU:0', 'TPU'),
        LogicalDevice('/job:tpu_worker/task:3/device:TPU:1', 'TPU'),
        LogicalDevice('/job:tpu_worker/task:0/device:TPU:4', 'TPU'),
        LogicalDevice('/job:tpu_worker/task:1/device:TPU:5', 'TPU'),
        LogicalDevice('/job:tpu_worker/task:2/device:TPU:4', 'TPU'),
        LogicalDevice('/job:tpu_worker/task:3/device:TPU:5', 'TPU'),
    ]
    device_list = [
        session._DeviceAttributes(d.name, d.device_type, 1024, 0)
        for d in devices
    ]
    mock_eager_list_devices.return_value = devices
    mock_list_devices.return_value = device_list

    cluster_resolver = resolver.TPUClusterResolver(tpu='')
    self.assertEqual(cluster_resolver.num_accelerators(), {'TPU': 2})

  @mock.patch.object(framework.config, 'list_logical_devices')
  @mock.patch.object(session.BaseSession, 'list_devices')
  @mock.patch.object(resolver, 'is_running_in_gce',
                     mock_is_not_running_in_gce)
  def testNumAcceleratorsRetryFailure(self, mock_list_devices,
                                      mock_eager_list_devices):
    cluster_resolver = resolver.TPUClusterResolver(tpu='')
    mock_list_devices.side_effect = errors.DeadlineExceededError(
        None, None, 'timeout')
    mock_eager_list_devices.side_effect = errors.DeadlineExceededError(
        None, None, 'timeout')
    with self.assertRaises(RuntimeError):
      cluster_resolver.num_accelerators()

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


text:
{{ form.cnsaSectionTitle }}

    <input ng-if="!field.settings.replacing[f_id] && !form.fieldAddonLeft && !form.fieldAddonRight"
           ng-show="form.key"
           type="{{form.type}}"
           step="{{ form.schema.type == 'integer' ? 1 : 'any' }}"
           sf-changed="form"
           ng-attr-placeholder="{{form.placeholder}}"
           class="{{form.fieldHtmlClass}}"
           ng-attr-id="{{f_id}}"
           ng-model-options="form.ngModelOptions"
           ng-model="$$value$$"
           ng-disabled="form.readonly"
           schema-validate="form"
           name="{{f_id}}"
           ng-attr-title="{{form.description}}"
           aria-describedby="{{f_id}} Status">

    <input ng-if="field.settings.replacing[f_id] && !form.fieldAddonLeft && !form.fieldAddonRight"
           style="display:none"
           type="text"
           step="{{ form.schema.type == 'integer' ? 1 : 'any' }}"
           sf-changed="form"
           ng-attr-placeholder="{{form.placeholder}}"
           class="{{form.fieldHtmlClass}}"
           ng-attr-id="{{f_id}}"
           ng-model-options="form.ngModelOptions"
           ng-model="$$value$$"
           ng-disabled="form.readonly"
           schema-validate="form"
           name="{{f_id}}"
           ng-attr-title="{{form.description}}"
           aria-describedby="{{f_id}} Status">

        <input ng-show="form.key"
             type="{{form.type}}"
             step="{{ form.schema.type == 'integer' ? 1 : 'any' }}"
             sf-changed="form"
             ng-attr-placeholder="{{form.placeholder}}"
             class="{{form.fieldHtmlClass}}"
             ng-attr-id="{{f_id}}"
             ng-model-options="form.ngModelOptions"
             ng-model="$$value$$"
             ng-disabled="form.readonly"
             schema-validate="form"
             name="{{f_id}}"
             aria-describedby="{{f_id}} Status">

    <fb-replace-with-field
      target="#{{ f_id }}"
      controls="controls"
      enabled="true"
      field-elid="{{ field.elid }}"
      model="$$rplModel$$"
      attr="'$$rplAttr$$'"
      name="{{ ngModel.$name }}"
      lookup-fields="field.lookupFields"></fb-replace-with-field>


text:
package org.flowkeeper.client.ui.timer;

import org.flowkeeper.server.PomodoroType;

public abstract class TimerAdapter implements TimerListener {

	@Override
	public void onWorkCompleted(PomodoroType pomodoro, boolean successfully) {
	}

	@Override
	public void onPomodoroStarted(PomodoroType pomodoro) {
	}

	@Override
	public void onReady() {
	}

	@Override
	public void onTick() {
	}
}


text:
package com.meisolsson.githubsdk.model.git;

import com.meisolsson.githubsdk.model.PositionalCommentBase;
import com.google.auto.value.AutoValue;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;

@AutoValue
public abstract class GitComment extends PositionalCommentBase {
    public abstract Builder toBuilder();

    public static JsonAdapter<GitComment> jsonAdapter(Moshi moshi) {
        return new AutoValue_GitComment.MoshiJsonAdapter(moshi);
    }

    public static Builder builder() {
        return new AutoValue_GitComment.Builder();
    }

    @AutoValue.Builder
    public abstract static class Builder extends PositionalCommentBase.Builder<Builder> {
        public abstract GitComment build();
    }
}


text:
var Node = require("./node"),
    constraints = require("../constraint"),
    ReferenceEqualityConstraint = constraints.ReferenceEqualityConstraint;

var DEFUALT_CONSTRAINT = {
    isDefault: true,
    assert: function () {
        return true;
    },

    equal: function () {
        return false;
    }
};

var inversions = {
    "gt": "lte",
    "gte": "lte",
    "lt": "gte",
    "lte": "gte",
    "eq": "eq",
    "neq": "neq"
};

function normalizeRightIndexConstraint(rightIndex, indexes, op) {
    if (rightIndex === indexes[1]) {
        op = inversions[op];
    }
    return op;
}

function normalizeLeftIndexConstraint(leftIndex, indexes, op) {
    if (leftIndex === indexes[1]) {
        op = inversions[op];
    }
    return op;
}

Node.extend({

    instance: {

        constraint: DEFUALT_CONSTRAINT,

        constructor: function (leftMemory, rightMemory) {
            this._super(arguments);
            this.constraint = DEFUALT_CONSTRAINT;
            this.constraintAssert = DEFUALT_CONSTRAINT.assert;
            this.rightIndexes = [];
            this.leftIndexes = [];
            this.constraintLength = 0;
            this.leftMemory = leftMemory;
            this.rightMemory = rightMemory;
        },

        addConstraint: function (constraint) {
            if (constraint instanceof ReferenceEqualityConstraint) {
                var identifiers = constraint.getIndexableProperties();
                var alias = constraint.get("alias");
                if (identifiers.length === 2 && alias) {
                    var leftIndex, rightIndex, i = -1, indexes = [];
                    while (++i < 2) {
                        var index = identifiers[i];
                        if (index.match(new RegExp("^" + alias + "(\\.?)")) === null) {
                            indexes.push(index);
                            leftIndex = index;
                        } else {
                            indexes.push(index);
                            rightIndex = index;
                        }
                    }
                    if (leftIndex && rightIndex) {
                        var leftOp = normalizeLeftIndexConstraint(leftIndex, indexes, constraint.op),
                            rightOp = normalizeRightIndexConstraint(rightIndex, indexes, constraint.op);
                        this.rightMemory.addIndex(rightIndex, leftIndex, rightOp);
                        this.leftMemory.addIndex(leftIndex, rightIndex, leftOp);
                    }
                }
            }
            if (this.constraint.isDefault) {
                this.constraint = constraint;
                this.isDefault = false;
            } else {
                this.constraint = this.constraint.merge(constraint);
            }
            this.constraintAssert = this.constraint.assert;

        },

        equal: function (constraint) {
            return this.constraint.equal(constraint.constraint);
        },

        isMatch: function (lc, rc) {
            return this.constraintAssert(lc.factHash, rc.factHash);
        },

        match: function (lc, rc) {
            var ret = {isMatch: false};
            if (this.constraintAssert(lc.factHash, rc.factHash)) {
                ret = lc.match.merge(rc.match);
            }
            return ret;
        }

    }

}).as(module);


text:
function A_transposed_blocks = transposeBlocks(A,block_size)
  A_transposed_blocks = blockwiseTranspose(A,block_size)';
end


text:
package org.projectomakase.omakase.worker.tool.manifest.dash.model;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;

@XmlType(name = "actuateType", namespace = "http://www.w3.org/1999/xlink")
@XmlEnum
public enum ActuateType {

    @XmlEnumValue("onLoad")
    ON_LOAD("onLoad"),
    @XmlEnumValue("onRequest")
    ON_REQUEST("onRequest");
    private final String value;

    ActuateType(String v) {
        value = v;
    }

    public static ActuateType fromValue(String v) {
        for (ActuateType c : ActuateType.values()) {
            if (c.value.equals(v)) {
                return c;
            }
        }
        throw new IllegalArgumentException(v);
    }

    public String value() {
        return value;
    }

}


text:
				BigFlix Movie Store

 Movies

 New Movie


text:
namespace TriangleNet.Smoothing
{
    using System;
    using TriangleNet.Topology.DCEL;
    using TriangleNet.Voronoi;

    /// <summary>
    /// Factory which re-uses objects in the smoothing loop to enhance performance.
    /// </summary>
    /// <remarks>
    /// See <see cref="SimpleSmoother"/>.
    /// </remarks>
    class VoronoiFactory : IVoronoiFactory
    {
        ObjectPool<Vertex> vertices;
        ObjectPool<HalfEdge> edges;
        ObjectPool<Face> faces;

        public VoronoiFactory()
        {
            vertices = new ObjectPool<Vertex>();
            edges = new ObjectPool<HalfEdge>();
            faces = new ObjectPool<Face>();
        }

        public void Initialize(int vertexCount, int edgeCount, int faceCount)
        {
            vertices.Capacity = vertexCount;
            edges.Capacity = edgeCount;
            faces.Capacity = faceCount;

            for (int i = vertices.Count; i < vertexCount; i++)
            {
                vertices.Put(new Vertex(0, 0));
            }

            for (int i = edges.Count; i < edgeCount; i++)
            {
                edges.Put(new HalfEdge(null));
            }

            for (int i = faces.Count; i < faceCount; i++)
            {
                faces.Put(new Face(null));
            }

            Reset();
        }

        public void Reset()
        {
            vertices.Release();
            edges.Release();
            faces.Release();
        }

        public Vertex CreateVertex(double x, double y)
        {
            Vertex vertex;

            if (vertices.TryGet(out vertex))
            {
                vertex.x = x;
                vertex.y = y;
                vertex.leaving = null;

                return vertex;
            }

            vertex = new Vertex(x, y);

            vertices.Put(vertex);

            return vertex;
        }

        public HalfEdge CreateHalfEdge(Vertex origin, Face face)
        {
            HalfEdge edge;

            if (edges.TryGet(out edge))
            {
                edge.origin = origin;
                edge.face = face;
                edge.next = null;
                edge.twin = null;

                if (face != null && face.edge == null)
                {
                    face.edge = edge;
                }

                return edge;
            }

            edge = new HalfEdge(origin, face);

            edges.Put(edge);

            return edge;
        }

        public Face CreateFace(Geometry.Vertex vertex)
        {
            Face face;

            if (faces.TryGet(out face))
            {
                face.id = vertex.id;
                face.generator = vertex;
                face.edge = null;

                return face;
            }

            face = new Face(vertex);

            faces.Put(face);

            return face;
        }

        class ObjectPool<T> where T : class
        {
            int index, count;

            T[] pool;

            public int Count
            {
                get { return count; }
            }

            public int Capacity
            {
                get { return this.pool.Length; }
                set { Resize(value); }
            }

            public ObjectPool(int capacity = 3)
            {
                this.index = 0;
                this.count = 0;

                this.pool = new T[capacity];
            }

            public ObjectPool(T[] pool)
            {
                this.index = 0;
                this.count = 0;

                this.pool = pool;
            }

            public bool TryGet(out T obj)
            {
                if (this.index < this.count)
                {
                    obj = this.pool[this.index++];

                    return true;
                }

                obj = null;

                return false;
            }

            public void Put(T obj)
            {
                var capacity = this.pool.Length;

                if (capacity <= this.count)
                {
                    Resize(2 * capacity);
                }

                this.pool[this.count++] = obj;

                this.index++;
            }

            public void Release()
            {
                this.index = 0;
            }

            private void Resize(int size)
            {
                if (size > this.count)
                {
                    Array.Resize(ref this.pool, size);
                }
            }
        }
    }
}


text:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping default-access="field">
	<class name="com.ervacon.bitemporal.Person">
		<id name="id" type="long">
			<generator class="native"/>
		</id>

		<property name="name"/>
		<bag name="address" cascade="all-delete-orphan">
			<key column="person_id" not-null="true" update="false"/>
			<one-to-many entity-name="Address"/>
		</bag>
		<bag name="alive" cascade="all-delete-orphan">
			<key column="person_id" not-null="true" update="false"/>
			<one-to-many entity-name="Alive"/>
		</bag>
	</class>

	<class name="com.ervacon.bitemporal.BitemporalWrapper" entity-name="Address">
		<id name="id" type="long">
			<generator class="native"/>
		</id>

		<component name="value" class="com.ervacon.bitemporal.Address">
			<property name="line1"/>
			<property name="line2"/>
			<property name="line3"/>
		</component>

		<property name="validityInterval" type="com.ervacon.bitemporal.support.PersistentInterval">
			<column name="validityStart"/>
			<column name="validityEnd"/>
		</property>
		<property name="recordInterval" type="com.ervacon.bitemporal.support.PersistentInterval">
			<column name="recordStart"/>
			<column name="recordEnd"/>
		</property>
	</class>

	<class name="com.ervacon.bitemporal.BitemporalWrapper" entity-name="Alive">
		<id name="id" type="long">
			<generator class="native"/>
		</id>

		<property name="value" type="boolean"/>

		<property name="validityInterval" type="com.ervacon.bitemporal.support.PersistentInterval">
			<column name="validityStart"/>
			<column name="validityEnd"/>
		</property>
		<property name="recordInterval" type="com.ervacon.bitemporal.support.PersistentInterval">
			<column name="recordStart"/>
			<column name="recordEnd"/>
		</property>
	</class>
</hibernate-mapping>


text:
@interface GKWYNewsNewViewController : GKTabBaseViewController

@end


text:
using System;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.ResourceManager;
using Azure.ResourceManager.ResourceMover.Models;
using Azure.ResourceManager.Resources;

namespace Azure.ResourceManager.ResourceMover
{
    /// <summary> A class to add extension methods to Azure.ResourceManager.ResourceMover. </summary>
    public static partial class ResourceMoverExtensions
    {
        private static TenantResourceExtensionClient GetExtensionClient(TenantResource tenantResource)
        {
            return tenantResource.GetCachedClient((client) =>
            {
                return new TenantResourceExtensionClient(client, tenantResource.Id);
            }
            );
        }

        /// <summary>
        /// Request Path: /providers/Microsoft.Migrate/operations
        /// Operation Id: OperationsDiscovery_Get
        /// </summary>
        /// <param name="tenantResource"> The <see cref="TenantResource" /> instance the method will execute against. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <returns> An async collection of <see cref="MoverOperationsDiscovery" /> that may take multiple service requests to iterate over. </returns>
        public static AsyncPageable<MoverOperationsDiscovery> GetOperationsDiscoveriesAsync(this TenantResource tenantResource, CancellationToken cancellationToken = default)
        {
            return GetExtensionClient(tenantResource).GetOperationsDiscoveriesAsync(cancellationToken);
        }

        /// <summary>
        /// Request Path: /providers/Microsoft.Migrate/operations
        /// Operation Id: OperationsDiscovery_Get
        /// </summary>
        /// <param name="tenantResource"> The <see cref="TenantResource" /> instance the method will execute against. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <returns> A collection of <see cref="MoverOperationsDiscovery" /> that may take multiple service requests to iterate over. </returns>
        public static Pageable<MoverOperationsDiscovery> GetOperationsDiscoveries(this TenantResource tenantResource, CancellationToken cancellationToken = default)
        {
            return GetExtensionClient(tenantResource).GetOperationsDiscoveries(cancellationToken);
        }

        private static SubscriptionResourceExtensionClient GetExtensionClient(SubscriptionResource subscriptionResource)
        {
            return subscriptionResource.GetCachedClient((client) =>
            {
                return new SubscriptionResourceExtensionClient(client, subscriptionResource.Id);
            }
            );
        }

        /// <summary>
        /// Get all the Move Collections in the subscription.
        /// Request Path: /subscriptions/{subscriptionId}/providers/Microsoft.Migrate/moveCollections
        /// Operation Id: MoveCollections_ListMoveCollectionsBySubscription
        /// </summary>
        /// <param name="subscriptionResource"> The <see cref="SubscriptionResource" /> instance the method will execute against. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <returns> An async collection of <see cref="MoverResourceSetResource" /> that may take multiple service requests to iterate over. </returns>
        public static AsyncPageable<MoverResourceSetResource> GetMoverResourceSetsAsync(this SubscriptionResource subscriptionResource, CancellationToken cancellationToken = default)
        {
            return GetExtensionClient(subscriptionResource).GetMoverResourceSetsAsync(cancellationToken);
        }

        /// <summary>
        /// Get all the Move Collections in the subscription.
        /// Request Path: /subscriptions/{subscriptionId}/providers/Microsoft.Migrate/moveCollections
        /// Operation Id: MoveCollections_ListMoveCollectionsBySubscription
        /// </summary>
        /// <param name="subscriptionResource"> The <see cref="SubscriptionResource" /> instance the method will execute against. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <returns> A collection of <see cref="MoverResourceSetResource" /> that may take multiple service requests to iterate over. </returns>
        public static Pageable<MoverResourceSetResource> GetMoverResourceSets(this SubscriptionResource subscriptionResource, CancellationToken cancellationToken = default)
        {
            return GetExtensionClient(subscriptionResource).GetMoverResourceSets(cancellationToken);
        }

        private static ResourceGroupResourceExtensionClient GetExtensionClient(ResourceGroupResource resourceGroupResource)
        {
            return resourceGroupResource.GetCachedClient((client) =>
            {
                return new ResourceGroupResourceExtensionClient(client, resourceGroupResource.Id);
            }
            );
        }

        /// <summary> Gets a collection of MoverResourceSetResources in the ResourceGroupResource. </summary>
        /// <param name="resourceGroupResource"> The <see cref="ResourceGroupResource" /> instance the method will execute against. </param>
        /// <returns> An object representing collection of MoverResourceSetResources and their operations over a MoverResourceSetResource. </returns>
        public static MoverResourceSetCollection GetMoverResourceSets(this ResourceGroupResource resourceGroupResource)
        {
            return GetExtensionClient(resourceGroupResource).GetMoverResourceSets();
        }

        /// <summary>
        /// Gets the move collection.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/moveCollections/{moveCollectionName}
        /// Operation Id: MoveCollections_Get
        /// </summary>
        /// <param name="resourceGroupResource"> The <see cref="ResourceGroupResource" /> instance the method will execute against. </param>
        /// <param name="moverResourceSetName"> The Move Collection Name. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentException"> <paramref name="moverResourceSetName"/> is an empty string, and was expected to be non-empty. </exception>
        /// <exception cref="ArgumentNullException"> <paramref name="moverResourceSetName"/> is null. </exception>
        [ForwardsClientCalls]
        public static async Task<Response<MoverResourceSetResource>> GetMoverResourceSetAsync(this ResourceGroupResource resourceGroupResource, string moverResourceSetName, CancellationToken cancellationToken = default)
        {
            return await resourceGroupResource.GetMoverResourceSets().GetAsync(moverResourceSetName, cancellationToken).ConfigureAwait(false);
        }

        /// <summary>
        /// Gets the move collection.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Migrate/moveCollections/{moveCollectionName}
        /// Operation Id: MoveCollections_Get
        /// </summary>
        /// <param name="resourceGroupResource"> The <see cref="ResourceGroupResource" /> instance the method will execute against. </param>
        /// <param name="moverResourceSetName"> The Move Collection Name. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentException"> <paramref name="moverResourceSetName"/> is an empty string, and was expected to be non-empty. </exception>
        /// <exception cref="ArgumentNullException"> <paramref name="moverResourceSetName"/> is null. </exception>
        [ForwardsClientCalls]
        public static Response<MoverResourceSetResource> GetMoverResourceSet(this ResourceGroupResource resourceGroupResource, string moverResourceSetName, CancellationToken cancellationToken = default)
        {
            return resourceGroupResource.GetMoverResourceSets().Get(moverResourceSetName, cancellationToken);
        }

        #region MoverResourceSetResource
        /// <summary>
        /// Gets an object representing a <see cref="MoverResourceSetResource" /> along with the instance operations that can be performed on it but with no data.
        /// You can use <see cref="MoverResourceSetResource.CreateResourceIdentifier" /> to create a <see cref="MoverResourceSetResource" /> <see cref="ResourceIdentifier" /> from its components.
        /// </summary>
        /// <param name="client"> The <see cref="ArmClient" /> instance the method will execute against. </param>
        /// <param name="id"> The resource ID of the resource to get. </param>
        /// <returns> Returns a <see cref="MoverResourceSetResource" /> object. </returns>
        public static MoverResourceSetResource GetMoverResourceSetResource(this ArmClient client, ResourceIdentifier id)
        {
            return client.GetResourceClient(() =>
            {
                MoverResourceSetResource.ValidateResourceId(id);
                return new MoverResourceSetResource(client, id);
            }
            );
        }
        #endregion

        #region MoverResource
        /// <summary>
        /// Gets an object representing a <see cref="MoverResource" /> along with the instance operations that can be performed on it but with no data.
        /// You can use <see cref="MoverResource.CreateResourceIdentifier" /> to create a <see cref="MoverResource" /> <see cref="ResourceIdentifier" /> from its components.
        /// </summary>
        /// <param name="client"> The <see cref="ArmClient" /> instance the method will execute against. </param>
        /// <param name="id"> The resource ID of the resource to get. </param>
        /// <returns> Returns a <see cref="MoverResource" /> object. </returns>
        public static MoverResource GetMoverResource(this ArmClient client, ResourceIdentifier id)
        {
            return client.GetResourceClient(() =>
            {
                MoverResource.ValidateResourceId(id);
                return new MoverResource(client, id);
            }
            );
        }
        #endregion
    }
}


text:
package com.eric.amap.geocoder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.eric.amap.AmapResultImpl;
import com.eric.amap.bean.AmapResult;
import com.eric.amap.utils.AmapExceptions;
//import com.eric.amap.utils.AmapProxy;
import com.eric.amap.utils.AmapPost;
import com.eric.amap.utils.AmapSign;
import com.eric.amap.utils.Constants;
import com.eric.amap.utils.StringUtils;

/**
 * @author Administrator
 * @version
 * @see
 */
public class GeoCodeImpl implements GeoCodeInterface, Constants{

	private static final Logger logger = LoggerFactory.getLogger(GeoCodeImpl.class);

	private AmapSign amapSign = null;
	private AmapResult amapResult = null;
	//private AmapProxy amapProxy = null;
	private AmapPost amapPost = null;
	private Long startTime = null;
	private Long endTime = null;

	public GeoCodeImpl(){
		amapSign = new AmapSign();
		amapResult = new AmapResult();
		//amapProxy = AmapProxy.getAmapProxyInstance();
		amapPost = new AmapPost();
		amapResult.setOutput(OUTPUT_XML);
		amapResult.setCompress(COMPRESS_FALSE);
		amapResult.setLanguage(LANG_CN_STRING);
		amapResult.setFrom(UNKNOWN);
		amapResult.setChannel(CHANNEL_STRING);
	}

	public void emptyGeoCodeImpl(){
		amapSign = null;
		amapResult = null;
		//amapProxy = null;
		amapPost = null;
	}

	/**
	 * 地理编码查询
	 * SearchGeoCode
	 * @param
	 * @return
	 */
	public Object SearchGeoCode(String address, String adcode, String adcode_beginwith,
								String onerow, String channel, String from, String output,
								boolean compress, String language, String reponseType
								) throws AmapExceptions {

		this.startTime = System.currentTimeMillis();

		String repoString = null;
		Object returnObject = null;
		long currentTime = System.currentTimeMillis();
		String current_Time = String.valueOf(currentTime);
		currentTime = Long.parseLong(current_Time.substring(0,current_Time.length() - 3));
		StringBuffer urlBuffer = new StringBuffer();
		String url = "";
		AmapResultImpl amapResultImpl = null;

		try {
			if( reponseType.equalsIgnoreCase(RESPONSE_TYPE_XML)
				|| reponseType.equalsIgnoreCase(RESPONSE_TYPE_JSON)
				|| reponseType.equalsIgnoreCase(RESPONSE_TYPE_JSONP) ){

				url = this.getGeoCodeSign(SEARCHGEOCODE_STRING, address, "", "", adcode, adcode_beginwith,
										  onerow, reponseType);
				urlBuffer.append(url);
				//returnObject = amapProxy.requestAmap(HTTP_POST_METHOD_STRING, urlBuffer.toString());
				returnObject=amapPost.post(urlBuffer.toString());
			}

			if(reponseType.equalsIgnoreCase(RESPONSE_TYPE_OBJECT)){
				amapResultImpl = new AmapResultImpl();
				url = this.getGeoCodeSign(SEARCHGEOCODE_STRING, address, "", "", adcode, adcode_beginwith,
						  				  onerow, RESPONSE_TYPE_XML);
				urlBuffer.append(url);
				//repoString = amapProxy.requestAmap(HTTP_POST_METHOD_STRING, urlBuffer.toString());
				repoString = amapPost.post(urlBuffer.toString());
				if(repoString == null){
					return returnObject;
				}else{
					returnObject = amapResultImpl.toAmapResult(repoString);
				}
			}

			this.endTime = System.currentTimeMillis();
			logger.debug("Amap:SearchGeoCode:ExecuteDuration: " + (this.endTime - this.startTime) + " ms." );

			return returnObject;

		}catch(Exception e){
			logger.error("Amap:::SearchGeoCode====" + e.getMessage(), e.getCause());
			throw new AmapExceptions("Amap:::SearchGeoCode Exception:" + e.getMessage(), e.getCause());
		}
	}

	/**
	 * 逆地址编码查询
	 * SearchOppGeoCode
	 * 2013-03-06:高德答复,服务端对重复的数据做了排重处理,已解决。
	 * @param
	 * @return
	 */
	public Object SearchOppGeoCode(String longitude, String latitude, String channel,
			   					   String from, String output, boolean compress,
			   					   String language, String reponseType
			   					   ) throws AmapExceptions {

		this.startTime = System.currentTimeMillis();

		String url = "";
		String adcode = "";
		String adcodeBeginwith = "";
		String onerow = "";
		String repoString = null;
		Object returnObject = null;
		long currentTime = System.currentTimeMillis();
		String current_Time = String.valueOf(currentTime);
		currentTime = Long.parseLong(current_Time.substring(0,current_Time.length() - 3));
		StringBuffer urlBuffer = new StringBuffer();
		AmapResultImpl amapResultImpl = null;

		try {
			if( reponseType.equalsIgnoreCase(RESPONSE_TYPE_XML)
				|| reponseType.equalsIgnoreCase(RESPONSE_TYPE_JSON)
				|| reponseType.equalsIgnoreCase(RESPONSE_TYPE_JSONP) ){

				url = this.getGeoCodeSign(SEARCHOPPGEOCODE_STRING, "", longitude, latitude, adcode, adcodeBeginwith,
		  				  				  onerow, reponseType);
				urlBuffer.append(url);
				//returnObject = amapProxy.requestAmap(HTTP_POST_METHOD_STRING, urlBuffer.toString());
				returnObject = amapPost.post(urlBuffer.toString());
			}

			if(reponseType.equalsIgnoreCase(RESPONSE_TYPE_OBJECT)){
				amapResultImpl = new AmapResultImpl();
				url = this.getGeoCodeSign(SEARCHOPPGEOCODE_STRING, "", longitude, latitude, adcode, adcodeBeginwith,
		  				  				  onerow, RESPONSE_TYPE_XML);
				urlBuffer.append(url);
				//repoString = amapProxy.requestAmap(HTTP_POST_METHOD_STRING, urlBuffer.toString());
				repoString = amapPost.post(urlBuffer.toString());
				if(repoString == null){
					return returnObject;
				}else{
					returnObject = amapResultImpl.toAmapResult(repoString);
				}
			}

			//由于高德接口返回数据慢,导致错误,故增加此句代码,等候数据返回。
			//可能由于加入此行代码,导致用户感觉坐席响应速度慢,不利于用户体验,
			//故建议高德方面优化其接口,解决此问题。
			Thread.currentThread().sleep(1000);

			this.endTime = System.currentTimeMillis();
			logger.debug("Amap:SearchOppGeoCode:ExecuteDuration: " + (this.endTime - this.startTime) + " ms." );

			return returnObject;

		}catch(Exception e){
			logger.error("Amap:::SearchOppGeoCode====" + e.getMessage(), e.getCause());
			throw new AmapExceptions("Amap:::SearchOppGeoCode Exception:" + e.getMessage(), e.getCause());
		}
	}

	/**
	 * 根据输入的方法名,产生对应的url请求地址,包含签名Sign。
	 * @param String methodNameString  方法名
	 * 	      String address 地址
	 * @return String urlString  URL地址
	 *         String Sign 签名字串
	 */
	@SuppressWarnings("unused")
	public String getGeoCodeSign(String methodNameString, String address, String longitude, String latitude,
								 String adcode, String adcodeBeginwith, String onerow, String reponseType
								 ) throws AmapExceptions {

		this.startTime = System.currentTimeMillis();

		String sign = null;
		String temp = null;
		StringBuffer url = null;

		if(StringUtils.isNull(methodNameString)){
			throw new AmapExceptions("输入参数不能为空,请检查输入方法名!");
		}
		if(methodNameString.equalsIgnoreCase(SEARCHGEOCODE_STRING)){
			if(StringUtils.isNull(address)){
				throw new AmapExceptions("地址不能为空,请检查输入地址!");
			}
		}

		if(methodNameString.equalsIgnoreCase(SEARCHOPPGEOCODE_STRING)){
			if(StringUtils.isNull(longitude)){
				throw new AmapExceptions("经度不能为空,请检查输入经度!");
			}
			if(StringUtils.isNull(latitude)){
				throw new AmapExceptions("纬度不能为空,请检查输入纬度!");
			}
		}

		try{

			if(methodNameString.equalsIgnoreCase(SEARCHGEOCODE_STRING)){
				//temp = amapSign.covertBytes(address);
				sign = amapSign.getSign(address);
			}

			if(methodNameString.equalsIgnoreCase(SEARCHOPPGEOCODE_STRING)){
				//temp = amapSign.covertBytes(longitude, latitude);
				sign = amapSign.getSign(longitude, latitude);
			}

//			String result = amapSign.Md5(temp + "@" + SIGN);		// Éú³ÉÇ©Ãû
//			sign = result.toUpperCase();

			if(methodNameString.equalsIgnoreCase(SEARCHGEOCODE_STRING)){
				url = new StringBuffer(MAINURL_STRING + GEOCODE_STRING + "?channel=" + amapResult.getChannel());
			}

			if(methodNameString.equalsIgnoreCase(SEARCHOPPGEOCODE_STRING)){
				url = new StringBuffer(MAINURL_STRING + REVERSECODE_STRING + "?channel=" + amapResult.getChannel());
			}

			if(methodNameString.equalsIgnoreCase(SEARCHGEOCODE_STRING)){
				url.append("&address=" + address);

				if(!StringUtils.isNull(adcode)){
					url.append("&adcode=" + adcode);
				}else{
					// 缺省为空
				}

				if(!StringUtils.isNull(adcodeBeginwith)){
					url.append("&adcode_beginwith=" + adcodeBeginwith);
				}else{
					url.append("&adcode_beginwith=True");
				}

				if(!StringUtils.isNull(onerow)){
					url.append("&onerow=" + onerow);
				}else{
					url.append("&onerow=True");
				}
			}

			if(methodNameString.equalsIgnoreCase(SEARCHOPPGEOCODE_STRING)){
				url.append("&longitude=" + longitude);
				url.append("&latitude=" + latitude);
			}

			url.append("&from=" + amapResult.getFrom());

			if(reponseType.equalsIgnoreCase(RESPONSE_TYPE_XML)){
				amapResult.setOutput(OUTPUT_XML);
				url.append("&output=" + amapResult.getOutput());
			}

			if(reponseType.equalsIgnoreCase(RESPONSE_TYPE_JSON)){
				amapResult.setOutput(OUTPUT_JSON);
				url.append("&output=" + amapResult.getOutput());
			}

			if(reponseType.equalsIgnoreCase(RESPONSE_TYPE_JSONP)){
				amapResult.setOutput(OUTPUT_JSONP);
				url.append("&output=" + amapResult.getOutput());
			}

			if(StringUtils.isNull(reponseType)){
				amapResult.setOutput(OUTPUT_XML);	// 默认值XML
				url.append("&output=" + amapResult.getOutput());
			}

			url.append("&compress=" + amapResult.getCompress());
			url.append("&sign=" + sign);

			this.endTime = System.currentTimeMillis();
			logger.debug("Amap:getGeoCodeSign:ExecuteDuration: " + (this.endTime - this.startTime) + " ms." );

			return url.toString();

		}catch(Exception e){
			logger.error("Amap:::getGeoCodeSign====" + e.getMessage(), e.getCause());
			throw new AmapExceptions("Amap:::getGeoCodeSign Exception:" + e.getMessage(), e.getCause());
		}
	}
}


text:
<?php

namespace Application\Bundle\AdminBundle\Security\User\Provider;

use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Facebook;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use \BaseFacebook;
use \FacebookApiException;

class FacebookProvider implements UserProviderInterface
{
    /**
     * @var \Facebook
     */
    protected $facebook;
    protected $userManager;
    protected $validator;
    protected $container;

    public function __construct(BaseFacebook $facebook, $userManager, $validator, $container)
    {
        $this->facebook = $facebook;

        // Add this to not have the error "the ssl certificate is invalid."
        Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYPEER] = false;
        Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYHOST] = 2;

        $this->userManager = $userManager;
        $this->validator = $validator;
        $this->container = $container;
    }

    public function supportsClass($class)
    {
        return $this->userManager->supportsClass($class);
    }

    public function findUserByFbId($fbId)
    {
        return $this->userManager->findUserBy(array('facebookId' => $fbId));
    }

    public function findUserByUsername($username)
    {
        return $this->userManager->findUserBy(array('username' => $username));
    }

    public function connectExistingAccount()
    {

        try {
            $fbdata = $this->facebook->api('/me');
        } catch (FacebookApiException $e) {
            $fbdata = null;
            return false;
        }

        $alreadyExistingAccount = $this->findUserByFbId($fbdata['id']);

        if (!empty($alreadyExistingAccount)) {
            return false;
        }

        if (!empty($fbdata)) {

            $currentUserObj = $this->container->get('security.context')->getToken()->getUser();

            $user = $this->findUserByUsername($currentUserObj->getUsername());

            if (empty($user)) {
                return false;
            }

            $user->setFBData($fbdata);

            if (count($this->validator->validate($user, 'Facebook'))) {
                // TODO: the user was found obviously, but doesnt match our expectations, do something smart
                throw new UsernameNotFoundException('The facebook user could not be stored');
            }
            $this->userManager->updateUser($user);

            return true;
        }

        return false;

    }

    public function loadUserByUsername($username)
    {
        $user = $this->findUserByFbId($username);

        try {
            $fbdata = $this->facebook->api('/me');
        } catch (FacebookApiException $e) {
            $fbdata = null;
        }

        if (!empty($fbdata)) {
            if (empty($user)) {
                $user = $this->userManager->createUser();
                $user->setEnabled(true);
                $user->setPassword('');
            }

            if($user->getUsername() == '' || $user->getUsername() == null)
            {
                $user->setUsername($username . '@facebook.com');
            }

            $user->setFBData($fbdata);

            if (count($this->validator->validate($user, 'Facebook'))) {
                // TODO: the user was found obviously, but doesnt match our expectations, do something smart
                throw new UsernameNotFoundException('The facebook user could not be stored');
            }
            $this->userManager->updateUser($user);
        }

        if (empty($user)) {

            // TODO: the user was found obviously, but doesnt match our expectations, do something smart
            throw new UsernameNotFoundException('The facebook user could not be stored');

        }

        return $user;
    }

    public function refreshUser(UserInterface $user)
    {
        if (!$this->supportsClass(get_class($user)) || !$user->getFacebookId()) {
            throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user)));
        }

        return $this->loadUserByUsername($user->getFacebookId());
    }
}


text:
class SparkError(RuntimeError):
    pass


text:
layout: page
title: Contact
description: "Contact Start Bootstrap if you have suggestions for a new template, have feedback for us, or if you need help."
meta-title: "Contact"
meta-description: "Contact Start Bootstrap - Start Bootstrap help requests, template suggestions, and general feedback."
redirect_from:
  - /contact.php/
---

 Feedback & Template Suggestions

If you have general feedback, or if you have an idea for a template you would like to see on Start Bootstrap, please email us at:

feedback@startbootstrap.com

 Help Requests

If you need help with one of our templates, or if you are experiencing a bug, please visit our help page. If you still can't find an answer, please email us at:

help@startbootstrap.com

 Hire Us!

Do you want a custom Bootstrap theme? Do you like one of our templates, but want some additional features added? If so, you can hire the Start Bootstrap team to get your custom project done! We build HTML/CSS Bootstrap themes on a per project basis. We can work from design concepts, examples of other designs you like, or from PSD's! If you're interested in our custom design services, click here for more information, or email us at:

feedback@startbootstrap.com


text:
module Shipit
  class ApplicationRecord < Record
    self.abstract_class = true
  end
end


text:
@implementation UIViewController (Storyboard)

+ (id)initialControllerFromStoryboard {
    NSString *storyboardName = NSStringFromClass([self class]);
    return [self initialControllerFromStoryboard:storyboardName];
}

+ (id)controllerFromStoryboard {
    NSString *storyboardName = NSStringFromClass([self class]);
    return [self controllerFromStoryboard:storyboardName withIdentifier:storyboardName];
}

+ (id)controllerFromStoryboardWithIdentifier:(NSString *)identifier {
    NSString *storyboardName = NSStringFromClass([self class]);
    return [self controllerFromStoryboard:storyboardName withIdentifier:identifier];
}

+ (id)initialControllerFromStoryboard:(NSString *)storyboardName {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle:nil];
    return [storyboard instantiateInitialViewController];
}

+ (id)controllerFromStoryboard:(NSString *)storyboardName withIdentifier:(NSString *)identifier {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:storyboardName bundle:nil];
    return [storyboard instantiateViewControllerWithIdentifier:identifier];
}

@end


text:
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var crel = require('crel'),
    resizeo = require('../'),
    imagePath = 'kitten.jpg',
    toDataUri = require('to-datauri');

window.addEventListener('load', function(){

    crel(document.body,
        crel('img', {src: imagePath})
    );

    toDataUri(imagePath, function (error, uri) {
        resizeo(uri, 100, function(error, resizedUri) {
            crel(document.body,
                crel('img', {src: resizedUri})
            );
        });

        resizeo(uri, 200, function(error, resizedUri) {
            crel(document.body,
                crel('img', {src: resizedUri})
            );
        });

        resizeo(uri, 300, function(error, resizedUri) {
            crel(document.body,
                crel('img', {src: resizedUri})
            );
        });

        resizeo(uri, 400, function(error, resizedUri) {
            crel(document.body,
                crel('img', {src: resizedUri})
            );
        });

        resizeo(uri, 500, function(error, resizedUri) {
            crel(document.body,
                crel('img', {src: resizedUri})
            );
        });
    });
});
},{"../":2,"crel":3,"to-datauri":4}],2:[function(require,module,exports){
module.exports = function(dataUri, maxDimension, callback){
    var source = new Image();

    source.addEventListener('load', function(){
        var canvas = document.createElement('canvas'),
            ratio = Math.max(source.width, source.height) / maxDimension;

        canvas.width = source.width / ratio;
        canvas.height = source.height / ratio;

        var context = canvas.getContext('2d');

        context.drawImage(
            source,
            0,
            0,
            source.width,
            source.height,
            0,
            0,
            canvas.width,
            canvas.height
        );

        callback(null, canvas.toDataURL());
    });

    source.src = dataUri;
};
},{}],3:[function(require,module,exports){
//Copyright (C) 2012 Kory Nunn

//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

//The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

/*

    This code is not formatted for readability, but rather run-speed and to assist compilers.

    However, the code's intention should be transparent.

    *** IE SUPPORT ***

    If you require this library to work in IE7, add the following after declaring crel.

    var testDiv = document.createElement('div'),
        testLabel = document.createElement('label');

    testDiv.setAttribute('class', 'a');
    testDiv['className'] !== 'a' ? crel.attrMap['class'] = 'className':undefined;
    testDiv.setAttribute('name','a');
    testDiv['name'] !== 'a' ? crel.attrMap['name'] = function(element, value){
        element.id = value;
    }:undefined;

    testLabel.setAttribute('for', 'a');
    testLabel['htmlFor'] !== 'a' ? crel.attrMap['for'] = 'htmlFor':undefined;

*/

(function (root, factory) {
    if (typeof exports === 'object') {
        module.exports = factory();
    } else if (typeof define === 'function' && define.amd) {
        define(factory);
    } else {
        root.crel = factory();
    }
}(this, function () {
    var fn = 'function',
        obj = 'object',
        nodeType = 'nodeType',
        textContent = 'textContent',
        setAttribute = 'setAttribute',
        attrMapString = 'attrMap',
        isNodeString = 'isNode',
        isElementString = 'isElement',
        d = typeof document === obj ? document : {},
        isType = function(a, type){
            return typeof a === type;
        },
        isNode = typeof Node === fn ? function (object) {
            return object instanceof Node;
        } :
        // in IE <= 8 Node is an object, obviously..
        function(object){
            return object &&
                isType(object, obj) &&
                (nodeType in object) &&
                isType(object.ownerDocument,obj);
        },
        isElement = function (object) {
            return crel[isNodeString](object) && object[nodeType] === 1;
        },
        isArray = function(a){
            return a instanceof Array;
        },
        appendChild = function(element, child) {
          if(!crel[isNodeString](child)){
              child = d.createTextNode(child);
          }
          element.appendChild(child);
        };

    function crel(){
        var args = arguments, //Note: assigned to a variable to assist compilers. Saves about 40 bytes in closure compiler. Has negligable effect on performance.
            element = args[0],
            child,
            settings = args[1],
            childIndex = 2,
            argumentsLength = args.length,
            attributeMap = crel[attrMapString];

        element = crel[isElementString](element) ? element : d.createElement(element);
        // shortcut
        if(argumentsLength === 1){
            return element;
        }

        if(!isType(settings,obj) || crel[isNodeString](settings) || isArray(settings)) {
            --childIndex;
            settings = null;
        }

        // shortcut if there is only one child that is a string
        if((argumentsLength - childIndex) === 1 && isType(args[childIndex], 'string') && element[textContent] !== undefined){
            element[textContent] = args[childIndex];
        }else{
            for(; childIndex < argumentsLength; ++childIndex){
                child = args[childIndex];

                if(child == null){
                    continue;
                }

                if (isArray(child)) {
                  for (var i=0; i < child.length; ++i) {
                    appendChild(element, child[i]);
                  }
                } else {
                  appendChild(element, child);
                }
            }
        }

        for(var key in settings){
            if(!attributeMap[key]){
                element[setAttribute](key, settings[key]);
            }else{
                var attr = attributeMap[key];
                if(typeof attr === fn){
                    attr(element, settings[key]);
                }else{
                    element[setAttribute](attr, settings[key]);
                }
            }
        }

        return element;
    }

    // Used for mapping one kind of attribute to the supported version of that in bad browsers.
    crel[attrMapString] = {};

    crel[isElementString] = isElement;

    crel[isNodeString] = isNode;

    return crel;
}));

},{}],4:[function(require,module,exports){
module.exports = function (sourcePath, callback) {
    var canvas = document.createElement('canvas'),
        image = new Image();

    image.addEventListener('load', function () {
        var context = canvas.getContext('2d');

        canvas.width = image.width;
        canvas.height = image.height;

        context.drawImage(image, 0, 0);

        callback(null, canvas.toDataURL('image/png'));
    });

    image.addEventListener('error', callback);

    image.src = sourcePath;
};
},{}]},{},[1]);


text:
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

namespace Amazon.ElasticBeanstalk.Model
{
    ///
    /// <para>Result message containing a list of environment resource descriptions. </para>
    ///
    public class DescribeEnvironmentResourcesResult
    {

        private EnvironmentResourceDescription environmentResources;

        ///
        /// A list of EnvironmentResourceDescription.
        ///
        ///
        public EnvironmentResourceDescription EnvironmentResources
        {
            get { return this.environmentResources; }
            set { this.environmentResources = value; }
        }

        ///
        /// Sets the EnvironmentResources property
        ///
        /// <param name="environmentResources">The value to set for the EnvironmentResources property </param>
        /// <returns>this instance</returns>
        [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
        public DescribeEnvironmentResourcesResult WithEnvironmentResources(EnvironmentResourceDescription environmentResources)
        {
            this.environmentResources = environmentResources;
            return this;
        }

        // Check to see if EnvironmentResources property is set
        internal bool IsSetEnvironmentResources()
        {
            return this.environmentResources != null;
        }
    }
}


text:
package istioctl

import (
	"regexp"
	"strings"
	"testing"

	"istio.io/istio/pkg/test/framework/label"
	"istio.io/istio/pkg/test/framework/resource/environment"

	"istio.io/istio/pkg/test/framework"
	"istio.io/istio/pkg/test/framework/components/istio"
	"istio.io/istio/pkg/test/framework/components/istioctl"
)

var (
	inst istio.Instance
)

// This test requires `--istio.test.env=kube` because it tests istioctl managing k8s webhook configurations.
func TestMain(m *testing.M) {
	framework.
		NewSuite("istioctl_webhook_test", m).
		Label(label.CustomSetup).
		RequireEnvironment(environment.Kube).
		RequireSingleCluster().
		// Deploy Istio
		SetupOnEnv(environment.Kube, istio.Setup(&inst, setupConfig)).
		Run()
}

func setupConfig(cfg *istio.Config) {
	if cfg == nil {
		return
	}
	cfg.ControlPlaneValues = `
values:
  global:
    operatorManageWebhooks: true
    certificates:
      - dnsNames: [istio-pilot.istio-system.svc, istio-pilot.istio-system]
      - secretName: dns.istio-galley-service-account
        dnsNames: [istio-galley.istio-system.svc, istio-galley.istio-system]
      - secretName: dns.istio-sidecar-injector-service-account
        dnsNames: [istio-sidecar-injector.istio-system.svc, istio-sidecar-injector.istio-system]
`
}

// TestWebhookManagement tests "istioctl experimental post-install webhook" command.
func TestWebhookManagement(t *testing.T) {
	framework.
		NewTest(t).
		Run(func(ctx framework.TestContext) {
			ctx.Skip("TODO(github.com/istio/istio/issues/20289)")

			// Test that webhook configurations are enabled through istioctl successfully.
			args := []string{"experimental", "post-install", "webhook", "enable", "--validation", "--webhook-secret",
				"dns.istio-galley-service-account", "--namespace", "istio-system", "--validation-path", "./config/galley-webhook.yaml",
				"--injection-path", "./config/sidecar-injector-webhook.yaml"}
			istioCtl := istioctl.NewOrFail(ctx, ctx, istioctl.Config{})
			output, _, fErr := istioCtl.Invoke(args)
			if fErr != nil {
				t.Fatalf("error returned for 'istioctl %s': %v", strings.Join(args, " "), fErr)
			}

			// Check that the webhook configurations are successful
			expectedRegexps := []*regexp.Regexp{
				regexp.MustCompile(`finished reading cert`),
				regexp.MustCompile(`create webhook configuration istio-galley`),
				regexp.MustCompile(`create webhook configuration istio-sidecar-injector`),
				regexp.MustCompile(`webhook configurations have been enabled`),
			}
			for _, regexp := range expectedRegexps {
				if !regexp.MatchString(output) {
					t.Fatalf("output didn't match for 'istioctl %s'\n got %v\nwant: %v",
						strings.Join(args, " "), output, regexp)
				}
			}

			// Test that webhook statuses returned by running istioctl are as expected.
			args = []string{"experimental", "post-install", "webhook", "status"}
			istioCtl = istioctl.NewOrFail(ctx, ctx, istioctl.Config{})
			output, _, fErr = istioCtl.Invoke(args)
			if fErr != nil {
				t.Fatalf("error returned for 'istioctl %s': %v", strings.Join(args, " "), fErr)
			}

			// Check that the webhook statuses are as expected
			expectedRegexps = []*regexp.Regexp{
				regexp.MustCompile(`ValidatingWebhookConfiguration istio-galley is`),
				regexp.MustCompile(`MutatingWebhookConfiguration istio-sidecar-injector is`),
			}
			for _, regexp := range expectedRegexps {
				if !regexp.MatchString(output) {
					t.Fatalf("output didn't match for 'istioctl %s'\n got %v\nwant: %v",
						strings.Join(args, " "), output, regexp)
				}
			}

			// Currently, unable to test disabling webhooks because the disable command requires
			// user interaction: "Are you sure to delete webhook configuration(s)?", the deletion
			// will only proceed after user entering "yes".
		})
}


text:
#ifndef _UECHO_DEVICE_H_
#define _UECHO_DEVICE_H_

#include <uecho/object.h>

#ifdef __cplusplus
extern "C" {
#endif

/****************************************
 * Device
 ****************************************/

uEchoObject* uecho_device_new(void);

/****************************************
 * Device Object Super Class
 ****************************************/

enum {
  uEchoDeviceVersionAppendixA = 'A',
  uEchoDeviceVersionAppendixB = 'B',
  uEchoDeviceVersionAppendixC = 'C',
  uEchoDeviceVersionAppendixD = 'D',
  uEchoDeviceVersionAppendixE = 'E',
  uEchoDeviceVersionAppendixF = 'F',
  uEchoDeviceVersionAppendixG = 'G',
  uEchoDeviceVersionAppendixH = 'H',
  uEchoDeviceVersionAppendixI = 'I',
  uEchoDeviceVersionAppendixJ = 'J',
  uEchoDeviceVersionAppendixK = 'K',
  uEchoDeviceVersionAppendixL = 'L',
  uEchoDeviceVersionAppendixM = 'M',
  uEchoDeviceVersionAppendixN = 'N',
  uEchoDeviceVersionUnknown = 0,
  uEchoDeviceVersionAppendixDefault = uEchoDeviceVersionAppendixN,
};

typedef enum {
  uEchoDeviceOperatingStatus = 0x80,
  uEchoDeviceInstallationLocation = 0x81,
  uEchoDeviceStandardVersion = 0x82,
  uEchoDeviceIdentificationNumber = 0x83,
  uEchoDeviceMeasuredInstantaneousPowerConsumption = 0x84,
  uEchoDeviceMeasuredCumulativePowerConsumption = 0x85,
  uEchoDeviceManufacturerFaultCode = 0x86,
  uEchoDeviceCurrentLimitSetting = 0x87,
  uEchoDeviceFaultStatus = 0x88,
  uEchoDeviceFaultDescription = 0x89,
  uEchoDeviceManufacturerCode = uEchoObjectManufacturerCode,
  uEchoDeviceBusinessFacilityCode = 0x8B,
  uEchoDeviceProductCode = 0x8C,
  uEchoDeviceProductionNumber = 0x8D,
  uEchoDeviceProductionDate = 0x8E,
  uEchoDevicePowerSavingOperationSetting = 0x8F,
  uEchoDeviceRemoteControlSetting = 0x93,
  uEchoDeviceCurrentTimeSetting = 0x97,
  uEchoDeviceCurrentDateSetting = 0x98,
  uEchoDevicePowerLimitSetting = 0x99,
  uEchoDeviceCumulativeOperatingTime = 0x9A,
  uEchoDeviceAnnoPropertyMap = uEchoObjectAnnoPropertyMap,
  uEchoDeviceSetPropertyMap = uEchoObjectSetPropertyMap,
  uEchoDeviceGetPropertyMap = uEchoObjectGetPropertyMap,
} uEchoDeviceEPC;

typedef enum {
  uEchoDeviceOperatingStatusSize = 1,
  uEchoDeviceInstallationLocationSize = 1,
  uEchoDeviceStandardVersionSize = 4,
  uEchoDeviceIdentificationNumberSize = 9,
  uEchoDeviceMeasuredInstantaneousPowerConsumptionSize = 2,
  uEchoDeviceMeasuredCumulativePowerConsumptionSize = 4,
  uEchoDeviceManufacturerFaultCodeSize = 255,
  uEchoDeviceCurrentLimitSettingSize = 1,
  uEchoDeviceFaultStatusSize = 1,
  uEchoDeviceFaultDescriptionSize = 2,
  uEchoDeviceManufacturerCodeSize = uEchoObjectManufacturerCodeLen,
  uEchoDeviceBusinessFacilityCodeSize = 3,
  uEchoDeviceProductCodeSize = 12,
  uEchoDeviceProductionNumberSize = 12,
  uEchoDeviceProductionDateSize = 4,
  uEchoDevicePowerSavingOperationSettingSize = 1,
  uEchoDeviceRemoteControlSettingSize = 1,
  uEchoDeviceCurrentTimeSettingSize = 2,
  uEchoDeviceCurrentDateSettingSize = 4,
  uEchoDevicePowerLimitSettingSize = 2,
  uEchoDeviceCumulativeOperatingTimeSize = 5,
  uEchoDeviceAnnoPropertyMapSize = uEchoObjectAnnoPropertyMapMaxLen,
  uEchoDeviceSetPropertyMapSize = uEchoObjectSetPropertyMapMaxLen,
  uEchoDeviceGetPropertyMapSize = uEchoObjectGetPropertyMapMaxLen,
} uEchoDevicenEPCSize;

enum {
  uEchoDeviceOperatingStatusOn = 0x30,
  uEchoDeviceOperatingStatusOff = 0x31,
  uEchoDeviceFaultOccurred = 0x41,
  uEchoDeviceNoFaultOccurred = 0x42,
  uEchoDeviceInstallationLocationUnknown = 0x00,
};

bool uecho_device_addmandatoryproperties(uEchoObject* obj);

bool uecho_device_setoperatingstatus(uEchoObject* obj, bool stats);
bool uecho_device_setinstallationlocation(uEchoObject* obj, byte location);
bool uecho_device_setstandardversion(uEchoObject* obj, char ver);
bool uecho_device_setfaultstatus(uEchoObject* obj, bool stats);
bool uecho_device_setmanufacturercode(uEchoObject* obj, uEchoManufactureCode code);

bool uecho_device_isoperatingstatus(uEchoObject* obj);
byte uecho_device_getinstallationlocation(uEchoObject* obj);
char uecho_device_getstandardversion(uEchoObject* obj);
bool uecho_device_isfaultstatus(uEchoObject* obj);
uEchoManufactureCode uecho_device_getmanufacturercode(uEchoObject* obj);

#ifdef __cplusplus
} /* extern C */
#endif

#endif /* _UECHO_NODE_H_ */


text:
var fs = require('fs');

var start = require('./start');
var packageJson = require('./package.json');

var program = require('commander');

program.version(packageJson.version);

var action = null;

program.command('start')
    .description('Starting fake REST API service')
    .option('-p, --port <n>', 'port', null)
    .option('-c, --config <s>', 'config', null)
    .action(function (cmd, options) {

        action = 'start';

        var config;

        var configPath = cmd.config;

        if (configPath) {

            configPath = String(configPath);

            if (!fs.existsSync(configPath)) {
                console.log('no config file "' + configPath + '"');
                return;
            }

            var configText = fs.readFileSync(configPath);

            try  {
                config = JSON.parse(configText);
            } catch (e) {
                console.log('config must be valid JSON');
                return;
            }

        } else {
            config = {};
        }

        if (cmd.port) {
            config.port = cmd.port;
        }

        start(config);
    });

program.parse(process.argv);

if (!action) {
    program.outputHelp();
}