text:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Observable } from 'rxjs';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { Inject } from '@angular/core';
import { SensorParserConfigHistory } from '../../model/sensor-parser-config-history';
import { HttpClient } from '@angular/common/http';
import { SensorParserConfigReadonlyComponent } from './sensor-parser-config-readonly.component';
import { SensorParserConfigService } from '../../service/sensor-parser-config.service';
import { KafkaService } from '../../service/kafka.service';
import { TopologyStatus } from '../../model/topology-status';
import { SensorParserConfig } from '../../model/sensor-parser-config';
import { KafkaTopic } from '../../model/kafka-topic';
import { AuthenticationService } from '../../service/authentication.service';
import { SensorParserConfigHistoryService } from '../../service/sensor-parser-config-history.service';
import { StormService } from '../../service/storm.service';
import { MetronAlerts } from '../../shared/metron-alerts';
import { FieldTransformer } from '../../model/field-transformer';
import { SensorParserConfigReadonlyModule } from './sensor-parser-config-readonly.module';
import { SensorEnrichmentConfigService } from '../../service/sensor-enrichment-config.service';
import {
  SensorEnrichmentConfig,
  EnrichmentConfig,
  ThreatIntelConfig
} from '../../model/sensor-enrichment-config';
import { HdfsService } from '../../service/hdfs.service';
import { GrokValidationService } from '../../service/grok-validation.service';
import { RiskLevelRule } from '../../model/risk-level-rule';
import {AppConfigService} from '../../service/app-config.service';
import {MockAppConfigService} from '../../service/mock.app-config.service';

class MockRouter {
  navigateByUrl(url: string) {}
}

class MockActivatedRoute {
  private name: string;
  params: Observable<Params>;

  setNameForTest(name: string) {
    this.name = name;
    this.params = Observable.create(observer => {
      observer.next({ id: this.name });
      observer.complete();
    });
  }
}

class MockAuthenticationService extends AuthenticationService {

  public getCurrentUser(options): Observable<{}> {
    let response: { body: 'user' };
    return Observable.create(observer => {
      observer.next(response);
      observer.complete();
    });
  }
}

class MockSensorParserConfigHistoryService extends SensorParserConfigHistoryService {
  private sensorParserConfigHistory: SensorParserConfigHistory;

  public setForTest(sensorParserConfigHistory: SensorParserConfigHistory) {
    this.sensorParserConfigHistory = sensorParserConfigHistory;
  }

  public get(name: string): Observable<SensorParserConfigHistory> {
    return Observable.create(observer => {
      observer.next(this.sensorParserConfigHistory);
      observer.complete();
    });
  }
}

class MockSensorParserConfigService extends SensorParserConfigService {
}

class MockStormService extends StormService {
  private topologyStatus: TopologyStatus;

  public setForTest(topologyStatus: TopologyStatus) {
    this.topologyStatus = topologyStatus;
  }

  public getStatus(name: string): Observable<TopologyStatus> {
    return Observable.create(observer => {
      observer.next(this.topologyStatus);
      observer.complete();
    });
  }
}

class MockGrokValidationService extends GrokValidationService {

  public list(): Observable<string[]> {
    return Observable.create(observer => {
      observer.next({
        BASE10NUM:
          '(?<![0-9.+-])(?>[+-]?(?:(?:[0-9]+(?:\\.[0-9]+)?)|(?:\\.[0-9]+)))',
        BASE16FLOAT:
          '\\b(?<![0-9A-Fa-f.])(?:[+-]?(?:0x)?(?:(?:[0-9A-Fa-f]+(?:\\.[0-9A-Fa-f]*)?)|(?:\\.[0-9A-Fa-f]+)))\\b',
        BASE16NUM: '(?<![0-9A-Fa-f])(?:[+-]?(?:0x)?(?:[0-9A-Fa-f]+))',
        CISCOMAC: '(?:(?:[A-Fa-f0-9]{4}\\.){2}[A-Fa-f0-9]{4})',
        COMMONMAC: '(?:(?:[A-Fa-f0-9]{2}:){5}[A-Fa-f0-9]{2})',
        DATA: '.*?'
      });
      observer.complete();
    });
  }
}

class MockKafkaService extends KafkaService {
  private kafkaTopic: KafkaTopic;

  public setForTest(kafkaTopic: KafkaTopic) {
    this.kafkaTopic = kafkaTopic;
  }

  public get(name: string): Observable<KafkaTopic> {
    return Observable.create(observer => {
      observer.next(this.kafkaTopic);
      observer.complete();
    });
  }

  public sample(name: string): Observable<string> {
    return Observable.create(observer => {
      observer.next(JSON.stringify({ data: 'data1', data2: 'data3' }));
      observer.complete();
    });
  }
}

class MockHdfsService extends HdfsService {
  private fileList: string[];
  private contents: string;

  public setContents(contents: string) {
    this.contents = contents;
  }

  public list(path: string): Observable<string[]> {
    if (this.fileList === null) {
      return Observable.throw('Error');
    }
    return Observable.create(observer => {
      observer.next(this.fileList);
      observer.complete();
    });
  }

  public read(path: string): Observable<string> {
    if (this.contents === null) {
      return Observable.throw('Error');
    }
    return Observable.create(observer => {
      observer.next(this.contents);
      observer.complete();
    });
  }

  public post(path: string, contents: string): Observable<{}> {
    return Observable.create(observer => {
      observer.next({});
      observer.complete();
    });
  }

  public deleteFile(path: string): Observable<{}> {
    return Observable.create(observer => {
      observer.next({});
      observer.complete();
    });
  }
}

class MockSensorEnrichmentConfigService {
  private sensorEnrichmentConfig: SensorEnrichmentConfig;

  setForTest(sensorEnrichmentConfig: SensorEnrichmentConfig) {
    this.sensorEnrichmentConfig = sensorEnrichmentConfig;
  }

  public get(name: string): Observable<SensorEnrichmentConfig> {
    return Observable.create(observer => {
      observer.next(this.sensorEnrichmentConfig);
      observer.complete();
    });
  }

  public getAvailable(): Observable<string[]> {
    return Observable.create(observer => {
      observer.next(['geo', 'host', 'whois']);
      observer.complete();
    });
  }
}

