text:
<?php

declare(strict_types=1);

namespace spec\Sylius\Component\Promotion\Checker\Eligibility;

use PhpSpec\ObjectBehavior;
use Sylius\Component\Promotion\Checker\Eligibility\PromotionDurationEligibilityChecker;
use Sylius\Component\Promotion\Checker\Eligibility\PromotionEligibilityCheckerInterface;
use Sylius\Component\Promotion\Model\PromotionInterface;
use Sylius\Component\Promotion\Model\PromotionSubjectInterface;

/**
 * @author Mateusz Zalewski <mateusz.zalewski@lakion.com>
 */
final class PromotionDurationEligibilityCheckerSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType(PromotionDurationEligibilityChecker::class);
    }

    function it_implements_a_promotion_eligibility_checker_interface()
    {
        $this->shouldImplement(PromotionEligibilityCheckerInterface::class);
    }

    function it_returns_false_if_promotion_has_not_started_yet(
        PromotionSubjectInterface $promotionSubject,
        PromotionInterface $promotion
    ) {
        $promotion->getStartsAt()->willReturn(new \DateTime('+3 days'));

        $this->isEligible($promotionSubject, $promotion)->shouldReturn(false);
    }

    function it_returns_false_if_promotion_has_already_ended(
        PromotionSubjectInterface $promotionSubject,
        PromotionInterface $promotion
    ) {
        $promotion->getStartsAt()->willReturn(new \DateTime('-5 days'));
        $promotion->getEndsAt()->willReturn(new \DateTime('-3 days'));

        $this->isEligible($promotionSubject, $promotion)->shouldReturn(false);
    }

    function it_returns_true_if_promotion_is_currently_available(
        PromotionSubjectInterface $promotionSubject,
        PromotionInterface $promotion
    ) {
        $promotion->getStartsAt()->willReturn(new \DateTime('-2 days'));
        $promotion->getEndsAt()->willReturn(new \DateTime('+2 days'));

        $this->isEligible($promotionSubject, $promotion)->shouldReturn(true);
    }

    function it_returns_true_if_promotion_dates_are_not_specified(
        PromotionSubjectInterface $promotionSubject,
        PromotionInterface $promotion
    ) {
        $promotion->getStartsAt()->willReturn(null);
        $promotion->getEndsAt()->willReturn(null);

        $this->isEligible($promotionSubject, $promotion)->shouldReturn(true);
    }
}


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

<TITLE>
Uses of Interface org.eclipse.paho.client.mqttv3.MqttDeliveryToken
</TITLE>

<META NAME="date" CONTENT="2012-08-07">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Interface
org.eclipse.paho.client.mqttv3.MqttDeliveryToken

Packages that use MqttDeliveryToken

com.aware

org.eclipse.paho.client.mqttv3
Contains an API for connecting to a server which implements the MQTT V3
protocol.

org.eclipse.paho.client.mqttv3.internal

Uses of MqttDeliveryToken in com.aware

Methods in com.aware with parameters of type MqttDeliveryToken

 void
Mqtt.deliveryComplete(MqttDeliveryToken token)

          When the message was delivered successfully on the server
 Do nothing for now.

Uses of MqttDeliveryToken in org.eclipse.paho.client.mqttv3

Methods in org.eclipse.paho.client.mqttv3 that return MqttDeliveryToken

 MqttDeliveryToken[]
MqttClient.getPendingDeliveryTokens()

          Returns the delivery tokens for any outstanding publish operations.

 MqttDeliveryToken
MqttTopic.publish(byte[] payload,
        int qos,
        boolean retained)

          Publishes a message on the topic.

 MqttDeliveryToken
MqttTopic.publish(MqttMessage message)

          Publishes the specified message to this topic, but doesn't wait for
 a response.

Methods in org.eclipse.paho.client.mqttv3 with parameters of type MqttDeliveryToken

 void
MqttCallback.deliveryComplete(MqttDeliveryToken token)

          Called when delivery for a message has been completed, and all
 acknowledgements have been received.

Uses of MqttDeliveryToken in org.eclipse.paho.client.mqttv3.internal

Classes in org.eclipse.paho.client.mqttv3.internal that implement MqttDeliveryToken

 class
MqttDeliveryTokenImpl

Methods in org.eclipse.paho.client.mqttv3.internal that return MqttDeliveryToken

 MqttDeliveryToken[]
CommsTokenStore.getOutstandingTokens()

 MqttDeliveryToken[]
ClientComms.getPendingDeliveryTokens()

Methods in org.eclipse.paho.client.mqttv3.internal with parameters of type MqttDeliveryToken

 void
CommsCallback.deliveryComplete(MqttDeliveryToken token)

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

redpajama_set_name: RedPajamaGithub


text:
using Playnite.SDK;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;

namespace Playnite.Common
{
    public class CacheItem
    {
        public object CacheObject
        {
            get;
        }

        public DateTime LastAccess
        {
            get; internal set;
        }

        public DateTime CachedTime
        {
            get;
        }

        public long Size
        {
            get;
        }

        public Dictionary<string, object> Metadata
        {
            get;
        } = new Dictionary<string, object>();

        public CacheItem(object item, long size)
        {
            CacheObject = item;
            CachedTime = DateTime.Now;
            LastAccess = CachedTime;
            Size = size;
        }

        public CacheItem(object item, long size, Dictionary<string, object> metadata) : this (item, size)
        {
            Metadata = metadata;
        }
    }

    public class MemoryCache
    {
        private static readonly ILogger logger = LogManager.GetLogger();
        private ConcurrentDictionary<string, CacheItem> cache = new ConcurrentDictionary<string, CacheItem>();
        private long memorySizeLimit = 0;
        private long currentSize = 0;

        public MemoryCache(long memoryLimit)
        {
            memorySizeLimit = memoryLimit;
        }

        public void Clear()
        {
            cache.Clear();
            currentSize = 0;
            GC.Collect();
        }

        private void ReleaseOldestItems()
        {
            // ToArray reason:
            // https://stackoverflow.com/questions/11692389/getting-argument-exception-in-concurrent-dictionary-when-sorting-and-displaying
            foreach (var item in cache.ToArray().OrderBy(a => a.Value.LastAccess))
            {
                if (currentSize > memorySizeLimit)
                {
                    TryRemove(item.Key, out var removed);
                }
                else
                {
                    break;
                }
            }
        }

        public bool TryAdd(string id, object item, long size, Dictionary<string, object> metadata = null)
        {
            if (size >= memorySizeLimit)
            {
                logger.Warn($"Cannot add item to memory cache. Size: {size}, cache limit: {memorySizeLimit}");
                return false;
            }

            Interlocked.Add(ref currentSize, size);
            if (currentSize > memorySizeLimit)
            {
                ReleaseOldestItems();
            }

            if (metadata == null)
            {
                return cache.TryAdd(id, new CacheItem(item, size));
            }
            else
            {
                return cache.TryAdd(id, new CacheItem(item, size, metadata));
            }
        }

        public bool TryRemove(string id, out CacheItem item)
        {
            if (cache.TryRemove(id, out var cacheItem))
            {
                item = cacheItem;
                Interlocked.Add(ref currentSize, -cacheItem.Size);
                return true;
            }
            else
            {
                item = null;
                return false;
            }
        }

        public bool TryRemove(string id)
        {
            if (cache.TryRemove(id, out var cacheItem))
            {
                Interlocked.Add(ref currentSize, -cacheItem.Size);
                return true;
            }
            else
            {
                return false;
            }
        }

        public bool TryGet(string id, out CacheItem item)
        {
            if (cache.TryGetValue(id, out var cacheItem))
            {
                cacheItem.LastAccess = DateTime.Now;
                item = cacheItem;
                return true;
            }
            else
            {
                item = null;
                return false;
            }
        }
    }
}


