text:
import {authenticateSession} from 'ember-simple-auth/test-support';
import {click, currentURL, find, findAll} from '@ember/test-helpers';
import {enableLabsFlag} from '../../helpers/labs-flag';
import {enableNewsletters} from '../../helpers/newsletters';
import {enableStripe} from '../../helpers/stripe';
import {expect} from 'chai';
import {setupApplicationTest} from 'ember-mocha';
import {setupMirage} from 'ember-cli-mirage/test-support';
import {visit} from '../../helpers/visit';

describe('Acceptance: Member details', function () {
    let hooks = setupApplicationTest();
    setupMirage(hooks);

    let clock;
    let tier;

    beforeEach(async function () {
        this.server.loadFixtures('configs');
        this.server.loadFixtures('settings');
        enableLabsFlag(this.server, 'membersLastSeenFilter');
        enableLabsFlag(this.server, 'membersTimeFilters');

        enableStripe(this.server);
        enableNewsletters(this.server, true);

        // add a default tier that complimentary plans can be assigned to
        tier = this.server.create('tier', {
            id: '6213b3f6cb39ebdb03ebd810',
            name: 'Ghost Subscription',
            slug: 'ghost-subscription',
            created_at: '2022-02-21T16:47:02.000Z',
            updated_at: '2022-03-03T15:37:02.000Z',
            description: null,
            monthly_price_id: '6220df272fee0571b5dd0a0a',
            yearly_price_id: '6220df272fee0571b5dd0a0b',
            type: 'paid',
            active: true,
            welcome_page_url: '/'
        });

        let role = this.server.create('role', {name: 'Owner'});
        this.server.create('user', {roles: [role]});

        return await authenticateSession();
    });

    afterEach(function () {
        clock?.restore();
    });

    it('has a known base-state', async function () {
        const member = this.server.create('member', {
            id: 1,
            subscriptions: [
                this.server.create('subscription', {
                    id: 'sub_1KZGcmEGb07FFvyN9jwrwbKu',
                    customer: {
                        id: 'cus_LFmBWoSkB84lnr',
                        name: 'test',
                        email: 'test@ghost.org'
                    },
                    plan: {
                        id: 'price_1KZGc6EGb07FFvyNkK3umKiX',
                        nickname: 'Monthly',
                        amount: 500,
                        interval: 'month',
                        currency: 'USD'
                    },
                    status: 'canceled',
                    start_date: '2022-03-03T15:31:27.000Z',
                    default_payment_card_last4: '4242',
                    cancel_at_period_end: false,
                    cancellation_reason: null,
                    current_period_end: '2022-04-03T15:31:27.000Z',
                    price: {
                        id: 'price_1KZGc6EGb07FFvyNkK3umKiX',
                        price_id: '6220df272fee0571b5dd0a0a',
                        nickname: 'Monthly',
                        amount: 500,
                        interval: 'month',
                        type: 'recurring',
                        currency: 'USD',
                        tier: {
                            id: 'prod_LFmAAmCnnbzrvL',
                            name: 'Ghost Subscription',
                            tier_id: tier.id
                        }
                    },
                    offer: null
                }),
                this.server.create('subscription', {
                    id: 'sub_1KZGi6EGb07FFvyNDjZq98g8',
                    tier,
                    customer: {
                        id: 'cus_LFmGicpX4BkQKH',
                        name: '123',
                        email: 'test@ghost.org'
                    },
                    plan: {
                        id: 'price_1KZGc6EGb07FFvyNkK3umKiX',
                        nickname: 'Monthly',
                        amount: 500,
                        interval: 'month',
                        currency: 'USD'
                    },
                    status: 'active',
                    start_date: '2022-03-03T15:36:58.000Z',
                    default_payment_card_last4: '4242',
                    cancel_at_period_end: false,
                    cancellation_reason: null,
                    current_period_end: '2022-04-03T15:36:58.000Z',
                    price: {
                        id: 'price_1KZGc6EGb07FFvyNkK3umKiX',
                        price_id: '6220df272fee0571b5dd0a0a',
                        nickname: 'Monthly',
                        amount: 500,
                        interval: 'month',
                        type: 'recurring',
                        currency: 'USD',
                        tier: {
                            id: 'prod_LFmAAmCnnbzrvL',
                            name: 'Ghost Subscription',
                            tier_id: tier.id
                        }
                    },
                    offer: null
                })
            ],
            tiers: [
                tier
            ]
        });

        await visit(`/members/${member.id}`);

        expect(currentURL()).to.equal(`/members/${member.id}`);

        expect(findAll('[data-test-subscription]').length, 'displays all member subscriptions')
            .to.equal(2);
        await click('[data-test-button="save"]');
        expect(find('[data-test-button="save"]')).to.not.contain.text('Retry');
    });

    it('displays correctly one canceled subscription', async function () {
        const member = this.server.create('member', {
            id: 1,
            subscriptions: [
                this.server.create('subscription', {
                    id: 'sub_1KZGcmEGb07FFvyN9jwrwbKu',
                    tier,
                    customer: {
                        id: 'cus_LFmBWoSkB84lnr',
                        name: 'test',
                        email: 'test@ghost.org'
                    },
                    plan: {
                        id: 'price_1KZGc6EGb07FFvyNkK3umKiX',
                        nickname: 'Monthly',
                        amount: 500,
                        interval: 'month',
                        currency: 'USD'
                    },
                    status: 'canceled',
                    start_date: '2022-03-03T15:31:27.000Z',
                    default_payment_card_last4: '4242',
                    cancel_at_period_end: false,
                    cancellation_reason: null,
                    current_period_end: '2022-04-03T15:31:27.000Z',
                    price: {
                        id: 'price_1KZGc6EGb07FFvyNkK3umKiX',
                        price_id: '6220df272fee0571b5dd0a0a',
                        nickname: 'Monthly',
                        amount: 500,
                        interval: 'month',
                        type: 'recurring',
                        currency: 'USD',
                        tier: {
                            id: 'prod_LFmAAmCnnbzrvL',
                            name: 'Ghost Subscription',
                            tier_id: '6213b3f6cb39ebdb03ebd810'
                        }
                    },
                    offer: null
                })
            ],
            tiers: []
        });

        await visit(`/members/${member.id}`);

        expect(currentURL()).to.equal(`/members/${member.id}`);

        expect(findAll('[data-test-subscription]').length, 'displays all member subscriptions')
            .to.equal(1);
    });

    it('can add and remove complimentary subscription', async function () {
        const member = this.server.create('member', {name: 'Comp Member Test'});

        await visit(`/members/${member.id}`);

        expect(findAll('[data-test-button="add-complimentary"]').length, '# of add complimentary buttons')
            .to.equal(1);

        await click('[data-test-button="add-complimentary"]');
        expect(find('[data-test-modal="member-tier"]'), 'select tier modal').to.exist;
        expect(find('[data-test-text="select-tier-desc"]')).to.contain.text('Comp Member Test');
        expect(find('[data-test-tier-option="6213b3f6cb39ebdb03ebd810"]')).to.have.exist;
        expect(find('[data-test-tier-option="6213b3f6cb39ebdb03ebd810"]')).to.have.class('active');
        await click('[data-test-button="save-comp-tier"]');

        expect(findAll('[data-test-subscription]').length, '# of subscription blocks - after add comped')
            .to.equal(1);

        await click('[data-test-tier="6213b3f6cb39ebdb03ebd810"] [data-test-button="subscription-actions"]');
        await click('[data-test-tier="6213b3f6cb39ebdb03ebd810"] [data-test-button="remove-complimentary"]');

        expect(findAll('[data-test-subscription]').length, '# of subscription blocks - after remove comped')
            .to.equal(0);
    });

    it('can add complimentary subscription when member has canceled subscriptions', async function () {
        const member = this.server.create('member', {
            name: 'Comped for canceled sub test',
            subscriptions: [
                this.server.create('subscription', {
                    // tier, // _Not_ included as `tier` when subscription is canceled
                    status: 'canceled',
                    price: {
                        id: 'price_1',
                        tier: {
                            id: 'prod_1',
                            tier_id: tier.id
                        }
                    }
                })
            ]
        });

        await visit(`/members/${member.id}`);

        expect(findAll('[data-test-button="add-complimentary"]').length, '# of add complimentary buttons')
            .to.equal(1);

        await click('[data-test-button="add-complimentary"]');
        await click('[data-test-button="save-comp-tier"]');

        expect(findAll('[data-test-subscription]').length, '# of subscription blocks - after add comped')
            .to.equal(2);
        expect(findAll('[data-test-button="add-complimentary"]').length, '# of add complimentary buttons - after add comped')
            .to.equal(0);
    });

    it('handles multiple tiers', async function () {
        const tier2 = this.server.create('tier', {
            name: 'Second tier',
            slug: 'second-tier',
            created_at: '2022-02-21T16:47:02.000Z',
            updated_at: '2022-03-03T15:37:02.000Z',
            description: null,
            monthly_price_id: '6220df272fee0571b5dd0a0a',
            yearly_price_id: '6220df272fee0571b5dd0a0b',
            type: 'paid',
            active: true,
            welcome_page_url: '/'
        });

        const member = this.server.create('member', {name: 'Multiple tier test'});

        this.server.create('subscription', {member, tier, status: 'canceled', price: {id: '1', tier: {tier_id: tier.id}}});
        this.server.create('subscription', {member, tier, status: 'canceled', price: {id: '1', tier: {tier_id: tier.id}}});
        this.server.create('subscription', {member, tier: tier2, status: 'canceled', price: {id: '1', tier: {tier_id: tier2.id}}});

        await visit(`/members/${member.id}`);

        // all tiers and subscriptions are shown
        expect(findAll('[data-test-tier]').length, '# of tier blocks').to.equal(2);

        const p1 = `[data-test-tier="${tier.id}"]`;
        const p2 = `[data-test-tier="${tier2.id}"]`;

        expect(find(`${p1} [data-test-text="tier-name"]`)).to.contain.text('Ghost Subscription');
        expect(findAll(`${p1} [data-test-subscription]`).length, '# of tier 1 subscription blocks').to.equal(2);

        expect(find(`${p2} [data-test-text="tier-name"]`)).to.contain.text('Second tier');
        expect(findAll(`${p2} [data-test-subscription]`).length, '# of tier 2 subscription blocks').to.equal(1);

        // can add complimentary
        expect(findAll('[data-test-button="add-complimentary"]').length, '# of add-complimentary buttons').to.equal(1);
        await click('[data-test-button="add-complimentary"]');
        await click(`[data-test-tier-option="${tier2.id}"]`);
        await click('[data-test-button="save-comp-tier"]');

        expect(findAll(`${p2} [data-test-subscription]`).length, '# of tier 2 subscription blocks after comp added').to.equal(2);
    });
});