describe('Component: SensorParserConfigReadonly', () => {
  let component: SensorParserConfigReadonlyComponent;
  let fixture: ComponentFixture<SensorParserConfigReadonlyComponent>;
  let sensorParserConfigHistoryService: MockSensorParserConfigHistoryService;
  let sensorEnrichmentConfigService: MockSensorEnrichmentConfigService;
  let sensorParserConfigService: SensorParserConfigService;
  let kafkaService: MockKafkaService;
  let hdfsService: MockHdfsService;
  let grokValidationService: MockGrokValidationService;
  let stormService: MockStormService;
  let alerts: MetronAlerts;
  let authenticationService: AuthenticationService;
  let router: MockRouter;
  let activatedRoute: MockActivatedRoute;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [SensorParserConfigReadonlyModule],
      providers: [
        { provide: HttpClient },
        { provide: ActivatedRoute, useClass: MockActivatedRoute },
        {
          provide: SensorEnrichmentConfigService,
          useClass: MockSensorEnrichmentConfigService
        },
        {
          provide: SensorParserConfigHistoryService,
          useClass: MockSensorParserConfigHistoryService
        },
        {
          provide: SensorParserConfigService,
          useClass: MockSensorParserConfigService
        },
        { provide: StormService, useClass: MockStormService },
        { provide: KafkaService, useClass: MockKafkaService },
        { provide: HdfsService, useClass: MockHdfsService },
        { provide: GrokValidationService, useClass: MockGrokValidationService },
        { provide: Router, useClass: MockRouter },
        { provide: AppConfigService, useClass: MockAppConfigService },
        MetronAlerts
      ]
    });
    fixture = TestBed.createComponent(SensorParserConfigReadonlyComponent);
    component = fixture.componentInstance;
    activatedRoute = TestBed.get(ActivatedRoute);
    hdfsService = TestBed.get(HdfsService);
    sensorParserConfigHistoryService = TestBed.get(
      SensorParserConfigHistoryService
    );
    sensorEnrichmentConfigService = TestBed.get(SensorEnrichmentConfigService);
    sensorParserConfigService = TestBed.get(SensorParserConfigService);
    stormService = TestBed.get(StormService);
    kafkaService = TestBed.get(KafkaService);
    grokValidationService = TestBed.get(GrokValidationService);
    router = TestBed.get(Router);
    alerts = TestBed.get(MetronAlerts);
  }));

  it('should create an instance', async(() => {
    expect(component).toBeDefined();
  }));

  it('should have metadata defined ', async(() => {
    // the expected value refers to the number of fields that should be visible in the readonly view
    expect(component.editViewMetaData.length).toEqual(32);
  }));

  it('should have sensorsService with parserName and grokPattern defined and kafkaService defined', async(() => {
    let sensorParserInfo = new SensorParserConfigHistory();
    let sensorParserConfig = new SensorParserConfig();
    let kafkaTopic = new KafkaTopic();
    let topologyStatus = new TopologyStatus();

    sensorParserConfig.sensorTopic = 'bro';
    sensorParserConfig.parserClassName = 'org.apache.metron.parsers.GrokParser';
    sensorParserConfig.parserConfig = {
      grokPattern: 'SQUID_DELIMITED squid grok statement'
    };
    sensorParserInfo.config = sensorParserConfig;

    kafkaTopic.name = 'bro';
    kafkaTopic.numPartitions = 1;
    kafkaTopic.replicationFactor = 1;

    topologyStatus.name = 'bro';
    topologyStatus.latency = 10.1;
    topologyStatus.throughput = 15.2;

    let broEnrichment = {
      fieldMap: {
        geo: ['ip_dst_addr'],
        host: ['ip_dst_addr'],
        whois: [],
        stellar: { config: { group1: {} } }
      },
      fieldToTypeMap: {},
      config: {}
    };
    let broThreatIntel = {
      threatIntel: {
        fieldMap: { hbaseThreatIntel: ['ip_dst_addr'] },
        fieldToTypeMap: { ip_dst_addr: ['malicious_ip'] }
      }
    };
    let broEnrichments = new SensorEnrichmentConfig();
    broEnrichments.enrichment = Object.assign(
      new EnrichmentConfig(),
      broEnrichment
    );
    broEnrichments.threatIntel = Object.assign(
      new ThreatIntelConfig(),
      broThreatIntel
    );

    sensorEnrichmentConfigService.setForTest(broEnrichments);
    sensorParserConfigHistoryService.setForTest(sensorParserInfo);
    kafkaService.setForTest(kafkaTopic);
    stormService.setForTest(topologyStatus);

    activatedRoute.setNameForTest('bro');

    component.ngOnInit();
    expect(component.startStopInProgress).toEqual(false);
    expect(component.sensorParserConfigHistory).toEqual(
      Object.assign(new SensorParserConfigHistory(), sensorParserInfo)
    );
    expect(component.kafkaTopic).toEqual(kafkaTopic);
    expect(component.sensorEnrichmentConfig).toEqual(broEnrichments);
  }));

  it('getSensorStatusService should initialise the state variable to appropriate values ', async(() => {
    let sensorParserStatus = new TopologyStatus();
    sensorParserStatus.name = 'bro';
    sensorParserStatus.latency = 10.1;
    sensorParserStatus.status = null;
    sensorParserStatus.throughput = 15.2;

    stormService.setForTest(sensorParserStatus);

    component.getSensorStatusService();
    expect(component.getTopologyStatus('status')).toEqual('Stopped');
    expect(component.getTopologyStatus('sensorStatus')).toEqual('-');

    sensorParserStatus.status = 'ACTIVE';
    component.getSensorStatusService();
    stormService.setForTest(sensorParserStatus);
    expect(component.getTopologyStatus('status')).toEqual('Running');
    expect(component.getTopologyStatus('sensorStatus')).toEqual('Enabled');

    sensorParserStatus.status = 'KILLED';
    component.getSensorStatusService();
    stormService.setForTest(sensorParserStatus);
    expect(component.getTopologyStatus('status')).toEqual('Stopped');
    expect(component.getTopologyStatus('sensorStatus')).toEqual('-');

    sensorParserStatus.status = 'INACTIVE';
    component.getSensorStatusService();
    stormService.setForTest(sensorParserStatus);
    expect(component.getTopologyStatus('status')).toEqual('Disabled');
    expect(component.getTopologyStatus('sensorStatus')).toEqual('Disabled');
  }));

  it('setGrokStatement should set the variables appropriately ', async(() => {
    let grokStatement = 'SQUID_DELIMITED squid grok statement';
    hdfsService.setContents(grokStatement);
    let sensorParserInfo = new SensorParserConfigHistory();
    let sensorParserConfig = new SensorParserConfig();
    sensorParserConfig.parserConfig = {};

    sensorParserConfig.parserConfig['grokPath'] = '/squid/grok/path';
    sensorParserInfo.config = sensorParserConfig;

    component.sensorParserConfigHistory = sensorParserInfo;
    component.setGrokStatement();

    expect(component.grokStatement).toEqual(grokStatement);
  }));

  it('setTransformsConfigKeys/getTransformsOutput should return the keys of the transforms config  ', async(() => {
    let sensorParserInfo = new SensorParserConfigHistory();
    let sensorParserConfig = new SensorParserConfig();
    let fieldTransformer1 = new FieldTransformer();
    let fieldTransformer2 = new FieldTransformer();

    fieldTransformer1.config = { a: 'abc', x: 'xyz' };
    fieldTransformer1.output = ['a', 'b', 'c'];
    fieldTransformer2.config = { x: 'klm', b: 'def' };
    fieldTransformer2.output = ['a', 'b', 'c'];
    sensorParserConfig.fieldTransformations = [
      fieldTransformer1,
      fieldTransformer2
    ];
    sensorParserInfo.config = sensorParserConfig;

    component.setTransformsConfigKeys();
    let transformsOutput = component.getTransformsOutput();

    expect(component.transformsConfigKeys.length).toEqual(0);
    expect(component.transformsConfigKeys).toEqual([]);
    expect(component.transformsConfigMap).toEqual({});
    expect(transformsOutput).toEqual('-');

    component.sensorParserConfigHistory = sensorParserInfo;
    component.setTransformsConfigKeys();
    transformsOutput = component.getTransformsOutput();

    expect(component.transformsConfigKeys.length).toEqual(3);
    expect(component.transformsConfigKeys).toEqual(['a', 'b', 'x']);
    expect(component.transformsConfigMap).toEqual({
      a: ['abc'],
      b: ['def'],
      x: ['xyz', 'klm']
    });
    expect(transformsOutput).toEqual('a, b, c');
  }));

  it('goBack should navigate to sensors page', async(() => {
    router.navigateByUrl = jasmine.createSpy('navigateByUrl');

    component.goBack();

    expect(router.navigateByUrl).toHaveBeenCalledWith('/sensors');
  }));

  it('onEditSensor should navigate to sensor edit', async(() => {
    router.navigateByUrl = jasmine.createSpy('navigateByUrl');

    component.selectedSensorName = 'abc';

    component.onEditSensor();
    expect(router.navigateByUrl).toHaveBeenCalledWith(
      '/sensors(dialog:sensors-config/abc)'
    );
  }));

  it('should set sensorEnrichmentConfig and aggregationConfigKeys to be initialised', async(() => {
    let threatIntel = {
      fieldMap: {
        hbaseThreatIntel: ['ip_dst_addr', 'ip_src_addr', 'action']
      },
      fieldToTypeMap: {
        ip_dst_addr: ['malicious_ip'],
        ip_src_addr: ['malicious_ip'],
        action: ['malicious_ip']
      },
      config: {},
      triageConfig: {
        riskLevelRules: [
          {
            rule: "IN_SUBNET(ip_dst_addr, '192.168.0.0/24')",
            score: 3,
            name: 'test1',
            comment: 'This is a comment'
          },
          {
            rule: "user.type in [ 'admin', 'power' ] and asset.type == 'web'",
            score: 3,
            name: 'test2',
            comment: 'This is another comment'
          }
        ],
        aggregator: 'MAX',
        aggregationConfig: {}
      }
    };
    let expected: RiskLevelRule[] = [
      {
        rule: "IN_SUBNET(ip_dst_addr, '192.168.0.0/24')",
        score: 3,
        name: 'test1',
        comment: 'This is a comment'
      },
      {
        rule: "user.type in [ 'admin', 'power' ] and asset.type == 'web'",
        score: 3,
        name: 'test2',
        comment: 'This is another comment'
      }
    ];

    let sensorEnrichmentConfig = new SensorEnrichmentConfig();
    sensorEnrichmentConfig.threatIntel = Object.assign(
      new ThreatIntelConfig(),
      threatIntel
    );
    sensorEnrichmentConfigService.setForTest(sensorEnrichmentConfig);

    component.getEnrichmentData();

    expect(component.sensorEnrichmentConfig).toEqual(sensorEnrichmentConfig);
    expect(component.rules).toEqual(expected);
  }));

  let setDataForSensorOperation = function() {
    let sensorParserInfo = new SensorParserConfigHistory();
    let sensorParserConfig = new SensorParserConfig();
    let kafkaTopic = new KafkaTopic();
    let topologyStatus = new TopologyStatus();

    sensorParserConfig.sensorTopic = 'bro';
    sensorParserConfig.parserClassName = 'org.apache.metron.parsers.GrokParser';
    sensorParserConfig.parserConfig = {
      grokPattern: 'SQUID_DELIMITED squid grok statement'
    };
    sensorParserInfo.config = sensorParserConfig;

    kafkaTopic.name = 'bro';
    kafkaTopic.numPartitions = 1;
    kafkaTopic.replicationFactor = 1;

    topologyStatus.name = 'bro';
    topologyStatus.latency = 10.1;
    topologyStatus.throughput = 15.2;

    let broEnrichment = {
      fieldMap: {
        geo: ['ip_dst_addr'],
        host: ['ip_dst_addr'],
        whois: [],
        stellar: { config: { group1: {} } }
      },
      fieldToTypeMap: {},
      config: {}
    };
    let broThreatIntel = {
      threatIntel: {
        fieldMap: { hbaseThreatIntel: ['ip_dst_addr'] },
        fieldToTypeMap: { ip_dst_addr: ['malicious_ip'] }
      }
    };
    let broEnrichments = new SensorEnrichmentConfig();
    broEnrichments.enrichment = Object.assign(
      new EnrichmentConfig(),
      broEnrichment
    );
    broEnrichments.threatIntel = Object.assign(
      new ThreatIntelConfig(),
      broThreatIntel
    );

    kafkaService.setForTest(kafkaTopic);
    stormService.setForTest(topologyStatus);
    sensorEnrichmentConfigService.setForTest(broEnrichments);
    sensorParserConfigHistoryService.setForTest(sensorParserInfo);
  };

  it('onStartSensor should  start sensor', async(() => {
    spyOn(stormService, 'startParser').and.returnValue(
      Observable.create(observer => {
        observer.next({});
        observer.complete();
      })
    );

    alerts.showSuccessMessage = jasmine.createSpy('showSuccessMessage');
    setDataForSensorOperation();

    component.selectedSensorName = 'abc';

    component.onStartSensor();

    expect(stormService.startParser).toHaveBeenCalledWith('abc');
    expect(alerts.showSuccessMessage).toHaveBeenCalledWith(
      'Started sensor abc'
    );
  }));

  it('onStopSensor should stop the sensor', async(() => {
    spyOn(stormService, 'stopParser').and.returnValue(
      Observable.create(observer => {
        observer.next({});
        observer.complete();
      })
    );

    alerts.showSuccessMessage = jasmine.createSpy('showSuccessMessage');
    setDataForSensorOperation();

    component.selectedSensorName = 'abc';

    component.onStopSensor();

    expect(stormService.stopParser).toHaveBeenCalledWith('abc');
    expect(alerts.showSuccessMessage).toHaveBeenCalledWith(
      'Stopped sensor abc'
    );
  }));

  it('onEnableSensor should enable sensor', async(() => {
    spyOn(stormService, 'activateParser').and.returnValue(
      Observable.create(observer => {
        observer.next({});
        observer.complete();
      })
    );

    alerts.showSuccessMessage = jasmine.createSpy('showSuccessMessage');
    setDataForSensorOperation();

    component.selectedSensorName = 'abc';

    component.onEnableSensor();

    expect(stormService.activateParser).toHaveBeenCalledWith('abc');
    expect(alerts.showSuccessMessage).toHaveBeenCalledWith(
      'Enabled sensor abc'
    );
  }));

  it('onDisableSensor should disable the sensor', async(() => {
    spyOn(stormService, 'deactivateParser').and.returnValue(
      Observable.create(observer => {
        observer.next({});
        observer.complete();
      })
    );

    alerts.showSuccessMessage = jasmine.createSpy('showSuccessMessage');
    setDataForSensorOperation();

    component.selectedSensorName = 'abc';

    component.onDisableSensor();

    expect(stormService.deactivateParser).toHaveBeenCalledWith('abc');
    expect(alerts.showSuccessMessage).toHaveBeenCalledWith(
      'Disabled sensor abc'
    );
  }));

  it('onDeleteSensor should delete the sensor', async(() => {
    spyOn(
      sensorParserConfigService,
      'deleteSensorParserConfig'
    ).and.returnValue(
      Observable.create(observer => {
        observer.next({});
        observer.complete();
      })
    );

    alerts.showSuccessMessage = jasmine.createSpy('showSuccessMessage');
    router.navigateByUrl = jasmine.createSpy('navigateByUrl');
    setDataForSensorOperation();

    component.selectedSensorName = 'abc';

    component.onDeleteSensor();

    expect(
      sensorParserConfigService.deleteSensorParserConfig
    ).toHaveBeenCalledWith('abc');
    expect(alerts.showSuccessMessage).toHaveBeenCalledWith(
      'Deleted sensor abc'
    );
    expect(router.navigateByUrl).toHaveBeenCalledWith('/sensors');
  }));

  it('toggleStartStopInProgress should toggle the variable for showing progressbar', async(() => {
    expect(component.startStopInProgress).toEqual(false);

    component.startStopInProgress = true;
    expect(component.startStopInProgress).toEqual(true);

    component.startStopInProgress = false;
    expect(component.startStopInProgress).toEqual(false);
  }));

  it('should toggleTransformLink', async(() => {
    expect(component.transformLinkText).toEqual('show more');

    component.toggleTransformLink();
    expect(component.transformLinkText).toEqual('show less');

    component.toggleTransformLink();
    expect(component.transformLinkText).toEqual('show more');
  }));

  it('should toggleThreatTriageLink', async(() => {
    expect(component.threatTriageLinkText).toEqual('show more');

    component.toggleThreatTriageLink();
    expect(component.threatTriageLinkText).toEqual('show less');

    component.toggleThreatTriageLink();
    expect(component.threatTriageLinkText).toEqual('show more');
  }));

  it('should hide start', async(() => {
    component.topologyStatus.status = 'ACTIVE';
    expect(component.isStartHidden()).toEqual(true);

    component.topologyStatus.status = 'INACTIVE';
    expect(component.isStartHidden()).toEqual(true);

    component.topologyStatus.status = 'Stopped';
    expect(component.isStartHidden()).toEqual(false);

    component.topologyStatus.status = 'KILLED';
    expect(component.isStartHidden()).toEqual(false);
  }));

  it('should hide stop', async(() => {
    component.topologyStatus.status = 'ACTIVE';
    expect(component.isStopHidden()).toEqual(false);

    component.topologyStatus.status = 'INACTIVE';
    expect(component.isStopHidden()).toEqual(false);

    component.topologyStatus.status = 'Stopped';
    expect(component.isStopHidden()).toEqual(true);

    component.topologyStatus.status = 'KILLED';
    expect(component.isStopHidden()).toEqual(true);
  }));

  it('should hide enable', async(() => {
    component.topologyStatus.status = 'ACTIVE';
    expect(component.isEnableHidden()).toEqual(true);

    component.topologyStatus.status = 'INACTIVE';
    expect(component.isEnableHidden()).toEqual(false);

    component.topologyStatus.status = 'Stopped';
    expect(component.isEnableHidden()).toEqual(true);

    component.topologyStatus.status = 'KILLED';
    expect(component.isEnableHidden()).toEqual(true);
  }));

  it('should hide disable', async(() => {
    component.topologyStatus.status = 'ACTIVE';
    expect(component.isDisableHidden()).toEqual(false);

    component.topologyStatus.status = 'INACTIVE';
    expect(component.isDisableHidden()).toEqual(true);

    component.topologyStatus.status = 'Stopped';
    expect(component.isDisableHidden()).toEqual(true);

    component.topologyStatus.status = 'KILLED';
    expect(component.isDisableHidden()).toEqual(true);
  }));
});