text:
/**
 * 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 org.apache.aurora.scheduler.stats;

import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.twitter.common.stats.StatsProvider;
import com.twitter.common.testing.easymock.EasyMockTest;

import org.apache.aurora.gen.ResourceAggregate;
import org.apache.aurora.scheduler.base.ResourceAggregates;
import org.apache.aurora.scheduler.stats.SlotSizeCounter.MachineResource;
import org.apache.aurora.scheduler.stats.SlotSizeCounter.MachineResourceProvider;
import org.apache.aurora.scheduler.storage.entities.IResourceAggregate;
import org.junit.Before;
import org.junit.Test;

import static org.easymock.EasyMock.expect;
import static org.junit.Assert.assertEquals;

public class SlotSizeCounterTest extends EasyMockTest {

  private static final IResourceAggregate SMALL =
      IResourceAggregate.build(new ResourceAggregate(1.0, 1024, 4096));
  private static final IResourceAggregate LARGE = ResourceAggregates.scale(SMALL, 4);

  private static final Map<String, IResourceAggregate> SLOT_SIZES = ImmutableMap.of(
      "small", SMALL,
      "large", LARGE);

  private MachineResourceProvider slotProvider;
  private StatsProvider statsProvider;
  private Runnable slotCounter;

  private AtomicLong smallCounter = new AtomicLong();
  private AtomicLong smallDedicatedCounter = new AtomicLong();
  private AtomicLong largeCounter = new AtomicLong();
  private AtomicLong largeDedicatedCounter = new AtomicLong();

  @Before
  public void setUp() {
    slotProvider = createMock(MachineResourceProvider.class);
    statsProvider = createMock(StatsProvider.class);
    slotCounter = new SlotSizeCounter(SLOT_SIZES, slotProvider, new CachedCounters(statsProvider));
  }

  private void expectStatExport() {
    expect(statsProvider.makeCounter(SlotSizeCounter.getStatName("small", false)))
        .andReturn(smallCounter);
    expect(statsProvider.makeCounter(SlotSizeCounter.getStatName("small", true)))
        .andReturn(smallDedicatedCounter);
    expect(statsProvider.makeCounter(SlotSizeCounter.getStatName("large", false)))
        .andReturn(largeCounter);
    expect(statsProvider.makeCounter(SlotSizeCounter.getStatName("large", true)))
        .andReturn(largeDedicatedCounter);
  }

  private void expectGetSlots(MachineResource... returned) {
    expect(slotProvider.get()).andReturn(ImmutableList.copyOf(returned));
  }

  @Test
  public void testNoOffers() {
    expectStatExport();
    expectGetSlots();

    control.replay();

    slotCounter.run();
    assertEquals(0, smallCounter.get());
    assertEquals(0, smallDedicatedCounter.get());
    assertEquals(0, largeCounter.get());
    assertEquals(0, largeDedicatedCounter.get());
  }

  @Test
  public void testTinyOffers() {
    expectStatExport();
    expectGetSlots(
        new MachineResource(IResourceAggregate.build(new ResourceAggregate(0.1, 1, 1)), false));

    control.replay();

    slotCounter.run();
    assertEquals(0, smallCounter.get());
    assertEquals(0, smallDedicatedCounter.get());
    assertEquals(0, largeCounter.get());
    assertEquals(0, largeDedicatedCounter.get());
  }

  @Test
  public void testStarvedResourceVector() {
    expectStatExport();
    expectGetSlots(
        new MachineResource(
            IResourceAggregate.build(new ResourceAggregate(1000, 16384, 1)), false));

    control.replay();

    slotCounter.run();
    assertEquals(0, smallCounter.get());
    assertEquals(0, smallDedicatedCounter.get());
    assertEquals(0, largeCounter.get());
    assertEquals(0, largeDedicatedCounter.get());
  }

  @Test
  public void testCountSlots() {
    expectStatExport();
    expectGetSlots(
        new MachineResource(SMALL, false),
        new MachineResource(SMALL, false),
        new MachineResource(LARGE, false),
        new MachineResource(ResourceAggregates.scale(LARGE, 4), false),
        new MachineResource(IResourceAggregate.build(new ResourceAggregate(1, 1, 1)), false),
        new MachineResource(SMALL, true),
        new MachineResource(SMALL, true),
        new MachineResource(ResourceAggregates.scale(SMALL, 2), true));

    control.replay();

    slotCounter.run();
    assertEquals(22, smallCounter.get());
    assertEquals(4, smallDedicatedCounter.get());
    assertEquals(5, largeCounter.get());
    assertEquals(0, largeDedicatedCounter.get());
  }
}


text:
mods=(mlx4_core mlx4_ib ib_umad ib_uverbs ib_ipoib)
for i in ${mods[@]}
do
  mod=$(cat /etc/modules | grep $i)
  if [ -z "$mod" ]
  then
    echo $i | tee --append /etc/modules
  fi
  mod=$(lsmod | grep $i)
  if [ -z "$mod" ]
  then
    modprobe $i
  fi
done

# Install IB Subnet Manager
if [ -z "$(command -v opensm)" ]
then
  apt-get update
  apt-get -y install ifenslave-2.6 opensm
  update-rc.d -f opensm remove
  update-rc.d opensm defaults
  update-rc.d opensm enable
  service opensm restart
fi


text:
import {
    beforeEach,
    beforeEachProviders,
    describe,
    expect,
    it,
    inject,
} from '@angular/core/testing';
import {ComponentFixture, TestComponentBuilder} from '@angular/compiler/testing';
import {Component} from '@angular/core';
import {By} from '@angular/platform-browser';
import {InputSelectComponent, InputOptionComponent, InputSelectConfig} from './input-select.component';

describe('Component: InputSelect', () => {
    describe('Single Select', () => {
        let builder:TestComponentBuilder;

        beforeEachProviders(() => [InputSelectComponent]);
        beforeEach(inject([TestComponentBuilder], function (tcb:TestComponentBuilder) {
            builder = tcb;
        }));

        it('should create the component', inject([], () => {
            return builder.createAsync(SingleInputSelectComponentTestController)
                .then((fixture:ComponentFixture<any>) => {
                    let testController = fixture.componentInstance;
                    let query = fixture.debugElement.query(By.directive(InputSelectComponent));
                    expect(query).toBeTruthy();
                    expect(query.componentInstance).toBeTruthy();

                    fixture.detectChanges();
                    expect(query.componentInstance.value).toBe(testController.options[0]);

                    let config = new InputSelectConfig('multi', 'id');
                    expect(config.type).toBe('multi');
                    expect(config.idField).toBe('id');
                });
        }));

        it('should use the supplied template', inject([], () => {
            return builder.createAsync(Single2InputSelectComponentTestController)
                .then((fixture:ComponentFixture<any>) => {
                    let testController = fixture.componentInstance;
                    let query = fixture.debugElement.query(By.directive(InputSelectComponent));
                    fixture.detectChanges();
                    expect(query.nativeElement.innerHTML.split('one with salt').length).toBe(3);

                    testController.value1 = null;
                    fixture.detectChanges();
                    expect(query.nativeElement.innerHTML.split('one with salt').length).toBe(2);
                });
        }));

        it('should update value of component when parent changes', inject([], () => {
            return builder.createAsync(SingleInputSelectComponentTestController)
                .then((fixture:ComponentFixture<any>) => {
                    let testController = fixture.componentInstance;
                    let compController = fixture.debugElement.query(By.directive(InputSelectComponent)).componentInstance;

                    fixture.detectChanges();
                    expect(compController.value).toBe(testController.options[0]);

                    testController.value1 = testController.options[1];
                    fixture.detectChanges();
                    expect(compController.value).toBe(testController.options[1]);

                    compController.value = testController.options[1];
                    fixture.detectChanges();
                    expect(compController.value).toBe(testController.options[1]);
                });
        }));

        it('should update value of parent when component changes', inject([], () => {
            return builder.createAsync(SingleInputSelectComponentTestController)
                .then((fixture:ComponentFixture<any>) => {
                    let testController = fixture.componentInstance;
                    let compController = fixture.debugElement.query(By.directive(InputSelectComponent)).componentInstance;

                    fixture.detectChanges();
                    expect(compController.value).toBe(testController.options[0]);

                    compController.value = testController.options[1];
                    fixture.detectChanges();
                    expect(testController.value1).toBe(testController.options[1]);
                });
        }));

        it('popupToggle', inject([], () => {
            return builder.createAsync(SingleInputSelectComponentTestController)
                .then((fixture:ComponentFixture<any>) => {
                    let compController = fixture.debugElement.query(By.directive(InputSelectComponent)).componentInstance;

                    fixture.detectChanges();
                    expect(compController._popupOpen).toBeFalsy();
                    expect(compController._classes.opened).toBeFalsy();
                    expect(compController._classes.closed).toBeTruthy();

                    compController.popupToggle();
                    fixture.detectChanges();
                    expect(compController._popupOpen).toBeTruthy();
                    expect(compController._classes.opened).toBeTruthy();
                    expect(compController._classes.closed).toBeFalsy();

                    compController.popupToggle();
                    fixture.detectChanges();
                    expect(compController._popupOpen).toBeFalsy();
                    expect(compController._classes.opened).toBeFalsy();
                    expect(compController._classes.closed).toBeTruthy();
                });
        }));

        it('window click should close', inject([], () => {
            return builder.createAsync(SingleInputSelectComponentTestController)
                .then((fixture:ComponentFixture<any>) => {
                    let compController = fixture.debugElement.query(By.directive(InputSelectComponent)).componentInstance;

                    fixture.detectChanges();
                    expect(compController._popupOpen).toBeFalsy();

                    compController.popupToggle();
                    fixture.detectChanges();
                    expect(compController._popupOpen).toBeTruthy();

                    compController.checkDocumentEvent({
                        path: [
                            compController._element.nativeElement
                        ]
                    });
                    fixture.detectChanges();
                    expect(compController._popupOpen).toBeTruthy();

                    compController.checkDocumentEvent({
                        path: []
                    });
                    fixture.detectChanges();
                    expect(compController._popupOpen).toBeFalsy();
                });
        }));

        it('open up when near bottom of screen', inject([], () => {
            return builder.createAsync(SingleInputSelectComponentTestController)
                .then((fixture:ComponentFixture<any>) => {
                    let compController = fixture.debugElement.query(By.directive(InputSelectComponent)).componentInstance;

                    compController.window.innerHeight = 200;
                    compController.popupOpen();
                    fixture.detectChanges();
                    expect(compController._classes.opened).toBeTruthy();
                    expect(compController._classes.closed).toBeFalsy();
                    expect(compController._classes.openUp).toBeTruthy();
                    expect(compController._classes.openDown).toBeFalsy();

                    compController.window.innerHeight = 2000;
                    compController.popupOpen();
                    fixture.detectChanges();
                    expect(compController._classes.opened).toBeTruthy();
                    expect(compController._classes.closed).toBeFalsy();
                    expect(compController._classes.openUp).toBeFalsy();
                    expect(compController._classes.openDown).toBeTruthy();
                });
        }));

        it('get a proper title', inject([], () => {
            return builder.createAsync(SingleInputSelectComponentTestController)
                .then((fixture:ComponentFixture<any>) => {
                    let testController = fixture.componentInstance;
                    let compController = fixture.debugElement.query(By.directive(InputSelectComponent)).componentInstance;

                    fixture.detectChanges();
                    expect(compController.getTitle()).toBe(testController.options[0]);

                    compController.value = null;
                    expect(compController.getTitle()).toBe('Select');

                    compController.options = [
                        {name: 'one', id: 1},
                        {name: 'two', id: 2},
                        {name: 'thr', id: 3},
                    ];
                    compController.value = 2;
                    compController.config.type = 'single';
                    compController.config.idField = 'id';
                    expect(compController.getTitle()).toBe(compController.options[1]);

                    compController.value = [3];
                    compController.config.type = 'multi';
                    expect(compController.getTitle()).toBe(compController.options[2]);
                });
        }));

        it('get get an item value', inject([], () => {
            return builder.createAsync(SingleInputSelectComponentTestController)
                .then((fixture:ComponentFixture<any>) => {
                    let compController = fixture.debugElement.query(By.directive(InputSelectComponent)).componentInstance;

                    let item = {name: 'one', id: 1};

                    fixture.detectChanges();
                    expect(compController.getItemValue(item)).toBe(item);

                    compController.config.idField = 'id';
                    expect(compController.getItemValue(item)).toBe(1);
                });
        }));

        it('item clicked', inject([], () => {
            return builder.createAsync(SingleInputSelectComponentTestController)
                .then((fixture:ComponentFixture<any>) => {
                    let testController = fixture.componentInstance;
                    let compController = fixture.debugElement.query(By.directive(InputSelectComponent)).componentInstance;

                    fixture.detectChanges();
                    expect(compController.value).toBe(testController.options[0]);

                    compController.itemClicked(testController.options[1]);
                    fixture.detectChanges();
                    expect(compController.value).toBe(testController.options[1]);
                });
        }));

        it('should navigate properly', inject([], () => {
            return builder.createAsync(SingleInputSelectComponentTestController)
                .then((fixture:ComponentFixture<any>) => {
                    let compController = fixture.debugElement.query(By.directive(InputSelectComponent)).componentInstance;
                    fixture.detectChanges();

                    compController.navigate(1);
                    expect(document.activeElement.innerHTML).toContain('>one<');

                    compController.navigate(1, document.activeElement);
                    expect(document.activeElement.innerHTML).toContain('>two<');

                    compController.navigate(1, document.activeElement);
                    expect(document.activeElement.innerHTML).toContain('>three<');

                    compController.navigate(1, document.activeElement);
                    expect(document.activeElement.innerHTML).toContain('>one<');

                    compController.navigate(-1, document.activeElement);
                    expect(document.activeElement.innerHTML).toContain('>three<');

                    compController.navigate(-1, document.activeElement);
                    expect(document.activeElement.innerHTML).toContain('>two<');
                });
        }));
    });

    describe('Multi Select', () => {
        let builder:TestComponentBuilder;

        beforeEachProviders(() => [InputSelectComponent]);
        beforeEach(inject([TestComponentBuilder], function (tcb:TestComponentBuilder) {
            builder = tcb;
        }));

        it('should create the component', inject([], () => {
            return builder.createAsync(MultiInputSelectComponentTestController)
                .then((fixture:ComponentFixture<any>) => {
                    let query = fixture.debugElement.query(By.directive(InputSelectComponent));
                    expect(query).toBeTruthy();
                    expect(query.componentInstance).toBeTruthy();

                    fixture.detectChanges();
                    expect(query.componentInstance.value).toBeFalsy();
                });
        }));

        it('should use the supplied template', inject([], () => {
            return builder.createAsync(MultiInputSelectComponentTestController)
                .then((fixture:ComponentFixture<any>) => {
                    let query = fixture.debugElement.query(By.directive(InputSelectComponent));
                    fixture.detectChanges();

                    expect(query.nativeElement.innerHTML).toContain('one with tacos');
                });
        }));

        it('get a proper title', inject([], () => {
            return builder.createAsync(MultiInputSelectComponentTestController)
                .then((fixture:ComponentFixture<any>) => {
                    let testController = fixture.componentInstance;
                    let compController = fixture.debugElement.query(By.directive(InputSelectComponent)).componentInstance;

                    fixture.detectChanges();
                    expect(compController.getTitle()).toBe('Select');

                    compController.value = [testController.options[0]];
                    fixture.detectChanges();
                    expect(compController.getTitle()).toBe('one');

                    compController.value = [testController.options[0], testController.options[1]];
                    fixture.detectChanges();
                    expect(compController.getTitle()).toContain('2');

                    compController.value = testController.options;
                    fixture.detectChanges();
                    expect(compController.getTitle()).toContain('All');
                });
        }));

        it('item clicked', inject([], () => {
            return builder.createAsync(MultiInputSelectComponentTestController)
                .then((fixture:ComponentFixture<any>) => {
                    let testController = fixture.componentInstance;
                    let compController = fixture.debugElement.query(By.directive(InputSelectComponent)).componentInstance;

                    fixture.detectChanges();
                    expect(compController.value).toBeFalsy();

                    compController.itemClicked(testController.options[1]);
                    fixture.detectChanges();
                    expect(compController.value).toContain(testController.options[1]);

                    compController.itemClicked(testController.options[2]);
                    fixture.detectChanges();
                    expect(compController.value).toContain(testController.options[1]);
                    expect(compController.value).toContain(testController.options[2]);

                    compController.itemClicked(testController.options[1]);
                    fixture.detectChanges();
                    expect(compController.value).toContain(testController.options[2]);
                });
        }));
    });
});

@Component({
    selector: 'test',
    template: `
        <sh-input-select [(ngModel)]="value1" [options]="options"></sh-input-select>
    `,
    directives: [InputSelectComponent]
})
class SingleInputSelectComponentTestController {
    options = [
        'one',
        'two',
        'three',
    ];
    value1 = this.options[0];
}

@Component({
    selector: 'test',
    template: `
        <sh-input-select [(ngModel)]="value1" [options]="options">
            <template sh-input-option let-option>{{option}} with salt</template>
        </sh-input-select>
    `,
    directives: [InputSelectComponent, InputOptionComponent]
})
class Single2InputSelectComponentTestController {
    options = [
        'one',
        'two',
        'three',
    ];
    value1 = this.options[0];
}

@Component({
    selector: 'test',
    template: `
        <sh-input-select [(ngModel)]="value1" [options]="options" [config]="config">
            <template sh-input-option let-option>{{option}} with tacos</template>
        </sh-input-select>
    `,
    directives: [InputSelectComponent, InputOptionComponent]
})
class MultiInputSelectComponentTestController {
    options = [
        'one',
        'two',
        'three',
    ];
    value1;
    config = new InputSelectConfig('multi');
}


text:
import gzip
import cPickle
import sys
import argparse

def main():
    arg_fmt = argparse.RawTextHelpFormatter
    parser = argparse.ArgumentParser(formatter_class=arg_fmt,
                                     description=main.__doc__)
    required = parser.add_argument_group('required arguments')
    required.add_argument(
        '-f', '--filename', required=True,
        help='select file name.'
    )
    args = parser.parse_args()
    with gzip.open('../data/histogram_data/' + args.filename + '.pkl.gz', 'rb') as gf:
        data = cPickle.load(gf)
    print(data)
    print(len(data[0]))

if __name__ == "__main__":
    main()


text:
module ManageIQ
  module API
    class BaseController
      module Hosts
        CREDENTIALS_ATTR = "credentials"
        AUTH_TYPE_ATTR = "auth_type"
        DEFAULT_AUTH_TYPE = "default"

        def edit_resource_hosts(type, id, data = {})
          credentials = data.delete(CREDENTIALS_ATTR)
          raise BadRequestError, "Cannot update non-credentials attributes of host resource" if data.any?
          resource_search(id, type, collection_class(:hosts)).tap do |host|
            all_credentials = Array.wrap(credentials).each_with_object({}) do |creds, hash|
              auth_type = creds.delete(AUTH_TYPE_ATTR) || DEFAULT_AUTH_TYPE
              creds.reverse_merge!(:userid => host.authentication_userid(auth_type))
              hash[auth_type.to_sym] = creds.symbolize_keys!
            end
            host.update_authentication(all_credentials) if all_credentials.present?
          end
        end
      end
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace App.Helpers.KeyboardHook
{
    /// <summary>
    /// The enumeration of possible modifiers.
    /// </summary>
    [Flags]
    public enum ModifierKeys : uint
    {
        Alt = 1,
        Control = 2,
        Shift = 4,
        Win = 8
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<article id="1292">
	<title>Computer-Assisted Design of Complex Organic Synthesis	</title>
	<author>Corey, E.J.Wipke, W.T.	</author>
	<text>
		  This article is concerned with the general theory of chemical synthesis and
		with the application of machine computation to the generation of chemical
		pathways for the synthesis of complicated organic molecules.  The basis for
		the approach which has been developed comes in large measure from the methods
		used by chemists in the solution of certain types of synthetic problems.
	</text>
</article>


text:
export type OfTypeFunc<T> = () => T;

class Maybe<T = unknown> {
  private readonly __value: T;

  /**
   * Private constructor. Use Maybe.of() instead.
   * @constructor
   */
  private constructor(val: T) {
    this.__value = val;
  }

  /**
   * Public constructor. Creates an instance of Maybe.
   * @param val {*} Object, string, number, or function (direct object access)
   * @example const exampleObj = {
   *      foo: 'bar',
   *      baz: [1,2,3]
   * };
   *
   * const maybe1 = Maybe.of(exampleObj);
   * const maybe2 = Maybe.of(() => exampleObj.baz.1);
   * @returns {Maybe} A Maybe monad
   */
  static of<T>(val: unknown | OfTypeFunc<T>): Maybe {
    try {
      return new Maybe(typeof val === 'function' ? val() : val);
    } catch (error) {
      return new Maybe(undefined);
    }
  }

  /**
   * Get the monad's value
   * @example const maybe1 = Maybe.of(123);
   * const maybe2 = Maybe.of(null);
   *
   * maybe1.join();   // 123
   * maybe2.join();   // null
   * @returns {*} Returns the value of the monad
   */
  join(): T {
    return this.__value;
  }

  /**
   * Determine whether the monad's value exists
   * @example const maybe1 = Maybe.of(123);
   * const maybe2 = Maybe.of(undefined);
   *
   * maybe1.isJust();    // true
   * maybe2.isJust();    // false
   * @returns {boolean} true if the value is defined,
   * false if the monad is null or undefined.
   */
  isJust(): boolean {
    return !this.isNothing();
  }

  /**
   * Determine whether the monad's value is null or undefined
   * @example const maybe1 = Maybe.of(null);
   * const maybe2 = Maybe.of(123);
   *
   * maybe1.isNothing();    // true
   * maybe2.isNothing()     // false
   * @returns {boolean} true if the value is null or
   * undefined, false if the value is defined.
   */
  isNothing(): boolean {
    return this.__value === null || this.__value === undefined;
  }

  /**
   * Chain to the end of a monad as the default value to return if the isNothing() is true
   * @param defaultValue {string} Return this value when
   * join() is called and isNothing() is true
   * @example const maybe1 = Maybe.of(null);
   *
   * maybe1.orElse('N/A');
   * maybe1.join();   // 'N/A'
   * @returns {Maybe} A monad containing the default value
   */
  orElse(defaultValue: unknown): Maybe {
    if (this.isNothing()) {
      return Maybe.of(defaultValue);
    }
    return this;
  }

  /**
   * Apply a transformation to the monad
   * @param transform {function} The transformation function to apply to the monad
   * @example Maybe.of(1).map(val => val + 1);
   * @returns {Maybe} A monad created from the result of the transformation
   */
  map(transform: (val: T) => T | Maybe<T>): Maybe {
    if (typeof transform !== 'function') throw new Error('transform must be a function');
    if (this.isNothing()) {
      return Maybe.of(undefined);
    }
    return Maybe.of(transform(this.join()));
  }

  /**
   * Chain together functions that return Maybe monads
   * @param chain {function} Function that is passed the value of the calling monad, and returns a monad.
   * @example function addOne (val) {
   *   return Maybe.of(val + 1);
   * }
   *
   * const three = Maybe.of(1)
   *  .chain(addOne)
   *  .chain(addOne)
   *  .join();
   * @returns {Maybe} A monad created from the result of the transformation
   */
  chain(chain: (val: T) => Maybe<T>): Maybe {
    if (typeof chain !== 'function') throw new Error('chain must be a function');
    return this.map(chain).join() as Maybe
  }
}