text:
/* eslint-disable import/export */
export function lte(rawRule: Date): (value: Date | string) => boolean
export function lte(rawRule: string): (value: Date | string) => boolean
export function lte(rawRule: number): (value: number | string) => boolean

export function lte(rawRule: string | number | Date) {
  let rule = rawRule
  // Handling correctly formed dates
  if (typeof rule === 'string' && !Number.isNaN(new Date(rawRule).valueOf())) {
    rule = new Date(rawRule)
  }
  if (rule instanceof Date) {
    return (value: string | Date) => {
      if (value instanceof Date) {
        return value.valueOf() <= rule.valueOf()
      } else {
        return new Date(value).valueOf() <= rule.valueOf()
      }
    }
  }
  if (typeof rule === 'number') {
    return (value: number | string) =>
      typeof value === 'number' ? value <= rule : parseFloat(value) <= rule
  }
  return (value: number) => value <= rule
}

redpajama_set_name: RedPajamaGithub


text:
using UnityEngine;
using System.Collections;

public class PlayerBooster : MonoBehaviour {

    //ブーストの力
    [SerializeField]
    float boostPower = 1.0f;

    Rigidbody rigidBody = null;

	// Use this for initialization
	void Start () {
        rigidBody = GetComponent<Rigidbody>();

	}

    void FixedUpdate()
    {
        if (Input.GetAxisRaw("Boost") != 0)
        {
            Boost();
        }
    }

    void Boost()
    {
        rigidBody.AddForce(Vector3.up * boostPower, ForceMode.VelocityChange);

    }
}


text:
// @filename: file1.ts
export var x;


text:
using BGC.Core.Models;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static TestUtils.MockUtilities;

namespace BGC.Services.Tests.GlossaryServiceTests
{
    [TestFixture]
    public class AddOrUpdateTest
    {
        [Test]
        public void AddsEntry()
        {
            var store = new List<GlossaryEntry>();
            var svc = new GlossaryService(GetMockRepository(store).Object);

            var newEntry = new GlossaryEntry();
            svc.AddOrUpdate(newEntry);

            Assert.AreSame(newEntry, store.Single());
        }

        [Test]
        public void UpdatesExistingEntry()
        {
            var store = new List<GlossaryEntry>();
            var svc = new GlossaryService(GetMockRepository(store).Object);

            var oldDefinitions = new List<GlossaryDefinition>()
            {
                new GlossaryDefinition(CultureInfo.GetCultureInfo("en-US"), "OLD", "term"),
                new GlossaryDefinition(CultureInfo.GetCultureInfo("de-DE"), "ALT", "term"),
            };

            var newDefinitions = new List<GlossaryDefinition>()
            {
                new GlossaryDefinition(CultureInfo.GetCultureInfo("en-US"), "NEW", "term"),
                new GlossaryDefinition(CultureInfo.GetCultureInfo("de-DE"), "NEU", "term"),
            };

            var commonId = new Guid("01234567-0004-0004-0004-123456789ABC");
            var existingEntry = new GlossaryEntry() { Id = commonId, Definitions = oldDefinitions };
            var editedEntry = new GlossaryEntry() { Id = commonId, Definitions = newDefinitions };

            store.Add(existingEntry);

            svc.AddOrUpdate(editedEntry);

            Assert.AreEqual(1, store.Count);

            IEnumerable<string> expectedDefinitions = newDefinitions.Select(def => def.Definition).OrderBy(x => x);
            IEnumerable<string> actualDefinitions = store.First().Definitions.Select(def => def.Definition).OrderBy(x => x);
            Assert.IsTrue(expectedDefinitions.SequenceEqual(actualDefinitions));
        }

        [Test]
        public void ThrowsExceptionIfNullEntry()
        {
            var store = new List<GlossaryEntry>();
            var svc = new GlossaryService(GetMockRepository(store).Object);

            Assert.Throws<ArgumentNullException>(() =>
            {
                svc.AddOrUpdate(null);
            });
        }
    }

    [TestFixture]
    public class DeleteTests
    {
        [Test]
        public void ThrowsExceptionIfNullEntry()
        {
            var svc = new GlossaryService(GetMockRepository(new List<GlossaryEntry>()).Object);

            Assert.Throws<ArgumentNullException>(() => svc.Delete(null));
        }
    }
}


text:
package org.apache.cassandra.distributed.test;

import org.junit.Assert;
import org.junit.Test;

import org.apache.cassandra.distributed.Cluster;
import org.apache.cassandra.distributed.api.ConsistencyLevel;
import org.apache.cassandra.serializers.BooleanSerializer;

public class BooleanTest extends TestBaseImpl
{
    @Test
    public void booleanTest() throws Throwable
    {
        try(Cluster cluster = init(Cluster.build(1).start()))
        {
            cluster.schemaChange("create table " + KEYSPACE + ".tbl (id int, ck boolean, t int, primary key ((id, ck)))");
            for (int i = 0; i < 10; i++)
                cluster.coordinator(1).execute(withKeyspace("insert into %s.tbl (id, ck, t) values (?, true, ?)"), ConsistencyLevel.ALL, i, i);
            cluster.get(1).nodetoolResult("getsstables", KEYSPACE, "tbl", "1:true");
            cluster.forEach(i -> i.runOnInstance(() -> {
                Assert.assertEquals(0, BooleanSerializer.instance.serialize(true).position());
                Assert.assertEquals(0, BooleanSerializer.instance.serialize(false).position());
            }));
        }
    }
}


text:
const ReactDOM = require('react-dom');
const React = require('react')
const Backbone = require('backbone');
const View = require('./view-controller.js')

const AppRouter = Backbone.Router.extend({
  routes: {
    "" : "showTitlePage",
    "homePage" : "showHomePage",
    "auth" : "showAuthPage"
  },

  showTitlePage: function(){
    console.log('test me')
    ReactDOM.render(<View currentView="title"/>, document.querySelector("#ui"))
  },

  showHomePage: function(){

    ReactDOM.render(<View currentView="home"/>, document.querySelector("#ui"))
  },

  showAuthPage: function(){
    ReactDOM.render(<View currentView="auth"/>, document.querySelector("#ui"))
  },

  initialize: function(){
    Backbone.history.start()
  }

})

new AppRouter()


text:
Here are all our interviews

Discover and get inspired...

                    All Interviews

                Business
                Art
                Technology

or create your own and become one of our editors

                    Create Interview


text:
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2022, OpenNebula Project, OpenNebula Systems                */
/*                                                                            */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may    */
/* not use this file except in compliance with the License. You may obtain    */
/* a copy of the License at                                                   */
/*                                                                            */
/* http://www.apache.org/licenses/LICENSE-2.0                                 */
/*                                                                            */
/* Unless required by applicable law or agreed to in writing, software        */
/* distributed under the License is distributed on an "AS IS" BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
/* See the License for the specific language governing permissions and        */
/* limitations under the License.                                             */
/*--------------------------------------------------------------------------- */

package goca

import (
	"encoding/xml"
	"errors"

	"github.com/OpenNebula/one/src/oca/go/src/goca/schemas/shared"
	"github.com/OpenNebula/one/src/oca/go/src/goca/schemas/vmgroup"
)

// VMGroupsController is a controller for vm groups entities
type VMGroupsController entitiesController

// VMGroupController is a controller for vm group entity
type VMGroupController entityController

// VMGroups returns a VMGroups controller
func (c *Controller) VMGroups() *VMGroupsController {
	return &VMGroupsController{c}
}

// VMGroup returns a VMGroup controller
func (c *Controller) VMGroup(id int) *VMGroupController {
	return &VMGroupController{c, id}
}

// ByName returns a VMGroup ID from name
func (c *VMGroupsController) ByName(name string, args ...int) (int, error) {
	var id int

	vmGroupPool, err := c.Info(args...)
	if err != nil {
		return -1, err
	}

	match := false
	for i := 0; i < len(vmGroupPool.VMGroups); i++ {
		if vmGroupPool.VMGroups[i].Name != name {
			continue
		}
		if match {
			return -1, errors.New("multiple resources with that name")
		}
		id = vmGroupPool.VMGroups[i].ID
		match = true
	}
	if !match {
		return -1, errors.New("resource not found")
	}

	return id, nil
}

// Info returns a vm group pool. A connection to OpenNebula is
// performed.
func (vc *VMGroupsController) Info(args ...int) (*vmgroup.Pool, error) {

	fArgs, err := handleArgs(args)
	if err != nil {
		return nil, err
	}

	response, err := vc.c.Client.Call("one.vmgrouppool.info", fArgs...)
	if err != nil {
		return nil, err
	}

	vmGroupPool := &vmgroup.Pool{}
	err = xml.Unmarshal([]byte(response.Body()), vmGroupPool)
	if err != nil {
		return nil, err
	}

	return vmGroupPool, nil
}

// Info retrieves information for the vm group.
func (vc *VMGroupController) Info(decrypt bool) (*vmgroup.VMGroup, error) {
	response, err := vc.c.Client.Call("one.vmgroup.info", vc.ID, decrypt)
	if err != nil {
		return nil, err
	}
	vmGroup := &vmgroup.VMGroup{}
	err = xml.Unmarshal([]byte(response.Body()), vmGroup)
	if err != nil {
		return nil, err
	}

	return vmGroup, nil
}

// Create allocates a new vmGroup. It returns the new vmGroup ID.
func (vc *VMGroupsController) Create(tpl string) (int, error) {
	response, err := vc.c.Client.Call("one.vmgroup.allocate", tpl)
	if err != nil {
		return -1, err
	}

	return response.BodyInt(), nil
}

// Clone clones an existing vmGroup.
// * newName: Name for the new vmGroup.
func (vc *VMGroupController) Clone(newName string) error {
	_, err := vc.c.Client.Call("one.vmgroup.clone", vc.ID, newName)
	return err
}

// Delete deletes the given vmGroup from the pool.
func (vc *VMGroupController) Delete() error {
	_, err := vc.c.Client.Call("one.vmgroup.delete", vc.ID)
	return err
}

// Update replaces the vmGroup template content.
// * tpl: The new vmGroup template contents. Syntax can be the usual attribute=value or XML.
// * appendTemplate: Update type: 0: Replace the whole template. 1: Merge new template with the existing one.
func (vc *VMGroupController) Update(tpl string, uType int) error {
	_, err := vc.c.Client.Call("one.vmgroup.update", vc.ID, tpl, uType)
	return err
}

