text:
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @implements {UI.Searchable}
 * @unrestricted
 */
Profiler.HeapProfileView = class extends Profiler.ProfileView {
  /**
   * @param {!Profiler.SamplingHeapProfileHeader} profileHeader
   */
  constructor(profileHeader) {
    super();

    this._profileHeader = profileHeader;
    this._profileType = profileHeader.profileType();
    const views = [
      Profiler.ProfileView.ViewTypes.Flame, Profiler.ProfileView.ViewTypes.Heavy, Profiler.ProfileView.ViewTypes.Tree
    ];

    const isNativeProfile = this._profileType.id === Profiler.SamplingNativeHeapProfileType.TypeId ||
        this._profileType.id === Profiler.SamplingNativeHeapSnapshotType.TypeId;
    if (isNativeProfile)
      views.push(Profiler.ProfileView.ViewTypes.Text);

    this.initialize(new Profiler.HeapProfileView.NodeFormatter(this), views);
    const profile = new Profiler.SamplingHeapProfileModel(profileHeader._profile || profileHeader.protocolProfile());
    this.adjustedTotal = profile.total;
    this.setProfile(profile);

    this._selectedSizeText = new UI.ToolbarText();

    if (Runtime.experiments.isEnabled('samplingHeapProfilerTimeline')) {
      this._timelineOverview = new Profiler.HeapTimelineOverview();
      this._timelineOverview.addEventListener(
          Profiler.HeapTimelineOverview.IdsRangeChanged, this._onIdsRangeChanged.bind(this));
      this._timelineOverview.show(this.element, this.element.firstChild);
      this._timelineOverview.start();

      this._profileType.addEventListener(
          Profiler.SamplingHeapProfileType.Events.StatsUpdate, this._onStatsUpdate, this);
      this._profileType.once(Profiler.ProfileType.Events.ProfileComplete).then(() => {
        this._profileType.removeEventListener(
            Profiler.SamplingHeapProfileType.Events.StatsUpdate, this._onStatsUpdate, this);
        this._timelineOverview.stop();
        this._timelineOverview.updateGrid();
      });
    }
  }

  /**
   * @override
   * @return {!Array<!UI.ToolbarItem>}
   */
  syncToolbarItems() {
    return [...super.syncToolbarItems(), this._selectedSizeText];
  }

  /**
   * @param {!Common.Event} event
   */
  _onIdsRangeChanged(event) {
    const minId = /** @type {number} */ (event.data.minId);
    const maxId = /** @type {number} */ (event.data.maxId);
    this._selectedSizeText.setText(ls`Selected size: ${Number.bytesToString(event.data.size)}`);
    this._setSelectionRange(minId, maxId);
  }

  /**
   * @param {number} minId
   * @param {number} maxId
   */
  _setSelectionRange(minId, maxId) {
    const profile = new Profiler.SamplingHeapProfileModel(
        this._profileHeader._profile || this._profileHeader.protocolProfile(), minId, maxId);
    this.adjustedTotal = profile.total;
    this.setProfile(profile);
  }

  /**
   * @param {!Common.Event} event
   */
  _onStatsUpdate(event) {
    const profile = event.data;

    if (!this._totalTime) {
      this._timestamps = [];
      this._sizes = [];
      this._max = [];
      this._ordinals = [];
      this._totalTime = 30000;
      this._lastOrdinal = 0;
    }

    this._sizes.fill(0);
    this._sizes.push(0);
    this._timestamps.push(Date.now());
    this._ordinals.push(this._lastOrdinal + 1);
    this._lastOrdinal = profile.samples.reduce((res, sample) => Math.max(res, sample.ordinal), this._lastOrdinal);
    for (const sample of profile.samples) {
      const bucket = this._ordinals.upperBound(sample.ordinal) - 1;
      this._sizes[bucket] += sample.size;
    }
    this._max.push(this._sizes.peekLast());

    if (this._timestamps.peekLast() - this._timestamps[0] > this._totalTime)
      this._totalTime *= 2;

    const samples = /** @type {!Profiler.HeapTimelineOverview.Samples} */ ({
      sizes: this._sizes,
      max: this._max,
      ids: this._ordinals,
      timestamps: this._timestamps,
      totalTime: this._totalTime
    });

    this._timelineOverview.setSamples(samples);
  }

  /**
   * @override
   * @param {string} columnId
   * @return {string}
   */
  columnHeader(columnId) {
    switch (columnId) {
      case 'self':
        return Common.UIString('Self Size (bytes)');
      case 'total':
        return Common.UIString('Total Size (bytes)');
    }
    return '';
  }

  /**
   * @override
   * @return {!PerfUI.FlameChartDataProvider}
   */
  createFlameChartDataProvider() {
    return new Profiler.HeapFlameChartDataProvider(
        /** @type {!Profiler.SamplingHeapProfileModel} */ (this.profile()), this._profileHeader.heapProfilerModel());
  }

  /**
   * @override
   * @param {!UI.SimpleView} view
   */
  populateTextView(view) {
    const guides = '+!:|';
    let text = `Sampling memory profile.\n\nDate/Time:       ${new Date()}\n` +
        `Report Version:  7\n` +
        `App Version:     ${/Chrom\S*/.exec(navigator.appVersion)[0] || 'Unknown'}\n` +
        `Node Weight:     1 KiB\n` +
        `Total Size:      ${Math.round(this.profile().root.total / 1024)} KiB\n` +
        `----\n\nCall graph:\n`;
    const sortedChildren = this.profile().root.children.sort((a, b) => b.total - a.total);
    const modules = this.profile().modules.map(
        m => Object.assign({address: BigInt(m.baseAddress), endAddress: BigInt(m.baseAddress) + BigInt(m.size)}, m));
    modules.sort((m1, m2) => m1.address > m2.address ? 1 : m1.address < m2.address ? -1 : 0);
    for (const child of sortedChildren)
      printTree('    ', child !== sortedChildren.peekLast(), child);

    text += '\nBinary Images:\n';
    for (const module of modules) {
      const fileName = /[^/\\]*$/.exec(module.name)[0];
      const version = '1.0';
      const formattedUuid = module.uuid.includes('-') ?
          module.uuid :
          module.uuid.replace(/(.{8})(.{4})(.{4})(.{4})(.{12}).*/, '$1-$2-$3-$4-$5');
      text += `${('0x' + module.address.toString(16)).padStart(18)} - `;
      text += `${('0x' + (module.endAddress - BigInt(1)).toString(16)).padStart(18)}`;
      text += `  ${fileName} (${version}) <${formattedUuid}> ${module.name}\n`;
    }

    view.contentElement.createChild('pre', 'profile-text-view monospace').textContent = text;

    /**
     * @param {string} padding
     * @param {boolean} drawGuide
     * @param {!SDK.ProfileNode} node
     */
    function printTree(padding, drawGuide, node) {
      const addressText = /0x[0-9a-f]*|[0-9]*/.exec(node.functionName)[0] || '';
      let module;
      if (addressText) {
        const address = BigInt(addressText);
        const pos = modules.upperBound(address, (address, module) => address - module.address);
        if (pos > 0 && address < modules[pos - 1].endAddress)
          module = modules[pos - 1];
      }
      const functionName =
          (addressText ? node.functionName.substr(addressText.length + 1) : node.functionName) || '???';
      text += `${padding}${Math.round(node.total / 1024)}  ${functionName}  `;
      if (module) {
        const fileName = /[^/\\]*$/.exec(module.name);
        if (fileName)
          text += `(in ${fileName})  `;
        const offset = BigInt(addressText) - module.address;
        text += `load address ${module.baseAddress} + 0x${offset.toString(16)}  `;
      }
      if (addressText)
        text += `[${addressText}]`;
      text += '\n';
      const guideChar = drawGuide ? guides[padding.length / 2 % guides.length] : ' ';
      const nextPadding = padding + guideChar + ' ';
      const sortedChildren = node.children.sort((a, b) => b.total - a.total);
      for (const child of sortedChildren)
        printTree(nextPadding, child !== sortedChildren.peekLast(), child);
    }
  }
};

/**
 * @unrestricted
 */
Profiler.SamplingHeapProfileTypeBase = class extends Profiler.ProfileType {
  /**
   * @param {string} typeId
   * @param {string} description
   */
  constructor(typeId, description) {
    super(typeId, description);
    this._recording = false;
  }

  /**
   * @override
   * @return {?Profiler.SamplingHeapProfileHeader}
   */
  profileBeingRecorded() {
    return /** @type {?Profiler.SamplingHeapProfileHeader} */ (super.profileBeingRecorded());
  }

  /**
   * @override
   * @return {string}
   */
  typeName() {
    return 'Heap';
  }

  /**
   * @override
   * @return {string}
   */
  fileExtension() {
    return '.heapprofile';
  }

  get buttonTooltip() {
    return this._recording ? ls`Stop heap profiling` : ls`Start heap profiling`;
  }

  /**
   * @override
   * @return {boolean}
   */
  buttonClicked() {
    if (this._recording)
      this._stopRecordingProfile();
    else
      this._startRecordingProfile();
    return this._recording;
  }

  _startRecordingProfile() {
    const heapProfilerModel = UI.context.flavor(SDK.HeapProfilerModel);
    if (this.profileBeingRecorded() || !heapProfilerModel)
      return;
    const profileHeader = new Profiler.SamplingHeapProfileHeader(heapProfilerModel, this);
    this.setProfileBeingRecorded(profileHeader);
    this.addProfile(profileHeader);
    profileHeader.updateStatus(ls`Recording\u2026`);

    const icon = UI.Icon.create('smallicon-warning');
    icon.title = ls`Heap profiler is recording`;
    UI.inspectorView.setPanelIcon('heap_profiler', icon);

    this._recording = true;
    this._startSampling();
  }

  async _stopRecordingProfile() {
    this._recording = false;
    if (!this.profileBeingRecorded() || !this.profileBeingRecorded().heapProfilerModel())
      return;

    this.profileBeingRecorded().updateStatus(ls`Stopping\u2026`);
    const profile = await this._stopSampling();
    const recordedProfile = this.profileBeingRecorded();
    if (recordedProfile) {
      console.assert(profile);
      recordedProfile.setProtocolProfile(profile);
      recordedProfile.updateStatus('');
      this.setProfileBeingRecorded(null);
    }
    UI.inspectorView.setPanelIcon('heap_profiler', null);
    this.dispatchEventToListeners(Profiler.ProfileType.Events.ProfileComplete, recordedProfile);
  }

  /**
   * @override
   * @param {string} title
   * @return {!Profiler.ProfileHeader}
   */
  createProfileLoadedFromFile(title) {
    return new Profiler.SamplingHeapProfileHeader(null, this, title);
  }

  /**
   * @override
   */
  profileBeingRecordedRemoved() {
    this._stopRecordingProfile();
  }

  _startSampling() {
    throw 'Not implemented';
  }

  /**
   * return {!Promise<!Protocol.HeapProfiler.SamplingHeapProfile>}
   */
  _stopSampling() {
    throw 'Not implemented';
  }
};