text:
package hr.fer.zemris.vhdllab.service.impl;

import hr.fer.zemris.vhdllab.applets.editor.newtb.enums.TimeScale;
import hr.fer.zemris.vhdllab.applets.editor.newtb.exceptions.UniformTestbenchParserException;
import hr.fer.zemris.vhdllab.applets.editor.newtb.model.Testbench;
import hr.fer.zemris.vhdllab.applets.editor.newtb.model.TestbenchParser;
import hr.fer.zemris.vhdllab.entity.File;
import hr.fer.zemris.vhdllab.entity.FileType;
import hr.fer.zemris.vhdllab.service.Simulator;
import hr.fer.zemris.vhdllab.service.WorkspaceService;
import hr.fer.zemris.vhdllab.service.exception.CompilationException;
import hr.fer.zemris.vhdllab.service.exception.NoAvailableProcessException;
import hr.fer.zemris.vhdllab.service.exception.SimulationException;
import hr.fer.zemris.vhdllab.service.exception.SimulatorTimeoutException;
import hr.fer.zemris.vhdllab.service.hierarchy.Hierarchy;
import hr.fer.zemris.vhdllab.service.hierarchy.HierarchyNode;
import hr.fer.zemris.vhdllab.service.result.CompilationMessage;
import hr.fer.zemris.vhdllab.service.result.Result;
import hr.fer.zemris.vhdllab.service.util.SecurityUtils;
import hr.fer.zemris.vhdllab.util.IOUtil;
import hr.fer.zemris.vhdllab.util.StringUtil;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.ExecuteStreamHandler;
import org.apache.commons.exec.ExecuteWatchdog;
import org.apache.commons.exec.Executor;
import org.apache.commons.exec.PumpStreamHandler;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.UnhandledException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * A wrapper for GHDL (http://ghdl.free.fr/).
 */
public class GhdlSimulator extends ServiceSupport implements Simulator {

    /**
     * Logger for this class
     */
    private static final Logger LOG = Logger.getLogger(GhdlSimulator.class);

    private static final int PROCESS_TIMEOUT = 2000;
    private static final int MAX_SIMULTANEOUS_PROCESSES = 20;
    private static final int ACQUIRE_TIMEOUT = 1;
    private static final TimeUnit ACQUIRE_TIME_UNIT = TimeUnit.SECONDS;

    private static final String PROP_COMPILATION_CMD = "compilation.cmd";
    private static final String PROP_SIMULATION_CMD = "simulation.cmd";

    private final Semaphore semaphore = new Semaphore(MAX_SIMULTANEOUS_PROCESSES);

    private boolean leaveSimulationResults = true;

    private Properties properties;

    @Autowired
    private WorkspaceService workspaceService;

    private Properties getProperties() {
        if (properties == null) {
            properties = new Properties();
            InputStream is = this.getClass().getClassLoader().getResourceAsStream("ghdl.properties");
            try {
                properties.load(is);
            } catch (IOException e) {
                throw new IllegalStateException(e);
            }
            IOUtils.closeQuietly(is);
        }

        return properties;
    }

    @Override
    public List<CompilationMessage> compile(Integer fileId) throws CompilationException {
        try {
            if (!semaphore.tryAcquire(ACQUIRE_TIMEOUT, ACQUIRE_TIME_UNIT)) {
                throw new NoAvailableProcessException(MAX_SIMULTANEOUS_PROCESSES);
            }
        } catch (InterruptedException e) {
            throw new NoAvailableProcessException(e);
        }

        List<CompilationMessage> result;
        try {
            result = compileImpl(fileId);
        } finally {
            semaphore.release();
        }

        return result;
    }

    @Override
    public Result simulate(Integer fileId) throws SimulationException {
        try {
            if (!semaphore.tryAcquire(ACQUIRE_TIMEOUT, ACQUIRE_TIME_UNIT)) {
                throw new NoAvailableProcessException(MAX_SIMULTANEOUS_PROCESSES);
            }
        } catch (InterruptedException e) {
            throw new NoAvailableProcessException(e);
        }

        Result result;
        try {
            result = simulateImpl(fileId);
        } finally {
            semaphore.release();
        }

        return result;
    }

    private List<CompilationMessage> compileImpl(Integer fileId) {
        SimulationContext context = createContext(fileId);
        context.compileOnly = true;

        try {
            doCompile(context);
        } catch (IOException e) {
            throw new CompilationException(e);
        }

        return listToCompilationMessages(context.result);
    }

    private Result simulateImpl(Integer fileId) {
        SimulationContext context = createContext(fileId);

        String waveform;
        try {
            doCompile(context);

            prepairSimulationCommandLine(context);
            context.result = executeProcess(context.commandLine, context.tempDirectory);
            waveform = extractWaveform(context);
        } catch (IOException e) {
            throw new CompilationException(e);
        } finally {
            if (!leaveSimulationResults) {
                FileUtils.deleteQuietly(context.tempDirectory);
            }
        }

        return new Result(waveform, context.result);
    }

    @SuppressWarnings("synthetic-access")
    private SimulationContext createContext(Integer fileId) {
        SimulationContext context = new SimulationContext();
        context.targetFile = loadFile(fileId);
        return context;
    }

    private void doCompile(SimulationContext context) throws IOException {
        try {
            context.tempDirectory = createTempDirectory(context.targetFile.getId());
            context.dependencies = orderFileNames(context.targetFile);

            copyFiles(context.dependencies, context.targetFile.getProject().getId(), context.tempDirectory);

            context.commandLine = prepairCompilationCommandLine(context.dependencies);
            context.result = executeProcess(context.commandLine, context.tempDirectory);
        } finally {
            if (context.compileOnly) {
                FileUtils.deleteQuietly(context.tempDirectory);
            }
        }
    }

    private List<String> orderFileNames(File file) {
        Hierarchy hierarchy = workspaceService.extractHierarchy(file.getProject().getId());
        List<File> ordered = new ArrayList<File>();
        orderFileNames(ordered, hierarchy, hierarchy.getNode(file));
        List<String> names = new ArrayList<String>(ordered.size());
        for (File f : ordered) {
            names.add(f.getName());
        }
        return names;
    }

    private void orderFileNames(List<File> ordered, Hierarchy hierarchy, HierarchyNode node) {
        Set<String> missing = node.getMissingDependencies();
        if (!missing.isEmpty()) {
            String dep = missing.iterator().next();
            throw new CompilationException(node.getFile().getName() + " uses " + dep + " however that circuit doesn't exist. Neither compilation nor simulation can be run.");
        }

        Set<HierarchyNode> dependencies = hierarchy.getDependenciesFor(node);
        for (HierarchyNode n : dependencies) {
            orderFileNames(ordered, hierarchy, n);
        }
        if (!ordered.contains(node.getFile())) {
            ordered.add(node.getFile());
        }
    }

    private java.io.File createTempDirectory(Integer fileId) throws IOException {
        String suffix = "_by_user-" + SecurityUtils.getUser() + "__file_id-" + fileId;
        java.io.File tempFile = java.io.File.createTempFile("ghd", suffix, getRootDir());
        java.io.File tempDir = new java.io.File(tempFile.getParentFile(), "DIR" + tempFile.getName());
        FileUtils.forceMkdir(tempDir);
        FileUtils.deleteQuietly(tempFile);
        LOG.debug("Created temp directory: " + tempDir.getPath());
        return tempDir;
    }

    private java.io.File getRootDir() {
        java.io.File root = null;

        String tmpDir = getProperties().getProperty("tmp.dir");
        if (tmpDir != null && !tmpDir.equals("${ghdl.tmp.dir}")) {
            root = new java.io.File(tmpDir);
        }

        LOG.debug("Temp root dir resolved as: " + root);
        return root;
    }

    private void copyFiles(List<String> dependencies, Integer projectId, java.io.File tempDirectory) throws IOException {
        for (String dep : dependencies) {
            File depFile = findProjectOrPredefinedFile(projectId, dep);
            String data = depFile.getData();
            if (!depFile.getType().equals(FileType.PREDEFINED)) {
                data = metadataExtractor.generateVhdl(depFile).getData();
            }
            java.io.File fileOnDisk = new java.io.File(tempDirectory, dep + ".vhdl");
            FileUtils.writeStringToFile(fileOnDisk, data, IOUtil.DEFAULT_ENCODING);
        }
    }

    private CommandLine createCommandLine(String cmd) {
        return CommandLine.parse(cmd);
    }

    private CommandLine prepairCompilationCommandLine(List<String> dependencies) {
        String cmd = getProperties().getProperty(PROP_COMPILATION_CMD);

        String[] files = new String[dependencies.size()];
        for (int i = 0; i < dependencies.size(); i++) {
            files[i] = dependencies.get(i) + ".vhdl";
        }
        cmd = cmd.replace("{files}", StringUtils.join(files, ' '));

        return createCommandLine(cmd);
    }

    private void prepairSimulationCommandLine(SimulationContext context) {
        String cmd = getProperties().getProperty(PROP_SIMULATION_CMD);
        cmd = cmd.replace("{files}", context.targetFile.getName());

        CommandLine cl = createCommandLine(cmd);
        cl.addArgument("--vcd=simout.vcd");

        Testbench tb = null;
        try {
            tb = TestbenchParser.parseXml(context.targetFile.getData());
        } catch (UniformTestbenchParserException e) {
            throw new SimulationException(e);
        }
        long simulationLength = tb.getSimulationLength();
        if (simulationLength <= 0) {
            simulationLength = 100;
        } else {
            simulationLength = simulationLength / TimeScale.getMultiplier(tb.getTimeScale());
            simulationLength = (long) (simulationLength * 1.1);
        }
        cl.addArgument("--stop-time=" + simulationLength + tb.getTimeScale().toString().toLowerCase());

        context.commandLine = cl;
    }

    private List<String> executeProcess(CommandLine cl, java.io.File tempDirectory) throws ExecuteException,
            IOException {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Executing process: " + cl.toString());
        }

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ExecuteStreamHandler handler = new PumpStreamHandler(bos);
        ExecuteWatchdog watchdog = new ExecuteWatchdog(PROCESS_TIMEOUT);
        Executor executor = new DefaultExecutor();
        executor.setWorkingDirectory(tempDirectory);
        executor.setWatchdog(watchdog);
        executor.setStreamHandler(handler);
        /*
         * It seems that when ExecuteWatchdog terminates process by invoking
         * destroy method, process terminates with exit code 143. And since we
         * manually ask watchdog if he killed the process, exit code 143 is
         * marked as successful (just so our code can be executed).
         *
         * Exit code 1 in case of compilation error(s).
         */
        executor.setExitValues(new int[] { 0, 1, 143 });
        try {
            executor.execute(cl);
        } catch (ExecuteException e) {
            LOG.warn("Process output dump:\n" + bos.toString());
            throw e;
        }

        if (watchdog.killedProcess()) {
            throw new SimulatorTimeoutException(PROCESS_TIMEOUT);
        }
        String output;
        try {
            output = bos.toString(IOUtil.DEFAULT_ENCODING);
        } catch (UnsupportedEncodingException e) {
            throw new UnhandledException(e);
        }
        if (StringUtils.isBlank(output)) {
            return Collections.emptyList();
        }
        return Arrays.asList(StringUtil.splitToNewLines(output));
    }

    private List<CompilationMessage> listToCompilationMessages(List<String> errors) {
        List<CompilationMessage> list = new ArrayList<CompilationMessage>(errors.size());
        for (String e : errors) {
            String[] line = parseGHDLErrorMessage(e);
            if (line.length == 4) {
                list
                        .add(new CompilationMessage(line[0], Integer.parseInt(line[1]), Integer.parseInt(line[2]),
                                line[3]));
            } else {
                list.add(new CompilationMessage(line[1]));
            }
        }
        return list;
    }

    private String[] parseGHDLErrorMessage(String m) {
        String msg = m;
        String[] res = new String[] { msg, null, null, null };
        for (int i = 0; i < 3; i++) {
            int pos = msg.indexOf(':');
            if (pos != -1) {
                res[i] = msg.substring(0, pos);
                msg = msg.substring(pos + 1);
                res[i + 1] = msg;
            } else {
                return new String[] {
                        res[0],
                        (res[1] == null ? "" : res[1]) + (res[2] == null ? "" : ":" + res[2])
                                + (res[3] == null ? "" : ":" + res[3]) };
            }
        }
        if (res[0].toUpperCase().endsWith(".VHDL")) {
            res[0] = res[0].substring(0, res[0].length() - 5);
        } else if (res[0].toUpperCase().endsWith(".VHD")) {
            res[0] = res[0].substring(0, res[0].length() - 4);
        }
        return res;
    }

    private String extractWaveform(SimulationContext context) throws IOException {
        String waveform = "";

        java.io.File simout = new java.io.File(context.tempDirectory, "simout.vcd");
        if(simout.exists()) {
            String vcd = FileUtils.readFileToString(new java.io.File(context.tempDirectory, "simout.vcd"),
                    IOUtil.DEFAULT_ENCODING);
            VcdParser parser = new VcdParser(StringUtil.splitToNewLines(vcd));
            parser.parse();
            waveform = parser.getResultInString();
        }

        return waveform;
    }

    private static class SimulationContext {
        /*
         * Since this is a private class used by simulator exclusively there is
         * no need for getters and setters.
         */
        public boolean compileOnly;
        public java.io.File tempDirectory;
        public File targetFile;
        public List<String> dependencies;
        public CommandLine commandLine;
        public List<String> result;
    }

}