export default Maybe;


text:
/*
 * @author Rukmal Weerawarana
 *
 * @description Socket.io configuration file
 */

var AUTHORS = ['1062761833', '1234567890']; // <-- Change this to the Facebook ID's of the authors

function SocketConfig (server) {
	var io = require('socket.io').listen(server, { log: false });

	io.sockets.on('connection', function (socket) {
		socket.on('facebook-login-info', function (data) {
			var response;
			if (data.status != 'connected') {
				response = false;
			} else if (AUTHORS.indexOf(data.authResponse.userID) === -1){
				response = true;
			} else {
				response = true;
			}
			console.log(response);
			socket.emit('nodeblog-auth-response', response);
		});
	});
};

module.exports = SocketConfig;


text:
body
{
  margin: 0 0 0 0;
  padding: 20 20 20 20;
  width: 100%;
  height: 100%;
  color: #25354F;
  background-color: #E8E8E8;
  font-family: "Gill Sans MT", "Gill Sans", GillSans, sans-serif;
  font-size:20pt;
}

div.toolbar {
  position: fixed; z-index: 200;
  top: auto; bottom: 0; left: 0; right: 0;
  height: 1.2em; text-align: right;
  padding-left: 1em;
  padding-right: 1em;
  font-size: 60%;
  color: blue;
  background-color: rgb(240,240,240);
  border-top: solid 1px rgb(180,180,180);
}

div.toolbar span.copyright {
  color: black;
  margin-left: 0.5em;
}

div.initial_prompt {
  position: absolute;
  z-index: 1000;
  bottom: 1.2em;
  width: 100%;
  background-color: rgb(200,200,200);
  opacity: 0.35;
  background-color: rgba(200,200,200, 0.35);
  cursor: pointer;
}

div.initial_prompt p.help {
  text-align: center;
}

div.initial_prompt p.close {
  text-align: right;
  font-style: italic;
}

div.slidy_toc {
  position: absolute;
  z-index: 300;
  width: 60%;
  max-width: 30em;
  height: 30em;
  overflow: auto;
  top: auto;
  right: auto;
  left: 4em;
  bottom: 4em;
  padding: 1em;
  background: rgb(240,240,240);
  border-style: solid;
  border-width: 2px;
  font-size: 60%;
}

div.slidy_toc .toc_heading {
  text-align: center;
  width: 100%;
  margin: 0;
  margin-bottom: 1em;
  border-bottom-style: solid;
  border-bottom-color: rgb(180,180,180);
  border-bottom-width: 1px;
}

div.slide {
  z-index: 20;
  margin: 0 0 0 0;
  padding-top: 0;
  padding-bottom: 0;
  padding-left: 20px;
  padding-right: 20px;
  border-width: 0;
  clear: both;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  line-height: 120%;
  background-color: #D7DADB;
}

div.background {
  display: none;
}

div.handout {
  margin-left: 20px;
  margin-right: 20px;
}

div.slide.titlepage {
  text-align: center;
}

div.slide.titlepage h1 {
  padding-top: 10%;
  margin-right: 0;
}

div.slide h1 {
	color: #FC4349;
  padding-left: 0;
  padding-right: 20pt;
  padding-top: 4pt;
  padding-bottom: 4pt;
  margin-top: 0;
  margin-left: 0;
  margin-right: 60pt;
  margin-bottom: 0.5em;
  display: block;
  font-size: 160%;
  line-height: 1.2em;
  xbackground: transparent;
  background-color: #25354F;
	color: #FC4349;

  padding-left: 10px;
		height: 110px;
   background-image: url('CSClogo.jpg');
     background-repeat: no-repeat;
    background-attachment: fixed;
    background-position: 80% 1%;
}