/**
 * @unrestricted
 */
Profiler.SamplingHeapProfileType = class extends Profiler.SamplingHeapProfileTypeBase {
  constructor() {
    super(Profiler.SamplingHeapProfileType.TypeId, ls`Allocation sampling`);
    Profiler.SamplingHeapProfileType.instance = this;
    this._updateTimer = null;
    this._updateIntervalMs = 200;
  }

  get treeItemTitle() {
    return ls`SAMPLING PROFILES`;
  }

  get description() {
    return ls`Record memory allocations using sampling method.
              This profile type has minimal performance overhead and can be used for long running operations.
              It provides good approximation of allocations broken down by JavaScript execution stack.`;
  }

  /**
   * @override
   * @return {boolean}
   */
  hasTemporaryView() {
    return Runtime.experiments.isEnabled('samplingHeapProfilerTimeline');
  }

  /**
   * @override
   */
  _startSampling() {
    this.profileBeingRecorded().heapProfilerModel().startSampling();
    if (Runtime.experiments.isEnabled('samplingHeapProfilerTimeline'))
      this._updateTimer = setTimeout(this._updateStats.bind(this), this._updateIntervalMs);
  }

  /**
   * @override
   * return {!Promise<!Protocol.HeapProfiler.SamplingHeapProfile>}
   */
  _stopSampling() {
    clearTimeout(this._updateTimer);
    this._updateTimer = null;
    this.dispatchEventToListeners(Profiler.SamplingHeapProfileType.Events.RecordingStopped);
    return this.profileBeingRecorded().heapProfilerModel().stopSampling();
  }

  async _updateStats() {
    const profile = await this.profileBeingRecorded().heapProfilerModel().getSamplingProfile();
    if (!this._updateTimer)
      return;
    this.dispatchEventToListeners(Profiler.SamplingHeapProfileType.Events.StatsUpdate, profile);
    this._updateTimer = setTimeout(this._updateStats.bind(this), this._updateIntervalMs);
  }
};

Profiler.SamplingHeapProfileType.TypeId = 'SamplingHeap';

/** @enum {symbol} */
Profiler.SamplingHeapProfileType.Events = {
  RecordingStopped: Symbol('RecordingStopped'),
  StatsUpdate: Symbol('StatsUpdate')
};

/**
 * @unrestricted
 */
Profiler.SamplingNativeHeapProfileType = class extends Profiler.SamplingHeapProfileTypeBase {
  constructor() {
    super(Profiler.SamplingNativeHeapProfileType.TypeId, ls`Native memory allocation sampling`);
    Profiler.SamplingNativeHeapProfileType.instance = this;
  }

  get treeItemTitle() {
    return ls`NATIVE SAMPLING PROFILES`;
  }

  get description() {
    return ls`Allocation profiles show sampled native memory allocations from the renderer process.`;
  }

  /**
   * @override
   */
  _startSampling() {
    this.profileBeingRecorded().heapProfilerModel().startNativeSampling();
  }

  /**
   * @override
   * return {!Promise<!Protocol.HeapProfiler.SamplingHeapProfile>}
   */
  _stopSampling() {
    return this.profileBeingRecorded().heapProfilerModel().stopNativeSampling();
  }
};

Profiler.SamplingNativeHeapProfileType.TypeId = 'SamplingNativeHeapRecording';

/**
 * @unrestricted
 */
Profiler.SamplingNativeHeapSnapshotType = class extends Profiler.SamplingHeapProfileTypeBase {
  /**
   * @param {string} processType
   */
  constructor(processType) {
    super(Profiler.SamplingNativeHeapSnapshotType.TypeId, ls`Native memory allocation snapshot (${processType})`);
  }

  /**
   * @override
   * @return {boolean}
   */
  isInstantProfile() {
    return true;
  }

  get treeItemTitle() {
    return ls`NATIVE SNAPSHOTS`;
  }

  get description() {
    return ls`Native memory snapshots show sampled native allocations in the renderer process since start up.
              Chrome has to be started with --sampling-heap-profiler flag.
              Check flags at chrome://flags`;
  }

  /**
   * @override
   * @return {boolean}
   */
  buttonClicked() {
    this._takeSnapshot();
    return false;
  }

  /**
   * @return {!Promise}
   */
  async _takeSnapshot() {
    if (this.profileBeingRecorded())
      return;
    const heapProfilerModel = UI.context.flavor(SDK.HeapProfilerModel);
    if (!heapProfilerModel)
      return;

    const profile =
        new Profiler.SamplingHeapProfileHeader(heapProfilerModel, this, ls`Snapshot ${this.nextProfileUid()}`);
    this.setProfileBeingRecorded(profile);
    this.addProfile(profile);
    profile.updateStatus(ls`Snapshotting\u2026`);

    const protocolProfile = await this._takeNativeSnapshot(/** @type {!SDK.HeapProfilerModel} */ (heapProfilerModel));
    const recordedProfile = this.profileBeingRecorded();
    if (recordedProfile) {
      console.assert(protocolProfile);
      recordedProfile.setProtocolProfile(protocolProfile);
      recordedProfile.updateStatus('');
      this.setProfileBeingRecorded(null);
    }

    this.dispatchEventToListeners(Profiler.ProfileType.Events.ProfileComplete, recordedProfile);
  }

  /**
   * @param {!SDK.HeapProfilerModel} heapProfilerModel
   * @return {!Promise<!Protocol.HeapProfiler.SamplingHeapProfile>}
   */
  _takeNativeSnapshot(heapProfilerModel) {
    throw 'Not implemented';
  }
};

Profiler.SamplingNativeHeapSnapshotType.TypeId = 'SamplingNativeHeapSnapshot';

Profiler.SamplingNativeHeapSnapshotBrowserType = class extends Profiler.SamplingNativeHeapSnapshotType {
  constructor() {
    super(ls`Browser`);
    Profiler.SamplingNativeHeapSnapshotBrowserType.instance = this;
  }

  /**
   * @override
   * @param {!SDK.HeapProfilerModel} heapProfilerModel
   * @return {!Promise<!Protocol.HeapProfiler.SamplingHeapProfile>}
   */
  async _takeNativeSnapshot(heapProfilerModel) {
    return await heapProfilerModel.takeNativeBrowserSnapshot();
  }
};

Profiler.SamplingNativeHeapSnapshotRendererType = class extends Profiler.SamplingNativeHeapSnapshotType {
  constructor() {
    super(ls`Renderer`);
    Profiler.SamplingNativeHeapSnapshotRendererType.instance = this;
  }

  /**
   * @override
   * @param {!SDK.HeapProfilerModel} heapProfilerModel
   * @return {!Promise<!Protocol.HeapProfiler.SamplingHeapProfile>}
   */
  async _takeNativeSnapshot(heapProfilerModel) {
    return await heapProfilerModel.takeNativeSnapshot();
  }
};

/**
 * @unrestricted
 */
Profiler.SamplingHeapProfileHeader = class extends Profiler.WritableProfileHeader {
  /**
   * @param {?SDK.HeapProfilerModel} heapProfilerModel
   * @param {!Profiler.SamplingHeapProfileTypeBase} type
   * @param {string=} title
   */
  constructor(heapProfilerModel, type, title) {
    super(
        heapProfilerModel && heapProfilerModel.debuggerModel(), type,
        title || Common.UIString('Profile %d', type.nextProfileUid()));
    this._heapProfilerModel = heapProfilerModel;
    this._protocolProfile =
        /** @type {!Protocol.HeapProfiler.SamplingHeapProfile} */ ({head: {callFrame: {}, children: []}});
  }

  /**
   * @override
   * @return {!Profiler.ProfileView}
   */
  createView() {
    return new Profiler.HeapProfileView(this);
  }

  /**
   * @return {!Protocol.HeapProfiler.SamplingHeapProfile}
   */
  protocolProfile() {
    return this._protocolProfile;
  }

  /**
   * @return {?SDK.HeapProfilerModel}
   */
  heapProfilerModel() {
    return this._heapProfilerModel;
  }
};

/**
 * @unrestricted
 */
Profiler.SamplingHeapProfileNode = class extends SDK.ProfileNode {
  /**
   * @param {!Protocol.HeapProfiler.SamplingHeapProfileNode} node
   */
  constructor(node) {
    const callFrame = node.callFrame || /** @type {!Protocol.Runtime.CallFrame} */ ({
                        // Backward compatibility for old CpuProfileNode format.
                        functionName: node['functionName'],
                        scriptId: node['scriptId'],
                        url: node['url'],
                        lineNumber: node['lineNumber'] - 1,
                        columnNumber: node['columnNumber'] - 1
                      });
    super(callFrame);
    this.self = node.selfSize;
  }
};

/**
 * @unrestricted
 */
Profiler.SamplingHeapProfileModel = class extends SDK.ProfileTreeModel {
  /**
   * @param {!Protocol.HeapProfiler.SamplingHeapProfile} profile
   * @param {number=} minOrdinal
   * @param {number=} maxOrdinal
   */
  constructor(profile, minOrdinal, maxOrdinal) {
    super();
    this.modules = profile.modules || [];

    /** @type {?Map<number, number>} */
    let nodeIdToSizeMap = null;
    if (minOrdinal || maxOrdinal) {
      nodeIdToSizeMap = new Map();
      minOrdinal = minOrdinal || 0;
      maxOrdinal = maxOrdinal || Infinity;
      for (const sample of profile.samples) {
        if (sample.ordinal < minOrdinal || sample.ordinal > maxOrdinal)
          continue;
        const size = nodeIdToSizeMap.get(sample.nodeId) || 0;
        nodeIdToSizeMap.set(sample.nodeId, size + sample.size);
      }
    }

    this.initialize(translateProfileTree(profile.head));

    /**
     * @param {!Protocol.HeapProfiler.SamplingHeapProfileNode} root
     * @return {!Profiler.SamplingHeapProfileNode}
     */
    function translateProfileTree(root) {
      const resultRoot = new Profiler.SamplingHeapProfileNode(root);
      const sourceNodeStack = [root];
      const targetNodeStack = [resultRoot];
      while (sourceNodeStack.length) {
        const sourceNode = sourceNodeStack.pop();
        const targetNode = targetNodeStack.pop();
        targetNode.children = sourceNode.children.map(child => {
          const targetChild = new Profiler.SamplingHeapProfileNode(child);
          if (nodeIdToSizeMap)
            targetChild.self = nodeIdToSizeMap.get(child.id) || 0;
          return targetChild;
        });
        sourceNodeStack.pushAll(sourceNode.children);
        targetNodeStack.pushAll(targetNode.children);
      }
      pruneEmptyBranches(resultRoot);
      return resultRoot;
    }

    /**
     * @param {!SDK.ProfileNode} node
     * @return {boolean}
     */
    function pruneEmptyBranches(node) {
      node.children = node.children.filter(pruneEmptyBranches);
      return !!(node.children.length || node.self);
    }
  }
};