// Chmod changes the permission bits of a vmGroup.
func (vc *VMGroupController) Chmod(perm shared.Permissions) error {
	args := append([]interface{}{vc.ID}, perm.ToArgs()...)
	_, err := vc.c.Client.Call("one.vmgroup.chmod", args...)
	return err
}

// Chown changes the ownership of a vmGroup.
// * userID: The User ID of the new owner. If set to -1, it will not change.
// * groupID: The Group ID of the new group. If set to -1, it will not change.
func (vc *VMGroupController) Chown(userID, groupID int) error {
	_, err := vc.c.Client.Call("one.vmgroup.chown", vc.ID, userID, groupID)
	return err
}

// Rename renames a vmGroup.
// * newName: The new name.
func (vc *VMGroupController) Rename(newName string) error {
	_, err := vc.c.Client.Call("one.vmgroup.rename", vc.ID, newName)
	return err
}

// Lock locks the vmGroup following lock level. See levels in locks.go.
func (vc *VMGroupController) Lock(level shared.LockLevel) error {
	_, err := vc.c.Client.Call("one.vmgroup.lock", vc.ID, level)
	return err
}

// Unlock unlocks the vmGroup.
func (vc *VMGroupController) Unlock() error {
	_, err := vc.c.Client.Call("one.vmgroup.unlock", vc.ID)
	return err
}


text:
'use strict';

const { join } = require('path');
const { rmdir, writeFile } = require('hexo-fs');
const { highlight, prismHighlight } = require('hexo-util');
const Promise = require('bluebird');

describe('include_code', () => {
  const Hexo = require('../../../lib/hexo');
  const hexo = new Hexo(join(__dirname, 'include_code_test'));
  const includeCode = Promise.method(require('../../../lib/plugins/tag/include_code')(hexo));
  const path = join(hexo.source_dir, hexo.config.code_dir, 'test.js');
  const defaultCfg = JSON.parse(JSON.stringify(hexo.config));

  const fixture = [
    'if (tired && night){',
    '  sleep();',
    '}'
  ].join('\n');

  const code = args => includeCode(args.split(' '));

  before(() => writeFile(path, fixture));

  beforeEach(() => {
    hexo.config = JSON.parse(JSON.stringify(defaultCfg));
  });

  after(() => rmdir(hexo.base_dir));

  describe('highlightjs', () => {
    it('default', async () => {
      hexo.config.highlight.enable = true;
      hexo.config.prismjs.enable = false;

      const expected = highlight(fixture, {
        lang: 'js',
        caption: 'test.jsview raw'
      });

      const result = await code('test.js');
      result.should.eql(expected);
    });

    it('title', async () => {
      const expected = highlight(fixture, {
        lang: 'js',
        caption: 'Hello worldview raw'
      });

      const result = await code('Hello world test.js');
      result.should.eql(expected);
    });

    it('lang', async () => {
      const expected = highlight(fixture, {
        lang: 'js',
        caption: 'Hello worldview raw'
      });

      const result = await code('Hello world lang:js test.js');
      result.should.eql(expected);
    });

    it('language_attr', async () => {
      const original = hexo.config.highlight.language_attr;
      hexo.config.highlight.language_attr = true;

      const expected = highlight(fixture, {
        lang: 'js',
        caption: 'Hello worldview raw',
        languageAttr: true
      });

      const result = await code('Hello world lang:js test.js');
      result.should.eql(expected);

      hexo.config.highlight.language_attr = original;
    });

    it('from', async () => {
      const fixture = [
        '}'
      ].join('\n');
      const expected = highlight(fixture, {
        lang: 'js',
        caption: 'Hello worldview raw'
      });

      const result = await code('Hello world lang:js from:3 test.js');
      result.should.eql(expected);
    });

    it('to', async () => {
      const fixture = [
        'if (tired && night){',
        '  sleep();'
      ].join('\n');
      const expected = highlight(fixture, {
        lang: 'js',
        caption: 'Hello worldview raw'
      });

      const result = await code('Hello world lang:js to:2 test.js');
      result.should.eql(expected);
    });

    it('from and to', async () => {
      const fixture = [
        'sleep();'
      ].join('\n');
      const expected = highlight(fixture, {
        lang: 'js',
        caption: 'Hello worldview raw'
      });

      const result = await code('Hello world lang:js from:2 to:2 test.js');
      result.should.eql(expected);
    });

    it('file not found', async () => {
      const result = await code('nothing');
      should.not.exist(result);
    });

    it('disabled', async () => {
      hexo.config.highlight.enable = false;

      const result = await code('test.js');
      result.should.eql('
' + fixture + '
');
    });
  });

  describe('prismjs', () => {
    beforeEach(() => {
      hexo.config.highlight.enable = false;
      hexo.config.prismjs.enable = true;
    });

    it('default', async () => {
      const expected = prismHighlight(fixture, {
        lang: 'js',
        caption: 'test.jsview raw'
      });

      const result = await code('test.js');
      result.should.eql(expected);
    });

    it('lang', async () => {
      const expected = prismHighlight(fixture, {
        lang: 'js',
        caption: 'Hello worldview raw'
      });

      const result = await code('Hello world lang:js test.js');
      result.should.eql(expected);
    });

    it('from', async () => {
      const fixture = [
        '}'
      ].join('\n');
      const expected = prismHighlight(fixture, {
        lang: 'js',
        caption: 'Hello worldview raw'
      });

      const result = await code('Hello world lang:js from:3 test.js');
      result.should.eql(expected);
    });

    it('to', async () => {
      const fixture = [
        'if (tired && night){',
        '  sleep();'
      ].join('\n');
      const expected = prismHighlight(fixture, {
        lang: 'js',
        caption: 'Hello worldview raw'
      });

      const result = await code('Hello world lang:js to:2 test.js');
      result.should.eql(expected);
    });

    it('from and to', async () => {
      const fixture = [
        'sleep();'
      ].join('\n');
      const expected = prismHighlight(fixture, {
        lang: 'js',
        caption: 'Hello worldview raw'
      });

      const result = await code('Hello world lang:js from:2 to:2 test.js');
      result.should.eql(expected);
    });

    it('title', async () => {
      const expected = prismHighlight(fixture, {
        lang: 'js',
        caption: 'Hello worldview raw'
      });

      const result = await code('Hello world test.js');
      result.should.eql(expected);
    });

    it('file not found', async () => {
      const result = await code('nothing');
      should.not.exist(result);
    });

    it('disabled', async () => {
      hexo.config.highlight.enable = false;
      hexo.config.prismjs.enable = false;

      const result = await code('test.js');
      result.should.eql('
' + fixture + '
');
    });
  });
});


text:
// Code generated by go-swagger; DO NOT EDIT.

package storage

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"context"
	"net/http"
	"time"

	"github.com/go-openapi/errors"
	"github.com/go-openapi/runtime"
	cr "github.com/go-openapi/runtime/client"
	"github.com/go-openapi/strfmt"
	"github.com/go-openapi/swag"

	"github.com/netapp/trident/storage_drivers/ontap/api/rest/models"
)

// NewAggregateCreateParams creates a new AggregateCreateParams object,
// with the default timeout for this client.
//
// Default values are not hydrated, since defaults are normally applied by the API server side.
//
// To enforce default values in parameter, use SetDefaults or WithDefaults.
func NewAggregateCreateParams() *AggregateCreateParams {
	return &AggregateCreateParams{
		timeout: cr.DefaultTimeout,
	}
}

// NewAggregateCreateParamsWithTimeout creates a new AggregateCreateParams object
// with the ability to set a timeout on a request.
func NewAggregateCreateParamsWithTimeout(timeout time.Duration) *AggregateCreateParams {
	return &AggregateCreateParams{
		timeout: timeout,
	}
}

// NewAggregateCreateParamsWithContext creates a new AggregateCreateParams object
// with the ability to set a context for a request.
func NewAggregateCreateParamsWithContext(ctx context.Context) *AggregateCreateParams {
	return &AggregateCreateParams{
		Context: ctx,
	}
}

// NewAggregateCreateParamsWithHTTPClient creates a new AggregateCreateParams object
// with the ability to set a custom HTTPClient for a request.
func NewAggregateCreateParamsWithHTTPClient(client *http.Client) *AggregateCreateParams {
	return &AggregateCreateParams{
		HTTPClient: client,
	}
}

/*
AggregateCreateParams contains all the parameters to send to the API endpoint

	for the aggregate create operation.

	Typically these are written to a http.Request.
*/
type AggregateCreateParams struct {

	/* DiskSize.

	   If set, POST only selects disks of the specified size.
	*/
	DiskSizeQueryParameter *int64

	/* Info.

	   Info specification
	*/
	Info *models.Aggregate

	/* ReturnRecords.

	   The default is false.  If set to true, the records are returned.
	*/
	ReturnRecordsQueryParameter *bool

	/* ReturnTimeout.

	   The number of seconds to allow the call to execute before returning. When doing a POST, PATCH, or DELETE operation on a single record, the default is 0 seconds.  This means that if an asynchronous operation is started, the server immediately returns HTTP code 202 (Accepted) along with a link to the job.  If a non-zero value is specified for POST, PATCH, or DELETE operations, ONTAP waits that length of time to see if the job completes so it can return something other than 202.
	*/
	ReturnTimeoutQueryParameter *int64

	timeout    time.Duration
	Context    context.Context
	HTTPClient *http.Client
}

// WithDefaults hydrates default values in the aggregate create params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *AggregateCreateParams) WithDefaults() *AggregateCreateParams {
	o.SetDefaults()
	return o
}

// SetDefaults hydrates default values in the aggregate create params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *AggregateCreateParams) SetDefaults() {
	var (
		returnRecordsQueryParameterDefault = bool(false)

		returnTimeoutQueryParameterDefault = int64(0)
	)

	val := AggregateCreateParams{
		ReturnRecordsQueryParameter: &returnRecordsQueryParameterDefault,
		ReturnTimeoutQueryParameter: &returnTimeoutQueryParameterDefault,
	}

	val.timeout = o.timeout
	val.Context = o.Context
	val.HTTPClient = o.HTTPClient
	*o = val
}

// WithTimeout adds the timeout to the aggregate create params
func (o *AggregateCreateParams) WithTimeout(timeout time.Duration) *AggregateCreateParams {
	o.SetTimeout(timeout)
	return o
}

// SetTimeout adds the timeout to the aggregate create params
func (o *AggregateCreateParams) SetTimeout(timeout time.Duration) {
	o.timeout = timeout
}

// WithContext adds the context to the aggregate create params
func (o *AggregateCreateParams) WithContext(ctx context.Context) *AggregateCreateParams {
	o.SetContext(ctx)
	return o
}

// SetContext adds the context to the aggregate create params
func (o *AggregateCreateParams) SetContext(ctx context.Context) {
	o.Context = ctx
}