@media screen and (max-device-width: 1024px)
{
  div.slide { font-size: 100%; }
}

@media screen and (max-device-width: 800px)
{
  div.slide { font-size: 200%; }
  div.slidy_toc {
    top: 1em;
    left: 1em;
    right: auto;
    width: 80%;
    font-size: 180%;
  }
}

div.toc-heading {
  width: 100%;
  border-bottom: solid 1px rgb(180,180,180);
  margin-bottom: 1em;
  text-align: center;
}

img {
  image-rendering: optimize-quality;
}

pre {
 font-size: 80%;
 font-weight: bold;
 line-height: 120%;
 padding-top: 0.2em;
 padding-bottom: 0.2em;
 padding-left: 1em;
 padding-right: 1em;
 border-style: solid;
 border-left-width: 1em;
 border-top-width: thin;
 border-right-width: thin;
 border-bottom-width: thin;
 border-color: #95ABD0;
 color: #00428C;
 background-color: #E4E5E7;
}

li pre { margin-left: 0; }

blockquote { font-style: italic }

img { background-color: transparent }

p.copyright { font-size: smaller }

.center { text-align: center }
.footnote { font-size: smaller; margin-left: 2em; }

a img { border-width: 0; border-style: none }

a:visited { color: navy }
a:link { color: navy }
a:hover { color: red; text-decoration: underline }
a:active { color: red; text-decoration: underline }

a {text-decoration: none}
.toolbar a:link {color: blue}
.toolbar a:visited {color: blue}
.toolbar a:active {color: red}
.toolbar a:hover {color: red}

ul { list-style-type: square; }
ul ul { list-style-type: disc; }
ul ul ul { list-style-type: circle; }
ul ul ul ul { list-style-type: disc; }
li { margin-left: 0.5em; margin-top: 0.5em; }
li li { font-size: 85%; font-style: italic }
li li li { font-size: 85%; font-style: normal }

div dt
{
  margin-left: 0;
  margin-top: 1em;
  margin-bottom: 0.5em;
  font-weight: bold;
}
div dd
{
  margin-left: 2em;
  margin-bottom: 0.5em;
}

p,pre,ul,ol,blockquote,h2,h3,h4,h5,h6,dl,table {
  margin-left: 1em;
  margin-right: 1em;
}

p.subhead { font-weight: bold; margin-top: 2em; }

.smaller { font-size: smaller }
.bigger { font-size: 130% }

td,th { padding: 0.2em }

ul {
  margin: 0.5em 1.5em 0.5em 1.5em;
  padding: 0;
}

ol {
  margin: 0.5em 1.5em 0.5em 1.5em;
  padding: 0;
}

ul { list-style-type: square; }
ul ul { list-style-type: disc; }
ul ul ul { list-style-type: circle; }
ul ul ul ul { list-style-type: disc; }

ul li {
  list-style: square;
  margin: 0.1em 0em 0.6em 0;
  padding: 0 0 0 0;
  line-height: 140%;
}

ol li {
  margin: 0.1em 0em 0.6em 1.5em;
  padding: 0 0 0 0px;
  line-height: 140%;
  list-style-type: decimal;
}

li ul li {
  font-size: 85%;
  font-style: italic;
  list-style-type: disc;
  background: transparent;
  padding: 0 0 0 0;
}
li li ul li {
  font-size: 85%;
  font-style: normal;
  list-style-type: circle;
  background: transparent;
  padding: 0 0 0 0;
}
li li li ul li {
  list-style-type: disc;
  background: transparent;
  padding: 0 0 0 0;
}

li ol li {
  list-style-type: decimal;
}

li li ol li {
  list-style-type: decimal;
}

/*
 setting class="outline on ol or ul makes it behave as an
 ouline list where blocklevel content in li elements is
 hidden by default and can be expanded or collapsed with
 mouse click. Set class="expand" on li to override default
*/

ol.outline li:hover { cursor: pointer }
ol.outline li.nofold:hover { cursor: default }

ul.outline li:hover { cursor: pointer }
ul.outline li.nofold:hover { cursor: default }

ol.outline { list-style:decimal; }
ol.outline ol { list-style-type:lower-alpha }

ol.outline li.nofold {
  padding: 0 0 0 20px;
  background: transparent url(../graphics/nofold-dim.gif) no-repeat 0px 0.5em;
}
ol.outline li.unfolded {
  padding: 0 0 0 20px;
  background: transparent url(../graphics/fold-dim.gif) no-repeat 0px 0.5em;
}
ol.outline li.folded {
  padding: 0 0 0 20px;
  background: transparent url(../graphics/unfold-dim.gif) no-repeat 0px 0.5em;
}
ol.outline li.unfolded:hover {
  padding: 0 0 0 20px;
  background: transparent url(../graphics/fold.gif) no-repeat 0px 0.5em;
}
ol.outline li.folded:hover {
  padding: 0 0 0 20px;
  background: transparent url(../graphics/unfold.gif) no-repeat 0px 0.5em;
}

ul.outline li.nofold {
  padding: 0 0 0 20px;
  background: transparent url(../graphics/nofold-dim.gif) no-repeat 0px 0.5em;
}
ul.outline li.unfolded {
  padding: 0 0 0 20px;
  background: transparent url(../graphics/fold-dim.gif) no-repeat 0px 0.5em;
}
ul.outline li.folded {
  padding: 0 0 0 20px;
  background: transparent url(../graphics/unfold-dim.gif) no-repeat 0px 0.5em;
}
ul.outline li.unfolded:hover {
  padding: 0 0 0 20px;
  background: transparent url(../graphics/fold.gif) no-repeat 0px 0.5em;
}
ul.outline li.folded:hover {
  padding: 0 0 0 20px;
  background: transparent url(../graphics/unfold.gif) no-repeat 0px 0.5em;
}

tr.header {
    background-color: black;
    color: white
}
tr.even {
    background-color: #CCC;
}
caption{
    color: red
}
table {border: 1px solid black;
padding-top: 7px;
padding-bottom: 14px;

-moz-box-shadow: 10px 10px 5px #888;
-webkit-box-shadow: 10px 10px 5px #888;
box-shadow: 10px 10px 5px #888;
}

/* for slides with class "title" in table of contents */
a.titleslide { font-weight: bold; font-style: italic }

/*
 hide images for work around for save as bug
 where browsers fail to save images used by CSS
*/
img.hidden { display: none; visibility: hidden }
div.initial_prompt { display: none; visibility: hidden }

  div.slide {
     visibility: visible;
     position: inherit;
  }
  div.handout {
     border-top-style: solid;
     border-top-width: thin;
     border-top-color: black;
  }

@media screen {
  .hidden { display: none; visibility: visible }

  div.slide.hidden { display: block; visibility: visible }
  div.handout.hidden { display: block; visibility: visible }
  div.background { display: none; visibility: hidden }
  body.single_slide div.initial_prompt { display: block; visibility: visible }
  body.single_slide div.background { display: block; visibility: visible }
  body.single_slide div.background.hidden { display: none; visibility: hidden }
  body.single_slide .invisible { visibility: hidden }
  body.single_slide .hidden { display: none; visibility: hidden }
  body.single_slide div.slide { position: absolute }
  body.single_slide div.handout { display: none; visibility: hidden }
}

@media print {
  .hidden { display: block; visibility: visible }

  div.slide pre { font-size: 60%; padding-left: 0.5em; }
  div.toolbar { display: none; visibility: hidden; }
  div.slidy_toc { display: none; visibility: hidden; }
  div.background { display: none; visibility: hidden; }
  div.slide { page-break-before: always }
  /* :first-child isn't reliable for print media */
  div.slide.first-slide { page-break-before: avoid }
}


text:
This package provides the [rkt-run](doc/rkt-run.md) command, which
is intended to be installed setuid root, to enabled unprivileged users
to run containers using `rkt`, in a controlled fashion.

There are also `rkt-run-helper` and `rkt-run-slave` commands - see below.

`rkt-run` provides the following features:

* enable unprivileged users to run rkt

* enable concurrent use of pods

* preservation of working directory of host within container

The system-wide configuration enables the system administrator to
control the following aspects of the `rkt run` command line:

* aliases for images and their executables

* volumes to be mounted

* automatic prefix re-writing of image names

* general, run, and image options

## Basic Usage

All `rkt run` options are controlled by the config file,
[/etc/rktrunner.toml](doc/rktrunner.toml.md), which should be carefully setup
by the local sysadmin.

Example use:
```
$ rkt-run -i -v qiime_
```

The `-v` option prints the full `rkt run` command which is
being run, as follows:
```
# /usr/bin/rkt --insecure-options=image run --interactive --net=host --set-env=HOME=/home/guestsi --volume volume-config,kind=empty,uid=511,gid=511 --volume volume-data,kind=empty,uid=511,gid=511 --volume home,kind=host,source=/home/guestsi quay.io/biocontainers/qiime:1.9.1--py27_0 --mount volume=home,target=/home/guestsi --user=511 --group=511 --exec sh
```

Note that the options are taken from the [config file](doc/rktrunner.toml.md), which in this case looks like this:
```
rkt = "/usr/bin/rkt"
default-interactive-cmd = "sh"

[options]
general = ["--insecure-options=image"]
run = ["--net=host", "--set-env=HOME=/home/{{.Username}}"]
image = ["--user={{.Uid}}", "--group={{.Gid}}"]

[volume.home]
volume = "kind=host,source={{.HomeDir}}"
mount = "target=/home/{{.Username}}"

[volume.volume-config]
volume = "kind=empty,uid={{.Uid}},gid={{.Gid}}"

[volume.volume-data]
volume = "kind=empty,uid={{.Uid}},gid={{.Gid}}"

[alias.qiime_]
image = "quay.io/biocontainers/qiime:1.9.1--py27_0"
```

For further information, see the manpages for [rkt-run](doc/rkt-run.md)
and [rktrunner.toml](doc/rktrunner.toml.md)

## Concurrent use of pods

The configuration option `worker-pods` may be used to enable concurrent use of pods.  This is an optimisation, useful when large numbers of concurrent application processes are required.  For each user and image, a single pod may be shared across all the application instances, by means of `rkt enter`.

When using `worker-pods`, it is important to remove idle workers using `rktrunner-gc`, which should be run regularly as root.

Before starting many application instances in parallel, it is necessary to prime the pump, that is, create an initial worker.  This may easily be done using `rkt-run --prepare`, which simply creates a worker for the image in question, and exits without running the application.

Note that this feature is unlikely to be useful without the following `rkt` issues being addressed.