/**
 * @implements {Profiler.ProfileDataGridNode.Formatter}
 * @unrestricted
 */
Profiler.HeapProfileView.NodeFormatter = class {
  /**
   * @param {!Profiler.HeapProfileView} profileView
   */
  constructor(profileView) {
    this._profileView = profileView;
  }

  /**
   * @override
   * @param {number} value
   * @return {string}
   */
  formatValue(value) {
    return Number.withThousandsSeparator(value);
  }

  /**
   * @override
   * @param {number} value
   * @param {!Profiler.ProfileDataGridNode} node
   * @return {string}
   */
  formatPercent(value, node) {
    return Common.UIString('%.2f\xa0%%', value);
  }

  /**
   * @override
   * @param  {!Profiler.ProfileDataGridNode} node
   * @return {?Element}
   */
  linkifyNode(node) {
    const heapProfilerModel = this._profileView._profileHeader.heapProfilerModel();
    return this._profileView.linkifier().maybeLinkifyConsoleCallFrame(
        heapProfilerModel ? heapProfilerModel.target() : null, node.profileNode.callFrame, 'profile-node-file');
  }
};

/**
 * @unrestricted
 */
Profiler.HeapFlameChartDataProvider = class extends Profiler.ProfileFlameChartDataProvider {
  /**
   * @param {!SDK.ProfileTreeModel} profile
   * @param {?SDK.HeapProfilerModel} heapProfilerModel
   */
  constructor(profile, heapProfilerModel) {
    super();
    this._profile = profile;
    this._heapProfilerModel = heapProfilerModel;
  }

  /**
   * @override
   * @return {number}
   */
  minimumBoundary() {
    return 0;
  }

  /**
   * @override
   * @return {number}
   */
  totalTime() {
    return this._profile.root.total;
  }

  /**
   * @override
   * @param {number} value
   * @param {number=} precision
   * @return {string}
   */
  formatValue(value, precision) {
    return Common.UIString('%s\xa0KB', Number.withThousandsSeparator(value / 1e3));
  }

  /**
   * @override
   * @return {!PerfUI.FlameChart.TimelineData}
   */
  _calculateTimelineData() {
    /**
     * @param  {!SDK.ProfileNode} node
     * @return {number}
     */
    function nodesCount(node) {
      return node.children.reduce((count, node) => count + nodesCount(node), 1);
    }
    const count = nodesCount(this._profile.root);
    /** @type {!Array<!SDK.ProfileNode>} */
    const entryNodes = new Array(count);
    const entryLevels = new Uint16Array(count);
    const entryTotalTimes = new Float32Array(count);
    const entryStartTimes = new Float64Array(count);
    let depth = 0;
    let maxDepth = 0;
    let position = 0;
    let index = 0;

    /**
     * @param {!SDK.ProfileNode} node
     */
    function addNode(node) {
      const start = position;
      entryNodes[index] = node;
      entryLevels[index] = depth;
      entryTotalTimes[index] = node.total;
      entryStartTimes[index] = position;
      ++index;
      ++depth;
      node.children.forEach(addNode);
      --depth;
      maxDepth = Math.max(maxDepth, depth);
      position = start + node.total;
    }
    addNode(this._profile.root);

    this._maxStackDepth = maxDepth + 1;
    this._entryNodes = entryNodes;
    this._timelineData = new PerfUI.FlameChart.TimelineData(entryLevels, entryTotalTimes, entryStartTimes, null);

    return this._timelineData;
  }

  /**
   * @override
   * @param {number} entryIndex
   * @return {?Element}
   */
  prepareHighlightedEntryInfo(entryIndex) {
    const node = this._entryNodes[entryIndex];
    if (!node)
      return null;
    const entryInfo = [];
    /**
     * @param {string} title
     * @param {string} value
     */
    function pushEntryInfoRow(title, value) {
      entryInfo.push({title: title, value: value});
    }
    pushEntryInfoRow(Common.UIString('Name'), UI.beautifyFunctionName(node.functionName));
    pushEntryInfoRow(Common.UIString('Self size'), Number.bytesToString(node.self));
    pushEntryInfoRow(Common.UIString('Total size'), Number.bytesToString(node.total));
    const linkifier = new Components.Linkifier();
    const link = linkifier.maybeLinkifyConsoleCallFrame(
        this._heapProfilerModel ? this._heapProfilerModel.target() : null, node.callFrame);
    if (link)
      pushEntryInfoRow(Common.UIString('URL'), link.textContent);
    linkifier.dispose();
    return Profiler.ProfileView.buildPopoverTable(entryInfo);
  }
};


text:
<?php
/**
 * Public REST for pages
 *
 * @author   Anton Shevchuk
 * @created  30.10.12 09:29
 */

namespace Application;

use Application\Pages;
use Bluz\Controller\Controller;
use Bluz\Controller\Mapper\Rest;

/**
 * Get all pages or just one by ID
 * For everyone
 *
 * @OA\Head(
 *   path="/api/pages/{pageId}",
 *   tags={"pages"},
 *   operationId="getPageById",
 *   summary="Find page by ID",
 *   @OA\Parameter(
 *      name="pageId",
 *      in="path",
 *      required=true,
 *      description="ID of page that needs to be fetched",
 *      @OA\Schema(type="integer")
 *    ),
 *    @OA\Response(response=200, description="Given page found"),
 *    @OA\Response(@OA\JsonContent(ref="#/components/schemas/error"), response=404, description="Page not found")
 * )
 *
 * @OA\Get(
 *   path="/api/pages/{pageId}",
 *   tags={"pages"},
 *   operationId="getPageById",
 *   summary="Find page by ID",
 *   @OA\Parameter(
 *      name="pageId",
 *      in="path",
 *      required=true,
 *      description="ID of page that needs to be fetched",
 *      @OA\Schema(type="integer")
 *    ),
 *    @OA\Response(
 *      @OA\JsonContent(ref="#/components/schemas/page"),
 *      response=200,
 *      description="Given page found"
 *   ),
 *   @OA\Response(@OA\JsonContent(ref="#/components/schemas/error"), response=404, description="Page not found")
 * )
 *
 * @OA\Get(
 *     path="/api/pages/",
 *     tags={"pages"},
 *     method="GET",
 *     operationId="getPageCollection",
 *     summary="Collection of items",
 *     @OA\Parameter(ref="#/components/parameters/offset_in_query"),
 *     @OA\Parameter(ref="#/components/parameters/limit_in_query"),
 *     @OA\Response(
 *          @OA\JsonContent(type="array", @OA\Items(ref="#/components/schemas/page")),
 *          response=200,
 *          description="Collection"
 *     ),
 *     @OA\Response(
 *          @OA\JsonContent(type="array", @OA\Items(ref="#/components/schemas/page")),
 *          response=206,
 *          description="Collection (partial)"
 *     )
 * )
 *
 * @accept JSON
 * @return mixed
 */
return function () {
    /**
     * @var Controller $this
     */
    $rest = new Rest(Pages\Crud::getInstance());

    $rest
        ->head('system', 'rest/head')
        ->fields(
            [
                'id',
                'title',
                'content',
                'keywords',
                'description'
            ]
        );
    $rest
        ->get('system', 'rest/get')
        ->fields(
            [
                'id',
                'title',
                'content',
                'keywords',
                'description'
            ]
        );

    return $rest->run();
};

redpajama_set_name: RedPajamaGithub


text:
"""
`aslr` command test module
"""

from tests.utils import GefUnitTestGeneric, findlines, gdb_start_silent_cmd, removeuntil

class AslrCommand(GefUnitTestGeneric):
    """`aslr` command test module"""

    cmd = "aslr"

    def test_cmd_aslr_show(self):
        # show
        res = gdb_start_silent_cmd(self.cmd, after=("show disable-randomization",))
        self.assertNoException(res)
        self.assertIn("ASLR is currently ", res)
        self.assertEqual(res.count("ASLR is currently "), 1)

        # compare
        pattern = "ASLR is currently "
        cmd_output = removeuntil(pattern, findlines(pattern, res)[0])
        pattern = "virtual address space is "
        gdb_output = findlines(pattern, res)[0].split()[-1]
        if gdb_output == "on.":
            self.assertEqual(cmd_output, "disabled")
        else:
            self.assertEqual(cmd_output, "enabled")

    def test_cmd_aslr_toggle(self):
        # current value
        res = gdb_start_silent_cmd(self.cmd)
        pattern = "ASLR is currently "
        default_value = removeuntil(pattern, findlines(pattern, res)[0])

        # toggle
        if default_value == "enabled":
            res = gdb_start_silent_cmd(f"{self.cmd} off", after=(f"{self.cmd}"))
            cmd_output = removeuntil(pattern, findlines(pattern, res)[0])
            self.assertEqual(cmd_output, "disabled")
        elif default_value == "disabled":
            res = gdb_start_silent_cmd(f"{self.cmd} on", after=(f"{self.cmd}"))
            cmd_output = removeuntil(pattern, findlines(pattern, res)[0])
            self.assertEqual(cmd_output, "enabled")
        else:
            raise Exception(f"incorrect value: {default_value}")


text:
using Exceptionless.Core.Validation;
using FluentValidation;
using FluentValidation.Results;

namespace Exceptionless.Core.Extensions;

public static class ValidationExtensions {
    public static string ToErrorMessage(this IEnumerable<ValidationFailure> failures) {
        return failures == null ? null : String.Join(Environment.NewLine, failures.Select(f => f.ErrorMessage));
    }

    public static IRuleBuilderOptions<T, TProperty> IsObjectId<T, TProperty>(this IRuleBuilder<T, TProperty> ruleBuilder) {
        return ruleBuilder.SetValidator(new IsObjectIdValidator<T, TProperty>());
    }
}


text:
package org.jboss.migration.eap;

/**
 * The EAP 7.4 CD {@link org.jboss.migration.core.ServerProvider}.
 * @author emmartins
 */
public class EAPCDServerProvider7_4 extends EAPServerProvider7_4 {

    @Override
    protected String getProductNameRegex() {
        return "JBoss EAP CD";
    }

    @Override
    public String getName() {
        return "JBoss EAP CD 7.4";
    }
}


text:
<?php

defined('JPATH_PLATFORM') or die;