// WithHTTPClient adds the HTTPClient to the aggregate create params
func (o *AggregateCreateParams) WithHTTPClient(client *http.Client) *AggregateCreateParams {
	o.SetHTTPClient(client)
	return o
}

// SetHTTPClient adds the HTTPClient to the aggregate create params
func (o *AggregateCreateParams) SetHTTPClient(client *http.Client) {
	o.HTTPClient = client
}

// WithDiskSizeQueryParameter adds the diskSize to the aggregate create params
func (o *AggregateCreateParams) WithDiskSizeQueryParameter(diskSize *int64) *AggregateCreateParams {
	o.SetDiskSizeQueryParameter(diskSize)
	return o
}

// SetDiskSizeQueryParameter adds the diskSize to the aggregate create params
func (o *AggregateCreateParams) SetDiskSizeQueryParameter(diskSize *int64) {
	o.DiskSizeQueryParameter = diskSize
}

// WithInfo adds the info to the aggregate create params
func (o *AggregateCreateParams) WithInfo(info *models.Aggregate) *AggregateCreateParams {
	o.SetInfo(info)
	return o
}

// SetInfo adds the info to the aggregate create params
func (o *AggregateCreateParams) SetInfo(info *models.Aggregate) {
	o.Info = info
}

// WithReturnRecordsQueryParameter adds the returnRecords to the aggregate create params
func (o *AggregateCreateParams) WithReturnRecordsQueryParameter(returnRecords *bool) *AggregateCreateParams {
	o.SetReturnRecordsQueryParameter(returnRecords)
	return o
}

// SetReturnRecordsQueryParameter adds the returnRecords to the aggregate create params
func (o *AggregateCreateParams) SetReturnRecordsQueryParameter(returnRecords *bool) {
	o.ReturnRecordsQueryParameter = returnRecords
}

// WithReturnTimeoutQueryParameter adds the returnTimeout to the aggregate create params
func (o *AggregateCreateParams) WithReturnTimeoutQueryParameter(returnTimeout *int64) *AggregateCreateParams {
	o.SetReturnTimeoutQueryParameter(returnTimeout)
	return o
}

// SetReturnTimeoutQueryParameter adds the returnTimeout to the aggregate create params
func (o *AggregateCreateParams) SetReturnTimeoutQueryParameter(returnTimeout *int64) {
	o.ReturnTimeoutQueryParameter = returnTimeout
}

// WriteToRequest writes these params to a swagger request
func (o *AggregateCreateParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {

	if err := r.SetTimeout(o.timeout); err != nil {
		return err
	}
	var res []error

	if o.DiskSizeQueryParameter != nil {

		// query param disk_size
		var qrDiskSize int64

		if o.DiskSizeQueryParameter != nil {
			qrDiskSize = *o.DiskSizeQueryParameter
		}
		qDiskSize := swag.FormatInt64(qrDiskSize)
		if qDiskSize != "" {

			if err := r.SetQueryParam("disk_size", qDiskSize); err != nil {
				return err
			}
		}
	}
	if o.Info != nil {
		if err := r.SetBodyParam(o.Info); err != nil {
			return err
		}
	}

	if o.ReturnRecordsQueryParameter != nil {

		// query param return_records
		var qrReturnRecords bool

		if o.ReturnRecordsQueryParameter != nil {
			qrReturnRecords = *o.ReturnRecordsQueryParameter
		}
		qReturnRecords := swag.FormatBool(qrReturnRecords)
		if qReturnRecords != "" {

			if err := r.SetQueryParam("return_records", qReturnRecords); err != nil {
				return err
			}
		}
	}

	if o.ReturnTimeoutQueryParameter != nil {

		// query param return_timeout
		var qrReturnTimeout int64

		if o.ReturnTimeoutQueryParameter != nil {
			qrReturnTimeout = *o.ReturnTimeoutQueryParameter
		}
		qReturnTimeout := swag.FormatInt64(qrReturnTimeout)
		if qReturnTimeout != "" {

			if err := r.SetQueryParam("return_timeout", qReturnTimeout); err != nil {
				return err
			}
		}
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}


text:
/*jslint node: true*/
/*global describe: true, before:true, it: true*/

var Promise = require('bluebird');
var chai = require("chai"),
    expect = require("chai").expect;
var randomWords = require('random-words');

var argv = require('optimist').demand('config').argv;
var environment = argv.config;
var nconf = require('nconf');
nconf.argv().env().file({ file: 'config.json' });

var cf_api_url = nconf.get(environment + "_" + 'CF_API_URL'),
    username = nconf.get(environment + "_" + 'username'),
    password = nconf.get(environment + "_" + 'password');

var CloudController = require("../../../../lib/model/cloudcontroller/CloudController");
var CloudFoundryUsersUAA = require("../../../../lib/model/uaa/UsersUAA");
var CloudFoundryApps = require("../../../../lib/model/cloudcontroller/Apps");
var CloudFoundrySpaces = require("../../../../lib/model/cloudcontroller/Spaces");
var CloudFoundryUserProvidedServices = require("../../../../lib/model/cloudcontroller/UserProvidedServices");
var CloudFoundryServiceInstances = require("../../../../lib/model/cloudcontroller/ServiceInstances");
var CloudFoundryServicePlans = require("../../../../lib/model/cloudcontroller/ServicePlans");
var BuildPacks = require("../../../../lib/model/cloudcontroller/BuildPacks");
CloudController = new CloudController();
CloudFoundryUsersUAA = new CloudFoundryUsersUAA();
CloudFoundryApps = new CloudFoundryApps();
CloudFoundrySpaces = new CloudFoundrySpaces();
CloudFoundryServiceInstances = new CloudFoundryServiceInstances();
CloudFoundryServicePlans = new CloudFoundryServicePlans();
CloudFoundryUserProvidedServices = new CloudFoundryUserProvidedServices();
BuildPacks = new BuildPacks();

describe("Cloud foundry Service Instances", function () {
    "use strict";
    var authorization_endpoint = null;
    var token_endpoint = null;
    var token_type = null;
    var access_token = null;
    var space_guid = null;

    before(function () {
        this.timeout(25000);

        CloudController.setEndPoint(cf_api_url);
        CloudFoundryApps.setEndPoint(cf_api_url);
        CloudFoundrySpaces.setEndPoint(cf_api_url);
        CloudFoundryServiceInstances.setEndPoint(cf_api_url);
        CloudFoundryServicePlans.setEndPoint(cf_api_url);
        CloudFoundryUserProvidedServices.setEndPoint(cf_api_url);

        return CloudController.getInfo().then(function (result) {
            authorization_endpoint = result.authorization_endpoint;
            token_endpoint = result.token_endpoint;
            CloudFoundryUsersUAA.setEndPoint(authorization_endpoint);
            return CloudFoundryUsersUAA.login(username, password);
        }).then(function (result) {
            token_type = result.token_type;
            access_token = result.access_token;
            CloudFoundrySpaces.setToken(result);
            CloudFoundryServiceInstances.setToken(result);
            return CloudFoundrySpaces.getSpaces();
        }).then(function (result) {
            space_guid = result.resources[0].metadata.guid;
        });

    });

    function randomInt(low, high) {
        return Math.floor(Math.random() * (high - low) + low);
    }

    it("The platform returns a list of Service Instances available", function () {
        this.timeout(5000);

        return CloudFoundryServiceInstances.getInstances().then(function (result) {
            expect(result.total_results).is.a("number");
        });
    });

    it("The platform returns the first Service", function () {
        this.timeout(5000);

        var messageNoService = "No service";
        var service_instance_guid = null;
        return CloudFoundryServiceInstances.getInstances().then(function (result) {
            if(result.total_results === 0){
                return Promise.reject(messageNoService);
            }
            service_instance_guid = result.resources[0].metadata.guid;
            return CloudFoundryServiceInstances.getInstance(service_instance_guid);
        }).then(function (result) {
            expect(result.metadata.guid).is.a("string");
        }).catch(function (reason) {
            expect(reason).to.equal(messageNoService);
        });
    });

    it("The platform returns a list of Service Instance in a Space available", function () {
        this.timeout(5000);

        var filter = {
            q: 'space_guid:' + space_guid
        };
        return CloudFoundryServiceInstances.getInstances(filter).then(function (result) {
            expect(result.total_results).is.a("number");
        });
    });

    it("The platform returns Service Instance permissions", function () {
        this.timeout(5000);

        var service_instance_guid = null;
        return CloudFoundryServiceInstances.getInstances().then(function (result) {
            if(result.total_results === 0){
                return Promise.reject("No results")
            }
            service_instance_guid = result.resources[0].metadata.guid;
            return CloudFoundryServiceInstances.getInstancePermissions(service_instance_guid);
        }).then(function (result) {
            expect(result.manage).is.a("boolean");
        }).catch(function (reason) {
            expect(reason).to.equal("No results");
        });
    });

    it("The platform returns Service Instance Bindings", function () {
        this.timeout(5000);

        var service_instance_guid = null;
        return CloudFoundryServiceInstances.getInstances().then(function (result) {
            if(result.total_results === 0){
                return Promise.reject("No results")
            }
            service_instance_guid = result.resources[0].metadata.guid;
            return CloudFoundryServiceInstances.getInstanceBindings(service_instance_guid);
        }).then(function (result) {
            expect(result.total_results).is.a("number");
        }).catch(function (reason) {
            expect(reason).to.equal("No results");
        });
    });

    it("The platform returns Service Instance Routes", function () {
        this.timeout(5000);

        var service_instance_guid = null;
        return CloudFoundryServiceInstances.getInstances().then(function (result) {
            if(result.total_results === 0){
                return Promise.reject("No results")
            }
            service_instance_guid = result.resources[0].metadata.guid;
            return CloudFoundryServiceInstances.getInstanceRoutes(service_instance_guid);
        }).then(function (result) {
            expect(result.total_results).is.a("number");
        }).catch(function (reason) {
            expect(reason).to.equal("No results");
        });
    });

    it.skip("The platform creates a new Service Instance and then removes it.", function () {
        this.timeout(5000);

        return CloudFoundryServicePlans.getServicePlans().then(function (result) {
            var options = {
                name: 'sample-test-service-instance',
                service_plan_guid: result.resources[0].metadata.guid,
                space_guid: space_guid
            }
            return CloudFoundryServiceInstances.create(options);
        }).then(function (result) {
          expect(true).to.equal(true);
          return CloudFoundryServiceInstances.remove(result.metadata.guid);
        }).then(function (result) {
            expect(true).to.equal(true);
        });
    });
});


text:
#ifndef SkStackViewLayout_DEFINED
#define SkStackViewLayout_DEFINED

#include "SkView.h"

class SkStackViewLayout : public SkView::Layout {
public:
    SkStackViewLayout();

    enum Orient {
        kHorizontal_Orient,
        kVertical_Orient,

        kOrientCount
    };
    Orient  getOrient() const { return (Orient)fOrient; }
    void    setOrient(Orient);

    void        getMargin(SkRect*) const;
    void        setMargin(const SkRect&);

    SkScalar    getSpacer() const { return fSpacer; }
    void        setSpacer(SkScalar);

    /** Controls the posititioning in the same direction as the orientation
    */
    enum Pack {
        kStart_Pack,
        kCenter_Pack,
        kEnd_Pack,

        kPackCount
    };
    Pack    getPack() const { return (Pack)fPack; }
    void    setPack(Pack);

    /** Controls the posititioning at right angles to the orientation
    */
    enum Align {
        kStart_Align,
        kCenter_Align,
        kEnd_Align,
        kStretch_Align,

        kAlignCount
    };
    Align   getAlign() const { return (Align)fAlign; }
    void    setAlign(Align);

    bool    getRound() const { return SkToBool(fRound); }
    void    setRound(bool);

protected:
    virtual void onLayoutChildren(SkView* parent);
    virtual void onInflate(const SkDOM&, const SkDOM::Node*);

private:
    SkRect      fMargin;
    SkScalar    fSpacer;
    uint8_t     fOrient, fPack, fAlign, fRound;
};

class SkFillViewLayout : public SkView::Layout {
public:
            SkFillViewLayout();
    void    getMargin(SkRect*) const;
    void    setMargin(const SkRect&);

protected:
    // overrides;
    virtual void onLayoutChildren(SkView* parent);
    virtual void onInflate(const SkDOM& dom, const SkDOM::Node* node);

private:
    SkRect  fMargin;
    typedef SkView::Layout INHERITED;
};

#endif


text:
<?xml version='1.0' encoding='utf-8'?>
<widget id="com.ionicframework.starter" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>HelloCordova</name>
    <description>
        An Ionic Framework and Cordova project.
    </description>
    <author email="hi@ionicframework" href="http://ionicframework.com/">
      Ionic Framework Team
    </author>
    <content src="index.html" />
    <access origin="*" />
    <preference name="webviewbounce" value="false" />
    <preference name="UIWebViewBounce" value="false" />
    <preference name="DisallowOverscroll" value="true" />

    <!-- Ionic supports Android Jellybean and up -->
    <preference name="android-minSdkVersion" value="16" />

    <!-- Don't store local data in an iCloud backup. Turn this to "cloud" to enable storage
         to be sent to iCloud. Note: enabling this could result in Apple rejecting your app.
    -->
    <preference name="BackupWebStorage" value="none" />

    <feature name="StatusBar">
      <param name="ios-package" value="CDVStatusBar" onload="true" />
    </feature>
</widget>


text:
package com.siyeh.ipp.exceptions;

import com.intellij.psi.*;
import com.intellij.util.IncorrectOperationException;
import com.siyeh.ipp.base.Intention;
import com.siyeh.ipp.base.PsiElementPredicate;
import javax.annotation.Nonnull;

import java.util.List;

public class ReplaceArmWithTryFinallyIntention
  extends Intention {

  @Nonnull
  @Override
  protected PsiElementPredicate getElementPredicate() {
    return new AutomaticResourceManagementPredicate();
  }

  @Override
  protected void processIntention(@Nonnull PsiElement element)
    throws IncorrectOperationException {
    final PsiJavaToken token = (PsiJavaToken)element;
    final PsiTryStatement tryStatement =
      (PsiTryStatement)token.getParent();
    if (tryStatement == null) {
      return;
    }
    final boolean replaceAll = tryStatement.getCatchBlocks().length == 0;
    final PsiResourceList resourceList = tryStatement.getResourceList();
    if (resourceList == null) {
      return;
    }
    final List<PsiResourceVariable> resourceVariables =
      resourceList.getResourceVariables();
    final StringBuilder newTryStatement = new StringBuilder("{");
    for (PsiResourceVariable resourceVariable : resourceVariables) {
      newTryStatement.append(resourceVariable.getText());
      newTryStatement.append(";\ntry {");
    }
    final PsiCodeBlock tryBlock = tryStatement.getTryBlock();
    if (tryBlock == null) {
      return;
    }
    final PsiElement[] children = tryBlock.getChildren();
    for (int i = 1; i < children.length - 1; i++) {
      final PsiElement child = children[i];
      newTryStatement.append(child.getText());
    }
    final int resourceVariablesSize = resourceVariables.size();
    for (int i = resourceVariablesSize - 1; i >= 0; i--) {
      final PsiResourceVariable resourceVariable =
        resourceVariables.get(i);
      newTryStatement.append("} finally {\n");
      newTryStatement.append(resourceVariable.getName());
      newTryStatement.append(".close();\n}");
    }
    newTryStatement.append('}');
    final PsiElementFactory factory =
      JavaPsiFacade.getElementFactory(element.getProject());
    final PsiCodeBlock newCodeBlock =
      factory.createCodeBlockFromText(
        newTryStatement.toString(), element);
    if (replaceAll) {
      for (PsiStatement newStatement : newCodeBlock.getStatements()) {
        tryStatement.getParent().addBefore(newStatement,
                                           tryStatement);
      }
      tryStatement.delete();
    }
    else {
      resourceList.delete();
      tryBlock.replace(newCodeBlock);
    }
  }
}


text:
<?php

namespace Kolomiets\BlogBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;

class CommentAdmin extends Admin
{
    /**
     * @param FormMapper $formMapper
     */
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper->add('text', 'text');
    }

    /**
     * @param DatagridMapper $datagridMapper
     */
    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper->add('text');
    }

    /**
     * @param ListMapper $listMapper
     */
    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper->addIdentifier('text');
    }
}