* [fly: enter should honor uid/gid/supp-gid #3392](https://github.com/rkt/rkt/issues/3392)

* [fly: enter should honor env variables #3393](https://github.com/rkt/rkt/issues/3393)

These are expected to be fixed in rkt 1.28.0.

## rkt-run-helper

`rkt-run-helper` is a simple wrapper, which invokes `rkt-run` passing
as first argument the name it was invoked with, along with all the
other arguments.

The intended use is to have a directory on the system containing links
to `rkt-run-helper`, with names `ruby`, `julia`, etc.  Then, if this
directory is on the path, scripts starting with the standard shebang
line as below will use `rkt-run` to run the containerized interpreter.
This relies on aliases for these programs being defined in [rktrunner.toml](doc/rktrunner.toml.md).

```
#!/usr/bin/env ruby
puts 'Hello World from Ruby version ' + RUBY_VERSION
```

## rkt-run-slave

`rkt-run-slave` is another wrapper, which runs within the container.
It optionally changes to the working directory as on the host.


text:
#ifndef __SYSTEM_M451SERIES_H__
#define __SYSTEM_M451SERIES_H__

#ifdef __cplusplus
extern "C" {
#endif

#include <stdint.h>

/*---------------------------------------------------------------------------------------------------------*/
/* Macro Definition                                                                                */
/*---------------------------------------------------------------------------------------------------------*/
#ifndef DEBUG_PORT
# define DEBUG_PORT      UART0       /*!< Select Debug Port which is used for retarget.c to output debug message to UART */
#endif

/*----------------------------------------------------------------------------
  Define clocks
 *----------------------------------------------------------------------------*/

#define __HSI       (12000000UL)    /*!< PLL default output is 72MHz */
#define __HXT       (12000000UL)    /*!< External Crystal Clock Frequency     */
#define __LXT       (32768UL)       /*!< External Crystal Clock Frequency 32.768KHz */
#define __HIRC      (22118400UL)    /*!< Internal 22M RC Oscillator Frequency */
#define __LIRC      (10000UL)       /*!< Internal 10K RC Oscillator Frequency */
#define __SYS_OSC_CLK     (    ___HSI)    /* Main oscillator frequency        */

#define __SYSTEM_CLOCK    (1*__HXT)

extern uint32_t SystemCoreClock;     /*!< System Clock Frequency (Core Clock)  */
extern uint32_t CyclesPerUs;         /*!< Cycles per micro second              */
extern uint32_t PllClock;            /*!< PLL Output Clock Frequency           */

/**
 * Initialize the system
 *
 * @param  None
 * @return None
 *
 * @brief  Setup the microcontroller system.
 *         Initialize the System and update the SystemCoreClock variable.
 */
extern void SystemInit(void);

/**
 * Update SystemCoreClock variable
 *
 * @param  None
 * @return None
 *
 * @brief  Updates the SystemCoreClock with current core Clock
 *         retrieved from cpu registers.
 */
extern void SystemCoreClockUpdate(void);

#ifdef __cplusplus
}
#endif

#endif /* __SYSTEM_M451SERIES_H__ */
/*** (C) COPYRIGHT 2013~2015 Nuvoton Technology Corp. ***/


text:
#include "webrtc/base/sha1digest.h"

namespace rtc {

size_t Sha1Digest::Size() const {
  return kSize;
}

void Sha1Digest::Update(const void* buf, size_t len) {
  SHA1Update(&ctx_, static_cast<const uint8*>(buf), len);
}

size_t Sha1Digest::Finish(void* buf, size_t len) {
  if (len < kSize) {
    return 0;
  }
  SHA1Final(&ctx_, static_cast<uint8*>(buf));
  SHA1Init(&ctx_);  // Reset for next use.
  return kSize;
}

}  // namespace rtc


text:
package domain

func setGORMShowSQL()  {
	Gdb.Debug()
	Gdb.LogMode(true)
}


text:
/**
 * Created by Anton.Koptelov on 06.12.2016.
 */
var webdriver = require('selenium-webdriver'),
    chrome = require('selenium-webdriver/chrome'),
    by = webdriver.By,
    test = require('selenium-webdriver/testing'),
    assert = require('assert');

test.describe('Task 11. Make the scenario of registration of the user', function () {
    var driver,
        something = (Math.random().toString(36).substring(7) + "@superMail.ru"), // элегантное решение +) берем число и переводим в 36 разрядное, потом убираем первые 7 символов, ну чтоб покороче
        newUser = {
            taxId: '1234567890',
            company: 'Selen',
            firstName: 'Anton',
            lastName: 'Koptelov',
            address1: 'г. Самара ул. Ленина',
            address2: 'allWorld',
            postCode: '443100',
            city: 'Samara',
            country: 'Albania',
            // country: 'Russian Federation',
            email: something,
            // + "@superMail.ru",
            phone: '+7987100500',
            password: 'password',
            subscribe: false
        };

    test.before(function () {
        driver = new webdriver.Builder()
            .forBrowser('chrome')
            .build();
    });
    test.after(function () {
        driver.sleep('2000');  //Что бы успеть заметить конечное состояние
        driver.quit();
    });

    test.it('Открыть главную страницу', function () {
        driver.get('http://localhost/litecart/');
        driver.findElement(by.css('div#logotype-wrapper'));
    });

    test.it('Открыть страницу регистрации', function () {
        driver.findElement(by.css('form[name="login_form"] a')).click();
        driver.findElement(by.css('button[name="create_account"]'));
    });

    test.it('Заполнить поля данными', function () {
        var form = driver.findElement(by.name('customer_form')),
            createButton = driver.findElement(by.css('button[name="create_account"]'));

        console.log('Регистрируем любителя уточек: ');
        console.log(newUser);
        Promise.all([
            form.findElement(by.name('tax_id')).sendKeys(newUser.taxId),
            form.findElement(by.name('company')).sendKeys(newUser.company),
            form.findElement(by.name('firstname')).sendKeys(newUser.firstName),
            form.findElement(by.name('lastname')).sendKeys(newUser.lastName),
            form.findElement(by.name('address1')).sendKeys(newUser.address1),
            form.findElement(by.name('address2')).sendKeys(newUser.address2),
            form.findElement(by.name('postcode')).sendKeys(newUser.postCode),
            form.findElement(by.name('city')).sendKeys(newUser.city),
            form.findElement(by.name('country_code')).findElement(by.xpath('option[contains(text(),"' + newUser.country + '")]')).click(),
            form.findElement(by.name('email')).sendKeys(newUser.email),
            form.findElement(by.name('phone')).sendKeys(newUser.phone),
            form.findElement(by.name('password')).sendKeys(newUser.password),
            form.findElement(by.name('confirmed_password')).sendKeys(newUser.password),
            form.findElement(by.name('newsletter')).isSelected().then(function (value) {
                if (value != newUser.subscribe) { el_subscribe.click() }
            })
        ]).then(function () {
            driver.sleep('5000'); //для отладки
            createButton.click();
            driver.findElement(by.css('div#notices div[class="notice success"]'));
            console.log('Пользователь успешно создан')
        })
    });

    test.it('Выйти из пользователя', function () {
        driver.findElement(by.xpath('//div[@id="box-account"]//a[contains(text(),"Logout")]')).click();
        driver.findElement(by.css('div#notices div[class="notice success"]'))
    });
    test.it('Повторный вход для проверки', function (done) {
        var loginPanel = driver.findElement(by.name('login_form'));
        loginPanel.findElement(by.name('email')).sendKeys(newUser.email);
        loginPanel.findElement(by.name('password')).sendKeys(newUser.password);
        loginPanel.findElement(by.name('login')).click();
        driver.findElement(by.css('div#notices div[class="notice success"]')).getText()
            .then(function (greeting) {
                return greeting.search(newUser.firstName + ' ' + newUser.lastName) != -1 ? done() : done("Пользователя назвали другим именем");
            });
    });
})


text:
exclude_rule 'MD001'

# MD002 - First header should be a h1 header.
exclude_rule 'MD002'

# MD003 - Header Style.
rule 'MD003', :style => :atx

# MD004 - Unordered list style.
rule 'MD004', :style => :consistent

# MD005 - Inconsistent indentation for list items at the same level.
rule 'MD005'

# MD006 - Bullets starting at beginning of line.
rule 'MD006'

# MD007 - Unordered list indentation.
rule 'MD007', :indent => 4

# MD009 - Trailing spaces.
rule 'MD009', :br_spaces => 0

# MD010 - Hard tabs.
exclude_rule 'MD010'

# MD012 - Multiple consecutive blank lines.
rule 'MD012'

# MD013 - Line length.
exclude_rule 'MD013'

# MD014 - Dollar signs used before commands without showing output.
exclude_rule 'MD014'

# MD018 - No space after hash on atx style header.
rule 'MD018'

# MD019 - Multiple spaces after hash on atx style header.
rule 'MD019'

# MD022 - Headers should be surrounded by blank lines.
rule 'MD022'

# MD023 - Headers must start at the beginning of the line.
rule 'MD023'

# MD024 - Multiple headers with the same content.
exclude_rule 'MD024'

# MD025 - Multiple top level headers in the same document.
rule 'MD025'

# MD026 - Trailing punctuation in header.
exclude_rule 'MD026'

# MD027 - Multiple spaces after blockquote symbol.
rule 'MD027'

# MD028 - Blank line inside blockquote.
rule 'MD028'

# MD029 - Ordered list item prefix.
exclude_rule 'MD029'

# MD030 - Spaces after list markers.
rule 'MD030', :ul_single => 1, :ol_single => 1, :ul_multi => 1, :ol_multi => 1

# MD031 - Fenced code blocks should be surrounded by blank lines.
rule 'MD031'

# MD032 - Lists should be surrounded by blank lines.
rule 'MD032'

# MD033 - Inline HTML.
exclude_rule 'MD033'

# MD035 - Horizontal rule style.
rule 'MD035', :style => '---'

# MD036 - Emphasis used instead of a header.
exclude_rule 'MD036'

# MD037 - Spaces inside emphasis markers.
rule 'MD037'

# MD038 - Spaces inside code span elements.
rule 'MD038'

# MD039 - Spaces inside link text.
exclude_rule 'MD039'

# MD040 - Fenced code blocks specified language.
rule 'MD040'

# MD041 - First line in file should be a top level header.
exclude_rule 'MD041'


text:
using System;
using System.Runtime.InteropServices;
using Vestris.ResourceLib;
using System.IO;
using System.ComponentModel;

namespace InstallerLib
{
    /// <summary>
    /// Kernel32 interop for resource functions
    /// </summary>
    public abstract class ResourceUpdate
    {
        /// <summary>
        /// Returns a handle to either a language-neutral portable executable file (LN file) or a
        /// language-specific resource file (.mui file) that can be used by the UpdateResource function
        /// to add, delete, or replace resources in a binary module.
        /// </summary>
        /// <param name="pFileName">Pointer to a null-terminated string that specifies the binary file in which to update resources.</param>
        /// <param name="bDeleteExistingResources">Specifies whether to delete the pFileName parameter's existing resources.</param>
        /// <returns>If the function succeeds, the return value is a handle that can be used by the UpdateResource and EndUpdateResource functions.</returns>
        [DllImport("kernel32.dll", EntryPoint = "BeginUpdateResourceW", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        internal static extern IntPtr BeginUpdateResource(string pFileName, bool bDeleteExistingResources);

        /// <summary>
        /// Adds, deletes, or replaces a resource in a portable executable (PE) file.
        /// There are some restrictions on resource updates in files that contain Resource Configuration (RC Config) data:
        /// language-neutral (LN) files and language-specific resource (.mui) files.
        /// </summary>
        /// <param name="hUpdate">A module handle returned by the BeginUpdateResource function, referencing the file to be updated.</param>
        /// <param name="lpType">Pointer to a null-terminated string specifying the resource type to be updated.</param>
        /// <param name="lpName">Pointer to a null-terminated string specifying the name of the resource to be updated.</param>
        /// <param name="wLanguage">Specifies the language identifier of the resource to be updated.</param>
        /// <param name="lpData">Pointer to the resource data to be inserted into the file indicated by hUpdate.</param>
        /// <param name="cbData">Specifies the size, in bytes, of the resource data at lpData.</param>
        /// <returns>Returns TRUE if successful or FALSE otherwise.</returns>
        [DllImport("kernel32.dll", EntryPoint = "UpdateResourceW", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        internal static extern bool UpdateResource(IntPtr hUpdate, IntPtr lpType, IntPtr lpName, UInt16 wLanguage, byte[] lpData, UInt32 cbData);

        /// <summary>
        /// Commits or discards changes made prior to a call to UpdateResource.
        /// </summary>
        /// <param name="hUpdate">A module handle returned by the BeginUpdateResource function, and used by UpdateResource, referencing the file to be updated.</param>
        /// <param name="fDiscard">Specifies whether to write the resource updates to the file. If this parameter is TRUE, no changes are made. If it is FALSE, the changes are made: the resource updates will take effect.</param>
        /// <returns>Returns TRUE if the function succeeds; FALSE otherwise.</returns>
        [DllImport("kernel32.dll", EntryPoint = "EndUpdateResourceW", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
        internal static extern bool EndUpdateResource(IntPtr hUpdate, bool fDiscard);

        internal static void WriteFile(
            IntPtr h,
            ResourceId resourceType,
            ResourceId resourceName,
            UInt16 resourceLanguage,
            string input)
        {
            using (FileStream binaryStream = new FileStream(input, FileMode.Open, FileAccess.Read))
            {
                byte[] data = null;

                try
                {
                    data = new byte[binaryStream.Length];
                    binaryStream.Read(data, 0, (int)binaryStream.Length);
                }
                catch (Exception ex)
                {
                    throw new Exception(string.Format("Error reading {0}: {1}", input, ex.Message),
                        ex);
                }

                Write(h, resourceType, resourceName, resourceLanguage, data);
            }
        }

        internal static void Write(
            IntPtr h,
            ResourceId resourceType,
            ResourceId resourceName,
            UInt16 resourceLanguage,
            byte[] buffer)
        {
            try
            {
                if (!UpdateResource(h, resourceType.Id, resourceName.Id, resourceLanguage, buffer, (uint) buffer.Length))
                    throw new Win32Exception(Marshal.GetLastWin32Error());
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Error writing {0}: {1}", resourceName, ex.Message),
                    ex);
            }
        }
    }
}


text:
using System.Reflection;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("HealthMonitoring.Integration.PushClient")]
[assembly: AssemblyDescription("HealthMonitoring push monitor type integration client")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Wonga")]
[assembly: AssemblyProduct("HealthMonitoring.Integration.PushClient")]
[assembly: AssemblyCopyright("Copyright © Wonga")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("83b5cdac-0057-4bfe-923c-c3f6ed6d1e7f")]


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">AndroidTestHarness</string>
</resources>


text:
/*
 *  Duktape 0.10.0 reused a va_list argument when pushing a formatted string
 *  and the initial buffer size was not enough.  This bug testcase tries to
 *  trigger that issue.  Unfortunately it is not triggered with every compiler.
 *
 *  Reported by Andreas Oman.
 */

/*===
about to push, strlen(fmt)=256
push done
result: 1234523456123452345612345234561234523456xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
===*/

#define  CHARS40  "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

void test(duk_context *ctx) {
	const char *fmt =
	        "%d%d%d%d%d%d%d%d"
	        CHARS40
	        CHARS40
	        CHARS40
	        CHARS40
	        CHARS40
	        CHARS40;

	/* The bug only manifests when the initial vsnprintf() attempt
	 * runs out of buffer space.  The initial buffer guess is
	 * min(256, strlen(fmt) + 16).
	 *
	 * Here the format string is 16 + 240 bytes, so the guess will
	 * be 256 bytes.  The formatted string will be 8x5 + 240 bytes
	 * = 280 bytes, so a retry happens.
	 */
	printf("about to push, strlen(fmt)=%d\n", (int) strlen(fmt));
	fflush(stdout);

	duk_push_sprintf(ctx,
	                 fmt,
	                 12345, 23456, 12345, 23456,
	                 12345, 23456, 12345, 23456);

	printf("push done\n");
	fflush(stdout);

	printf("result: %s\n", duk_get_string(ctx, -1));
	fflush(stdout);
}


text:
{
  schema: :component,
  table: :service_accociations,
  columns: {
    relationship: { type: :varchar, size: 100 },
    service_antecendent_id: {
      type: :bigint,
      foreign_key_rel_type: :component,
      on_delete: :cascade,
      on_update: :cascade
    },
    service_dependent_id: {
      type: :bigint,
      foreign_key_rel_type: :component,
      on_delete: :cascade,
      on_update: :cascade
    }
  },
  virtual_columns: {
    dependent_parent_services: {
      type: :json,
      hidden: true,
      remote_dependencies:[
        {
          model_name: :component,
          join_type: :inner,
          convert: true,
          alias: :service_instance,
          join_cond: { id: :service_dependent_id },
          cols: [:id, :display_name, :specific_type]
        }
      ]
    }
  }
}


text:
/* -*- Mode: js2; indent-tabs-mode: nil; tab-width: 4; js2-indent-offset: 4; js2-basic-offset: 4; -*-
 * vim: set ts=4 sw=4 et tw=99 ft=js:
 */
import * as escodegen from "../external-deps/escodegen/escodegen-es6";

import * as debug from "./debug";

import { ReplaceUnaryVoid } from "./passes/replace-unary-void";

const passes = [ReplaceUnaryVoid];

export function run(tree) {
    passes.forEach(passType => {
        let pass = new passType();
        tree = pass.visit(tree);
        debug.log(2, `after: ${passType.name}`);
        debug.log(2, () => escodegen.generate(tree));
    });
    return tree;
}


text:
class Fastly::CreateDomain
  include Fastly::Request

  ACCEPTED_PARAMETERS = %w(name comment).freeze

  request_method :post
  request_path { |r| "/service/#{r.service_id}/version/#{r.number}/domain" }
  request_params(&:accepted_attributes)

  parameter :service_id
  parameter :number
  parameter :attributes

  def mock
    find!(:service_versions, service_id, number.to_i)
    name = accepted_attributes.fetch('name')
    domain = accepted_attributes.merge('version' => number, 'service_id' => service_id)
    cistern.data[:domains][service_id][number.to_i][name] = domain

    mock_response(domain)
  end
end


text:
/***************************************************************************/
/*																		   */
/*	  MODULE:	measurementMgrSM.h										   */
/*    PURPOSE:	measurement Manager module State Machine header file       */
/*																		   */
/***************************************************************************/

#ifndef __MEASUREMENTMGRSM_H__
#define __MEASUREMENTMGRSM_H__

#include "fsm.h"

/** State machine states */
typedef enum
{
	MEASUREMENTMGR_STATE_IDLE					= 0,
    MEASUREMENTMGR_STATE_PROCESSING_REQUEST		= 1,
    MEASUREMENTMGR_STATE_WAITING_FOR_SCR		= 2,
    MEASUREMENTMGR_STATE_MEASURING				= 3,
	MEASUREMENTMGR_STATE_LAST					= 4
} measurementMgrSM_States;

/** State machine events */
typedef enum
{
	MEASUREMENTMGR_EVENT_CONNECTED				= 0,
	MEASUREMENTMGR_EVENT_DISCONNECTED			= 1,
	MEASUREMENTMGR_EVENT_ENABLE					= 2,
	MEASUREMENTMGR_EVENT_DISABLE				= 3,
    MEASUREMENTMGR_EVENT_FRAME_RECV				= 4,
    MEASUREMENTMGR_EVENT_SEND_REPORT			= 5,
	MEASUREMENTMGR_EVENT_REQUEST_SCR			= 6,
    MEASUREMENTMGR_EVENT_SCR_WAIT				= 7,
    MEASUREMENTMGR_EVENT_SCR_RUN				= 8,
    MEASUREMENTMGR_EVENT_ABORT					= 9,
    MEASUREMENTMGR_EVENT_COMPLETE				= 10,
    MEASUREMENTMGR_EVENT_FW_RESET				= 11,
	MEASUREMENTMGR_EVENT_LAST					= 12
} measurementMgrSM_Events;

#define MEASUREMENTMGR_NUM_STATES		MEASUREMENTMGR_STATE_LAST
#define MEASUREMENTMGR_NUM_EVENTS		MEASUREMENTMGR_EVENT_LAST

TI_STATUS measurementMgrSM_config(TI_HANDLE hMeasurementMgr);

TI_STATUS measurementMgrSM_event(TI_UINT8 * currentState, TI_UINT8 event, TI_HANDLE hMeasurementMgr);

#endif /* __MEASUREMENTMGRSM_H__*/


text:
<?php
namespace Nemesis\LaravelRest\Transformers;

use Illuminate\Database\Eloquent\Model;

/**
 * Example
 *
 * Class ExampleTransformer
 * @package App\Transformers
 *
 * @author Bondarenko Kirill <bondarenko.kirill@gmail.com
 */
class ExampleTransformer extends Transformer
{

    /**
     * Преобразование одной записи из коллекции
     *
     * @param Model $item
     * @param array $relations
     * @return array
     */
    public function transform($item, $relations = [])
    {
        $data = [
            'id' => $item->id,
            'name' => $item->name,
            'description' => $item->description,
        ];

        $this->appendRelations($data, $item, $relations);

        return $data;
    }
}


text:
package com.pedro.encoder.input.gl;

/**
 * Created by pedro on 21/9/21.
 */
public enum FilterAction {
  SET, SET_INDEX, ADD, ADD_INDEX, CLEAR, REMOVE, REMOVE_INDEX
}


text:
module Spree
  class ZipCode < ActiveRecord::Base

    validates :name, :presence => true

    def <=>(other)
      name <=> other.name
    end

    def to_s
      name
    end
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Nat. Arr. Brit. Pl. (London) 1: 432 (1821)

#### Original name
Cetraria pinastri f. pinastri

### Remarks
null


text:
package org.apache.mina.example.chat;

import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;

/**
 * (Entry point) Chat server which uses Spring and the serverContext.xml
 * file to set up MINA and the server handler.
 *
 * @author Apache MINA Project
 */
public class SpringMain {

    public static void main(String[] args) throws Exception {
        if (System.getProperty("com.sun.management.jmxremote") != null) {
            System.out.println("JMX enabled.");
        } else {
            System.out
                    .println("JMX disabled. Please set the "
                            + "'com.sun.management.jmxremote' system property to enable JMX.");
        }
        getApplicationContext();
        System.out.println("Listening ...");
    }

    public static ConfigurableApplicationContext getApplicationContext() {
        return new ClassPathXmlApplicationContext("org/apache/mina/example/chat/serverContext.xml");
    }
}


text:
#include <string.h>
#include <uuid/uuid.h>
#include <string>

#include "aossl/uuid/include/uuid_interface.h"
#include "aossl/core/include/buffers.h"

#ifndef AOSSL_UUID_INCLUDE_UUID_ADMIN_H_
#define AOSSL_UUID_INCLUDE_UUID_ADMIN_H_

namespace AOSSL {

// UUID Admin

// The UUID Admin is in charge of generating any Universally Unique
// ID's that are required throughout program execution
class UuidAdmin: public UuidInterface {
 public:
  UuidAdmin() {}
  ~UuidAdmin() {}
  //! Generate a new UUID and allocate memory for it.

  //! The method will generate on the means of generation present on your
  //! system.  In some cases, this may result in UUID's being generated that
  //! pose a security risk.  In this case, that fact will be clearly called out
  //! in the logs, and it is recommended that production systems are
  //! tested to ensure that UUID's are generated in a safe manner
  StringBuffer* generate();
  //! Generate a new UUID in the pre-existing string buffer.

  //! The method will generate on the means of generation present on your
  //! system.  In some cases, this may result in UUID's being generated that
  //! pose a security risk.  In this case, that fact will be clearly called out
  //! in the logs, and it is recommended that production systems are
  //! tested to ensure that UUID's are generated in a safe manner
  void generate(StringBuffer& buf);
};

}  // namespace AOSSL

#endif  // AOSSL_UUID_INCLUDE_UUID_ADMIN_H_


text:
#include "defs.h"
#include "gdbcore.h"
#include "gdbcmd.h"
#include "gdbthread.h"
#include "btrace.h"
#include "py-record.h"
#include "py-record-btrace.h"
#include "record-btrace.h"
#include "disasm.h"

#if defined (IS_PY3K)

#define BTPY_PYSLICE(x) (x)

#else

#define BTPY_PYSLICE(x) ((PySliceObject *) x)

#endif

/* Python object for btrace record lists.  */

typedef struct {
  PyObject_HEAD

  /* The thread this list belongs to.  */
  thread_info *thread;

  /* The first index being part of this list.  */
  Py_ssize_t first;

  /* The last index begin part of this list.  */
  Py_ssize_t last;

  /* Stride size.  */
  Py_ssize_t step;

  /* Either &BTPY_CALL_TYPE or &RECPY_INSN_TYPE.  */
  PyTypeObject* element_type;
} btpy_list_object;

/* Python type for btrace lists.  */

static PyTypeObject btpy_list_type = {
  PyVarObject_HEAD_INIT (NULL, 0)
};

/* Returns either a btrace_insn for the given Python gdb.RecordInstruction
   object or sets an appropriate Python exception and returns NULL.  */

static const btrace_insn *
btrace_insn_from_recpy_insn (const PyObject * const pyobject)
{
  const btrace_insn *insn;
  const recpy_element_object *obj;
  thread_info *tinfo;
  btrace_insn_iterator iter;

  if (Py_TYPE (pyobject) != &recpy_insn_type)
    {
      PyErr_Format (gdbpy_gdb_error, _("Must be gdb.RecordInstruction"));
      return NULL;
    }

  obj = (const recpy_element_object *) pyobject;
  tinfo = obj->thread;

  if (tinfo == NULL || btrace_is_empty (tinfo))
    {
      PyErr_Format (gdbpy_gdb_error, _("No such instruction."));
      return NULL;
    }

  if (btrace_find_insn_by_number (&iter, &tinfo->btrace, obj->number) == 0)
    {
      PyErr_Format (gdbpy_gdb_error, _("No such instruction."));
      return NULL;
    }

  insn = btrace_insn_get (&iter);
  if (insn == NULL)
    {
      PyErr_Format (gdbpy_gdb_error, _("Not a valid instruction."));
      return NULL;
    }

  return insn;
}

/* Returns either a btrace_function for the given Python
   gdb.RecordFunctionSegment object or sets an appropriate Python exception and
   returns NULL.  */

static const btrace_function *
btrace_func_from_recpy_func (const PyObject * const pyobject)
{
  const btrace_function *func;
  const recpy_element_object *obj;
  thread_info *tinfo;
  btrace_call_iterator iter;

  if (Py_TYPE (pyobject) != &recpy_func_type)
    {
      PyErr_Format (gdbpy_gdb_error, _("Must be gdb.RecordFunctionSegment"));
      return NULL;
    }

  obj = (const recpy_element_object *) pyobject;
  tinfo = obj->thread;

  if (tinfo == NULL || btrace_is_empty (tinfo))
    {
      PyErr_Format (gdbpy_gdb_error, _("No such function segment."));
      return NULL;
    }

  if (btrace_find_call_by_number (&iter, &tinfo->btrace, obj->number) == 0)
    {
      PyErr_Format (gdbpy_gdb_error, _("No such function segment."));
      return NULL;
    }

  func = btrace_call_get (&iter);
  if (func == NULL)
    {
      PyErr_Format (gdbpy_gdb_error, _("Not a valid function segment."));
      return NULL;
    }

  return func;
}

/* Looks at the recorded item with the number NUMBER and create a
   gdb.RecordInstruction or gdb.RecordGap object for it accordingly.  */

static PyObject *
btpy_insn_or_gap_new (thread_info *tinfo, Py_ssize_t number)
{
  btrace_insn_iterator iter;
  int err_code;

  btrace_find_insn_by_number (&iter, &tinfo->btrace, number);
  err_code = btrace_insn_get_error (&iter);

  if (err_code != 0)
    {
      const btrace_config *config;
      const char *err_string;

      config = btrace_conf (&tinfo->btrace);
      err_string = btrace_decode_error (config->format, err_code);

      return recpy_gap_new (err_code, err_string, number);
    }

  return recpy_insn_new (tinfo, RECORD_METHOD_BTRACE, number);
}

/* Create a new gdb.BtraceList object.  */

static PyObject *
btpy_list_new (thread_info *thread, Py_ssize_t first, Py_ssize_t last, Py_ssize_t step,
	       PyTypeObject *element_type)
{
  btpy_list_object * const obj = PyObject_New (btpy_list_object,
					       &btpy_list_type);

  if (obj == NULL)
    return NULL;

  obj->thread = thread;
  obj->first = first;
  obj->last = last;
  obj->step = step;
  obj->element_type = element_type;

  return (PyObject *) obj;
}

/* Implementation of RecordInstruction.sal [gdb.Symtab_and_line] for btrace.
   Returns the SAL associated with this instruction.  */

PyObject *
recpy_bt_insn_sal (PyObject *self, void *closure)
{
  const btrace_insn * const insn = btrace_insn_from_recpy_insn (self);
  PyObject *result = NULL;

  if (insn == NULL)
    return NULL;

  TRY
    {
      result = symtab_and_line_to_sal_object (find_pc_line (insn->pc, 0));
    }
  CATCH (except, RETURN_MASK_ALL)
    {
      GDB_PY_HANDLE_EXCEPTION (except);
    }
  END_CATCH

  return result;
}

/* Implementation of RecordInstruction.pc [int] for btrace.
   Returns the instruction address.  */

PyObject *
recpy_bt_insn_pc (PyObject *self, void *closure)
{
  const btrace_insn * const insn = btrace_insn_from_recpy_insn (self);

  if (insn == NULL)
    return NULL;

  return gdb_py_long_from_ulongest (insn->pc);
}

/* Implementation of RecordInstruction.size [int] for btrace.
   Returns the instruction size.  */

PyObject *
recpy_bt_insn_size (PyObject *self, void *closure)
{
  const btrace_insn * const insn = btrace_insn_from_recpy_insn (self);

  if (insn == NULL)
    return NULL;

  return PyInt_FromLong (insn->size);
}

/* Implementation of RecordInstruction.is_speculative [bool] for btrace.
   Returns if this instruction was executed speculatively.  */

PyObject *
recpy_bt_insn_is_speculative (PyObject *self, void *closure)
{
  const btrace_insn * const insn = btrace_insn_from_recpy_insn (self);

  if (insn == NULL)
    return NULL;

  if (insn->flags & BTRACE_INSN_FLAG_SPECULATIVE)
    Py_RETURN_TRUE;
  else
    Py_RETURN_FALSE;
}

/* Implementation of RecordInstruction.data [buffer] for btrace.
   Returns raw instruction data.  */

PyObject *
recpy_bt_insn_data (PyObject *self, void *closure)
{
  const btrace_insn * const insn = btrace_insn_from_recpy_insn (self);
  gdb::byte_vector buffer;
  PyObject *object;

  if (insn == NULL)
    return NULL;

  TRY
    {
      buffer.resize (insn->size);
      read_memory (insn->pc, buffer.data (), insn->size);
    }
  CATCH (except, RETURN_MASK_ALL)
    {
      GDB_PY_HANDLE_EXCEPTION (except);
    }
  END_CATCH

  object = PyBytes_FromStringAndSize ((const char *) buffer.data (),
				      insn->size);

  if (object == NULL)
    return NULL;

#ifdef IS_PY3K
  return PyMemoryView_FromObject (object);
#else
  return PyBuffer_FromObject (object, 0, Py_END_OF_BUFFER);
#endif

}

/* Implementation of RecordInstruction.decoded [str] for btrace.
   Returns the instruction as human readable string.  */

PyObject *
recpy_bt_insn_decoded (PyObject *self, void *closure)
{
  const btrace_insn * const insn = btrace_insn_from_recpy_insn (self);
  string_file strfile;

  if (insn == NULL)
    return NULL;

  TRY
    {
      gdb_print_insn (target_gdbarch (), insn->pc, &strfile, NULL);
    }
  CATCH (except, RETURN_MASK_ALL)
    {
      gdbpy_convert_exception (except);
      return NULL;
    }
  END_CATCH

  return PyBytes_FromString (strfile.string ().c_str ());
}

/* Implementation of RecordFunctionSegment.level [int] for btrace.
   Returns the call level.  */

PyObject *
recpy_bt_func_level (PyObject *self, void *closure)
{
  const btrace_function * const func = btrace_func_from_recpy_func (self);
  thread_info *tinfo;

  if (func == NULL)
    return NULL;

  tinfo = ((recpy_element_object *) self)->thread;
  return PyInt_FromLong (tinfo->btrace.level + func->level);
}

/* Implementation of RecordFunctionSegment.symbol [gdb.Symbol] for btrace.
   Returns the symbol associated with this function call.  */

PyObject *
recpy_bt_func_symbol (PyObject *self, void *closure)
{
  const btrace_function * const func = btrace_func_from_recpy_func (self);

  if (func == NULL)
    return NULL;

  if (func->sym == NULL)
    Py_RETURN_NONE;

  return symbol_to_symbol_object (func->sym);
}

/* Implementation of RecordFunctionSegment.instructions [list] for btrace.
   Returns the list of instructions that belong to this function call.  */

PyObject *
recpy_bt_func_instructions (PyObject *self, void *closure)
{
  const btrace_function * const func = btrace_func_from_recpy_func (self);
  unsigned int len;

  if (func == NULL)
    return NULL;

  len = func->insn.size ();

  /* Gaps count as one instruction.  */
  if (len == 0)
    len = 1;

  return btpy_list_new (((recpy_element_object *) self)->thread,
			func->insn_offset, func->insn_offset + len, 1,
			&recpy_insn_type);
}

/* Implementation of RecordFunctionSegment.up [RecordFunctionSegment] for
   btrace.  Returns the caller / returnee of this function.  */

PyObject *
recpy_bt_func_up (PyObject *self, void *closure)
{
  const btrace_function * const func = btrace_func_from_recpy_func (self);

  if (func == NULL)
    return NULL;

  if (func->up == 0)
    Py_RETURN_NONE;

  return recpy_func_new (((recpy_element_object *) self)->thread,
			 RECORD_METHOD_BTRACE, func->up);
}

/* Implementation of RecordFunctionSegment.prev [RecordFunctionSegment] for
   btrace.  Returns a previous segment of this function.  */

PyObject *
recpy_bt_func_prev (PyObject *self, void *closure)
{
  const btrace_function * const func = btrace_func_from_recpy_func (self);

  if (func == NULL)
    return NULL;

  if (func->prev == 0)
    Py_RETURN_NONE;

  return recpy_func_new (((recpy_element_object *) self)->thread,
			 RECORD_METHOD_BTRACE, func->prev);
}

/* Implementation of RecordFunctionSegment.next [RecordFunctionSegment] for
   btrace.  Returns a following segment of this function.  */

PyObject *
recpy_bt_func_next (PyObject *self, void *closure)
{
  const btrace_function * const func = btrace_func_from_recpy_func (self);

  if (func == NULL)
    return NULL;

  if (func->next == 0)
    Py_RETURN_NONE;

  return recpy_func_new (((recpy_element_object *) self)->thread,
			 RECORD_METHOD_BTRACE, func->next);
}

/* Implementation of BtraceList.__len__ (self) -> int.  */

static Py_ssize_t
btpy_list_length (PyObject *self)
{
  const btpy_list_object * const obj = (btpy_list_object *) self;
  const Py_ssize_t distance = obj->last - obj->first;
  const Py_ssize_t result = distance / obj->step;

  if ((distance % obj->step) == 0)
    return result;

  return result + 1;
}

/* Implementation of
   BtraceList.__getitem__ (self, key) -> BtraceInstruction and
   BtraceList.__getitem__ (self, key) -> BtraceFunctionCall.  */

static PyObject *
btpy_list_item (PyObject *self, Py_ssize_t index)
{
  const btpy_list_object * const obj = (btpy_list_object *) self;
  Py_ssize_t number;

  if (index < 0 || index >= btpy_list_length (self))
    return PyErr_Format (PyExc_IndexError, _("Index out of range: %zd."),
			 index);

  number = obj->first + (obj->step * index);

  if (obj->element_type == &recpy_insn_type)
    return recpy_insn_new (obj->thread, RECORD_METHOD_BTRACE, number);
  else
    return recpy_func_new (obj->thread, RECORD_METHOD_BTRACE, number);
}

/* Implementation of BtraceList.__getitem__ (self, slice) -> BtraceList.  */

static PyObject *
btpy_list_slice (PyObject *self, PyObject *value)
{
  const btpy_list_object * const obj = (btpy_list_object *) self;
  const Py_ssize_t length = btpy_list_length (self);
  Py_ssize_t start, stop, step, slicelength;

  if (PyInt_Check (value))
    {
      Py_ssize_t index = PyInt_AsSsize_t (value);

      /* Emulate Python behavior for negative indices.  */
      if (index < 0)
	index += length;

      return btpy_list_item (self, index);
    }

  if (!PySlice_Check (value))
    return PyErr_Format (PyExc_TypeError, _("Index must be int or slice."));

  if (0 != PySlice_GetIndicesEx (BTPY_PYSLICE (value), length, &start, &stop,
				 &step, &slicelength))
    return NULL;

  return btpy_list_new (obj->thread, obj->first + obj->step * start,
			obj->first + obj->step * stop, obj->step * step,
			obj->element_type);
}

/* Helper function that returns the position of an element in a BtraceList
   or -1 if the element is not in the list.  */

static LONGEST
btpy_list_position (PyObject *self, PyObject *value)
{
  const btpy_list_object * const list_obj = (btpy_list_object *) self;
  const recpy_element_object * const obj = (const recpy_element_object *) value;
  Py_ssize_t index = obj->number;

  if (list_obj->element_type != Py_TYPE (value))
    return -1;

  if (list_obj->thread != obj->thread)
    return -1;

  if (index < list_obj->first || index > list_obj->last)
    return -1;

  index -= list_obj->first;

  if (index % list_obj->step != 0)
    return -1;

  return index / list_obj->step;
}

/* Implementation of "in" operator for BtraceLists.  */

static int
btpy_list_contains (PyObject *self, PyObject *value)
{
  if (btpy_list_position (self, value) < 0)
    return 0;

  return 1;
}

/* Implementation of BtraceLists.index (self, value) -> int.  */

static PyObject *
btpy_list_index (PyObject *self, PyObject *value)
{
  const LONGEST index = btpy_list_position (self, value);

  if (index < 0)
    return PyErr_Format (PyExc_ValueError, _("Not in list."));

  return gdb_py_long_from_longest (index);
}

/* Implementation of BtraceList.count (self, value) -> int.  */

static PyObject *
btpy_list_count (PyObject *self, PyObject *value)
{
  /* We know that if an element is in the list, it is so exactly one time,
     enabling us to reuse the "is element of" check.  */
  return PyInt_FromLong (btpy_list_contains (self, value));
}

/* Python rich compare function to allow for equality and inequality checks
   in Python.  */

static PyObject *
btpy_list_richcompare (PyObject *self, PyObject *other, int op)
{
  const btpy_list_object * const obj1 = (btpy_list_object *) self;
  const btpy_list_object * const obj2 = (btpy_list_object *) other;

  if (Py_TYPE (self) != Py_TYPE (other))
    {
      Py_INCREF (Py_NotImplemented);
      return Py_NotImplemented;
    }

  switch (op)
  {
    case Py_EQ:
      if (obj1->thread == obj2->thread
	  && obj1->element_type == obj2->element_type
	  && obj1->first == obj2->first
	  && obj1->last == obj2->last
	  && obj1->step == obj2->step)
	Py_RETURN_TRUE;
      else
	Py_RETURN_FALSE;

    case Py_NE:
      if (obj1->thread != obj2->thread
	  || obj1->element_type != obj2->element_type
	  || obj1->first != obj2->first
	  || obj1->last != obj2->last
	  || obj1->step != obj2->step)
	Py_RETURN_TRUE;
      else
	Py_RETURN_FALSE;

    default:
      break;
  }

  Py_INCREF (Py_NotImplemented);
  return Py_NotImplemented;
}

/* Implementation of
   BtraceRecord.method [str].  */

PyObject *
recpy_bt_method (PyObject *self, void *closure)
{
  return PyString_FromString ("btrace");
}

/* Implementation of
   BtraceRecord.format [str].  */

PyObject *
recpy_bt_format (PyObject *self, void *closure)
{
  const recpy_record_object * const record = (recpy_record_object *) self;
  const struct thread_info * const tinfo = record->thread;
  const struct btrace_config * config;

  if (tinfo == NULL)
    Py_RETURN_NONE;

  config = btrace_conf (&tinfo->btrace);

  if (config == NULL)
    Py_RETURN_NONE;

  return PyString_FromString (btrace_format_short_string (config->format));
}

/* Implementation of
   BtraceRecord.replay_position [BtraceInstruction].  */

PyObject *
recpy_bt_replay_position (PyObject *self, void *closure)
{
  const recpy_record_object * const record = (recpy_record_object *) self;
  thread_info * tinfo = record->thread;

  if (tinfo == NULL)
    Py_RETURN_NONE;

  if (tinfo->btrace.replay == NULL)
    Py_RETURN_NONE;

  return btpy_insn_or_gap_new (tinfo,
			       btrace_insn_number (tinfo->btrace.replay));
}

/* Implementation of
   BtraceRecord.begin [BtraceInstruction].  */

PyObject *
recpy_bt_begin (PyObject *self, void *closure)
{
  const recpy_record_object * const record = (recpy_record_object *) self;
  thread_info *const tinfo = record->thread;
  struct btrace_insn_iterator iterator;

  if (tinfo == NULL)
    Py_RETURN_NONE;

  btrace_fetch (tinfo, record_btrace_get_cpu ());

  if (btrace_is_empty (tinfo))
    Py_RETURN_NONE;

  btrace_insn_begin (&iterator, &tinfo->btrace);
  return btpy_insn_or_gap_new (tinfo, btrace_insn_number (&iterator));
}

/* Implementation of
   BtraceRecord.end [BtraceInstruction].  */

PyObject *
recpy_bt_end (PyObject *self, void *closure)
{
  const recpy_record_object * const record = (recpy_record_object *) self;
  thread_info *const tinfo = record->thread;
  struct btrace_insn_iterator iterator;

  if (tinfo == NULL)
    Py_RETURN_NONE;

  btrace_fetch (tinfo, record_btrace_get_cpu ());

  if (btrace_is_empty (tinfo))
    Py_RETURN_NONE;

  btrace_insn_end (&iterator, &tinfo->btrace);
  return btpy_insn_or_gap_new (tinfo, btrace_insn_number (&iterator));
}

/* Implementation of
   BtraceRecord.instruction_history [list].  */

PyObject *
recpy_bt_instruction_history (PyObject *self, void *closure)
{
  const recpy_record_object * const record = (recpy_record_object *) self;
  thread_info *const tinfo = record->thread;
  struct btrace_insn_iterator iterator;
  unsigned long first = 0;
  unsigned long last = 0;

   if (tinfo == NULL)
     Py_RETURN_NONE;

   btrace_fetch (tinfo, record_btrace_get_cpu ());

   if (btrace_is_empty (tinfo))
     Py_RETURN_NONE;

   btrace_insn_begin (&iterator, &tinfo->btrace);
   first = btrace_insn_number (&iterator);

   btrace_insn_end (&iterator, &tinfo->btrace);
   last = btrace_insn_number (&iterator);

   return btpy_list_new (tinfo, first, last, 1, &recpy_insn_type);
}

/* Implementation of
   BtraceRecord.function_call_history [list].  */

PyObject *
recpy_bt_function_call_history (PyObject *self, void *closure)
{
  const recpy_record_object * const record = (recpy_record_object *) self;
  thread_info *const tinfo = record->thread;
  struct btrace_call_iterator iterator;
  unsigned long first = 0;
  unsigned long last = 0;

  if (tinfo == NULL)
    Py_RETURN_NONE;

  btrace_fetch (tinfo, record_btrace_get_cpu ());

  if (btrace_is_empty (tinfo))
    Py_RETURN_NONE;

  btrace_call_begin (&iterator, &tinfo->btrace);
  first = btrace_call_number (&iterator);

  btrace_call_end (&iterator, &tinfo->btrace);
  last = btrace_call_number (&iterator);

  return btpy_list_new (tinfo, first, last, 1, &recpy_func_type);
}

/* Implementation of BtraceRecord.goto (self, BtraceInstruction) -> None.  */

PyObject *
recpy_bt_goto (PyObject *self, PyObject *args)
{
  const recpy_record_object * const record = (recpy_record_object *) self;
  thread_info *const tinfo = record->thread;
  const recpy_element_object *obj;
  PyObject *parse_obj;

  if (tinfo == NULL || btrace_is_empty (tinfo))
	return PyErr_Format (gdbpy_gdb_error, _("Empty branch trace."));

  if (!PyArg_ParseTuple (args, "O", &parse_obj))
    return NULL;

  if (Py_TYPE (parse_obj) != &recpy_insn_type)
    return PyErr_Format (PyExc_TypeError, _("Argument must be instruction."));
  obj = (const recpy_element_object *) parse_obj;

  TRY
    {
      struct btrace_insn_iterator iter;

      btrace_insn_end (&iter, &tinfo->btrace);

      if (btrace_insn_number (&iter) == obj->number)
	target_goto_record_end ();
      else
	target_goto_record (obj->number);
    }
  CATCH (except, RETURN_MASK_ALL)
    {
      GDB_PY_HANDLE_EXCEPTION (except);
    }
  END_CATCH

  Py_RETURN_NONE;
}

/* BtraceList methods.  */

struct PyMethodDef btpy_list_methods[] =
{
  { "count", btpy_list_count, METH_O, "count number of occurences"},
  { "index", btpy_list_index, METH_O, "index of entry"},
  {NULL}
};

/* BtraceList sequence methods.  */

static PySequenceMethods btpy_list_sequence_methods =
{
  NULL
};

/* BtraceList mapping methods.  Necessary for slicing.  */

static PyMappingMethods btpy_list_mapping_methods =
{
  NULL
};

/* Sets up the btrace record API.  */

int
gdbpy_initialize_btrace (void)
{
  btpy_list_type.tp_new = PyType_GenericNew;
  btpy_list_type.tp_flags = Py_TPFLAGS_DEFAULT;
  btpy_list_type.tp_basicsize = sizeof (btpy_list_object);
  btpy_list_type.tp_name = "gdb.BtraceObjectList";
  btpy_list_type.tp_doc = "GDB btrace list object";
  btpy_list_type.tp_methods = btpy_list_methods;
  btpy_list_type.tp_as_sequence = &btpy_list_sequence_methods;
  btpy_list_type.tp_as_mapping = &btpy_list_mapping_methods;
  btpy_list_type.tp_richcompare = btpy_list_richcompare;

  btpy_list_sequence_methods.sq_item = btpy_list_item;
  btpy_list_sequence_methods.sq_length = btpy_list_length;
  btpy_list_sequence_methods.sq_contains = btpy_list_contains;

  btpy_list_mapping_methods.mp_subscript = btpy_list_slice;

  return PyType_Ready (&btpy_list_type);
}