/**
 * Static class to handle loading of libraries.
 *
 * @package  Joomla.Platform
 * @since    11.1
 */
abstract class JLoader
{
	/**
	 * Container for already imported library paths.
	 *
	 * @var    array
	 * @since  11.1
	 */
	protected static $classes = array();

	/**
	 * Container for already imported library paths.
	 *
	 * @var    array
	 * @since  11.1
	 */
	protected static $imported = array();

	/**
	 * Container for registered library class prefixes and path lookups.
	 *
	 * @var    array
	 * @since  12.1
	 */
	protected static $prefixes = array();

	/**
	 * Holds proxy classes and the class names the proxy.
	 *
	 * @var    array
	 * @since  3.2
	 */
	protected static $classAliases = array();

	/**
	 * Holds the inverse lookup for proxy classes and the class names the proxy.
	 *
	 * @var    array
	 * @since  3.4
	 */
	protected static $classAliasesInverse = array();

	/**
	 * Container for namespace => path map.
	 *
	 * @var    array
	 * @since  12.3
	 */
	protected static $namespaces = array();

	/**
	 * Method to discover classes of a given type in a given path.
	 *
	 * @param   string   $classPrefix  The class name prefix to use for discovery.
	 * @param   string   $parentPath   Full path to the parent folder for the classes to discover.
	 * @param   boolean  $force        True to overwrite the autoload path value for the class if it already exists.
	 * @param   boolean  $recurse      Recurse through all child directories as well as the parent path.
	 *
	 * @return  void
	 *
	 * @since   11.1
	 */
	public static function discover($classPrefix, $parentPath, $force = true, $recurse = false)
	{
		try
		{
			if ($recurse)
			{
				$iterator = new RecursiveIteratorIterator(
					new RecursiveDirectoryIterator($parentPath),
					RecursiveIteratorIterator::SELF_FIRST
				);
			}
			else
			{
				$iterator = new DirectoryIterator($parentPath);
			}

			/* @type  $file  DirectoryIterator */
			foreach ($iterator as $file)
			{
				$fileName = $file->getFilename();

				// Only load for php files.
				if ($file->isFile() && $file->getExtension() == 'php')
				{
					// Get the class name and full path for each file.
					$class = strtolower($classPrefix . preg_replace('#\.php$#', '', $fileName));

					// Register the class with the autoloader if not already registered or the force flag is set.
					if (empty(self::$classes[$class]) || $force)
					{
						self::register($class, $file->getPath() . '/' . $fileName);
					}
				}
			}
		}
		catch (UnexpectedValueException $e)
		{
			// Exception will be thrown if the path is not a directory. Ignore it.
		}
	}

	/**
	 * Method to get the list of registered classes and their respective file paths for the autoloader.
	 *
	 * @return  array  The array of class => path values for the autoloader.
	 *
	 * @since   11.1
	 */
	public static function getClassList()
	{
		return self::$classes;
	}

	/**
	 * Method to get the list of registered namespaces.
	 *
	 * @return  array  The array of namespace => path values for the autoloader.
	 *
	 * @since   12.3
	 */
	public static function getNamespaces()
	{
		return self::$namespaces;
	}

	/**
	 * Loads a class from specified directories.
	 *
	 * @param   string  $key   The class name to look for (dot notation).
	 * @param   string  $base  Search this directory for the class.
	 *
	 * @return  boolean  True on success.
	 *
	 * @since   11.1
	 */
	public static function import($key, $base = null)
	{
		// Only import the library if not already attempted.
		if (!isset(self::$imported[$key]))
		{
			// Setup some variables.
			$success = false;
			$parts = explode('.', $key);
			$class = array_pop($parts);
			$base = (!empty($base)) ? $base : __DIR__;
			$path = str_replace('.', DIRECTORY_SEPARATOR, $key);

			// Handle special case for helper classes.
			if ($class == 'helper')
			{
				$class = ucfirst(array_pop($parts)) . ucfirst($class);
			}
			// Standard class.
			else
			{
				$class = ucfirst($class);
			}

			// If we are importing a library from the Joomla namespace set the class to autoload.
			if (strpos($path, 'joomla') === 0)
			{
				// Since we are in the Joomla namespace prepend the classname with J.
				$class = 'J' . $class;

				// Only register the class for autoloading if the file exists.
				if (is_file($base . '/' . $path . '.php'))
				{
					self::$classes[strtolower($class)] = $base . '/' . $path . '.php';
					$success = true;
				}
			}
			/*
			 * If we are not importing a library from the Joomla namespace directly include the
			 * file since we cannot assert the file/folder naming conventions.
			 */
			else
			{
				// If the file exists attempt to include it.
				if (is_file($base . '/' . $path . '.php'))
				{
					$success = (bool) include_once $base . '/' . $path . '.php';
				}
			}

			// Add the import key to the memory cache container.
			self::$imported[$key] = $success;
		}

		return self::$imported[$key];
	}

	/**
	 * Load the file for a class.
	 *
	 * @param   string  $class  The class to be loaded.
	 *
	 * @return  boolean  True on success
	 *
	 * @since   11.1
	 */
	public static function load($class)
	{
		// Sanitize class name.
		$class = strtolower($class);

		// If the class already exists do nothing.
		if (class_exists($class, false))
		{
			return true;
		}

		// If the class is registered include the file.
		if (isset(self::$classes[$class]))
		{
			include_once self::$classes[$class];

			return true;
		}

		return false;
	}

	/**
	 * Directly register a class to the autoload list.
	 *
	 * @param   string   $class  The class name to register.
	 * @param   string   $path   Full path to the file that holds the class to register.
	 * @param   boolean  $force  True to overwrite the autoload path value for the class if it already exists.
	 *
	 * @return  void
	 *
	 * @since   11.1
	 */
	public static function register($class, $path, $force = true)
	{
		// Sanitize class name.
		$class = strtolower($class);

		// Only attempt to register the class if the name and file exist.
		if (!empty($class) && is_file($path))
		{
			// Register the class with the autoloader if not already registered or the force flag is set.
			if (empty(self::$classes[$class]) || $force)
			{
				self::$classes[$class] = $path;
			}
		}
	}

	/**
	 * Register a class prefix with lookup path.  This will allow developers to register library
	 * packages with different class prefixes to the system autoloader.  More than one lookup path
	 * may be registered for the same class prefix, but if this method is called with the reset flag
	 * set to true then any registered lookups for the given prefix will be overwritten with the current
	 * lookup path. When loaded, prefix paths are searched in a "last in, first out" order.
	 *
	 * @param   string   $prefix   The class prefix to register.
	 * @param   string   $path     Absolute file path to the library root where classes with the given prefix can be found.
	 * @param   boolean  $reset    True to reset the prefix with only the given lookup path.
	 * @param   boolean  $prepend  If true, push the path to the beginning of the prefix lookup paths array.
	 *
	 * @return  void
	 *
	 * @throws  RuntimeException
	 *
	 * @since   12.1
	 */
	public static function registerPrefix($prefix, $path, $reset = false, $prepend = false)
	{
		// Verify the library path exists.
		if (!file_exists($path))
		{
			$path = (str_replace(JPATH_ROOT, '', $path) == $path) ? basename($path) : str_replace(JPATH_ROOT, '', $path);

			throw new RuntimeException('Library path ' . $path . ' cannot be found.', 500);
		}

		// If the prefix is not yet registered or we have an explicit reset flag then set set the path.
		if (!isset(self::$prefixes[$prefix]) || $reset)
		{
			self::$prefixes[$prefix] = array($path);
		}
		// Otherwise we want to simply add the path to the prefix.
		else
		{
			if ($prepend)
			{
				array_unshift(self::$prefixes[$prefix], $path);
			}
			else
			{
				self::$prefixes[$prefix][] = $path;
			}
		}
	}

	/**
	 * Offers the ability for "just in time" usage of `class_alias()`.
	 * You cannot overwrite an existing alias.
	 *
	 * @param   string  $alias     The alias name to register.
	 * @param   string  $original  The original class to alias.
	 *
	 * @return  boolean  True if registration was successful. False if the alias already exists.
	 *
	 * @since   3.2
	 */
	public static function registerAlias($alias, $original)
	{
		if (!isset(self::$classAliases[$alias]))
		{
			self::$classAliases[$alias] = $original;

			// Remove the root backslash if present.
			if ($original[0] == '\\')
			{
				$original = substr($original, 1);
			}

			if (!isset(self::$classAliasesInverse[$original]))
			{
				self::$classAliasesInverse[$original] = array($alias);
			}
			else
			{
				self::$classAliasesInverse[$original][] = $alias;
			}

			return true;
		}

		return false;
	}

	/**
	 * Register a namespace to the autoloader. When loaded, namespace paths are searched in a "last in, first out" order.
	 *
	 * @param   string   $namespace  A case sensitive Namespace to register.
	 * @param   string   $path       A case sensitive absolute file path to the library root where classes of the given namespace can be found.
	 * @param   boolean  $reset      True to reset the namespace with only the given lookup path.
	 * @param   boolean  $prepend    If true, push the path to the beginning of the namespace lookup paths array.
	 *
	 * @return  void
	 *
	 * @throws  RuntimeException
	 *
	 * @since   12.3
	 */
	public static function registerNamespace($namespace, $path, $reset = false, $prepend = false)
	{
		// Verify the library path exists.
		if (!file_exists($path))
		{
			$path = (str_replace(JPATH_ROOT, '', $path) == $path) ? basename($path) : str_replace(JPATH_ROOT, '', $path);

			throw new RuntimeException('Library path ' . $path . ' cannot be found.', 500);
		}

		// If the namespace is not yet registered or we have an explicit reset flag then set the path.
		if (!isset(self::$namespaces[$namespace]) || $reset)
		{
			self::$namespaces[$namespace] = array($path);
		}

		// Otherwise we want to simply add the path to the namespace.
		else
		{
			if ($prepend)
			{
				array_unshift(self::$namespaces[$namespace], $path);
			}
			else
			{
				self::$namespaces[$namespace][] = $path;
			}
		}
	}