text:
class SessionsController < ApplicationController
  skip_before_filter :login_required,  :except => :destroy
  before_filter :redirect_if_logged_in, :only => [ :new, :create ]
  before_filter :build_user_session,  :only => [ :new, :create ]

  def create
    if @session_user.save
      login(@session_user)
      redirect_to(user_path(current_user), :notice => "Welcome, you are now logged in.")
    else
      flash.now[:alert] = 'Login failed. Did you mistype?'
      render :action => :new
    end
  end

  def destroy
    logout
    redirect_to login_path
  end

protected
  def build_user_session
    @session_user = SessionUser.new(params[:session_user])
  end

  def redirect_if_logged_in
    redirect_to user_path(current_user) if logged_in?
  end
end


text:
int GetOffsetFromUtc()
{
#if QT_VERSION < 0x050200
    const QDateTime dateTime1 = QDateTime::currentDateTime();
    const QDateTime dateTime2 = QDateTime(dateTime1.date(), dateTime1.time(), Qt::UTC);
    return dateTime1.secsTo(dateTime2);
#else
    return QDateTime::currentDateTime().offsetFromUtc();
#endif
}

MasternodeList::MasternodeList(QWidget* parent) :
    QWidget(parent),
    nTimeFilterUpdatedDIP3(0),
    nTimeUpdatedDIP3(0),
    fFilterUpdatedDIP3(true),
    ui(new Ui::MasternodeList),
    clientModel(0),
    walletModel(0),
    mnListChanged(true)
{
    ui->setupUi(this);

    int columnAddressWidth = 200;
    int columnStatusWidth = 80;
    int columnPoSeScoreWidth = 80;
    int columnRegisteredWidth = 80;
    int columnLastPaidWidth = 80;
    int columnNextPaymentWidth = 100;
    int columnPayeeWidth = 130;
    int columnOperatorRewardWidth = 130;
    int columnCollateralWidth = 130;
    int columnOwnerWidth = 130;
    int columnVotingWidth = 130;

    ui->tableWidgetMasternodesDIP3->setColumnWidth(0, columnAddressWidth);
    ui->tableWidgetMasternodesDIP3->setColumnWidth(1, columnStatusWidth);
    ui->tableWidgetMasternodesDIP3->setColumnWidth(2, columnPoSeScoreWidth);
    ui->tableWidgetMasternodesDIP3->setColumnWidth(3, columnRegisteredWidth);
    ui->tableWidgetMasternodesDIP3->setColumnWidth(4, columnLastPaidWidth);
    ui->tableWidgetMasternodesDIP3->setColumnWidth(5, columnNextPaymentWidth);
    ui->tableWidgetMasternodesDIP3->setColumnWidth(6, columnPayeeWidth);
    ui->tableWidgetMasternodesDIP3->setColumnWidth(7, columnOperatorRewardWidth);
    ui->tableWidgetMasternodesDIP3->setColumnWidth(8, columnCollateralWidth);
    ui->tableWidgetMasternodesDIP3->setColumnWidth(9, columnOwnerWidth);
    ui->tableWidgetMasternodesDIP3->setColumnWidth(10, columnVotingWidth);

    // dummy column for proTxHash
    // TODO use a proper table model for the MN list
    ui->tableWidgetMasternodesDIP3->insertColumn(11);
    ui->tableWidgetMasternodesDIP3->setColumnHidden(11, true);

    ui->tableWidgetMasternodesDIP3->setContextMenuPolicy(Qt::CustomContextMenu);

    ui->filterLineEditDIP3->setPlaceholderText(tr("Filter by any property (e.g. address or protx hash)"));
    ui->checkBoxMyMasternodesOnly->setEnabled(false);

    QAction* copyProTxHashAction = new QAction(tr("Copy ProTx Hash"), this);
    QAction* copyCollateralOutpointAction = new QAction(tr("Copy Collateral Outpoint"), this);
    QAction* copyServiceAction = new QAction(tr("Copy Service"), this);
    QAction* copyPayoutAction = new QAction(tr("Copy Payout Address"), this);
    QAction* copyCollateralAction = new QAction(tr("Copy Collateral Address"), this);
    QAction* copyOwnerAction = new QAction(tr("Copy Owner Address"), this);
    QAction* copyVotingAction = new QAction(tr("Copy Voting Address"), this);
    contextMenuDIP3 = new QMenu();
    contextMenuDIP3->addAction(copyServiceAction);
    contextMenuDIP3->addAction(copyPayoutAction);
    contextMenuDIP3->addAction(copyCollateralAction);
    contextMenuDIP3->addAction(copyOwnerAction);
    contextMenuDIP3->addAction(copyVotingAction);
    contextMenuDIP3->addSeparator();
    contextMenuDIP3->addAction(copyProTxHashAction);
    contextMenuDIP3->addAction(copyCollateralOutpointAction);
    connect(ui->tableWidgetMasternodesDIP3, &QWidget::customContextMenuRequested, this, &MasternodeList::showContextMenuDIP3);
    connect(ui->tableWidgetMasternodesDIP3, &QTableView::doubleClicked, this, &MasternodeList::extraInfoDIP3_clicked);
    connect(copyProTxHashAction, &QAction::triggered, this, &MasternodeList::copyProTxHash_clicked);
    connect(copyCollateralOutpointAction, &QAction::triggered, this, &MasternodeList::copyCollateralOutpoint_clicked);
    connect(copyServiceAction, &QAction::triggered, this, &MasternodeList::copyService_clicked);
    connect(copyPayoutAction, &QAction::triggered, this, &MasternodeList::copyPayout_clicked);
    connect(copyCollateralAction, &QAction::triggered, this, &MasternodeList::copyCollateral_clicked);
    connect(copyOwnerAction, &QAction::triggered, this, &MasternodeList::copyOwner_clicked);
    connect(copyVotingAction, &QAction::triggered, this, &MasternodeList::copyVoting_clicked);

    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &MasternodeList::updateDIP3ListScheduled);
    timer->start(1000);
}