redpajama_set_name: RedPajamaGithub


text:
{{< layout}}

{{$main-content}}

You need a digital passport photo

You can get a friend to take a digital photo then upload it - we'll show you how.

              Continue

                    I have printed passport photos

                        You need to post 2 printed photos with your old passport. They must be taken within the last month.

We'll check your photos. Your application will be delayed if we have to ask for different ones.

Apply with printed photos

{{/main-content}}

{{/ layout}}


text:
package main

import (
	"flag"
	"log"
	"math"
	"os"
	"regexp"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/Shopify/sarama"
	"github.com/kouhin/envflag"
	"github.com/prometheus/client_golang/prometheus"
)

var (
	activeOnly          = flag.Bool("active-only", false, "Show only consumers with an active consumer protocol.")
	kafkaBrokers        = flag.String("kafka-brokers", "localhost:9092", "Comma separated list of kafka brokers.")
	prometheusAddr      = flag.String("prometheus-addr", ":7979", "Prometheus listen interface and port.")
	refreshInt          = flag.Int("refresh-interval", 15, "Time between offset refreshes in seconds.")
	saslUser            = flag.String("sasl-user", "", "SASL username.")
	saslPass            = flag.String("sasl-pass", "", "SASL password.")
	debug               = flag.Bool("debug", false, "Enable debug output.")
	algorithm           = flag.String("algorithm", "", "The SASL algorithm sha256 or sha512 as mechanism")
	enableCurrentOffset = flag.Bool("enable-current-offset", false, "Enables metrics for current offset of a consumer group")
	enableNewAPI        = flag.Bool("enable-new-api", false, "Enables new API, which allows to use optimized Kafka API calls")
	groupPattern        = flag.String("group-pattern", "", "Regular expression to filter consumer groups")
)

type TopicSet map[string]map[int32]int64

func init() {
	if err := envflag.Parse(); err != nil {
		panic(err)
	}
	if *debug {
		sarama.Logger = log.New(os.Stdout, "[Sarama] ", log.LstdFlags)
	}
}

func main() {
	go func() {
		var cycle uint8

		var groupRegexp *regexp.Regexp
		if *groupPattern != "" {
			var err error
			groupRegexp, err = regexp.Compile(*groupPattern)
			if err != nil {
				log.Fatal("Failed to compile regex")
			}
		}

		config := sarama.NewConfig()
		config.ClientID = "kafka-offset-lag-for-prometheus"
		config.Version = sarama.V0_9_0_0
		if *enableNewAPI {
			config.Version = sarama.V0_10_2_0
		}
		if *saslUser != "" {
			config.Net.SASL.Enable = true
			config.Net.SASL.User = *saslUser
			config.Net.SASL.Password = *saslPass
		}
		if *algorithm == "sha512" {
			config.Net.SASL.SCRAMClientGeneratorFunc = func() sarama.SCRAMClient { return &XDGSCRAMClient{HashGeneratorFcn: SHA512} }
			config.Net.SASL.Mechanism = sarama.SASLMechanism(sarama.SASLTypeSCRAMSHA512)
		} else if *algorithm == "sha256" {
			config.Net.SASL.SCRAMClientGeneratorFunc = func() sarama.SCRAMClient { return &XDGSCRAMClient{HashGeneratorFcn: SHA256} }
			config.Net.SASL.Mechanism = sarama.SASLMechanism(sarama.SASLTypeSCRAMSHA256)
		}

		client, err := sarama.NewClient(strings.Split(*kafkaBrokers, ","), config)

		if err != nil {
			log.Fatal("Unable to connect to given brokers.")
		}

		defer client.Close()

		for {
			topicSet := make(TopicSet)
			time.Sleep(time.Duration(*refreshInt) * time.Second)
			timer := prometheus.NewTimer(LookupHist)
			client.RefreshMetadata()
			// First grab our topics, all partiton IDs, and their offset head
			topics, err := client.Topics()
			if err != nil {
				log.Printf("Error fetching topics: %s", err.Error())
				continue
			}

			for _, topic := range topics {
				// Don't include internal topics
				if strings.HasPrefix(topic, "__") {
					continue
				}
				partitions, err := client.Partitions(topic)
				if err != nil {
					log.Printf("Error fetching partitions: %s", err.Error())
					continue
				}
				if *debug {
					log.Printf("Found topic '%s' with %d partitions", topic, len(partitions))
				}
				topicSet[topic] = make(map[int32]int64)
				for _, partition := range partitions {
					toff, err := client.GetOffset(topic, partition, sarama.OffsetNewest)
					if err != nil {
						log.Printf("Problem fetching offset for topic '%s', partition '%d'", topic, partition)
						continue
					}
					topicSet[topic][partition] = toff
				}
			}

			// Prometheus SDK never TTLs out data points so tmp consumers last
			// forever. Ugly hack to clean up data points from time to time.
			if cycle >= 99 {
				OffsetLag.Reset()
				CurrentOffset.Reset()
				cycle = 0
			}
			cycle++

			var wg sync.WaitGroup

			// Now lookup our group data using the metadata
			for _, broker := range client.Brokers() {
				// Sarama plays russian roulette with the brokers
				broker.Open(client.Config())
				_, err := broker.Connected()
				if err != nil {
					log.Printf("Could not speak to broker %s. Your advertised.listeners may be incorrect.", broker.Addr())
					continue
				}

				wg.Add(1)

				go func(broker *sarama.Broker) {
					defer wg.Done()
					if *enableNewAPI {
						refreshBrokerV2(broker, client, groupRegexp)
					} else {
						refreshBroker(broker, topicSet, groupRegexp)
					}
				}(broker)
			}

			wg.Wait()
			timer.ObserveDuration()
		}
	}()
	prometheusListen(*prometheusAddr)
}

func refreshBroker(broker *sarama.Broker, topicSet TopicSet, groupRegexp *regexp.Regexp) {
	groupsRequest := new(sarama.ListGroupsRequest)
	groupsResponse, err := broker.ListGroups(groupsRequest)

	if err != nil {
		log.Printf("Could not list groups: %s\n", err.Error())
		return
	}

	for group, ptype := range groupsResponse.Groups {
		// do we want to filter by active consumers?
		if *activeOnly && ptype != "consumer" {
			continue
		}
		if groupRegexp != nil && !groupRegexp.MatchString(group) {
			continue
		}
		// This is not very efficient but the kafka API sucks
		for topic, data := range topicSet {
			offsetsRequest := new(sarama.OffsetFetchRequest)
			offsetsRequest.Version = 1
			offsetsRequest.ConsumerGroup = group
			for partition := range data {
				offsetsRequest.AddPartition(topic, partition)
			}

			offsetsResponse, err := broker.FetchOffset(offsetsRequest)
			if err != nil {
				log.Printf("Could not get offset: %s\n", err.Error())
			}

			for _, blocks := range offsetsResponse.Blocks {
				for partition, block := range blocks {
					if *debug {
						log.Printf("Discovered group: %s, topic: %s, partition: %d, offset: %d\n", group, topic, partition, block.Offset)
					}
					// Offset will be -1 if the group isn't active on the topic
					if block.Offset >= 0 {
						// Because our offset operations aren't atomic we could end up with a negative lag
						lag := math.Max(float64(data[partition]-block.Offset), 0)
						OffsetLag.With(prometheus.Labels{
							"topic": topic, "group": group,
							"partition": strconv.FormatInt(int64(partition), 10),
						}).Set(lag)
						if *enableCurrentOffset {
							CurrentOffset.With(prometheus.Labels{
								"topic": topic, "group": group,
								"partition": strconv.FormatInt(int64(partition), 10),
							}).Set(math.Max(float64(block.Offset), 0))
						}
					}
				}
			}
		}
	}
}