	/**
	 * Method to setup the autoloaders for the Joomla Platform.
	 * Since the SPL autoloaders are called in a queue we will add our explicit
	 * class-registration based loader first, then fall back on the autoloader based on conventions.
	 * This will allow people to register a class in a specific location and override platform libraries
	 * as was previously possible.
	 *
	 * @param   boolean  $enablePsr       True to enable autoloading based on PSR-0.
	 * @param   boolean  $enablePrefixes  True to enable prefix based class loading (needed to auto load the Joomla core).
	 * @param   boolean  $enableClasses   True to enable class map based class loading (needed to auto load the Joomla core).
	 *
	 * @return  void
	 *
	 * @since   12.3
	 */
	public static function setup($enablePsr = true, $enablePrefixes = true, $enableClasses = true)
	{
		if ($enableClasses)
		{
			// Register the class map based autoloader.
			spl_autoload_register(array('JLoader', 'load'));
		}

		if ($enablePrefixes)
		{
			// Register the J prefix and base path for Joomla platform libraries.
			self::registerPrefix('J', JPATH_PLATFORM . '/joomla');

			// Register the prefix autoloader.
			spl_autoload_register(array('JLoader', '_autoload'));
		}

		if ($enablePsr)
		{
			// Register the PSR-0 based autoloader.
			spl_autoload_register(array('JLoader', 'loadByPsr0'));
			spl_autoload_register(array('JLoader', 'loadByAlias'));
		}
	}

	/**
	 * Method to autoload classes that are namespaced to the PSR-0 standard.
	 *
	 * @param   string  $class  The fully qualified class name to autoload.
	 *
	 * @return  boolean  True on success, false otherwise.
	 *
	 * @since   13.1
	 */
	public static function loadByPsr0($class)
	{
		// Remove the root backslash if present.
		if ($class[0] == '\\')
		{
			$class = substr($class, 1);
		}

		// Find the location of the last NS separator.
		$pos = strrpos($class, '\\');

		// If one is found, we're dealing with a NS'd class.
		if ($pos !== false)
		{
			$classPath = str_replace('\\', DIRECTORY_SEPARATOR, substr($class, 0, $pos)) . DIRECTORY_SEPARATOR;
			$className = substr($class, $pos + 1);
		}
		// If not, no need to parse path.
		else
		{
			$classPath = null;
			$className = $class;
		}

		$classPath .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';

		// Loop through registered namespaces until we find a match.
		foreach (self::$namespaces as $ns => $paths)
		{
			if (strpos($class, $ns) === 0)
			{
				// Loop through paths registered to this namespace until we find a match.
				foreach ($paths as $path)
				{
					$classFilePath = $path . DIRECTORY_SEPARATOR . $classPath;

					// We check for class_exists to handle case-sensitive file systems
					if (file_exists($classFilePath) && !class_exists($class, false))
					{
						return (bool) include_once $classFilePath;
					}
				}
			}
		}

		return false;
	}

	/**
	 * Method to autoload classes that have been aliased using the registerAlias method.
	 *
	 * @param   string  $class  The fully qualified class name to autoload.
	 *
	 * @return  boolean  True on success, false otherwise.
	 *
	 * @since   3.2
	 */
	public static function loadByAlias($class)
	{
		// Remove the root backslash if present.
		if ($class[0] == '\\')
		{
			$class = substr($class, 1);
		}

		if (isset(self::$classAliases[$class]))
		{
			// Force auto-load of the regular class
			class_exists(self::$classAliases[$class], true);

			// Normally this shouldn't execute as the autoloader will execute applyAliasFor when the regular class is
			// auto-loaded above.
			if (!class_exists($class, false) && !interface_exists($class, false))
			{
				class_alias(self::$classAliases[$class], $class);
			}
		}
	}

	/**
	 * Applies a class alias for an already loaded class, if a class alias was created for it.
	 *
	 * @param   string  $class  We'll look for and register aliases for this (real) class name
	 *
	 * @return  void
	 *
	 * @since   3.4
	 */
	public static function applyAliasFor($class)
	{
		// Remove the root backslash if present.
		if ($class[0] == '\\')
		{
			$class = substr($class, 1);
		}

		if (isset(self::$classAliasesInverse[$class]))
		{
			foreach (self::$classAliasesInverse[$class] as $alias)
			{
				class_alias($class, $alias);
			}
		}
	}

	/**
	 * Autoload a class based on name.
	 *
	 * @param   string  $class  The class to be loaded.
	 *
	 * @return  boolean  True if the class was loaded, false otherwise.
	 *
	 * @since   11.3
	 */
	private static function _autoload($class)
	{
		foreach (self::$prefixes as $prefix => $lookup)
		{
			$chr = strlen($prefix) < strlen($class) ? $class[strlen($prefix)] : 0;

			if (strpos($class, $prefix) === 0 && ($chr === strtoupper($chr)))
			{
				return self::_load(substr($class, strlen($prefix)), $lookup);
			}
		}

		return false;
	}

	/**
	 * Load a class based on name and lookup array.
	 *
	 * @param   string  $class   The class to be loaded (wihtout prefix).
	 * @param   array   $lookup  The array of base paths to use for finding the class file.
	 *
	 * @return  boolean  True if the class was loaded, false otherwise.
	 *
	 * @since   12.1
	 */
	private static function _load($class, $lookup)
	{
		// Split the class name into parts separated by camelCase.
		$parts = preg_split('/(?<=[a-z0-9])(?=[A-Z])/x', $class);

		// If there is only one part we want to duplicate that part for generating the path.
		$parts = (count($parts) === 1) ? array($parts[0], $parts[0]) : $parts;

		foreach ($lookup as $base)
		{
			// Generate the path based on the class name parts.
			$path = $base . '/' . implode('/', array_map('strtolower', $parts)) . '.php';

			// Load the file if it exists.
			if (file_exists($path))
			{
				return include $path;
			}
		}

		return false;
	}
}

// Check if jexit is defined first (our unit tests mock this)
if (!function_exists('jexit'))
{
	/**
	 * Global application exit.
	 *
	 * This function provides a single exit point for the platform.
	 *
	 * @param   mixed  $message  Exit code or string. Defaults to zero.
	 *
	 * @return  void
	 *
	 * @codeCoverageIgnore
	 * @since   11.1
	 */
	function jexit($message = 0)
	{
		exit($message);
	}
}

/**
 * Intelligent file importer.
 *
 * @param   string  $path  A dot syntax path.
 * @param   string  $base  Search this directory for the class.
 *
 * @return  boolean  True on success.
 *
 * @since   11.1
 */
function jimport($path, $base = null)
{
	return JLoader::import($path, $base);
}


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

namespace OMap
{
    public enum MapType
    {
        MapProperty,
        MapObject,
        MapCollection,
        MapFunction,
        MapAll,
        MapIgnore
    }

    public class MappingConfigurationEntry
    {
        public Type Source { get; private set; }
        public Type Target { get; private set; }
        public string EntryDescription { get; private set; }

        public MappingConfigurationEntry(Type source, Type target, string entryDescription)
        {
            Source = source;
            Target = target;
            EntryDescription = entryDescription;
        }
    }

    public class MappingConfigurationPropertyEntry : MappingConfigurationEntry
    {
        public Delegate MappingAction { get; private set; }
        public Type DependencyTupleType { get; private set; }
        public IDictionary<Type, string> NamedResolutions { get; private set; }

        public MappingConfigurationPropertyEntry(Type source, Type target, string entryDescription, Delegate mappingAction, Type dependencyTupleType, IDictionary<Type, string> namedResolutions)
            :base(source, target, entryDescription)
        {
            MappingAction = mappingAction;
            DependencyTupleType = dependencyTupleType;
            NamedResolutions = namedResolutions;
        }
    }

    public class MappingConfigurationObjectEntry : MappingConfigurationEntry
    {
        public Delegate GetSourceProperty { get; set; }
        public Delegate GetTargetProperty { get; set; }
        public Delegate SetTargetProperty { get; set; }
        public Type TargetPropertyType { get; set; }

        public MappingConfigurationObjectEntry(Type source, Type target, string entryDescription, Delegate getSourceProperty, Delegate getTargetProperty, Delegate setTargetProperty, Type targetPropertyType)
            : base(source, target, entryDescription)
        {
            GetSourceProperty = getSourceProperty;
            GetTargetProperty = getTargetProperty;
            SetTargetProperty = setTargetProperty;
            TargetPropertyType = targetPropertyType;
        }
    }

    public class MappingConfigurationCollectionEntry : MappingConfigurationEntry
    {
        public Delegate GetSourceProperty { get; set; }
        public Delegate GetTargetProperty { get; set; }
        public Delegate SetTargetProperty { get; set; }
        public Type TargetPropertyType { get; set; }

        public MappingConfigurationCollectionEntry(Type source, Type target, string entryDescription, Delegate getSourceProperty, Delegate getTargetProperty, Delegate setTargetProperty, Type targetPropertyType)
            : base(source, target, entryDescription)
        {
            GetSourceProperty = getSourceProperty;
            GetTargetProperty = getTargetProperty;
            SetTargetProperty = setTargetProperty;
            TargetPropertyType = targetPropertyType;
        }
    }

    public class MappingConfigurationFunctionEntry : MappingConfigurationEntry
    {
        public Delegate Action { get; private set; }
        public Type DependencyTupleType { get; private set; }
        public IDictionary<Type, string> NamedResolutions { get; private set; }

        public MappingConfigurationFunctionEntry(Type source, Type target, string entryDescription, Delegate action, Type dependencyTupleType, IDictionary<Type, string> namedResolutions)
            : base(source, target, entryDescription)
        {
            Action = action;
            DependencyTupleType = dependencyTupleType;
            NamedResolutions = namedResolutions;
        }
    }

    public class MappingConfiguration
    {
        private readonly List<MappingConfigurationEntry> _entries;

        public MappingConfiguration(List<MappingConfigurationEntry> entries)
        {
            _entries = entries;
        }

        public MappingConfigurationEntry[] GetEntries()
        {
            return _entries.ToArray();
        }
    }
}


text:
import { put, takeEvery } from 'redux-saga/effects';

import { SEND_MESSAGE } from '../actions/sendMessage';
import postActivity from '../actions/postActivity';
import whileConnected from './effects/whileConnected';

function* postActivityWithMessage({ payload: { channelData, method, text } }) {
  yield put(
    postActivity(
      {
        channelData,
        text,
        textFormat: 'plain',
        type: 'message'
      },
      method
    )
  );
}

function* sendMessageToPostActivity() {
  yield takeEvery(({ payload, type }) => type === SEND_MESSAGE && payload.text, postActivityWithMessage);
}

export default function* sendMessageToPostActivitySaga() {
  yield whileConnected(sendMessageToPostActivity);
}


text:
<?php

namespace Yucca\Component\Source\Exception;

/**
 * Class NoDataException
 * @package Yucca\Component\Source\Exception
 */
class NoDataException extends \Exception
{

}


text: ENGINE_API bool IsKeyReleased(const Event& event, Key::Code keyCode);


text:
<!DOCTYPE HTML>

     <meta charset="utf-8">
     <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
     <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="css/election.css" rel="stylesheet">
      <link href="css/bootstrap.min.css" rel="stylesheet">

    <link rel="stylesheet" href="css/site.css">

    <title>Elections 2014 | Daily Bruin</title>

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
        Toggle navigation

      </button>

      CANDIDATES