MasternodeList::~MasternodeList()
{
    delete ui;
}

void MasternodeList::setClientModel(ClientModel* model)
{
    this->clientModel = model;
    if (model) {
        // try to update list when masternode count changes
        connect(clientModel, &ClientModel::masternodeListChanged, this, &MasternodeList::handleMasternodeListChanged);
    }
}

void MasternodeList::setWalletModel(WalletModel* model)
{
    this->walletModel = model;
    ui->checkBoxMyMasternodesOnly->setEnabled(model != nullptr);
}

void MasternodeList::showContextMenuDIP3(const QPoint& point)
{
    QTableWidgetItem* item = ui->tableWidgetMasternodesDIP3->itemAt(point);
    if (item) contextMenuDIP3->exec(QCursor::pos());
}

void MasternodeList::handleMasternodeListChanged()
{
    LOCK(cs_dip3list);
    mnListChanged = true;
}

void MasternodeList::updateDIP3ListScheduled()
{
    TRY_LOCK(cs_dip3list, fLockAcquired);
    if (!fLockAcquired) return;

    if (!clientModel || clientModel->node().shutdownRequested()) {
        return;
    }

    // To prevent high cpu usage update only once in MASTERNODELIST_FILTER_COOLDOWN_SECONDS seconds
    // after filter was last changed unless we want to force the update.
    if (fFilterUpdatedDIP3) {
        int64_t nSecondsToWait = nTimeFilterUpdatedDIP3 - GetTime() + MASTERNODELIST_FILTER_COOLDOWN_SECONDS;
        ui->countLabelDIP3->setText(QString::fromStdString(strprintf("Please wait... %d", nSecondsToWait)));

        if (nSecondsToWait <= 0) {
            updateDIP3List();
            fFilterUpdatedDIP3 = false;
        }
    } else if (mnListChanged) {
        int64_t nMnListUpdateSecods = clientModel->masternodeSync().isBlockchainSynced() ? MASTERNODELIST_UPDATE_SECONDS : MASTERNODELIST_UPDATE_SECONDS*10;
        int64_t nSecondsToWait = nTimeUpdatedDIP3 - GetTime() + nMnListUpdateSecods;

        if (nSecondsToWait <= 0) {
            updateDIP3List();
            mnListChanged = false;
        }
    }
}

void MasternodeList::updateDIP3List()
{
    if (!clientModel || clientModel->node().shutdownRequested()) {
        return;
    }

    auto mnList = clientModel->getMasternodeList();
    std::map<uint256, CTxDestination> mapCollateralDests;

    {
        // Get all UTXOs for each MN collateral in one go so that we can reduce locking overhead for cs_main
        // We also do this outside of the below Qt list update loop to reduce cs_main locking time to a minimum
        LOCK(cs_main);
        mnList.ForEachMN(false, [&](const CDeterministicMNCPtr& dmn) {
            CTxDestination collateralDest;
            std::map<COutPoint, Coin> coins;
            coins[dmn->collateralOutpoint];
            clientModel->node().context()->chain->findCoins(coins);
            const Coin &coin = coins.at(dmn->collateralOutpoint);
            if (!coin.IsSpent() && ExtractDestination(coin.out.scriptPubKey, collateralDest)) {
                mapCollateralDests.emplace(dmn->proTxHash, collateralDest);
            }
        });
    }

    LOCK(cs_dip3list);

    QString strToFilter;
    ui->countLabelDIP3->setText("Updating...");
    ui->tableWidgetMasternodesDIP3->setSortingEnabled(false);
    ui->tableWidgetMasternodesDIP3->clearContents();
    ui->tableWidgetMasternodesDIP3->setRowCount(0);

    nTimeUpdatedDIP3 = GetTime();
    auto projectedPayees = mnList.GetProjectedMNPayees(mnList.GetValidMNsCount());
    std::map<uint256, int> nextPayments;
    for (size_t i = 0; i < projectedPayees.size(); i++) {
        const auto& dmn = projectedPayees[i];
        nextPayments.emplace(dmn->proTxHash, mnList.GetHeight() + (int)i + 1);
    }

    std::set<COutPoint> setOutpts;
    if (walletModel && ui->checkBoxMyMasternodesOnly->isChecked()) {
        std::vector<COutPoint> vOutpts;
        walletModel->wallet().listProTxCoins(vOutpts);
        for (const auto& outpt : vOutpts) {
            setOutpts.emplace(outpt);
        }
    }

    mnList.ForEachMN(false, [&](const CDeterministicMNCPtr& dmn) {
        if (walletModel && ui->checkBoxMyMasternodesOnly->isChecked()) {
            bool fMyMasternode = setOutpts.count(dmn->collateralOutpoint) ||
                walletModel->wallet().isSpendable(CTxDestination(WitnessV0KeyHash(dmn->pdmnState->keyIDOwner))) ||
                walletModel->wallet().isSpendable(CTxDestination(WitnessV0KeyHash(dmn->pdmnState->keyIDVoting))) ||
                walletModel->wallet().isSpendable(dmn->pdmnState->scriptPayout) ||
                walletModel->wallet().isSpendable(dmn->pdmnState->scriptOperatorPayout);
            if (!fMyMasternode) return;
        }
        // populate list
        // Address, Protocol, Status, Active Seconds, Last Seen, Pub Key
        QTableWidgetItem* addressItem = new QTableWidgetItem(QString::fromStdString(dmn->pdmnState->addr.ToString()));
        QTableWidgetItem* statusItem = new QTableWidgetItem(mnList.IsMNValid(dmn) ? tr("ENABLED") : (mnList.IsMNPoSeBanned(dmn) ? tr("POSE_BANNED") : tr("UNKNOWN")));
        QTableWidgetItem* PoSeScoreItem = new QTableWidgetItem(QString::number(dmn->pdmnState->nPoSePenalty));
        QTableWidgetItem* registeredItem = new QTableWidgetItem(QString::number(dmn->pdmnState->nRegisteredHeight));
        QTableWidgetItem* lastPaidItem = new QTableWidgetItem(QString::number(dmn->pdmnState->nLastPaidHeight));
        QTableWidgetItem* nextPaymentItem = new QTableWidgetItem(nextPayments.count(dmn->proTxHash) ? QString::number(nextPayments[dmn->proTxHash]) : tr("UNKNOWN"));

        CTxDestination payeeDest;
        QString payeeStr = tr("UNKNOWN");
        if (ExtractDestination(dmn->pdmnState->scriptPayout, payeeDest)) {
            payeeStr = QString::fromStdString(EncodeDestination(payeeDest));
        }
        QTableWidgetItem* payeeItem = new QTableWidgetItem(payeeStr);

        QString operatorRewardStr = tr("NONE");
        if (dmn->nOperatorReward) {
            operatorRewardStr = QString::number(dmn->nOperatorReward / 100.0, 'f', 2) + "% ";

            if (dmn->pdmnState->scriptOperatorPayout != CScript()) {
                CTxDestination operatorDest;
                if (ExtractDestination(dmn->pdmnState->scriptOperatorPayout, operatorDest)) {
                    operatorRewardStr += tr("to %1").arg(QString::fromStdString(EncodeDestination(operatorDest)));
                } else {
                    operatorRewardStr += tr("to UNKNOWN");
                }
            } else {
                operatorRewardStr += tr("but not claimed");
            }
        }
        QTableWidgetItem* operatorRewardItem = new QTableWidgetItem(operatorRewardStr);

        QString collateralStr = tr("UNKNOWN");
        auto collateralDestIt = mapCollateralDests.find(dmn->proTxHash);
        if (collateralDestIt != mapCollateralDests.end()) {
            collateralStr = QString::fromStdString(EncodeDestination(collateralDestIt->second));
        }
        QTableWidgetItem* collateralItem = new QTableWidgetItem(collateralStr);

        QString ownerStr = QString::fromStdString(EncodeDestination(WitnessV0KeyHash(dmn->pdmnState->keyIDOwner)));
        QTableWidgetItem* ownerItem = new QTableWidgetItem(ownerStr);

        QString votingStr = QString::fromStdString(EncodeDestination(WitnessV0KeyHash(dmn->pdmnState->keyIDVoting)));
        QTableWidgetItem* votingItem = new QTableWidgetItem(votingStr);

        QTableWidgetItem* proTxHashItem = new QTableWidgetItem(QString::fromStdString(dmn->proTxHash.ToString()));

        if (strCurrentFilterDIP3 != "") {
            strToFilter = addressItem->text() + " " +
                          statusItem->text() + " " +
                          PoSeScoreItem->text() + " " +
                          registeredItem->text() + " " +
                          lastPaidItem->text() + " " +
                          nextPaymentItem->text() + " " +
                          payeeItem->text() + " " +
                          operatorRewardItem->text() + " " +
                          collateralItem->text() + " " +
                          ownerItem->text() + " " +
                          votingItem->text() + " " +
                          proTxHashItem->text();
            if (!strToFilter.contains(strCurrentFilterDIP3)) return;
        }

        ui->tableWidgetMasternodesDIP3->insertRow(0);
        ui->tableWidgetMasternodesDIP3->setItem(0, 0, addressItem);
        ui->tableWidgetMasternodesDIP3->setItem(0, 1, statusItem);
        ui->tableWidgetMasternodesDIP3->setItem(0, 2, PoSeScoreItem);
        ui->tableWidgetMasternodesDIP3->setItem(0, 3, registeredItem);
        ui->tableWidgetMasternodesDIP3->setItem(0, 4, lastPaidItem);
        ui->tableWidgetMasternodesDIP3->setItem(0, 5, nextPaymentItem);
        ui->tableWidgetMasternodesDIP3->setItem(0, 6, payeeItem);
        ui->tableWidgetMasternodesDIP3->setItem(0, 7, operatorRewardItem);
        ui->tableWidgetMasternodesDIP3->setItem(0, 8, collateralItem);
        ui->tableWidgetMasternodesDIP3->setItem(0, 9, ownerItem);
        ui->tableWidgetMasternodesDIP3->setItem(0, 10, votingItem);
        ui->tableWidgetMasternodesDIP3->setItem(0, 11, proTxHashItem);
    });

    ui->countLabelDIP3->setText(QString::number(ui->tableWidgetMasternodesDIP3->rowCount()));
    ui->tableWidgetMasternodesDIP3->setSortingEnabled(true);
}