func refreshBrokerV2(broker *sarama.Broker, client sarama.Client, groupRegexp *regexp.Regexp) {
	groupsRequest := new(sarama.ListGroupsRequest)
	groupsResponse, err := broker.ListGroups(groupsRequest)

	if err != nil {
		log.Printf("Could not list groups: %s\n", err.Error())
		return
	}

	for group, ptype := range groupsResponse.Groups {
		// do we want to filter by active consumers?
		if *activeOnly && ptype != "consumer" {
			continue
		}
		if groupRegexp != nil && !groupRegexp.MatchString(group) {
			continue
		}
		offsetsRequest := new(sarama.OffsetFetchRequest)
		offsetsRequest.Version = 2
		offsetsRequest.ConsumerGroup = group

		offsetsResponse, err := broker.FetchOffset(offsetsRequest)
		if err != nil {
			log.Printf("Could not get offset: %s\n", err.Error())
		}

		for topic, partitions := range offsetsResponse.Blocks {

			for partition, block := range partitions {
				if *debug {
					log.Printf("Discovered group: %s, topic: %s, partition: %d, offset: %d\n", group, topic, partition, block.Offset)
				}

				partitionLatestOffset, err := client.GetOffset(topic, partition, sarama.OffsetNewest)

				if err != nil {
					log.Printf("Failed to obtain Latest Offset for topic: %s, partition: %d", topic, partition)
				}

				lag := math.Max(float64(partitionLatestOffset-block.Offset), 0)
				OffsetLag.With(prometheus.Labels{
					"topic": topic, "group": group,
					"partition": strconv.FormatInt(int64(partition), 10),
				}).Set(lag)
				if *enableCurrentOffset {
					CurrentOffset.With(prometheus.Labels{
						"topic": topic, "group": group,
						"partition": strconv.FormatInt(int64(partition), 10),
					}).Set(math.Max(float64(block.Offset), 0))
				}
			}
		}
	}
}


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

module.metadata = {
  "stability": "unstable"
};

const { Cu } = require("chrome");
const { ShimWaiver } = Cu.import("resource://gre/modules/ShimWaiver.jsm");

// Utility function that returns copy of the given `text` with last character
// removed if it is `"s"`.
function singularify(text) {
  return text[text.length - 1] === "s" ? text.substr(0, text.length - 1) : text;
}

// Utility function that takes event type, argument is passed to
// `document.createEvent` and returns name of the initializer method of the
// given event. Please note that there are some event types whose initializer
// methods can't be guessed by this function. For more details see following
// link: https://developer.mozilla.org/En/DOM/Document.createEvent
function getInitializerName(category) {
  return "init" + singularify(category);
}

/**
 * Registers an event `listener` on a given `element`, that will be called
 * when events of specified `type` is dispatched on the `element`.
 * @param {Element} element
 *    Dom element to register listener on.
 * @param {String} type
 *    A string representing the
 *    [event type](https://developer.mozilla.org/en/DOM/event.type) to
 *    listen for.
 * @param {Function} listener
 *    Function that is called whenever an event of the specified `type`
 *    occurs.
 * @param {Boolean} capture
 *    If true, indicates that the user wishes to initiate capture. After
 *    initiating capture, all events of the specified type will be dispatched
 *    to the registered listener before being dispatched to any `EventTarget`s
 *    beneath it in the DOM tree. Events which are bubbling upward through
 *    the tree will not trigger a listener designated to use capture.
 *    See [DOM Level 3 Events](http://www.w3.org/TR/DOM-Level-3-Events/#event-flow)
 *    for a detailed explanation.
 */
function on(element, type, listener, capture, shimmed = false) {
  // `capture` defaults to `false`.
  capture = capture || false;
  if (shimmed) {
    element.addEventListener(type, listener, capture);
  } else {
    ShimWaiver.getProperty(element, "addEventListener")(type, listener, capture);
  }
}
exports.on = on;

/**
 * Registers an event `listener` on a given `element`, that will be called
 * only once, next time event of specified `type` is dispatched on the
 * `element`.
 * @param {Element} element
 *    Dom element to register listener on.
 * @param {String} type
 *    A string representing the
 *    [event type](https://developer.mozilla.org/en/DOM/event.type) to
 *    listen for.
 * @param {Function} listener
 *    Function that is called whenever an event of the specified `type`
 *    occurs.
 * @param {Boolean} capture
 *    If true, indicates that the user wishes to initiate capture. After
 *    initiating capture, all events of the specified type will be dispatched
 *    to the registered listener before being dispatched to any `EventTarget`s
 *    beneath it in the DOM tree. Events which are bubbling upward through
 *    the tree will not trigger a listener designated to use capture.
 *    See [DOM Level 3 Events](http://www.w3.org/TR/DOM-Level-3-Events/#event-flow)
 *    for a detailed explanation.
 */
function once(element, type, listener, capture, shimmed = false) {
  on(element, type, function selfRemovableListener(event) {
    removeListener(element, type, selfRemovableListener, capture, shimmed);
    listener.apply(this, arguments);
  }, capture, shimmed);
}
exports.once = once;

/**
 * Unregisters an event `listener` on a given `element` for the events of the
 * specified `type`.
 *
 * @param {Element} element
 *    Dom element to unregister listener from.
 * @param {String} type
 *    A string representing the
 *    [event type](https://developer.mozilla.org/en/DOM/event.type) to
 *    listen for.
 * @param {Function} listener
 *    Function that is called whenever an event of the specified `type`
 *    occurs.
 * @param {Boolean} capture
 *    If true, indicates that the user wishes to initiate capture. After
 *    initiating capture, all events of the specified type will be dispatched
 *    to the registered listener before being dispatched to any `EventTarget`s
 *    beneath it in the DOM tree. Events which are bubbling upward through
 *    the tree will not trigger a listener designated to use capture.
 *    See [DOM Level 3 Events](http://www.w3.org/TR/DOM-Level-3-Events/#event-flow)
 *    for a detailed explanation.
 */
function removeListener(element, type, listener, capture, shimmed = false) {
  if (shimmed) {
    element.removeEventListener(type, listener, capture);
  } else {
    ShimWaiver.getProperty(element, "removeEventListener")(type, listener, capture);
  }
}
exports.removeListener = removeListener;

/**
 * Emits event of the specified `type` and `category` on the given `element`.
 * Specified `settings` are used to initialize event before dispatching it.
 * @param {Element} element
 *    Dom element to dispatch event on.
 * @param {String} type
 *    A string representing the
 *    [event type](https://developer.mozilla.org/en/DOM/event.type).
 * @param {Object} options
 *    Options object containing following properties:
 *    - `category`: String passed to the `document.createEvent`. Option is
 *      optional and defaults to "UIEvents".
 *    - `initializer`: If passed it will be used as name of the method used
 *      to initialize event. If omitted name will be generated from the
 *      `category` field by prefixing it with `"init"` and removing last
 *      character if it matches `"s"`.
 *    - `settings`: Array of settings that are forwarded to the event
 *      initializer after firs `type` argument.
 * @see https://developer.mozilla.org/En/DOM/Document.createEvent
 */
function emit(element, type, { category, initializer, settings }, shimmed = false) {
  category = category || "UIEvents";
  initializer = initializer || getInitializerName(category);
  let document = element.ownerDocument;
  let event = document.createEvent(category);
  event[initializer].apply(event, [type].concat(settings));
  if (shimmed) {
    element.dispatchEvent(event);
  } else {
    ShimWaiver.getProperty(element, "dispatchEvent")(event);
  }
};
exports.emit = emit;

// Takes DOM `element` and returns promise which is resolved
// when given element is removed from it's parent node.
const removed = element => {
  return new Promise(resolve => {
    const { MutationObserver } = element.ownerDocument.defaultView;
    const observer = new MutationObserver(mutations => {
      for (let mutation of mutations) {
        for (let node of mutation.removedNodes || []) {
          if (node === element) {
            observer.disconnect();
            resolve(element);
          }
        }
      }
    });
    observer.observe(element.parentNode, {childList: true});
  });
};
exports.removed = removed;

const when = (element, eventName, capture=false, shimmed=false) => new Promise(resolve => {
  const listener = event => {
    if (shimmed) {
      element.removeEventListener(eventName, listener, capture);
    } else {
      ShimWaiver.getProperty(element, "removeEventListener")(eventName, listener, capture);
    }
    resolve(event);
  };

  if (shimmed) {
    element.addEventListener(eventName, listener, capture);
  } else {
    ShimWaiver.getProperty(element, "addEventListener")(eventName, listener, capture);
  }
});
exports.when = when;


text:
// +k8s:deepcopy-gen=package,register

// Package v1 is the v1 version of the API.
// +groupName=enterprises.upmc.com
package v1


text:
using System;
using ChristmasPi.Util.Arguments;

namespace ChristmasPi.Data.Models {
    public class RuntimeConfiguration {
        [HelpSection("Debug")]
        [Argument("tr", "Allows the test renderer to be selected during setup", true)]
        public bool AllowTestRenderer;

        [HelpSection("Debug")]
        [Argument("ignorepriv", "Ignore admin privilege requirement", true)]
        public bool IgnorePrivileges;

        [HelpSection("Debug")]
        [Argument("debug", "Sets the logging level to debug", true)]
        public bool DebugLogging;

        [HelpSection("Debug")]
        [Argument("no-asp-logging", "Don't log ASP.NET data", true)]
        public bool NoASPLogging;

        [HelpSection("Debug")]
        [Argument("no-redirect-logging", "Don't log RedirectHandler data", true)]
        public bool NoRedirectLogging;

        [HelpSection("Debug")]
        [Argument("ignore-restart", "Ignore any restart attempts", true)]
        public bool IgnoreRestarts;

        [HelpSection("Debug")]
        [Argument("daemon-log-console", "Allow console logging in daemon mode", true)]
        public bool DaemonLogToConsole;

        [HelpSection("Debug")]
        [Argument("allow-debug-animations", "Allow viewing and playback of debug animations", true)]
        public bool AllowDebugAnimations;

        [HelpSection("Debug")]
        [Argument("use-service-installer-stub", "Use a stub for the service installer", true)]
        public bool UseServiceInstallerStub;

        [Argument("daemon", "Starts the server in a daemon configuration", true)]
        public bool DaemonMode;