GOVERNOR

CONGRESS

STATE SENATE

LA COUNTY BOARD OF SUPERVISORS

STATE ASSEMBLY

PROPOSITIONS

ENDORSEMENTS

RESULTS

WHERE TO VOTE

Governor

Jerry Brown

Congress

Ted Lieu

LA County Board of Supervisors

Sheila Kuehl

State Senate

Sandra Fluke

State Assembly

Sebastian Ridley-Thomas

Proposition

1

YES

Proposition

2

YES

Proposition

45

NO

Proposition

46

NO

Proposition

47

YES

Proposition

48

YES

Proposition

P

NO

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Jerry Brown

For the fourth time in as many decades, Californians have the option of choosing Democrat Jerry Brown to be their governor.

It's an easy choice to make.

Brown, who is finishing up his third term in the state's highest office, has an impressive track record of fiscal responsibility, forward-thinking policy-making and extensive experience navigating Sacramento's political coalitions.

In his most recent term, Brown has successfully turned California's dire financial crisis around, saving the state from almost certain bankruptcy and even managing to get state legislators to turn the state budget in on time the last four years in a row. His main victory comes in balancing the state budget for 2014, a remarkable feat considering the state was verging on default when he took office. Moreover, under his watch, California has gone from a multibillion-dollar deficit to a $1.9 billion surplus at the end of 2013, the first time there has been leftover cash in the state coffers since 2007.

But Brown has also been a responsible governor when it comes to legislation affecting the University of California. In 2011, he signed the California Dream Act, allowing undocumented students to have access to both state and private financial aid for higher education. More recently, Brown also signed the "yes means yes" bill into law, mandating an affirmative consent standard on college campuses.

However, this board has extreme reservations about Brown's hesitance to allocate excess funding to the UC. He was a major proponent of Proposition 30 in 2012, which raised taxes in an effort to bring millions in relief to the UC, but time and time again, he has shown an unwillingness to further institutional state support for the UC.

Another issue with Brown is his lack of transparency – his decision to shut down the website, http://www.transparency.ca.gov, in 2011, created by the Schwarzenegger administration to consolidate financial documents for easy public perusal, raised many red flags.

His September veto of three separate bills aimed at increasing government transparency, AB 194, AB 400 and AB 2058, is also cause for alarm, but ultimately does not diminish his general record of success.

Brown's opponent in this election is Republican and investment banker Neel Kashkari. Having served as interim assistant secretary of the Department of the Treasury's Office of Financial Stability, Kashkari has big government experience, but lacks the coalition-building and party navigation skills that make Brown such a strong contender. While his primary platform goals of fixing public education, increasing jobs and making higher education more affordable are nice on paper, his practical plans for creating substantial policy changes are generally vague.

Overall, Brown's experience and track record make him a more viable and capable choice for the state's chief executive

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Ted Lieu

With Henry Waxman's impressive 40-year career in the House of Representatives coming to an end, a freshman – attorney Elan Carr or State Sen. Ted Lieu – will be taking his place as the U.S. representative of California's 33rd congressional district.

This board believes that Lieu's experience with legislation as a state senator and his pragmatic platforms and plans for office set him apart as the best choice for the position.

Lieu comes into this race with three years of experience as a California state senator, working extensively with legislation.

Lieu has authored and introduced dozens of pieces of legislation, many signed by the governor, supporting important issues ranging from banning sexual orientation change therapy for minors to protecting children from sex offenders to increasing protections for journalists.

Lieu's platforms, like improving public education and strengthening the Affordable Care Act, are as strong as Carr's, but he stands out as the better candidate with his concrete understanding of how to reach these goals. He was able to name legislation and congressmen, in line with his platforms, that he intends to support if elected, and if he ever needs to author legislation himself, we know he has the experience to be successful.

Furthermore, Lieu set out criteria by which voters could gauge his success as a freshman congressman, including obtaining grants for wildlife corridors and transportation for this district and constituent services. Lieu's understanding that a freshman congressman will likely not draft or pass any legislation demonstrates a strong grasp of the limitations of the job.

Carr's platforms and plans for office are well-intentioned and fairly moderate, but his inability to show true understanding of how to achieve his goals in Congress holds him back.

Carr said public education and comprehensive immigration reform are two of his top priorities, and his goals of reaching across party lines and getting work done immediately are important for a freshman coming into today's Congress. But his platforms and ideals only sound like buzz words without the proper foundation and experience to turn them into a reality.

Lieu shares Carr's goals of reaching across party lines and getting work done, but he has to actually put these ideals into practice during his time as state senator. We believe that he'll be able to do it again in order to successfully represent California's 33rd congressional district.

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Sheila Kuehl

This board endorses Sheila Kuehl for the 3rd District seat on the Los Angeles County Board of Supervisors because of her experience in the California legislature and her dedication to advocacy.

Eight years as a state senator and six as a state assemblywoman will serve Kuehl well if she is elected this week. After managing a budget four times larger than she would in the supervisor seat, she is equipped to understand complex funding systems at the county level.

The UCLA alumna approaches her work with a profound understanding of the importance of standing up for marginalized communities and ensuring that the law protects the powerless. She learned this partially from firsthand experience with discrimination for being lesbian, even allegedly losing interviews because of it. At UCLA, she said she was kicked out of a sorority when her friends learned she loved a woman.

As a senator, she wrote laws to guarantee workers paid leave and to protect students and school staff from discrimination for their sexual orientations. She also co-founded the nonprofit California Women's Law Center, which works to produce legislation to protect women from assault and discrimination.

On the job, Kuehl would have to oversee county prisons, the correctional system for youth and family welfare programs. A seat with this power requires a leader who knows what inmates and youth need. Her attention to mental health patients in jail and her strategy of diversion for low-level offenders make Kuehl right for the position. Her plans to offer additional support to foster care youth past the age of 18 and increase collaboration between child welfare programs will also benefit the county.

While her opponent Bobby Shriver also supports diverting mentally ill people from jails, Kuehl's stronger background in advocacy work makes her the more qualified candidate for this task.

Like Shriver, she supports an incremental minimum wage increase to $15.37 an hour. While Kuehl plans to use her alliance with unions, Shriver has said he supports providing tax breaks for companies. Unlike Shriver, Kuehl is rightly skeptical that tax relief for companies will stimulate the economy.

L.A. County needs a leader who is dedicated to fighting discrimination and searching for ways to help the marginalized. Coupled with her history of advocacy, Kuehl's experience helps ensure that county dollars and policies will be used and implemented with attention to groups who need the most care.

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Sandra Fluke

This board endorses Sandra Fluke for State Senate for her concrete platforms that emphasize social justice. Though Fluke is new to the 26th district, we believe she will bring a much needed, fresh perspective to the Senate.

Fluke gained national recognition after testifying to members of Congress about the need for birth control to be covered by health insurance. If elected, she said she plans to continue advocating for issues of gender equality and health care access, among other issues. The focus on sexual health is especially important for a representative of UCLA, since a state audit found that the university does not do enough on sexual assault education.

In an interview with this board, Fluke expressed her support for California's new "yes means yes" law, indicating that she is willing to tackle controversial legislation.

Fluke is also one of the few candidates for any office to pointedly campaign for the rights of the LBGT community and the transgender community specifically. She's helped pass equal employment legislation and worked to ensure that domestic violence shelters accept all victims, regardless of their sexuality. Issues of basic equality should always be top priority, and Fluke has the knowledge and educational background to fight for them.

Both Fluke and her opponent, Ben Allen, are campaigning on issues of environmental sustainability, transportation reform and veteran resources among other topics. Both seem equally equipped to take on these issues at a state level, though Fluke has more experience helping state senators pass legislation.

Compared to Allen, who is a native of the district, Fluke has relatively little experience working with the UC system. Allen attended UC Berkeley School of Law and served as a student regent on the UC Board of Regents from 2007 to 2008. He is also currently a lecturer at the UCLA School of Law.

In his year as a student regent, he was able to push through a sustainability measure that secured more LEED lighting and sustainable food. But Allen's familiarity with the UC system does not automatically make him qualified for the lofty task of securing more state funding for the University.

Allen is currently a member of the Santa Monica-Malibu Unified School District, where he developed a "Cradle to Career" initiative to strategize a way to ensure more children have access to higher education. Achievements in a singular school district, although honorable, do not prepare a candidate for advocacy on the state level.

Although Allen has more experience in the district he is campaigning for, Fluke's progressive platforms makes her a better candidate for state senate.

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Sebastian Ridley-Thomas

The board endorses Sebastian Ridley-Thomas to continue representing the 54th district in the California State Assembly.

Ridley-Thomas has served as the representative for the district since December 2013, when he was voted into office during a special election.

Since then, Ridley-Thomas has focused on a number of issues, most notably public health. His primary concern seems to be improving state-funded mental health care, particularly targeting communities with little to adequate care or those who are at high risk for chronic homelessness.

Ridley-Thomas said he has been particularly concerned with the way the state handles the mentally ill homeless. In the wake of an incident where a California Highway Patrol officer beat a mentally ill homeless woman who wandered onto the 10 Freeway, Ridley-Thomas held a special joint committee hearing with law enforcement officials to discuss their policies regarding the mentally ill.

When asked about higher education, Ridley-Thomas discussed the importance of funding and investing in the University of California system. When pushed for details on how that investment should be made, Ridley-Thomas asserted that the most effective way to invest in the UC was to invest in students, notably through stronger financial aid packages for in-state undergraduates.

In his short term, Ridley-Thomas has already proven his chops in Sacramento, demonstrating concrete success as a legislator. One measure he proposed, which allows the California Department of Justice to cross-reference databases to determine whether confiscated firearms are legally owned, was recently signed into law by Gov. Jerry Brown. Ridley-Thomas was also involved with the passing of the affirmative consent or "Yes Means Yes" bill earlier this year.

Moreover, Ridley-Thomas is a strong proponent for the repeal of Proposition 209.

While he noted that the measure is most associated with higher education admissions, Ridley-Thomas added that in order to help the repeal effort, advocates will need to focus on demonstrating the other costs Proposition 209 has, particularly in terms of how it affects business-sector job opportunities for women and minorities, stifling economic mobility.

While Republican challenger Glen Ratcliff brings an important focus on small-business issues and a desire to reform the California tax code to the table, his statements on most issues were fairly vague and lacked concrete ideas for how to affect change in higher office.

Ratcliff's ideas about how to change K-12 education lacked both specifics and a practical understanding of how the state curriculum is set, and in particular, his statements regarding abolishing the minimum wage were particularly troubling to the board.

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Proposition 1

California is in the midst of one of the worst droughts in its history, and while the billions raised through Proposition 1 won't go towards buying rainwater, it still represents a positive step toward securing the state's water future.