void MasternodeList::on_filterLineEditDIP3_textChanged(const QString& strFilterIn)
{
    strCurrentFilterDIP3 = strFilterIn;
    nTimeFilterUpdatedDIP3 = GetTime();
    fFilterUpdatedDIP3 = true;
    ui->countLabelDIP3->setText(QString::fromStdString(strprintf("Please wait... %d", MASTERNODELIST_FILTER_COOLDOWN_SECONDS)));
}

void MasternodeList::on_checkBoxMyMasternodesOnly_stateChanged(int state)
{
    // no cooldown
    nTimeFilterUpdatedDIP3 = GetTime() - MASTERNODELIST_FILTER_COOLDOWN_SECONDS;
    fFilterUpdatedDIP3 = true;
}

CDeterministicMNCPtr MasternodeList::GetSelectedDIP3MN()
{
    if (!clientModel) {
        return nullptr;
    }

    std::string strProTxHash;
    {
        LOCK(cs_dip3list);

        QItemSelectionModel* selectionModel = ui->tableWidgetMasternodesDIP3->selectionModel();
        QModelIndexList selected = selectionModel->selectedRows();

        if (selected.count() == 0) return nullptr;

        QModelIndex index = selected.at(0);
        int nSelectedRow = index.row();
        strProTxHash = ui->tableWidgetMasternodesDIP3->item(nSelectedRow, 11)->text().toStdString();
    }

    uint256 proTxHash;
    proTxHash.SetHex(strProTxHash);

    auto mnList = clientModel->getMasternodeList();
    return mnList.GetMN(proTxHash);
}

void MasternodeList::extraInfoDIP3_clicked()
{
    auto dmn = GetSelectedDIP3MN();
    if (!dmn) {
        return;
    }

    UniValue json(UniValue::VOBJ);
    dmn->ToJson(*clientModel->node().context()->chain, json);

    // Title of popup window
    QString strWindowtitle = tr("Additional information for DIP3 Masternode %1").arg(QString::fromStdString(dmn->proTxHash.ToString()));
    QString strText = QString::fromStdString(json.write(2));

    QMessageBox::information(this, strWindowtitle, strText);
}

void MasternodeList::copyProTxHash_clicked()
{
    auto dmn = GetSelectedDIP3MN();
    if (!dmn) {
        return;
    }

    QApplication::clipboard()->setText(QString::fromStdString(dmn->proTxHash.ToString()));
}

void MasternodeList::copyCollateralOutpoint_clicked()
{
    auto dmn = GetSelectedDIP3MN();
    if (!dmn) {
        return;
    }

    QApplication::clipboard()->setText(QString::fromStdString(dmn->collateralOutpoint.ToStringShort()));
}

void MasternodeList::copyService_clicked()
{
    auto dmn = GetSelectedDIP3MN();
    if (!dmn) {
        return;
    }
    QApplication::clipboard()->setText(QString::fromStdString(dmn->pdmnState->addr.ToString()));
}
void MasternodeList::copyPayout_clicked()
{
    auto dmn = GetSelectedDIP3MN();
    if (!dmn) {
        return;
    }
    QString operatorStr;
    CTxDestination operatorDest;
    if (ExtractDestination(dmn->pdmnState->scriptOperatorPayout, operatorDest)) {
        operatorStr = QString::fromStdString(EncodeDestination(operatorDest));
    }

    QApplication::clipboard()->setText(operatorStr);
}
void MasternodeList::copyCollateral_clicked()
{
    auto dmn = GetSelectedDIP3MN();
    if (!dmn) {
        return;
    }
    auto mnList = clientModel->getMasternodeList();

    QString collateralStr;
    CTxDestination collateralDest;
    std::map<COutPoint, Coin> coins;
    coins[dmn->collateralOutpoint];
    clientModel->node().context()->chain->findCoins(coins);
    const Coin &coin = coins.at(dmn->collateralOutpoint);
    if (!coin.IsSpent() && ExtractDestination(coin.out.scriptPubKey, collateralDest)) {
        collateralStr = QString::fromStdString(EncodeDestination(collateralDest));
    }
    QApplication::clipboard()->setText(collateralStr);
}
void MasternodeList::copyOwner_clicked()
{
    auto dmn = GetSelectedDIP3MN();
    if (!dmn) {
        return;
    }
    QString ownerStr = QString::fromStdString(EncodeDestination(WitnessV0KeyHash(dmn->pdmnState->keyIDOwner)));
    QApplication::clipboard()->setText(ownerStr);
}
void MasternodeList::copyVoting_clicked()
{
    auto dmn = GetSelectedDIP3MN();
    if (!dmn) {
        return;
    }
    QString votingStr = QString::fromStdString(EncodeDestination(WitnessV0KeyHash(dmn->pdmnState->keyIDVoting)));
    QApplication::clipboard()->setText(votingStr);
}


text:
To correctly style our app, we need to replace following code:

```
<div id="app">APPLICATION CONTENT</div>
```

By :

```
<body>
  <section id="app" class="todoapp"></section>
  <footer class="info">
    <p>Double-click to edit a todo</p>
    <p>Created by <a href="http://github.com/wishpishh">Hannes Johansson</a> based on React example by <a href="http://github.com/petehunt/">petehunt</a></p>
    <p>Part of <a href="http://todomvc.com">TodoMVC</a></p>
  </footer>
  <script>__REACT_DEVTOOLS_GLOBAL_HOOK__ = parent.__REACT_DEVTOOLS_GLOBAL_HOOK__</script>
  <script type="text/javascript" src="assets/app.js"></script>
</body>
```


text:
package v1

import (
	"strings"
	"testing"

	"github.com/stretchr/testify/assert"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/validation"
)

func TestGameServerSetGameServer(t *testing.T) {
	gsSet := GameServerSet{
		ObjectMeta: metav1.ObjectMeta{
			Name:      "test",
			Namespace: "namespace",
			UID:       "1234",
			Labels: map[string]string{
				FleetNameLabel: "fleetname",
			},
		},
		Spec: GameServerSetSpec{
			Replicas: 10,
			Template: GameServerTemplateSpec{
				Spec: GameServerSpec{
					Ports: []GameServerPort{{ContainerPort: 1234}},
					Template: corev1.PodTemplateSpec{
						Spec: corev1.PodSpec{
							Containers: []corev1.Container{{Name: "container", Image: "myimage"}},
						},
					},
				},
			},
		},
	}

	gs := gsSet.GameServer()
	assert.Equal(t, "", gs.ObjectMeta.Name)
	assert.Equal(t, gsSet.ObjectMeta.Namespace, gs.ObjectMeta.Namespace)
	assert.Equal(t, gsSet.ObjectMeta.Name+"-", gs.ObjectMeta.GenerateName)
	assert.Equal(t, gsSet.ObjectMeta.Name, gs.ObjectMeta.Labels[GameServerSetGameServerLabel])
	assert.Equal(t, gsSet.ObjectMeta.Labels[FleetNameLabel], gs.ObjectMeta.Labels[FleetNameLabel])

	assert.Equal(t, gs.Spec, gsSet.Spec.Template.Spec)
	assert.True(t, metav1.IsControlledBy(gs, &gsSet))
}

// TestGameServerSetValidateUpdate test GameServerSet Validate() and ValidateUpdate()
func TestGameServerSetValidateUpdate(t *testing.T) {
	gsSpec := defaultGameServer().Spec
	gsSet := GameServerSet{
		ObjectMeta: metav1.ObjectMeta{Name: "test"},
		Spec: GameServerSetSpec{
			Replicas: 10,
			Template: GameServerTemplateSpec{
				Spec: gsSpec,
			},
		},
	}

	causes, ok := gsSet.ValidateUpdate(gsSet.DeepCopy())
	assert.True(t, ok)
	assert.Empty(t, causes)

	newGSS := gsSet.DeepCopy()
	newGSS.Spec.Replicas = 5
	causes, ok = gsSet.ValidateUpdate(newGSS)
	assert.True(t, ok)
	assert.Empty(t, causes)

	newGSS.Spec.Template.Spec.Ports[0].ContainerPort = 321
	causes, ok = gsSet.ValidateUpdate(newGSS)
	assert.False(t, ok)
	assert.Len(t, causes, 1)
	assert.Equal(t, "template", causes[0].Field)

	newGSS = gsSet.DeepCopy()
	longName := strings.Repeat("f", validation.LabelValueMaxLength+1)
	newGSS.Name = longName
	causes, ok = newGSS.Validate()
	assert.False(t, ok)
	assert.Len(t, causes, 1)
	assert.Equal(t, "Name", causes[0].Field)

	newGSS.Name = ""
	newGSS.GenerateName = longName
	causes, ok = newGSS.Validate()
	assert.True(t, ok)
	assert.Len(t, causes, 0)

	newGSS = gsSet.DeepCopy()
	newGSS.Name = longName
	causes, ok = gsSet.ValidateUpdate(newGSS)
	assert.False(t, ok)
	assert.Len(t, causes, 1)
	assert.Equal(t, "Name", causes[0].Field)

	newGSS = gsSet.DeepCopy()
	newGSS.Spec.Template.ObjectMeta.Labels = make(map[string]string)
	newGSS.Spec.Template.ObjectMeta.Labels[longName] = ""
	causes, ok = newGSS.Validate()
	assert.False(t, ok)
	assert.Len(t, causes, 1)
	assert.Equal(t, "labels", causes[0].Field)

	// Same validation applies to nested Labels which applies to GameServer pod
	newGSS = gsSet.DeepCopy()
	newGSS.Spec.Template.Spec.Template.ObjectMeta.Labels = make(map[string]string)
	newGSS.Spec.Template.Spec.Template.ObjectMeta.Labels[longName] = ""
	causes, ok = newGSS.Validate()
	assert.False(t, ok)
	assert.Len(t, causes, 1)
	assert.Equal(t, "labels", causes[0].Field)

	// Similar Annotations validation check
	newGSS = gsSet.DeepCopy()
	newGSS.Spec.Template.ObjectMeta.Annotations = make(map[string]string)
	newGSS.Spec.Template.ObjectMeta.Annotations[longName] = ""
	causes, ok = newGSS.Validate()
	assert.False(t, ok)
	assert.Len(t, causes, 1)
	assert.Equal(t, "annotations", causes[0].Field)

	// Nested GS Spec Annotations
	newGSS = gsSet.DeepCopy()
	newGSS.Spec.Template.Spec.Template.ObjectMeta.Annotations = make(map[string]string)
	newGSS.Spec.Template.Spec.Template.ObjectMeta.Annotations[longName] = ""
	causes, ok = newGSS.Validate()
	assert.False(t, ok)
	assert.Len(t, causes, 1)
	assert.Equal(t, "annotations", causes[0].Field)

	gsSet.Spec.Template.Spec.Template =
		corev1.PodTemplateSpec{
			Spec: corev1.PodSpec{
				Containers: []corev1.Container{{Name: "container", Image: "myimage"}, {Name: "container2", Image: "myimage"}},
			},
		}
	causes, ok = gsSet.Validate()

	assert.False(t, ok)
	assert.Len(t, causes, 2)
	assert.Equal(t, "container", causes[0].Field)
}


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