        public RuntimeConfiguration() {}
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Cryptococcus quasilinguae-pilosae Cooper {?}

### Remarks
null


text:
{-# LANGUAGE PolyKinds #-}
module T16517 where

import Data.Proxy
class C a where m :: Proxy (a :: k)


text:
require "open_geo_db/version"

module OpenGeoDb
end


text:
const webseed = require('./webseed')
const http = require('http')
const config = require('../config')
const debug = require('debug')('arxivum:webseed')

http.createServer(webseed.callback()).listen(config.WEBSEED_PORT)

debug('Webseed listening on port ' + config.WEBSEED_PORT)


text:
<?php

//Indication, Copyright Josh Fradley (http://github.com/joshf/Indication)

//Define version across the script
$version = "7.0";

?>


text:
package org.knowm.xchange.coinfloor.dto.trade;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Objects;

import org.knowm.xchange.currency.Currency;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.Order.OrderType;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

public class CoinfloorUserTransaction {
  public String datetime = "";

  public long id = 0;

  @JsonProperty("order_id")
  public long orderId = 0;

  public TransactionType type = TransactionType.UNKNOWN;

  public BigDecimal fee = BigDecimal.ZERO;

  // amounts: for TRADE transactions, negative -> BID, positive -> ASK
  // for other transactions, negative -> WITHDRAWAL, positive -> DEPOSIT
  @JsonProperty("xbt")
  public BigDecimal btc = BigDecimal.ZERO;

  public BigDecimal gbp = BigDecimal.ZERO;

  public BigDecimal usd = BigDecimal.ZERO;

  public BigDecimal eur = BigDecimal.ZERO;

  public BigDecimal eth = BigDecimal.ZERO;

  public BigDecimal ltc = BigDecimal.ZERO;

  public BigDecimal bch = BigDecimal.ZERO;

  public BigDecimal xrp = BigDecimal.ZERO;

  // prices
  @JsonProperty("xbt_gbp")
  public BigDecimal btc_gbp = BigDecimal.ZERO;

  @JsonProperty("xbt_usd")
  public BigDecimal btc_usd = BigDecimal.ZERO;

  @JsonProperty("xbt_eur")
  public BigDecimal btc_eur = BigDecimal.ZERO;

  @JsonProperty("bch_gbp")
  public BigDecimal bch_gbp = BigDecimal.ZERO;

  @JsonProperty("eth_gbp")
  public BigDecimal eth_gbp = BigDecimal.ZERO;

  @JsonProperty("xrp_gbp")
  public BigDecimal xrp_gbp = BigDecimal.ZERO;

  @JsonProperty("ltc_gbp")
  public BigDecimal ltc_gbp = BigDecimal.ZERO;

  public CurrencyPair getCurrencyPair() {
    if (isTrade()) {
      if (!Objects.equals(btc_gbp, BigDecimal.ZERO)) {
        return CurrencyPair.BTC_GBP;
      } else if (!Objects.equals(btc_usd, BigDecimal.ZERO)) {
        return CurrencyPair.BTC_USD;
      } else if (!Objects.equals(btc_eur, BigDecimal.ZERO)) {
        return CurrencyPair.BTC_EUR;
      } else if (!Objects.equals(bch_gbp, BigDecimal.ZERO)) {
        return CurrencyPair.BCH_GBP;
      } else if (!Objects.equals(eth_gbp, BigDecimal.ZERO)) {
        return CurrencyPair.ETH_GBP;
      } else if (!Objects.equals(xrp_gbp, BigDecimal.ZERO)) {
        return CurrencyPair.XRP_GBP;
      } else if (!Objects.equals(ltc_gbp, BigDecimal.ZERO)) {
        return CurrencyPair.LTC_GBP;
      }
    }
    return null; // not a trade or an unsupported currency pair
  }

  public BigDecimal getPrice() {
    if (isTrade()) {
      if (!Objects.equals(btc_gbp, BigDecimal.ZERO)) {
        return btc_gbp;
      } else if (!Objects.equals(btc_usd, BigDecimal.ZERO)) {
        return btc_usd;
      } else if (!Objects.equals(btc_eur, BigDecimal.ZERO)) {
        return btc_eur;
      } else if (!Objects.equals(bch_gbp, BigDecimal.ZERO)) {
        return bch_gbp;
      } else if (!Objects.equals(eth_gbp, BigDecimal.ZERO)) {
        return eth_gbp;
      } else if (!Objects.equals(xrp_gbp, BigDecimal.ZERO)) {
        return xrp_gbp;
      } else if (!Objects.equals(ltc_gbp, BigDecimal.ZERO)) {
        return ltc_gbp;
      }
    }
    return BigDecimal.ZERO; // not a trade or an unsupported currency pair
  }

  public Currency getCurrency() {
    if (isTrade()) {
      return null;
    } else if (btc.signum() != 0) {
      return Currency.BTC;
    } else if (gbp.signum() != 0) {
      return Currency.GBP;
    } else if (usd.signum() != 0) {
      return Currency.USD;
    } else if (eur.signum() != 0) {
      return Currency.EUR;
    } else if (ltc.signum() != 0) {
      return Currency.LTC;
    } else if (eth.signum() != 0) {
      return Currency.ETH;
    } else if (bch.signum() != 0) {
      return Currency.BCH;
    } else if (xrp.signum() != 0) {
      return Currency.XRP;
    } else {
      return null;
    }
  }

  public BigDecimal getAmount() {
    if (isTrade()) {
      if (getCurrencyPair().base == Currency.BTC) {
        return btc;
      } else if (getCurrencyPair().base == Currency.XRP) {
        return xrp;
      } else if (getCurrencyPair().base == Currency.LTC) {
        return ltc;
      } else if (getCurrencyPair().base == Currency.ETH) {
        return eth;
      } else if (getCurrencyPair().base == Currency.BCH) {
        return bch;
      } else {
        return BigDecimal.ZERO;
      }
    } else if (btc.signum() != 0) {
      return btc;
    } else if (bch.signum() != 0) {
      return bch;
    } else if (xrp.signum() != 0) {
      return xrp;
    } else if (ltc.signum() != 0) {
      return ltc;
    } else if (eth.signum() != 0) {
      return eth;
    } else if (gbp.signum() != 0) {
      return gbp;
    } else if (usd.signum() != 0) {
      return usd;
    } else if (eur.signum() != 0) {
      return eur;
    } else {
      return BigDecimal.ZERO; // an unsupported currency
    }
  }

  public OrderType getSide() {
    if (isTrade()) {
      switch (getAmount().signum()) {
        case 0:
        default:
          return null; // deposit or withdrawal
        case 1:
          return OrderType.BID;
        case -1:
          return OrderType.ASK;
      }
    } else {
      return null;
    }
  }

  public boolean isDeposit() {
    return type == TransactionType.DEPOSIT;
  }

  public boolean isWithdrawal() {
    return type == TransactionType.WITHDRAWAL;
  }

  public boolean isTrade() {
    return type == TransactionType.TRADE;
  }

  public TransactionType getType() {
    return type;
  }

  public String getDateTime() {
    return datetime;
  }

  public long getId() {
    return id;
  }

  public long getOrderId() {
    return orderId;
  }

  public BigDecimal getFee() {
    return fee;
  }

  @Override
  public String toString() {
    if (isTrade()) {
      return String.format("CoinfloorUserTransaction{datetime=%s, id=%d, orderId=%d, type=%s, currencyPair=%s side=%s amount=%s price=%s fee=%s}",
          datetime, id, orderId, type, getCurrencyPair(), getSide(), getAmount(), getPrice(), fee);
    } else {
      return String.format("CoinfloorUserTransaction{datetime=%s, id=%d, type=%s, currency=%s amount=%s }", datetime, id, type, getCurrency(),
          getAmount());
    }
  }

  public enum TransactionType {
    DEPOSIT, WITHDRAWAL, TRADE, UNKNOWN
  }

  public static class CoinfloorTransactionTypeDeserializer extends JsonDeserializer<TransactionType> {

    @Override
    public TransactionType deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
      switch (jp.getValueAsInt()) {
        case 0:
          return TransactionType.DEPOSIT;
        case 1:
          return TransactionType.WITHDRAWAL;
        case 2:
          return TransactionType.TRADE;
        default:
          return TransactionType.UNKNOWN;
      }
    }
  }
}


text:
using System.Collections.Generic;
using Mediachase.Commerce;

namespace EPiServer.Reference.Commerce.Site.Features.Global.Cart.ViewModels
{
    public abstract class CartViewModelBase
    {
        public decimal ItemCount { get; set; }

        public IEnumerable<CartItemViewModel> CartItems { get; set; }

        public Money Total { get; set; }
    }
}


text:
import { array, object, oneOfType, string } from 'prop-types';

const koiflyErrorPropType = {
  type: string,
  message: string,
  errors: oneOfType([array, object])
};

export default koiflyErrorPropType;


text:
using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace TestFu.Tests.Gestures
{
    public class GestureTestForm : Form
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.button1 = new System.Windows.Forms.Button();
            this.button2 = new System.Windows.Forms.Button();
            this.checkBox1 = new System.Windows.Forms.CheckBox();
            this.SuspendLayout();
//
// button1
//
            this.button1.Location = new System.Drawing.Point(13, 13);
            this.button1.Name = "button1";
            this.button1.TabIndex = 0;
            this.button1.Text = "button1";
            this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
            this.button2.Location = new System.Drawing.Point(95, 13);
            this.button2.Name = "button2";
            this.button2.TabIndex = 1;
            this.button2.Text = "button2";
            this.button2.Click += new System.EventHandler(this.button2_Click);
//
// checkBox1
//
            this.checkBox1.Location = new System.Drawing.Point(13, 43);
            this.checkBox1.Name = "checkBox1";
            this.checkBox1.Size = new System.Drawing.Size(76, 17);
            this.checkBox1.TabIndex = 2;
            this.checkBox1.Text = "checkBox1";
            this.checkBox1.CheckedChanged += new System.EventHandler(this.checkBox1_CheckedChanged);
//
// GestureTestForm
//
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(292, 266);
            this.Controls.Add(this.checkBox1);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.button1);
            this.Name = "GestureTestForm";
            this.Text = "GestureTestForm";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        public System.Windows.Forms.Button button1;
        public int button1ClickCount = 0;
        public System.Windows.Forms.Button button2;
        public int button2ClickCount = 0;
        public System.Windows.Forms.CheckBox checkBox1;
        public int checkBox1ClickCount = 0;
        public GestureTestForm()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.button1ClickCount++;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.button2ClickCount++;
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            this.checkBox1ClickCount++;
        }
    }
}


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Example 01.01 - Basic skeleton</title>
    <script type="text/javascript" src="../libs/three.js"></script>

    <style>
        body {
            /* set margin to 0 and overflow to hidden, to
             use the complete page */
            margin: 0;
            overflow: hidden;
        }
    </style>
</head>
<body>

<!-- Div which will hold the Output -->
<div id="WebGL-output">

</div>

<!-- Javascript code that runs our Three.js examples -->
<script type="text/javascript">

    // once everything is loaded, we run our Three.js stuff.
    function init() {
        // here we'll put the Three.js stuff
    }
    window.onload = init
</script>

</body>
</html>


text:
YOU ARE HERE

UI Tabs & Accordion

Tabs & Accordion - Components

          Basic

          Assumtion

            Dropdown

            @fat
            @mdo

Tabs-enabled widget

You will never know exactly how something will go until you try it.

You can think three hundred times and still have no precise result. If you see
          attractive girl all you need to do is to go and ask her to give you her phone. You don't
          need to think about HOW it can turn out. All you have to do is to GO and DO IT. It
          should be super-fast and easy. No hesitation. You ask me: "What to do with these
          fearful thoughts preventing me from doing that?" The answer is to ignore them, because
          they can't disappear immediately.

The same thing is for startups and ideas. If you have an idea right away after it appears in your mind you should go and make a first step to implement it.

          <button class="btn btn-inverse">Cancel</button>
          <button class="btn btn-primary">Some button</button>

Why don't use Lore Ipsum? I think if some one says don't use lore ipsum it's very controversial
          point. I think the opposite actually. Everyone knows what is lore ipsum - it is easy to understand if text is lore ipsum.

              Check
              Dance?

 If you will think too much it will sink in the swamp of never implemented plans and
          ideas or will just go away or will be implemented by someone else.

5 months of doing everything to achieve nothing.

You'll automatically skip - because you know - it's just non-informative stub. But what if there some text like this one?

          Plan it? Make it!

The same thing is for startups and ideas. If you have an idea right away after it appears
          in your mind you should go and make a first step to implement it.

Basic

Assumtion

Works

            I had an idea named Great Work. It was a service aimed to help people find their passion.
            Yes I know it sound crazy and super naïve but I worked on that. I started to work on
            planning, graphics, presentations, pictures, descriptions, articles, investments and so on.
            I worked on everything but not the project itself.

Why don't use Lore Ipsum? I think if some one says don't use lore ipsum it's very controversial
            point. I think the opposite actually. Everyone knows what is lore ipsum - it is easy to understand if text is lore ipsum.

                Check
                Dance?

 If you will think too much it will sink in the swamp of never implemented plans and
            ideas or will just go away or will be implemented by someone else.

5 months of doing everything to achieve nothing.