The $7.12 billion proposal has allocations for certain water projects like ecosystem and watershed protection and improvements in drinking water quality, with the largest chunk – about $2.7 billion – going to water storage projects.

The money will flow into California's aging water infrastructure, while also helping to develop a system that can reliably supply water in future years.

Of course, the projects outlined in the proposition don't come cheap. The bond proposal is expected to cost the state $360 million annually over the next 40 years.

However, not all the cost will be distributed to California taxpayers. A provision in the proposition requires certain projects to provide matching funds from non-state sources in order to receive bond funds.

Californians last voted on a water bond in 2006, approving $5.4 billion for water projects. In 2005, voters approved Proposition 50, which gave $3.4 billion for water projects.

All this goes to show that Proposition 1 won't be the last hard decision voters will have to make to secure California's water future, but the measure represents a necessary part of the solution of supplying water to an increasingly thirsty state.

Opponents of the proposition have said that it is a waste of taxpayer money and beholden to special interests who plan to use the funding for dams to benefit large agricultural companies instead of the average Californian.

But the current version of the proposition is already an updated version of an earlier $11.1 billion proposal which was pulled from the ballot and cut down for being too pork-laden.

The fund allocation for water storage projects also has no specific allowance toward dams. Instead, the independent California Water Commission is charged with identifying and supporting what they consider to be beneficial water projects.

An analysis of the proposition by the non-partisan Pacific Institute noted that the measure's effectiveness in addressing California's water issues is contingent on how the commission performs in finding and pursuing effective water projects.

Proposition 1 won't solve all the problems surrounding the current drought, but it will put plans in place that will help the state weather future water woes.

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Proposition 2

Despite several concerns, the Daily Bruin Editorial Board supports Proposition 2.

The proposition would create a rainy day fund with better controls than the state's previous attempt at establishing economic stability through an emergency fund.

California's economy is especially prone to unexpected ups and downs, and as such the state needs to take precautions to ease the impact of substantial economic downturns.

Although the governing principles behind Proposition 2 are sound, the ballot measure's regulation of school districts is not perfect.

The language that would restrict school districts from exceeding a cap in reserve funds should be repealed, since local officials are more well-equipped to dole out funding or save it for harder times than state lawmakers who work from Sacramento. The power to make financial decisions should remain in the hands of those with the most intimate knowledge of individual districts' needs.

Furthermore, although this board supports the creation of a new rainy day fund to help ensure economic stability, we urge Gov. Jerry Brown to focus on increasing funds for higher education should the ballot measure succeed.

With the new safety net in place, Brown must make strides toward restoring levels of state support to the University of California. Because the state has been operating under a surplus, Brown should shift money toward higher education at the same time the state saves for the future.

As state funding stands, the UC is likely facing tuition increases in the very near future. State support for the UC system saw dramatic decreases in the past 20 years, to the point that student tuition now pays for more of the UC budget than state allocated dollars. Although Brown has consistently urged the UC to maintain tuition and avoid rises in costs for students, without growing state support, the University will be forced to raise tuition levels. If California cannot support its university systems, the economy will suffer – with or without the fund.

This board supports Proposition 2, but hopes the investment in economic stability extends to higher education. With more money in its reserve coffers, we hope that Brown and the state will offer increases to public education without worrying for California's future economic status.

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Proposition 45

This board does not endorse Proposition 45 for the Nov. 4 ballot.

This measure would give the state insurance commissioner the ability to review and approve health insurance rates for individual and small group plans, striking down those that are excessive or unfair. The commissioner already has the power to review and strike down rates for auto insurance after the passage of Proposition 103 in 1988, which has saved Californians a considerable amount of money on auto insurance.

We support giving the state insurance commissioner the ability to extend his oversight powers to health insurance premiums. But Proposition 45 is not the way to accomplish that.

The measure is deeply flawed and fails to account for changes to California's health insurance market wrought by the Affordable Care Act and the creation of Covered California, our state's individual exchange market.

As an individual exchange market, Covered California negotiates prices with health insurance companies and gives consumers the ability to compare plans side by side. Throwing on another layer of regulation could disrupt the negotiated agreements Covered California is making with health insurers and ultimately undermine the effectiveness of the Affordable Care Act.

This is particularly true because all of those regulations would have to be sorted out and implemented in a very strict timeline. Health care premiums differ from other types of insurance in that they are set only once a year, and consumers only have one window of time – the state's annual open enrollment period – to sign up for their plans.

If Proposition 45 succeeds, there is a plethora of bureaucratic steps that must be taken to implement the new regulations before the open enrollment period begins. This lengthy process would require the insurance commissioner to review and approve or strike down rates after Covered California finishes negotiations with health care providers.

But the initiative fails to provide a timeline for the insurance commissioner to follow, and that lack of structure creates the potential for chaos in an already precarious system.

It's still early, but so far, Covered California seems to be an active marketplace that's succeeding in holding down rates for consumers. Adding another layer of regulation that does not consider the effects of the independent exchange could derail Covered California's progress.

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Proposition 46

Proposition 46 requires voters to make several important decisions about the future of their medical care and how it will be regulated in one comprehensive ballot measure.

A stronger state prescription database, a higher pain and suffering cap for medical malpractice lawsuits and drug and alcohol testing for certain medical professionals – would lead to greater accountability and safety among medical practitioners in the state of California. But this board endorses a vote of "No" on Proposition 46, because the logistical concerns this proposition raises and potential financial impacts far outweigh its intended benefits.

California currently ties for the lowest medical malpractice lawsuit damages cap in the nation: a maximum of $250,000 for pain and suffering, with additional damages possible to cover the economic effects of injuries caused by medical malpractice.

This cap needs to be raised in the coming years. A higher cap would ensure more legal help for patients who have economically suffered from medical malpractice and hold the medical community accountable for its patient care.

At the same time, the unknown costs of raising the pain and suffering cap to $1.1 million overnight provide reason for skepticism. Costs for medical care facilities in California would increase anywhere from "tens of millions of dollars to several hundred million dollars annually," according to the Legislative Analyst's Office.

The proposition also calls for the random drug and alcohol testing of certain physicians. This board does not take issue with state-organized drug and alcohol testing of physicians in the event of medical mistakes or surgical errors, a move that could significantly reduce court costs. With no particular aim and no clear evidence of pervasive drug and alcohol use among doctors, however, randomized tests could prove wasteful due to significant administrative costs.

Proposition 46's final measure would force providers to check the Controlled Substance Utilization Review and Evaluation System, or CURES, a prescription drug distribution database. The move would curb the efforts of many "doctor shoppers," or those seeking excessive amounts of prescription drugs, and limit the number of harmful pharmaceutical drugs disbursed. It is one this board approves if the state is willing to ensure all providers in the state are registered as soon as possible.

Proposition 46 aims to implement several measures that would, on the whole, improve the individual doctor's practice of medicine. Its potentially overwhelming costs, however, indicate the need for more research and planning with respect to malpractice law and drug and alcohol use among physicians.

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Proposition 47

We strongly endorse a yes on Proposition 47 because it will reduce exorbitant prison spending and redirect the savings to programs that are proven to help reduce crime such as school truancy prevention.

If passed, Proposition 47 would require misdemeanor sentences for the lowest level nonviolent crimes currently classified as felonies, such as certain drug possession and petty theft. It would also require resentencing for people serving felony sentences for these crimes.

The initiative presents a chance for Californians to reverse some of the devastating consequences of overcharging people for nonviolent crimes, a practice that perpetuates mass incarceration.

By far, the U.S. outpaces all other democracies in incarceration. Although Americans make up roughly only 5 percent of the world's population, we hold a quarter of the world's prison population. The rate of incarceration in the United States has quadrupled since 1970, and more than half the inmates in state prisons are serving terms for nonviolent crimes.

In California, state prisons are so overcrowded that the federal judges ruled them a gross violation of civil rights and ordered a cap on the number of inmates in 2009. This prompted an ill-conceived and costly prison realignment plan from Gov. Jerry Brown that shuffled thousands of inmates in state prisons to county jails, but did little to change the situation.

Despite lackluster results, state spending on corrections and rehabilitation increased by nearly $2 billion since 2011 when Brown began implementing his realignment plan.

The nonpartisan Legislative Analyst's Office estimates that the effects of Proposition 47 could eventually result in annual savings of hundreds of millions of dollars while allowing the state to really reduce – not just relocate – the prison population by several thousand inmates. They also estimate that counties could save several hundreds of millions of dollars annually, mostly from easing jail capacity.

Savings in the state budget from Proposition 47 will be earmarked for programs that effectively improve public safety and help rehabilitate former convicts, including K-12 dropout prevention, mental health and drug treatment and services for victims of crimes.

We believe Proposition 47, backed by prominent law enforcement officers, Los Angeles Unified School District and Los Angeles City Council , is a meaningful opportunity to scale back unjust, disproportionate sentencing for nonviolent crimes, a civic injustice with destructive social and economic consequences.

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Proposition 48

This editorial board endorses a "yes" vote on proposition 48.

Proposition 48 would allow a casino to be built by the North Fork Rancheria of Mono Indians off-reservation in Madera County. It would also prevent the construction of another casino by the Wiyot tribe in Humboldt County, who would instead be paid a share of the Madera casino's earnings.

Legislation surrounding Indian gaming casinos specifies casinos can only be built on reservation land, in an effort to ensure that they only benefit the tribes living on that land and not private corporations. Proposition 48 would set a precedent in California for "reservation shopping," the practice of allowing tribes to pick and choose where casinos are built.

In this case, reservation shopping should be allowed because a casino for the North Fork tribe could prove to be a huge economic boon for a historically disadvantaged group. Tribal gaming is a lucrative industry, taking in $7 billion each year. The Madera casino would generate approximately 4000 jobs, creating employment opportunities for a tribe with 69 percent of its population in poverty and 29 percent without jobs.

Opponents of this proposition say allowing the North Fork tribe to build a casino off their reservation would set a dangerous precedent for the proliferation of gambling in urban areas. But these opponents primarily comprise established Indian gaming casinos interested in stifling competition.

All tribes deserve an equal chance at improving the welfare of their communities which have long been and continue to be marginalized. Although opponents of the proposition have urged the North Fork tribe to build their casino on their original settlement in the Sierra National Forest, this land has been unable to garner investment because it is difficult to reach by car.

Thus, it is only fair that the North Fork tribe be allowed to build a casino elsewhere, at a location that would realistically help raise the North Fork tribe out of poverty.

While it is important to regulate gambling and keep its benefits restricted to Native American tribes, each case should be judged on its individual merits. As long as the initiative is primarily in a tribe's interest and does not harm the economy or environment, reservation shopping should not pose a problem.

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Proposition P