<title>Debugging with GDB: Types In Python</title>

<meta name="description" content="Debugging with GDB: Types In Python">
<meta name="keywords" content="Debugging with GDB: Types In Python">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="Concept-Index.html#Concept-Index" rel="index" title="Concept Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="Python-API.html#Python-API" rel="up" title="Python API">
<link href="Pretty-Printing-API.html#Pretty-Printing-API" rel="next" title="Pretty Printing API">
<link href="Values-From-Inferior.html#Values-From-Inferior" rel="prev" title="Values From Inferior">

Next: Pretty Printing API, Previous: Values From Inferior, Up: Python API   [Contents][Index]

23.2.2.4 Types In Python

GDB represents types from the inferior using the class
gdb.Type.

The following type-related functions are available in the gdb
module:

Function: gdb.lookup_type (name [, block])

This function looks up a type by its <var>name</var>, which must be a string.

If <var>block</var> is given, then <var>name</var> is looked up in that scope.
Otherwise, it is searched for globally.

Ordinarily, this function will return an instance of gdb.Type.
If the named type cannot be found, it will throw an exception.

If the type is a structure or class type, or an enum type, the fields
of that type can be accessed using the Python dictionary syntax.
For example, if some_type is a gdb.Type instance holding
a structure type, you can access its foo field with:

bar = some_type['foo']

bar will be a gdb.Field object; see below under the
description of the Type.fields method for a description of the
gdb.Field class.

An instance of Type has the following attributes:

Variable: Type.code

The type code for this type.  The type code will be one of the
TYPE_CODE_ constants defined below.

Variable: Type.name

The name of this type.  If this type has no name, then None
is returned.

Variable: Type.sizeof

The size of this type, in target char units.  Usually, a
target’s char type will be an 8-bit byte.  However, on some
unusual platforms, this type may have a different size.

Variable: Type.tag

The tag name for this type.  The tag name is the name after
struct, union, or enum in C and C<tt>++</tt>; not all
languages have this concept.  If this type has no tag name, then
None is returned.

The following methods are provided:

Function: Type.fields ()

For structure and union types, this method returns the fields.  Range
types have two fields, the minimum and maximum values.  Enum types
have one field per enum constant.  Function and method types have one
field per parameter.  The base types of C<tt>++</tt> classes are also
represented as fields.  If the type has no fields, or does not fit
into one of these categories, an empty sequence will be returned.

Each field is a gdb.Field object, with some pre-defined attributes:

bitpos

This attribute is not available for enum or static
(as in C<tt>++</tt> or Java) fields.  The value is the position, counting
in bits, from the start of the containing type.

enumval

This attribute is only available for enum fields, and its value
is the enumeration member’s integer representation.

name

The name of the field, or None for anonymous fields.

artificial

This is True if the field is artificial, usually meaning that
it was provided by the compiler and not the user.  This attribute is
always provided, and is False if the field is not artificial.

is_base_class

This is True if the field represents a base class of a C<tt>++</tt>
structure.  This attribute is always provided, and is False
if the field is not a base class of the type that is the argument of
fields, or if that type was not a C<tt>++</tt> class.

bitsize

If the field is packed, or is a bitfield, then this will have a
non-zero value, which is the size of the field in bits.  Otherwise,
this will be zero; in this case the field’s size is given by its type.

type

The type of the field.  This is usually an instance of Type,
but it can be None in some situations.

parent_type

The type which contains this field.  This is an instance of
gdb.Type.

Function: Type.array (<var>n1</var> [, <var>n2</var>])

Return a new gdb.Type object which represents an array of this
type.  If one argument is given, it is the inclusive upper bound of
the array; in this case the lower bound is zero.  If two arguments are
given, the first argument is the lower bound of the array, and the
second argument is the upper bound of the array.  An array’s length
must not be negative, but the bounds can be.

Function: Type.vector (<var>n1</var> [, <var>n2</var>])

Return a new gdb.Type object which represents a vector of this
type.  If one argument is given, it is the inclusive upper bound of
the vector; in this case the lower bound is zero.  If two arguments are
given, the first argument is the lower bound of the vector, and the
second argument is the upper bound of the vector.  A vector’s length
must not be negative, but the bounds can be.

The difference between an array and a vector is that
arrays behave like in C: when used in expressions they decay to a pointer
to the first element whereas vectors are treated as first class values.

Function: Type.const ()

Return a new gdb.Type object which represents a
const-qualified variant of this type.

Function: Type.volatile ()

Return a new gdb.Type object which represents a
volatile-qualified variant of this type.

Function: Type.unqualified ()

Return a new gdb.Type object which represents an unqualified
variant of this type.  That is, the result is neither const nor
volatile.

Function: Type.range ()

Return a Python Tuple object that contains two elements: the
low bound of the argument type and the high bound of that type.  If
the type does not have a range, GDB will raise a
gdb.error exception (see Exception Handling).

Function: Type.reference ()

Return a new gdb.Type object which represents a reference to this
type.

Function: Type.pointer ()

Return a new gdb.Type object which represents a pointer to this
type.

Function: Type.strip_typedefs ()

Return a new gdb.Type that represents the real type,
after removing all layers of typedefs.

Function: Type.target ()

Return a new gdb.Type object which represents the target type
of this type.

For a pointer type, the target type is the type of the pointed-to
object.  For an array type (meaning C-like arrays), the target type is
the type of the elements of the array.  For a function or method type,
the target type is the type of the return value.  For a complex type,
the target type is the type of the elements.  For a typedef, the
target type is the aliased type.

If the type does not have a target, this method will throw an
exception.

Function: Type.template_argument (n [, block])

If this gdb.Type is an instantiation of a template, this will
return a new gdb.Value or gdb.Type which represents the
value of the <var>n</var>th template argument (indexed starting at 0).

If this gdb.Type is not a template type, or if the type has fewer
than <var>n</var> template arguments, this will throw an exception.
Ordinarily, only C<tt>++</tt> code will have template types.

If <var>block</var> is given, then <var>name</var> is looked up in that scope.
Otherwise, it is searched for globally.

Function: Type.optimized_out ()

Return gdb.Value instance of this type whose value is optimized
out.  This allows a frame decorator to indicate that the value of an
argument or a local variable is not known.

Each type has a code, which indicates what category this type falls
into.  The available type categories are represented by constants
defined in the gdb module:

gdb.TYPE_CODE_PTR

The type is a pointer.

gdb.TYPE_CODE_ARRAY

The type is an array.

gdb.TYPE_CODE_STRUCT

The type is a structure.

gdb.TYPE_CODE_UNION

The type is a union.

gdb.TYPE_CODE_ENUM

The type is an enum.

gdb.TYPE_CODE_FLAGS

A bit flags type, used for things such as status registers.

gdb.TYPE_CODE_FUNC

The type is a function.

gdb.TYPE_CODE_INT

The type is an integer type.

gdb.TYPE_CODE_FLT

A floating point type.

gdb.TYPE_CODE_VOID

The special type void.

gdb.TYPE_CODE_SET

A Pascal set type.

gdb.TYPE_CODE_RANGE

A range type, that is, an integer type with bounds.

gdb.TYPE_CODE_STRING

A string type.  Note that this is only used for certain languages with
language-defined string types; C strings are not represented this way.

gdb.TYPE_CODE_BITSTRING

A string of bits.  It is deprecated.

gdb.TYPE_CODE_ERROR

An unknown or erroneous type.

gdb.TYPE_CODE_METHOD

A method type, as found in C<tt>++</tt> or Java.

gdb.TYPE_CODE_METHODPTR

A pointer-to-member-function.

gdb.TYPE_CODE_MEMBERPTR

A pointer-to-member.

gdb.TYPE_CODE_REF

A reference type.

gdb.TYPE_CODE_CHAR

A character type.

gdb.TYPE_CODE_BOOL

A boolean type.

gdb.TYPE_CODE_COMPLEX

A complex float type.

gdb.TYPE_CODE_TYPEDEF

A typedef to some other type.

gdb.TYPE_CODE_NAMESPACE

A C<tt>++</tt> namespace.

gdb.TYPE_CODE_DECFLOAT

A decimal floating point type.

gdb.TYPE_CODE_INTERNAL_FUNCTION

A function internal to GDB.  This is the type used to represent
convenience functions.

Further support for types is provided in the gdb.types
Python module (see gdb.types).

Next: Pretty Printing API, Previous: Values From Inferior, Up: Python API   [Contents][Index]


text:
from create_instance import LaunchInstance  # noqa
from resize_instance import ResizeInstance  # noqa
from update_instance import UpdateInstance  # noqa


text:
package com.barentine.totalconnect.ws;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for UpdateDoorbellDetailResult complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="UpdateDoorbellDetailResult">
 *   <complexContent>
 *     <extension base="{https://services.alarmnet.com/TC2/}WebMethodResults">
 *       <sequence>
 *         <element name="SetupStateID" type="{http://www.w3.org/2001/XMLSchema}int"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "UpdateDoorbellDetailResult", propOrder = {
    "setupStateID"
})
public class UpdateDoorbellDetailResult
    extends WebMethodResults
{

    @XmlElement(name = "SetupStateID")
    protected int setupStateID;

    /**
     * Gets the value of the setupStateID property.
     *
     */
    public int getSetupStateID() {
        return setupStateID;
    }

    /**
     * Sets the value of the setupStateID property.
     *
     */
    public void setSetupStateID(int value) {
        this.setupStateID = value;
    }

}