You'll automatically skip - because you know - it's just non-informative stub. But what if there some text like this one?

Basic

Assumtion

Works

            I had an idea named Great Work. It was a service aimed to help people find their passion.
            Yes I know it sound crazy and super naïve but I worked on that. I started to work on
            planning, graphics, presentations, pictures, descriptions, articles, investments and so on.
            I worked on everything but not the project itself.

Why don't use Lore Ipsum? I think if some one says don't use lore ipsum it's very controversial
            point. I think the opposite actually. Everyone knows what is lore ipsum - it is easy to understand if text is lore ipsum.

                Check
                Dance?

 If you will think too much it will sink in the swamp of never implemented plans and
            ideas or will just go away or will be implemented by someone else.

5 months of doing everything to achieve nothing.

You'll automatically skip - because you know - it's just non-informative stub. But what if there some text like this one?

    <accordion [closeOthers]="true" class="mb-lg show" id="accordion">
      <accordion-group isOpen="true">

            Collapsible Group Item

          Get base styles and flexible support for collapsible components like accordions and navigation.
          Using the collapse plugin, we built a simple accordion by extending the panel component.

      </accordion-group>
      <accordion-group>

            Random from the Web

Light Blue - is a next generation admin template based on the latest Metro design. There are few reasons we want to tell you, why we have created it: We didn't like the darkness of most of admin templates, so we created this light one. We didn't like the high contrast of most of admin templates, so we created this unobtrusive one. We searched for a
            solution of how to make widgets look like real widgets, so we decided that deep background - is what makes widgets look real.

- Some One

      </accordion-group>
      <accordion-group>

            Check It

          Why don't use Lore Ipsum? I think if some one says don't use lore ipsum it's very controversial point. I think the opposite actually.

      </accordion-group>
    </accordion>

    <accordion [closeOthers]="true" class="mb-lg show" id="accordion2">
      <accordion-group>

              Collapsible Group Item

            Get base styles and flexible support for collapsible components like accordions and navigation.
            Using the collapse plugin, we built a simple accordion by extending the panel component.
      </accordion-group>
      <accordion-group>

              Normal Text Insertion

Why don't use Lore Ipsum? I think if some one says don't use lore ipsum it's very
              controversial point. I think the opposite actually. Everyone knows what is lore ipsum
              - it is easy to understand if text is lore ipsum. You'll automatically skip -
              because you know - it's just non-informative stub. But what if there some text like
              this one? You start to read it! But the goal of this text is different. The goal is
              the example. So a bit of Lore Ipsum is always very good practice. Keep it in mind!

      </accordion-group>
      <accordion-group>

              Check It

            Why don't use Lore Ipsum? I think if some one says don't use lore ipsum it's very controversial point. I think the opposite actually.
      </accordion-group>
    </accordion>


text:
<bill session="110" type="h" number="7065" updated="2009-01-09T07:21:54-05:00">
	<status><introduced date="1222315200" datetime="2008-09-25"/></status>

	<introduced date="1222315200" datetime="2008-09-25"/>
	<titles>
		<title type="short" as="introduced">Health Workforce Investment Act of 2008</title>
		<title type="official" as="introduced">To amend the Public Health Service Act to address health workforce shortages.</title>
	</titles>
	<sponsor id="400309"/>
	<cosponsors>
		<cosponsor id="400263" joined="2008-09-25"/>
		<cosponsor id="400284" joined="2008-09-25"/>
		<cosponsor id="400062" joined="2008-09-25"/>
	</cosponsors>
	<actions>
		<action date="1222315200" datetime="2008-09-25"><text>Referred to the House Committee on Energy and Commerce.</text></action>
		<action date="1222315200" datetime="2008-09-25"><text>Referred to the Subcommittee on Health.</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>
	<summary>

	</summary>
</bill>


text:
import Ember from 'ember';

export default Ember.Route.extend({
  actions: {
    didTransition: function() {
      Ember.run.schedule("afterRender",this,function() {
        window.Prism.highlightAll();
        console.log('called');
      });

      return true;
    }
  }
});


text:
using LolHandbook.DataDragon;

namespace LolHandbook.ViewModels.Stubs
{
    public class StubChampionDetailViewModel : ChampionDetailViewModel
    {
        public StubChampionDetailViewModel(IDataDragonClient dataDragonClient) : base(dataDragonClient)
        {
            this.Id = "ID";
        }
    }
}


text:
<?php get_header_once(); ?>

<?php if(have_posts()): while(have_posts()): the_post(); ?>

      <?= get_the_title() ?>

        <?php the_content() ?>

<?php endwhile; endif; ?>

<?php get_footer_once(); ?>


text:
def superb_text_constructor_for(resource_name)
  resources resource_name, only: [] do
    mount SuperbTextConstructor::Engine => '/wysiwyg/:namespace'
  end
end


text:
namespace Builder {
	internal class Manufacturer {
		public void Construct(IPhoneBuilder builder) {
			builder.BuildOs();
			builder.BuildBattery();
			builder.BuildScreen();
			builder.BuildStylus();
		}
	}
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>UNIX Application Servers — MIT Kerberos Documentation</title>

    <link rel="stylesheet" href="../_static/agogo.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../_static/kerb.css" type="text/css" />

    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="MIT Kerberos Documentation" href="../index.html" />
    <link rel="up" title="Installation guide" href="install.html" />
    <link rel="next" title="Configuration Files" href="conf_files/index.html" />
    <link rel="prev" title="Installing and configuring UNIX client machines" href="install_clients.html" />

MIT Kerberos Documentation

        Contents |
        previous |
        next |
        index |
        Search |
    feedback

UNIX Application Servers¶

An application server is a host that provides one or more services
over the network.  Application servers can be “secure” or “insecure.”
A “secure” host is set up to require authentication from every client
connecting to it.  An “insecure” host will still provide Kerberos
authentication, but will also allow unauthenticated clients to
connect.

If you have Kerberos V5 installed on all of your client machines, MIT
recommends that you make your hosts secure, to take advantage of the
security that Kerberos authentication affords.  However, if you have
some clients that do not have Kerberos V5 installed, you can run an
insecure server, and still take advantage of Kerberos V5’s single
sign-on capability.

The keytab file¶

All Kerberos server machines need a keytab file to authenticate to the
KDC.  By default on UNIX-like systems this file is named DEFKTNAME.
The keytab file is an local copy of the host’s key.  The keytab file
is a potential point of entry for a break-in, and if compromised,
would allow unrestricted access to its host.  The keytab file should
be readable only by root, and should exist only on the machine’s local
disk.  The file should not be part of any backup of the machine,
unless access to the backup data is secured as tightly as access to
the machine’s root password.

In order to generate a keytab for a host, the host must have a
principal in the Kerberos database.  The procedure for adding hosts to
the database is described fully in Adding, modifying and deleting principals.  (See
Create host keytabs for slave KDCs for a brief description.)  The keytab is
generated by running kadmin and issuing the ktadd
command.

For example, to generate a keytab file to allow the host
<tt class="docutils literal">trillium.mit.edu</tt> to authenticate for the services host, ftp, and
pop, the administrator <tt class="docutils literal">joeadmin</tt> would issue the command (on
<tt class="docutils literal">trillium.mit.edu</tt>):

trillium% kadmin
kadmin5: ktadd host/trillium.mit.edu ftp/trillium.mit.edu
    pop/trillium.mit.edu
kadmin: Entry for principal host/trillium.mit.edu@ATHENA.MIT.EDU with
    kvno 3, encryption type DES-CBC-CRC added to keytab
    FILE:/etc/krb5.keytab.
kadmin: Entry for principal ftp/trillium.mit.edu@ATHENA.MIT.EDU with
    kvno 3, encryption type DES-CBC-CRC added to keytab
    FILE:/etc/krb5.keytab.
kadmin: Entry for principal pop/trillium.mit.edu@ATHENA.MIT.EDU with
    kvno 3, encryption type DES-CBC-CRC added to keytab
    FILE:/etc/krb5.keytab.
kadmin5: quit
trillium%

If you generate the keytab file on another host, you need to get a
copy of the keytab file onto the destination host (<tt class="docutils literal">trillium</tt>, in
the above example) without sending it unencrypted over the network.

Some advice about secure hosts¶

Kerberos V5 can protect your host from certain types of break-ins, but
it is possible to install Kerberos V5 and still leave your host
vulnerable to attack.  Obviously an installation guide is not the
place to try to include an exhaustive list of countermeasures for
every possible attack, but it is worth noting some of the larger holes
and how to close them.

We recommend that backups of secure machines exclude the keytab file
(DEFKTNAME).  If this is not possible, the backups should at least be
done locally, rather than over a network, and the backup tapes should
be physically secured.

The keytab file and any programs run by root, including the Kerberos
V5 binaries, should be kept on local disk.  The keytab file should be
readable only by root.

On this page

UNIX Application Servers

The keytab file

Some advice about secure hosts

Table of contents

For users

For administrators

Installation guide

Installing KDCs

Installing and configuring UNIX client machines

UNIX Application Servers

Configuration Files

Realm configuration decisions

Database administration

Account lockout

Configuring Kerberos with OpenLDAP back-end

Application servers

Host configuration

Backups of secure hosts

PKINIT configuration

OTP Preauthentication

Principal names and DNS

Encryption types

HTTPS proxy configuration

Authentication indicators

Administration  programs

MIT Kerberos defaults

Environment variables

Troubleshooting

Advanced topics

Various links

For application developers

For plugin module developers

Building Kerberos V5

Kerberos V5 concepts

Protocols and file formats

MIT Kerberos features

How to build this documentation from the source

Contributing to the MIT Kerberos Documentation

Resources

Full Table of Contents

Search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" size="18" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

Release: 1.16

                © Copyright 1985-2017, MIT.

        Contents |
        previous |
        next |
        index |
        Search |
    feedback


text:
package info.archinnov.achilles.internals.parser.context;

import static info.archinnov.achilles.internals.parser.TypeUtils.*;
import static java.util.stream.Collectors.toList;

import java.util.*;

import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.TypeName;

import info.archinnov.achilles.internals.parser.TypeUtils;

public class FunctionSignature {
    public final Optional<String> keyspace;
    public final TypeName sourceClass;
    public final String name;
    public final String methodName;
    public final TypeName sourceReturnType;
    public final List<TypeName> sourceParameterTypes;
    public final FunctionParamSignature returnTypeSignature;
    public final List<FunctionParamSignature> parameterSignatures;

    public FunctionSignature(Optional<String> keyspace, TypeName sourceClass, String name, String methodName, FunctionParamSignature returnTypeSignature,
                             List<FunctionParamSignature> parameterSignatures) {
        this.keyspace = keyspace;
        this.sourceClass = sourceClass;
        this.name = name;
        this.methodName = methodName;
        this.returnTypeSignature = returnTypeSignature;
        this.sourceReturnType = returnTypeSignature.sourceTypeName;
        this.parameterSignatures = parameterSignatures;
        this.sourceParameterTypes = parameterSignatures.stream().map(x -> x.sourceTypeName).collect(toList());
    }

    public FunctionSignature(Optional<String> keyspace, TypeName sourceClass, String name, FunctionParamSignature returnTypeSignature,
                             List<FunctionParamSignature> parameterSignatures) {
        this.keyspace = keyspace;
        this.sourceClass = sourceClass;
        this.name = name;
        this.methodName = name;
        this.returnTypeSignature = returnTypeSignature;
        this.sourceReturnType = returnTypeSignature.sourceTypeName;
        this.parameterSignatures = parameterSignatures;
        this.sourceParameterTypes = parameterSignatures.stream().map(x -> x.sourceTypeName).collect(toList());
    }