Securing land for parks is a serious undertaking for any county government.

In the most populous county in the United States, doing so requires a substantial amount of financial backing and commitment of taxpayer dollars –but when that funding already exists, it can't be overdrawn.

This board endorses a "No" vote on Measure P. While the $23 per parcel tax proposed by Measure P would provide Los Angeles County with a significant financial base to acquire and develop parklands, provide funds for gang prevention and job training programs among other goals, the existence of two park taxes in Los Angeles County with similar goals raise questions about the immediate need of these funds.

In 1992, county voters approved Proposition A, which provides $54 million annually to fund recreational areas and community programming. This proposition also allowed the county to purchase open space for parks and refurbishment of local historical landmarks like the Hollywood Bowl. This was followed up by a 1996 parks tax assessment that collected $28 million per year to cover maintenance and acquisition costs for county parks.

Proposition A runs out on June 30, 2015, but the 1996 park tax assessment will continue to pool money until June 30, 2019, which begs the question of whether Proposition P will be redundant, unnecessary tax until 2019. If the funds exist at the county level and will continue to draw in funding, the county should wait until the next election for a more specifically allocated tax.

Measure P was not placed on the 2014 ballot by the Los Angeles County Board of Supervisors until August, giving the voting community little time to sink its teeth into the actual workings of the tax prior to November's voting period. A lack of actual itemization – the tax's distribution is listed by percentages in the text of the proposition – shows there is no extensive plan on the county's part. Two additional years to plan would help the county create a better, more complete allocation the tax.

This board also questions the flat-rate taxation policy listed in Measure P. Instead of following Proposition A's lead and charging county residents based mostly on property size, each parcel would be charged $23 annually. We believe this pulls a significant amount of the financial burden from the county's wealthy property owners and places it on property owners who might have the same or higher value for these parks and programs, but to whom $23 means significantly more.

This fee structure hasn't been given a clear explanation. Neither has the distribution of taxpayer dollars. Both factors should not inspire confidence among voters in Los Angeles County.

            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

Elections 2014  |  Home  |  News  |  Sports  |  A&E  |  Opinion

Site by Li-Wei Tseng and Rakshit Garg, Contributors. Content © 2014 the Daily Bruin.


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/. */

package org.mozilla.gecko.sync.jpake.stage;

import java.io.UnsupportedEncodingException;

import org.mozilla.gecko.sync.ExtendedJSONObject;
import org.mozilla.gecko.sync.Logger;
import org.mozilla.gecko.sync.crypto.CryptoException;
import org.mozilla.gecko.sync.crypto.KeyBundle;
import org.mozilla.gecko.sync.jpake.JPakeClient;
import org.mozilla.gecko.sync.setup.Constants;

public class ComputeKeyVerificationStage extends JPakeStage {

  @Override
  public void execute(JPakeClient jClient) {
    Logger.debug(LOG_TAG, "Computing verification to send.");
    if (jClient.myKeyBundle == null) {
      Logger.error(LOG_TAG, "KeyBundle has not been set; aborting.");
      jClient.abort(Constants.JPAKE_ERROR_INTERNAL);
      return;
    }
    try {
      jClient.jOutgoing = computeKeyVerification(jClient.myKeyBundle, jClient.mySignerId);
    } catch (UnsupportedEncodingException e) {
      Logger.error(LOG_TAG, "Failure in key verification.", e);
      jClient.abort(Constants.JPAKE_ERROR_INVALID);
      return;
    } catch (CryptoException e) {
      Logger.error(LOG_TAG, "Encryption failure in key verification.", e);
      jClient.abort(Constants.JPAKE_ERROR_INTERNAL);
      return;
    }

    jClient.runNextStage();
  }

  /*
   * Helper function to compute a ciphertext, IV, and HMAC from derived
   * keyBundle for verifying other party.
   *
   * (Made 'public' for testing and is a stateless function.)
   */
  public ExtendedJSONObject computeKeyVerification(KeyBundle keyBundle, String signerId)
      throws UnsupportedEncodingException, CryptoException
  {
    Logger.debug(LOG_TAG, "Encrypting key verification value.");
    ExtendedJSONObject jPayload = JPakeClient.encryptPayload(JPakeClient.JPAKE_VERIFY_VALUE, keyBundle, true);
    ExtendedJSONObject result = new ExtendedJSONObject();
    result.put(Constants.JSON_KEY_TYPE, signerId + "3");
    result.put(Constants.JSON_KEY_VERSION, JPakeClient.KEYEXCHANGE_VERSION);
    result.put(Constants.JSON_KEY_PAYLOAD, jPayload.object);
    return result;
  }

}


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>EmbedlyDirective | angular2-embedly</title>
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="../assets/css/main.css">

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

Preparing search index...

The search index is not available

					angular2-embedly

						Options

								All

Public

Public/Protected

All

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

					Menu

					Globals

					EmbedlyDirective

Class EmbedlyDirective

Hierarchy

						EmbedlyDirective

Implements

OnChanges

Index

Constructors

constructor

Properties

el

embedly

on<wbr>Empty

url

width

Methods

ng<wbr>OnChanges

Constructors

constructor

new <wbr>Embedly<wbr>Directive(el: ElementRef, embedly: EmbedlyService): EmbedlyDirective

Defined in src/directives/embedly.directive.ts:11

Parameters

el: ElementRef

embedly: EmbedlyService

Returns EmbedlyDirective

Properties

Private el

el: ElementRef

Defined in src/directives/embedly.directive.ts:13

Private embedly

embedly: EmbedlyService

Defined in src/directives/embedly.directive.ts:13

on<wbr>Empty

on<wbr>Empty: EventEmitter<Object> = new EventEmitter<Object>()

Defined in src/directives/embedly.directive.ts:11

url

url: string

Defined in src/directives/embedly.directive.ts:9

width

width: number

Defined in src/directives/embedly.directive.ts:10

Methods

ng<wbr>OnChanges

ng<wbr>OnChanges(changes: SimpleChanges): any

Defined in src/directives/embedly.directive.ts:17

Parameters

changes: SimpleChanges

Returns any

						Globals

						Embedly<wbr>Directive

								constructor

								el

								embedly

								on<wbr>Empty

								url

								width

								ng<wbr>OnChanges

						Embedly<wbr>Service

						DIRECTIVES

						PROVIDERS

Legend

Module

Object literal

Variable

Function

Function with type parameter

Index signature

Type alias

Enumeration

Enumeration member

Property

Method

Interface

Interface with type parameter

Constructor

Property

Method

Index signature

Class

Class with type parameter

Constructor

Property

Method

Accessor

Index signature

Inherited constructor

Inherited property

Inherited method

Inherited accessor

Protected property

Protected method

Protected accessor

Private property

Private method

Private accessor

Static property

Static method

Generated using TypeDoc


text:
package a2ndrade.explore.ui;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.view.MenuItem;

import a2ndrade.explore.R;
import butterknife.BindView;

public class HomeActivity extends AbstractBaseActivity {
    private static final String BUNDLE_CURRENT_FRAGMENT_TAG = "BUNDLE_CURRENT_FRAGMENT_TAG";
    private static final String BUNDLE_CURRENT_MENU_ID = "BUNDLE_CURRENT_MENU_ID";

    @BindView(R.id.bottom_navigation)
    BottomNavigationView bottomNavigationView;

    int currentMenuId = R.id.menu_trending;
    String currentFragmentTag = TrendingFragment.TAG;

    @Override
    int getLayoutId() {
        return R.layout.activity_home;
    }

    @Override
    void onCreate0(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            currentMenuId = savedInstanceState.getInt(BUNDLE_CURRENT_MENU_ID);
            currentFragmentTag = savedInstanceState.getString(BUNDLE_CURRENT_FRAGMENT_TAG);
            updateMenuSelection();
        }

        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
        if (fragment == null) {
            // Default fragment
            getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, TrendingFragment.newInstance(), currentFragmentTag).commit();
        }

        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                final Menu menu = bottomNavigationView.getMenu();
                final MenuItem previousMenuItem = menu.findItem(currentMenuId);
                if (previousMenuItem != null && item.getItemId() != previousMenuItem.getItemId()) {
                    // Un-checked previous item
                    previousMenuItem.setChecked(false);
                }

                switch (item.getItemId()) {
                    case R.id.menu_trending:
                        swapFragment(TrendingFragment.TAG);
                        break;
                    case R.id.menu_integrations:
                        swapFragment(IntegrationsFragment.TAG);
                        break;
                    case R.id.menu_showcases:
                        swapFragment(ShowcasesFragment.TAG);
                        break;
                }
                currentMenuId = item.getItemId();
                bottomNavigationView.getMenu().findItem(currentMenuId).setChecked(true);
                return false;
            }
        });
    }

    void swapFragment(String newFragmentTag) {
        final FragmentManager manager = getSupportFragmentManager();
        final FragmentTransaction ft = manager.beginTransaction();
        // Get the previous fragment one and detach it instead of removing it
        final Fragment fragmentToDetach = manager.findFragmentByTag(currentFragmentTag);
        if (fragmentToDetach != null) {
            // The detach method detaches the fragment from the UI, but its state is maintained by the Fragment Manager
            ft.detach(fragmentToDetach);
        }

        // Update the current fragment tag and try to find it inside FragmentManager
        currentFragmentTag = newFragmentTag;
        Fragment fragmentToAttach = manager.findFragmentByTag(currentFragmentTag);
        if (fragmentToAttach == null) {
            fragmentToAttach = TrendingFragment.TAG.equals(currentFragmentTag) ? TrendingFragment.newInstance()
                    : IntegrationsFragment.TAG.equals(currentFragmentTag) ? IntegrationsFragment.newInstance() : ShowcasesFragment.newInstance();
            ft.replace(R.id.fragment_container, fragmentToAttach, currentFragmentTag);
        }
        ft.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
        ft.attach(fragmentToAttach).commit();
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(BUNDLE_CURRENT_MENU_ID, currentMenuId);
        outState.putString(BUNDLE_CURRENT_FRAGMENT_TAG, currentFragmentTag);
    }

    private void updateMenuSelection() {
        // Instead of traversing the menu, check for the latest current menu id
        if (R.id.menu_trending == currentMenuId) {
            // We know this is the first option so do nothing
            return;
        }

        final Menu menu = bottomNavigationView.getMenu();
        // Force the menu to not be selected
        final MenuItem firstMenuItem = menu.findItem(R.id.menu_trending);
        if (firstMenuItem != null) {
            firstMenuItem.setChecked(false);
        }

        final MenuItem currentMenuItem = menu.findItem(currentMenuId);
        if (currentMenuItem != null) {
            currentMenuItem.setChecked(true);
        }
    }
}