    public String getFunctionName() {
        return keyspace.isPresent() ? keyspace.get() + "." + name : name;
    }

    public TypeName returnTypeForFunctionParam() {
        return TypeUtils.determineTypeForFunctionParam(returnTypeSignature.sourceTypeName);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        FunctionSignature that = (FunctionSignature) o;
        return Objects.equals(keyspace, that.keyspace) &&
                Objects.equals(name.toLowerCase(), that.name.toLowerCase()) &&
                Objects.equals(sourceReturnType, that.sourceReturnType) &&
                Objects.equals(sourceParameterTypes, that.sourceParameterTypes);
    }

    @Override
    public int hashCode() {
        return Objects.hash(keyspace, name.toLowerCase(), methodName.toLowerCase(), sourceReturnType, sourceParameterTypes);
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("UDFSignature{");
        sb.append("keyspace=").append(keyspace);
        sb.append(", sourceClass=").append(sourceClass);
        sb.append(", methodName='").append(methodName).append('\'');
        sb.append(", name='").append(name).append('\'');
        sb.append(", returnType=").append(sourceReturnType);
        sb.append(", sourceParameterTypes=").append(sourceParameterTypes);
        sb.append('}');
        return sb.toString();
    }

    public static class FunctionParamSignature {
        public final String name;
        public final TypeName sourceTypeName;
        public final TypeName targetCQLTypeName;
        public final String targetCQLDataType;

        public static FunctionParamSignature VOID() {
            return new FunctionParamSignature("returnType", TypeName.VOID, TypeName.VOID, "");
        }

        public FunctionParamSignature(String name, TypeName sourceTypeName, TypeName targetCQLTypeName, String targetCQLDataType) {
            this.name = name;
            this.sourceTypeName = sourceTypeName;
            this.targetCQLTypeName = targetCQLTypeName;
            this.targetCQLDataType = targetCQLDataType;
        }

        public TypeName typeForFunctionParam() {
            return TypeUtils.determineTypeForFunctionParam(this.sourceTypeName);
        }

        public static FunctionParamSignature tupleType(String paramName, ClassName tupleTypeName, FunctionParamSignature... signatures) {
            final List<TypeName> typeNames = Arrays.stream(signatures)
                    .map(x -> x.sourceTypeName)
                    .collect(toList());
            final StringJoiner joiner = new StringJoiner(", ", "frozen<tuple<", ">>");

            Arrays.stream(signatures)
                    .forEach(x -> joiner.add(x.targetCQLDataType));

            return new FunctionParamSignature(paramName, genericType(tupleTypeName, typeNames.toArray(new TypeName[typeNames.size()])), JAVA_DRIVER_TUPLE_VALUE_TYPE, joiner.toString());
        }

        public static FunctionParamSignature listType(String paramName, FunctionParamSignature nestedSignature, boolean isFrozen) {
            if (isFrozen) {
                return new FunctionParamSignature(paramName, genericType(LIST, nestedSignature.sourceTypeName), genericType(LIST, nestedSignature.targetCQLTypeName), "frozen<list<" + nestedSignature.targetCQLDataType + ">>");
            } else {
                return new FunctionParamSignature(paramName, genericType(LIST, nestedSignature.sourceTypeName), genericType(LIST, nestedSignature.targetCQLTypeName), "list<" + nestedSignature.targetCQLDataType + ">");
            }
        }

        public static FunctionParamSignature setType(String paramName, FunctionParamSignature nestedSignature, boolean isFrozen) {
            if (isFrozen) {
                return new FunctionParamSignature(paramName, genericType(SET, nestedSignature.sourceTypeName), genericType(SET, nestedSignature.targetCQLTypeName), "frozen<set<" + nestedSignature.targetCQLDataType + ">>");
            } else {
                return new FunctionParamSignature(paramName, genericType(SET, nestedSignature.sourceTypeName), genericType(SET, nestedSignature.targetCQLTypeName), "set<" + nestedSignature.targetCQLDataType + ">");
            }
        }

        public static FunctionParamSignature mapType(String paramName, FunctionParamSignature keySignature, FunctionParamSignature valueSignature, boolean isFrozen) {
            if (isFrozen) {
                return new FunctionParamSignature(paramName,
                        genericType(MAP, keySignature.sourceTypeName, valueSignature.sourceTypeName),
                        genericType(MAP, keySignature.targetCQLTypeName, valueSignature.targetCQLTypeName),
                        "frozen<map<" + keySignature.targetCQLDataType + ", " + valueSignature.targetCQLDataType + ">>");
            } else {
                return new FunctionParamSignature(paramName,
                        genericType(MAP, keySignature.sourceTypeName, valueSignature.sourceTypeName),
                        genericType(MAP, keySignature.targetCQLTypeName, valueSignature.targetCQLTypeName),
                        "map<" + keySignature.targetCQLDataType + ", " + valueSignature.targetCQLDataType + ">");
            }
        }

        public static FunctionParamSignature optionalType(String paramName, FunctionParamSignature nestedSignature) {
            return new FunctionParamSignature(paramName,  genericType(OPTIONAL, nestedSignature.sourceTypeName), nestedSignature.targetCQLTypeName, nestedSignature.targetCQLDataType);
        }

        @Override
        public String toString() {
            final StringBuilder sb = new StringBuilder("UDFParamSignature{");
            sb.append("name='").append(name).append('\'');
            sb.append(", sourceTypeName=").append(sourceTypeName);
            sb.append(", targetCQLTypeName=").append(targetCQLTypeName);
            sb.append(", targetCQLDataType='").append(targetCQLDataType).append('\'');
            sb.append('}');
            return sb.toString();
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            FunctionParamSignature that = (FunctionParamSignature) o;
            return Objects.equals(name, that.name) &&
                    Objects.equals(sourceTypeName, that.sourceTypeName) &&
                    Objects.equals(targetCQLTypeName, that.targetCQLTypeName) &&
                    Objects.equals(targetCQLDataType, that.targetCQLDataType);
        }

        @Override
        public int hashCode() {
            return Objects.hash(name, sourceTypeName, targetCQLTypeName, targetCQLDataType);
        }
    }
}


text:
Alex Junior

## Perfil

Meu nome é Alex Junior, trabalho atualmente como Analista Programador PHP, mas atuo como desenvolvedor full stack.

Possuo 4 anos de experiencia com desenvolvimento, mesclando front-end com back-end.

Estou cursando 7º semestre de Ciência da Computação.

## Links

* [Facebook](https://www.facebook.com/alexjunior012)
* [Twitter](https://twitter.com/alexjunior012)
* [Google+](https://plus.google.com/+AlexJunior012)
* [Linkedin](https://br.linkedin.com/in/alexjunior012)
* [Site](http://www.alexjunior012.com.br)
* alexjunior.web@gmail.com

## Gostaria de retribuir a ajuda do Alex?

Só adicionar nas redes sociais, mandar um abraço e repassar o conhecimento adquirido.

## Pupilos(as) do Alex Junior
[Romário Coimbra](/pupilos/perfis/RomarioCoimbra.md)


text:
.. note::   *The commands below are presumed to be run relative to the project root
            unless explicitly stated otherwise.* ``./`` *also refers to the project root.*


text:
/
#define STRINGLIB_IS_UNICODE 1

#define FASTSEARCH ucs4lib_fastsearch
#define STRINGLIB(F) ucs4lib_##F
#define STRINGLIB_OBJECT PyUnicodeObject
#define STRINGLIB_SIZEOF_CHAR 4
#define STRINGLIB_MAX_CHAR 0x10FFFFu
#define STRINGLIB_CHAR Py_UCS4
#define STRINGLIB_TYPE_NAME "unicode"
#define STRINGLIB_PARSE_CODE "U"
#define STRINGLIB_EMPTY unicode_empty
#define STRINGLIB_ISSPACE Py_UNICODE_ISSPACE
#define STRINGLIB_ISLINEBREAK BLOOM_LINEBREAK
#define STRINGLIB_ISDECIMAL Py_UNICODE_ISDECIMAL
#define STRINGLIB_TODECIMAL Py_UNICODE_TODECIMAL
#define STRINGLIB_STR PyUnicode_4BYTE_DATA
#define STRINGLIB_LEN PyUnicode_GET_LENGTH
#define STRINGLIB_NEW _PyUnicode_FromUCS4
#define STRINGLIB_CHECK PyUnicode_Check
#define STRINGLIB_CHECK_EXACT PyUnicode_CheckExact

#define STRINGLIB_TOSTR PyObject_Str
#define STRINGLIB_TOASCII PyObject_ASCII

#define _Py_InsertThousandsGrouping _PyUnicode_ucs4_InsertThousandsGrouping


text:
Overture
========

Overture is a JavaScript library that contains all the tools you need to build a slick, modern web app. It was originally built to power [FastMail](https://www.fastmail.com)'s awesome webmail.

To get started, check out the heavily commented Todo demo app in the `examples` folder, or use your browser web dev tools on the live demo at: <http://overturejs.com/examples/Todo/>.

You can find API documentation and download a pre-built copy of the library from <http://overturejs.com>.

Overture is MIT licensed. No animals were harmed in the making of this code.

Building from Source
--------------------

Prerequisites: just Node 6+ and optionally Yarn.

    git clone https://github.com/fastmail/overture.git
    cd overture
    yarn  # `npm install` works too

If you want to build the parbroken documentation as well:

    make docs


text:
<html>
<body>
This package contains the core library client interface.
</body>
</html>


text:
package org.wave.scanner.validators;

import static org.junit.Assert.assertEquals;

import java.io.File;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.wave.scanner.enums.ErrorEnum;
import org.wave.scanner.exceptions.ScannerException;
import org.wave.scanner.validators.SourceValidator;

public class SourceValidatorTest {

	private SourceValidator validator;

	@Before
	public void setUp() {
		this.validator = new SourceValidator();
	}

	@Test(expected = ScannerException.class)
	public void deveLancarExcecaoQuandoOSourceFolderForNuloException() throws ScannerException {
		this.validator.validate(null);
	}

	@Test
	public void deveLancarExcecaoQuandoOSourceFolderForNulo() {
		try {
			this.validator.validate(null);
		} catch (ScannerException e) {
			assertEquals(ErrorEnum.NULL_FOLDER.getMessage(), e.getMessage());
		}
	}

	@Test(expected = ScannerException.class)
	public void deveLancarExcecaoQuandoOSourceFolderNaoExistirException() throws ScannerException {
		File sourceFolder = new File("docs");

		this.validator.validate(sourceFolder);
	}

	@Test
	public void deveLancarExcecaoQuandoOSourceFolderNaoExistir() {
		File sourceFolder = new File("docs");

		try {
			this.validator.validate(sourceFolder);
		} catch (ScannerException e) {
			assertEquals(ErrorEnum.FOLDER_NOT_FOUND.getMessage(sourceFolder.getName()), e.getMessage());
		}
	}

	@Test(expected = ScannerException.class)
	public void deveLancarExcecaoQuandoOSourceFolderNaoForDiretorioException() throws ScannerException {
		File sourceFolder = new File("test/org/wave/scanner/examples/src");

		this.validator.validate(sourceFolder);
	}

	@Test
	public void deveLancarExcecaoQuandoOSourceFolderNaoForDiretorio() {
		File sourceFolder = new File("test/org/wave/scanner/examples/src");

		try {
			this.validator.validate(sourceFolder);
		} catch (ScannerException e) {
			assertEquals(ErrorEnum.INVALID_FOLDER.getMessage(sourceFolder.getName()), e.getMessage());
		}
	}

	@After
	public void tearDown() {
		this.validator = null;
	}

}