text:
package net.krazyweb.util;

import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.MouseButton;
import javafx.stage.Popup;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class AutoCompletePopup {

	@SuppressWarnings("unused")
	private static Logger log = LogManager.getLogger(AutoCompletePopup.class);

	private Popup popup = new Popup();
	private ListView<String> optionList;
	private TextField textField;

	private AutoCompletePopup() {

		popup.setAutoHide(false);
		popup.setHideOnEscape(true);
		popup.setWidth(100);
		popup.setHeight(300);

	}

	public static void bind(final TextField textField, final ObservableList<String> options) {

		StringUtils.sortByClosestMatch(options, textField.getText());

		AutoCompletePopup autoCompletePopup = new AutoCompletePopup();
		autoCompletePopup.optionList = new ListView<>(options);
		autoCompletePopup.textField = textField;

		autoCompletePopup.popup.getContent().add(autoCompletePopup.optionList);

		textField.focusedProperty().addListener((observable, wasFocused, isFocused) -> {
			if (isFocused) {
				autoCompletePopup.show();
			} else {
				autoCompletePopup.popup.hide();
			}
		});

		textField.textProperty().addListener((observable, oldValue, newValue) -> {
			StringUtils.sortByClosestMatch(options, newValue);
			autoCompletePopup.optionList.getSelectionModel().selectFirst();
		});

		autoCompletePopup.optionList.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
		autoCompletePopup.optionList.setOnMouseClicked(event -> {
			if (event.getButton() == MouseButton.PRIMARY && event.getClickCount() >= 2) {
				textField.setText(autoCompletePopup.optionList.getSelectionModel().getSelectedItem());
				autoCompletePopup.popup.hide();
				Platform.runLater(textField::end);
			}
		});

		autoCompletePopup.optionList.setOnKeyPressed(event -> {

			switch (event.getCode()) {
				case ENTER:
					textField.setText(autoCompletePopup.optionList.getSelectionModel().getSelectedItem());
					autoCompletePopup.popup.hide();
					Platform.runLater(textField::end);
					break;
				case ESCAPE:
					autoCompletePopup.popup.hide();
					break;
				case UP:
					if (autoCompletePopup.optionList.getSelectionModel().isSelected(0)) {
						autoCompletePopup.popup.hide();
					}
					break;
				case A:
					if (event.isControlDown()) {
						autoCompletePopup.textField.selectAll();
						event.consume();
					}
					break;
				case END:
					autoCompletePopup.textField.end();
					event.consume();
					break;
				case HOME:
					autoCompletePopup.textField.home();
					event.consume();
					break;
			}

		});

		textField.setOnKeyPressed(event -> {
			if (event.getCode() == KeyCode.DOWN) {
				autoCompletePopup.show();
			}
		});

	}

	private void show() {

		popup.show(textField,
				textField.getScene().getWindow().getX() + textField.localToScene(0, 0).getX() + textField.getScene().getX(),
				textField.getScene().getWindow().getY() + textField.localToScene(0, 0).getY() + textField.getScene().getY() + textField.heightProperty().get());
		optionList.getSelectionModel().selectFirst();

	}

}


text:
/*global define*/
define([
        './defaultValue',
        './defined',
        './DeveloperError',
        './EllipseGeometry'
    ], function(
        defaultValue,
        defined,
        DeveloperError,
        EllipseGeometry) {
    "use strict";

    /**
     * A description of a circle on the ellipsoid.
     *
     * @alias CircleGeometry
     * @constructor
     *
     * @param {Object} options Object with the following properties:
     * @param {Cartesian3} options.center The circle's center point in the fixed frame.
     * @param {Number} options.radius The radius in meters.
     * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid the circle will be on.
     * @param {Number} [options.height=0.0] The height above the ellipsoid.
     * @param {Number} [options.granularity=0.02] The angular distance between points on the circle in radians.
     * @param {VertexFormat} [options.vertexFormat=VertexFormat.DEFAULT] The vertex attributes to be computed.
     * @param {Number} [options.extrudedHeight=0.0] The height of the extrusion relative to the ellipsoid.
     * @param {Number} [options.stRotation=0.0] The rotation of the texture coordinates, in radians. A positive rotation is counter-clockwise.
     *
     * @exception {DeveloperError} radius must be greater than zero.
     * @exception {DeveloperError} granularity must be greater than zero.
     *
     * @see CircleGeometry.createGeometry
     *
     * @example
     * // Create a circle.
     * var circle = new Cesium.CircleGeometry({
     *   center : Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883),
     *   radius : 100000.0
     * });
     * var geometry = Cesium.CircleGeometry.createGeometry(circle);
     */
    var CircleGeometry = function(options) {
        options = defaultValue(options, defaultValue.EMPTY_OBJECT);
        var radius = options.radius;

        //>>includeStart('debug', pragmas.debug);
        if (!defined(radius)) {
            throw new DeveloperError('radius is required.');
        }
        if (radius <= 0.0) {
            throw new DeveloperError('radius must be greater than zero.');
        }
        //>>includeEnd('debug');

        var ellipseGeometryOptions = {
            center : options.center,
            semiMajorAxis : radius,
            semiMinorAxis : radius,
            ellipsoid : options.ellipsoid,
            height : options.height,
            extrudedHeight : options.extrudedHeight,
            granularity : options.granularity,
            vertexFormat : options.vertexFormat,
            stRotation : options.stRotation
        };
        this._ellipseGeometry = new EllipseGeometry(ellipseGeometryOptions);
        this._workerName = 'createCircleGeometry';
    };

    /**
     * Computes the geometric representation of a circle on an ellipsoid, including its vertices, indices, and a bounding sphere.
     *
     * @param {CircleGeometry} circleGeometry A description of the circle.
     * @returns {Geometry} The computed vertices and indices.
     */
    CircleGeometry.createGeometry = function(circleGeometry) {
        return EllipseGeometry.createGeometry(circleGeometry._ellipseGeometry);
    };

    return CircleGeometry;
});

redpajama_set_name: RedPajamaGithub


text:
require 'rails_helper'

RSpec.feature 'Course: Administration: Administration' do
  subject { page }

  let(:instance) { create(:instance) }

  with_tenant(:instance) do
    let(:course) { create(:course) }
    before { login_as(user, scope: :user) }

    context 'As an Course Manager' do
      let(:user) { create(:course_manager, :approved, course: course).user }

      scenario 'I can view the Course Admin Sidebar item' do
        visit course_path(course)

        expect(page).to have_selector('li', text: 'layouts.course_admin.title')
      end

      scenario 'I can change the course attributes' do
        visit course_admin_path(course)

        fill_in 'course_title', with: ''
        click_button I18n.t('helpers.submit.course.update')
        expect(course.reload.title).not_to eq('')
        expect(page).to have_selector('div.has-error')

        new_title = 'New Title'
        new_description = 'New Description'
        fill_in 'course_title',          with: new_title
        fill_in 'course_description',    with: new_description
        click_button I18n.t('helpers.submit.course.update')

        expect(page).to have_selector('div.alert.alert-success')
        expect(course.reload.title).to eq(new_title)
        expect(course.reload.description).to eq(new_description)
      end
    end

    context 'As a Course Teaching Assistant' do
      let(:user) { create(:course_teaching_assistant, :approved, course: course).user }

      scenario 'I cannot view the Course Admin Sidebar item' do
        visit course_path(course)

        expect(page).not_to have_selector('li', text: 'layouts.course_admin.title')
      end
    end

    context 'As a Course Student' do
      let(:user) { create(:course_student, :approved, course: course).user }

      scenario 'I cannot view the Course Admin Sidebar item' do
        visit course_path(course)

        expect(page).not_to have_selector('li', text: 'layouts.course_admin.title')
      end
    end
  end
end


text:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Observable, Subscription } from 'rxjs/Rx';
import { Product } from '../../models/index';
import { ShoppingBagState } from '../../states/index';
import { ProductListService } from '../../services/index';

@Component({
  moduleId: module.id,
  selector: 'sd-shopping-list',
  templateUrl: 'shopping-list.component.html',
  styleUrls: ['shopping-list.component.css'],
})

export class ShoppingListComponent implements OnInit, OnDestroy {
  public products: Product[];
  private subscription: Subscription;

  constructor(
    private productListService: ProductListService,
    private shoppingBagState: ShoppingBagState) { }

  public ngOnInit() {
    const shoppingBagProducts = Observable.combineLatest(
      this.productListService.get(),
      this.shoppingBagState.get()
    ).map(([productList, shoppingBag]: [Product[], string[]]): Product[] => {
      return productList.filter((product: Product) => shoppingBag.indexOf(product.id) >= 0);
    });

    this.subscription = shoppingBagProducts.subscribe((products: Product[]) => {
      this.products = products;
    });
  }

  public ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }

  public isInBag(productId: string): boolean {
    return this.products.filter((product: Product) => product.id === productId).length > 0;
  }

  public toggleInBag(productId: string): void {
    if (this.isInBag(productId)) {
      this.shoppingBagState.removeProduct(productId);
    } else {
      this.shoppingBagState.addProduct(productId);
    }
  }
}


text:
package com.battlelancer.seriesguide.util;

import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.battlelancer.seriesguide.R;
import com.battlelancer.seriesguide.enums.EpisodeFlags;
import com.battlelancer.seriesguide.provider.SeriesGuideContract.Episodes;
import com.battlelancer.seriesguide.provider.SeriesGuideContract.Shows;
import com.jakewharton.trakt.Trakt;
import com.jakewharton.trakt.services.ShowService;
import java.util.ArrayList;
import java.util.List;
import retrofit.RetrofitError;
import timber.log.Timber;

public class TraktSync extends AsyncTask<Void, Void, Integer> {

    private Context mContext;

    private final Button mUploadButton;
    private final View mProgressIndicator;

    private boolean mIsSyncingUnseen;

    public TraktSync(Context context, Button uploadButton, View progressIndicator,
            boolean isSyncingUnseen) {
        mContext = context;
        mUploadButton = uploadButton;
        mProgressIndicator = progressIndicator;
        mIsSyncingUnseen = isSyncingUnseen;
    }

    @Override
    protected void onPreExecute() {
        mProgressIndicator.setVisibility(View.VISIBLE);
        mUploadButton.setEnabled(false);
    }

    @Override
    protected Integer doInBackground(Void... params) {
        Timber.d("Syncing with trakt...");

        Trakt trakt = ServiceUtils.getTraktWithAuth(mContext);
        if (trakt == null) {
            return TraktTools.FAILED_CREDENTIALS;
        }

        return syncToTrakt(trakt);
    }

    private Integer syncToTrakt(Trakt trakt) {
        // get show ids in local database for which syncing is enabled
        Cursor showTvdbIds = mContext.getContentResolver().query(Shows.CONTENT_URI, new String[] {
                Shows._ID
        }, Shows.SYNCENABLED + "=1", null, null);

        if (showTvdbIds == null) {
            return TraktTools.FAILED;
        }
        if (showTvdbIds.getCount() == 0) {
            return TraktTools.SUCCESS_NOWORK;
        }

        Integer resultCode = TraktTools.SUCCESS;
        ShowService showService = trakt.showService();

        while (showTvdbIds.moveToNext()) {
            int showTvdbId = showTvdbIds.getInt(0);
            List<ShowService.Episodes.Episode> watchedEpisodes = new ArrayList<>();

            // build a list of all watched episodes
            Cursor seenEpisodes = mContext.getContentResolver().query(
                    Episodes.buildEpisodesOfShowUri(showTvdbId), TraktSyncQuery.PROJECTION,
                    TraktSyncQuery.SELECTION_WATCHED, null, null);
            if (seenEpisodes != null) {
                buildEpisodeList(watchedEpisodes, seenEpisodes);
                seenEpisodes.close();
            }

            // build unseen episodes trakt post
            List<ShowService.Episodes.Episode> unwatchedEpisodes = new ArrayList<>();
            if (mIsSyncingUnseen) {
                Cursor unseenEpisodes = mContext.getContentResolver().query(
                        Episodes.buildEpisodesOfShowUri(showTvdbId), TraktSyncQuery.PROJECTION,
                        TraktSyncQuery.SELECTION_UNWATCHED, null, null);
                if (unseenEpisodes != null) {
                    buildEpisodeList(unwatchedEpisodes, unseenEpisodes);
                    unseenEpisodes.close();
                }
            }

            // last chance to abort
            if (isCancelled()) {
                resultCode = null;
                break;
            }

            try {
                // post to trakt
                if (watchedEpisodes.size() > 0) {
                    showService.episodeSeen(new ShowService.Episodes(
                            showTvdbId, watchedEpisodes
                    ));
                }
                if (mIsSyncingUnseen && unwatchedEpisodes.size() > 0) {
                    showService.episodeUnseen(new ShowService.Episodes(
                            showTvdbId, unwatchedEpisodes
                    ));
                }
            } catch (RetrofitError e) {
                Timber.e(e, "Uploading episodes failed");
                resultCode = TraktTools.FAILED_API;
                break;
            }
        }

        showTvdbIds.close();
        return resultCode;
    }

    private static void buildEpisodeList(List<ShowService.Episodes.Episode> watchedEpisodes,
            Cursor seenEpisodes) {
        while (seenEpisodes.moveToNext()) {
            int season = seenEpisodes.getInt(0);
            int episode = seenEpisodes.getInt(1);
            watchedEpisodes.add(new ShowService.Episodes.Episode(season, episode));
        }
    }

    @Override
    protected void onCancelled() {
        Timber.d("Syncing with trakt...CANCELED");
        Toast.makeText(mContext, R.string.trakt_error_general, Toast.LENGTH_LONG).show();
        restoreViewStates();
    }

    @Override
    protected void onPostExecute(Integer result) {
        Timber.d("Uploading to trakt...DONE (" + result + ")");

        int messageResId;
        int duration = Toast.LENGTH_SHORT;

        switch (result) {
            case TraktTools.FAILED:
            case TraktTools.FAILED_API:
                messageResId = R.string.trakt_error_general;
                duration = Toast.LENGTH_LONG;
                break;
            case TraktTools.FAILED_CREDENTIALS:
                messageResId = R.string.trakt_error_credentials;
                duration = Toast.LENGTH_LONG;
                break;
            case TraktTools.SUCCESS_NOWORK:
                messageResId = R.string.upload_no_work;
                break;
            default:
            case TraktTools.SUCCESS:
                messageResId = R.string.upload_done;
                break;
        }

        Toast.makeText(mContext, messageResId, duration).show();
        restoreViewStates();
    }

    private void restoreViewStates() {
        mProgressIndicator.setVisibility(View.GONE);
        mUploadButton.setEnabled(true);
    }

    public interface TraktSyncQuery {

        public String[] PROJECTION = new String[] {
                Episodes.SEASON, Episodes.NUMBER
        };

        public String SELECTION_WATCHED = Episodes.WATCHED + "=" + EpisodeFlags.WATCHED;

        public String SELECTION_UNWATCHED = Episodes.WATCHED + "!=" + EpisodeFlags.WATCHED;
    }
}


text:
namespace AnEngine::Game
{
	class SampleMeshRenderer : public Renderer
	{
		const static uint32_t NumLights = 3u;

		struct LightState
		{
			XMFLOAT4 position;
			XMFLOAT4 direction;
			XMFLOAT4 color;
			XMFLOAT4 falloff;

			XMFLOAT4X4 view;
			XMFLOAT4X4 projection;
		};

		struct MyConstantBuffer
		{
			XMFLOAT4X4 model;
			XMFLOAT4X4 view;
			XMFLOAT4X4 projection;
			XMFLOAT4 ambientColor;
			BOOL sampleShadowMap;
			BOOL padding[3];
			LightState lights[NumLights];
		};

		std::wstring m_fileName;

		Microsoft::WRL::ComPtr<ID3D12RootSignature> m_rootSignature;
		RenderCore::GraphicPSO* m_psoShadowMap;

		Microsoft::WRL::ComPtr<ID3D12Resource> m_depthStencil;
		ID3D12DescriptorHeap* m_dsvHeap;
		D3D12_CPU_DESCRIPTOR_HANDLE m_dsvHandle;
		D3D12_GPU_DESCRIPTOR_HANDLE m_dsvGpuHandle;

		RenderCore::Resource::VertexBuffer* m_vertexBuffer;
		Microsoft::WRL::ComPtr<ID3D12Resource> m_textures[_countof(SampleAssets::Textures)];
		Microsoft::WRL::ComPtr<ID3D12Resource> m_textureUploads[_countof(SampleAssets::Textures)];
		ID3D12DescriptorHeap* m_cbvSrvHeap;
		ID3D12DescriptorHeap* m_samplerHeap;

		D3D12_CPU_DESCRIPTOR_HANDLE m_cbvHandle;
		D3D12_CPU_DESCRIPTOR_HANDLE m_samplerHandle;
		D3D12_GPU_DESCRIPTOR_HANDLE m_cbvGpuHandle;
		D3D12_GPU_DESCRIPTOR_HANDLE m_samplerGpuHandle;

		D3D12_GPU_DESCRIPTOR_HANDLE m_nullSrvHandle;
		D3D12_GPU_DESCRIPTOR_HANDLE m_shadowDepthHandle;
		D3D12_GPU_DESCRIPTOR_HANDLE m_shadowCbvHandle;

		Microsoft::WRL::ComPtr<ID3D12Resource> m_shadowTexture;

		Microsoft::WRL::ComPtr<ID3D12Resource> m_constantBuffer;
		Microsoft::WRL::ComPtr<ID3D12Resource> m_shadowConstantBuffer;
		MyConstantBuffer* mp_shadowConstantBufferWO;
		MyConstantBuffer* mp_sceneConstantBufferWO;

		LightState m_lights[NumLights];
		LightCamera m_lightCameras[NumLights];

		CD3DX12_VIEWPORT m_viewport;
		CD3DX12_RECT m_scissorRect;

		RenderCore::Fence* m_fence;

	public:
		SampleMeshRenderer(wstring&& fileName);

		// 通过 Renderer 继承
		virtual void LoadAsset() override;
		virtual void OnRender(ID3D12GraphicsCommandList* iList, ID3D12CommandAllocator* iAllocator) override;

		virtual void Destory() override;
	};
}
#endif // !__SAMPLEMESHRENDER_H__


text:
package org.drools.process.core;

public interface ParameterDefinition extends TypeObject {

    String getName();
    void setName(String name);

}


text:
<?php

/**
 * FurryBear
 *
 * PHP Version 5.3
 *
 * @category Congress_API
 * @package  FurryBear
 * @author   lobostome <lobostome@local.dev>
 * @license  http://opensource.org/licenses/MIT MIT License
 * @link     https://github.com/lobostome/FurryBear
 */

/**
 * Test for autoloader.
 *
 * @category Congress_API
 * @package  FurryBear
 * @author   lobostome <lobostome@local.dev>
 * @license  http://opensource.org/licenses/MIT MIT License
 * @link     https://github.com/lobostome/FurryBear
 */
class SplClassLoaderTest extends PHPUnit_Framework_TestCase {

    /**
     * A reference to the SplClassLoader object.
     *
     * @var \SplClassLoader
     */
    protected $autoload;

    /**
     * Create fixtures.
     */
    protected function setUp()
    {
        require_once __DIR__ . '/../SplClassLoader.php';
        $this->autoload = new SplClassLoader(__DIR__ . '/../src');
    }

    /**
     * Test to ensure the loader autoloads the needed classes.
     */
    public function testClassLoad()
    {
        $this->assertInstanceOf('Furrybear\FurryBear',
                                new \FurryBear\FurryBear());
    }

    /**
     * Test to ensure the autoload function is registered.
     */
    public function testRegister()
    {
        $this->autoload->register();

        $spl_autoload_functions = spl_autoload_functions();

        foreach($spl_autoload_functions as $f) {
            if(is_array($f) && $f[0] instanceof SplClassLoader) {
                $this->assertEquals($f[1], 'furrybear_autoload');
            }
        }
    }

    /**
     * Test file not found.
     */
    public function testFileDoesNotExistException()
    {
        $this->setExpectedException('\\FurryBear\\Common\\Exception\\FileDoesNotExistException');
        new \FurryBear\Something();
    }

    /**
     * Clean up fixtures.
     */
    protected function tearDown()
    {
        spl_autoload_unregister(array('SplClassLoader', 'furrybear_autoload'));
    }
}


text:
package de.dpunkt.myaktion.resources;

import de.dpunkt.myaktion.model.Campaign;
import de.dpunkt.myaktion.services.CampaignService;

import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.util.List;

@Path("/organizer/campaign")
public class CampaignResource {

    @Inject
    private CampaignService campaignService;

    @GET
    @Path("/list")
    @Produces(MediaType.APPLICATION_JSON)
    public List<Campaign> getAllCampaigns() {
        List<Campaign> allCampaigns = campaignService.getAllCampaigns();
        allCampaigns.forEach(campaign -> {
            campaign.setDonations(null);
            campaign.setOrganizer(null);
        });
        return allCampaigns;
    }

    @DELETE
    @Path("/{campaignId}")
    public void deleteCampaign(@PathParam(value = "campaignId") Long campaignId) {
        campaignService.deleteCampaign(campaignId);
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Campaign addCampaign(Campaign campaign) {
        return campaignService.addCampaign(campaign);
    }

    @PUT
    @Path("/{campaignId}")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Campaign updateCampaign(@PathParam(value = "campaignId") Long campaignId,
                                   Campaign newCampaign) {
        Campaign campaign = campaignService.getCampaign(campaignId);
        campaign.setName(newCampaign.getName());
        campaign.setDonationMinimum(newCampaign.getDonationMinimum());
        campaign.setTargetAmount(newCampaign.getTargetAmount());
        newCampaign = campaignService.updateCampaign(campaign);
        newCampaign.setDonations(null);
        newCampaign.setOrganizer(null);
        return newCampaign;
    }

}


text:
@interface TermsConditionsNetworkOperation : BaseNetworkOperation

@end


text:
namespace chromecast {
namespace media {

namespace {

const int kOpusSamplingRate = 48000;
const uint8_t kFakeOpusExtraData[19] = {
  'O', 'p', 'u', 's', 'H', 'e', 'a', 'd',  // offset 0, OpusHead
  0,  // offset 8, version
  2,  // offset 9, channels
  0, 0,  // offset 10, skip
  static_cast<uint8_t>(kOpusSamplingRate & 0xFF),  // offset 12, LE
  static_cast<uint8_t>((kOpusSamplingRate >> 8) & 0xFF),
  static_cast<uint8_t>((kOpusSamplingRate >> 16) & 0xFF),
  static_cast<uint8_t>((kOpusSamplingRate >> 24) & 0xFF),
  0, 0,  // offset 16, gain
  0,  // offset 18, stereo mapping
};

const int kStereoOutputChannelCount = 2;
const int kLayout71OutputChannelCount = 8;
const int kMaxChannelInput = 2;

class CastAudioDecoderImpl : public CastAudioDecoder {
 public:
  CastAudioDecoderImpl(
      const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
      const InitializedCallback& initialized_callback,
      OutputFormat output_format)
      : task_runner_(task_runner),
        initialized_callback_(initialized_callback),
        output_format_(output_format),
        initialized_(false),
        decode_pending_(false),
        weak_factory_(this) {
    if (base::CommandLine::InitializedForCurrentProcess() &&
        base::CommandLine::ForCurrentProcess()->HasSwitch(
            switches::kAlsaNumOutputChannels)) {
      base::StringToInt(
          base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
              switches::kAlsaNumOutputChannels),
          &num_output_channels_);
    } else {
      num_output_channels_ = kStereoOutputChannelCount;
    }
    DCHECK(num_output_channels_ == kStereoOutputChannelCount ||
           num_output_channels_ == kLayout71OutputChannelCount);
  }

  ~CastAudioDecoderImpl() override {}

  void Initialize(const media::AudioConfig& config) {
    DCHECK(!initialized_);
    DCHECK_LE(config_.channel_number, kMaxChannelInput);
    config_ = config;

    if (config_.channel_number == 1) {
      // If the input is mono, create a ChannelMixer to convert mono to stereo.
      // TODO(kmackay) Support other channel format conversions?
      mixer_.reset(new ::media::ChannelMixer(::media::CHANNEL_LAYOUT_MONO,
                                             ::media::CHANNEL_LAYOUT_STEREO));
    }
    if (num_output_channels_ == kLayout71OutputChannelCount) {
      // If there are 8 output channel, create a Channel Mixer to convert
      // stereo to CHANNEL_LAYOUT_7_1.
      // TODO(tianyuwang): This is a hack for 8 channel test USB speaker.
      // Channel mixer from MONO TO LAYOUT 7_1 doesn't work with the current
      // test USB speaker. As a result, we need to convert MONO channel
      // to STEREO first then convert it to LAYOUT_7_1.
      mixer_7_1_.reset(new ::media::ChannelMixer(::media::CHANNEL_LAYOUT_STEREO,
                                                 ::media::CHANNEL_LAYOUT_7_1));
    }

    base::WeakPtr<CastAudioDecoderImpl> self = weak_factory_.GetWeakPtr();
    if (config.codec == media::kCodecOpus) {
      // Insert fake extradata to make OpusAudioDecoder work with v2mirroring.
      if (config_.extra_data.empty() &&
          config_.samples_per_second == kOpusSamplingRate &&
          config_.channel_number == 2)
        config_.extra_data.assign(
            kFakeOpusExtraData,
            kFakeOpusExtraData + sizeof(kFakeOpusExtraData));
      decoder_.reset(new ::media::OpusAudioDecoder(task_runner_));
    } else {
      decoder_.reset(new ::media::FFmpegAudioDecoder(
          task_runner_, make_scoped_refptr(new ::media::MediaLog())));
    }
    decoder_->Initialize(
        media::DecoderConfigAdapter::ToMediaAudioDecoderConfig(config_),
        nullptr, base::Bind(&CastAudioDecoderImpl::OnInitialized, self),
        base::Bind(&CastAudioDecoderImpl::OnDecoderOutput, self));
    // Unfortunately there is no result from decoder_->Initialize() until later
    // (the pipeline status callback is posted to the task runner).
  }

  // CastAudioDecoder implementation:
  bool Decode(const scoped_refptr<media::DecoderBufferBase>& data,
              const DecodeCallback& decode_callback) override {
    DCHECK(!decode_callback.is_null());
    DCHECK(task_runner_->BelongsToCurrentThread());
    if (!initialized_ || decode_pending_) {
      decode_queue_.push(std::make_pair(data, decode_callback));
    } else {
      DecodeNow(data, decode_callback);
    }
    return true;
  }

 private:
  typedef std::pair<scoped_refptr<media::DecoderBufferBase>, DecodeCallback>
      DecodeBufferCallbackPair;

  void DecodeNow(const scoped_refptr<media::DecoderBufferBase>& data,
                 const DecodeCallback& decode_callback) {
    if (data->end_of_stream()) {
      // Post the task to ensure that |decode_callback| is not called from
      // within a call to Decode().
      task_runner_->PostTask(FROM_HERE,
                             base::Bind(decode_callback, kDecodeOk, data));
      return;
    }

    // FFmpegAudioDecoder requires a timestamp to be set.
    base::TimeDelta timestamp =
        base::TimeDelta::FromMicroseconds(data->timestamp());
    if (timestamp == ::media::kNoTimestamp())
      data->set_timestamp(base::TimeDelta());

    decode_pending_ = true;
    decoder_->Decode(
        data->ToMediaBuffer(),
        base::Bind(&CastAudioDecoderImpl::OnDecodeStatus,
                   weak_factory_.GetWeakPtr(), timestamp, decode_callback));
  }

  void OnInitialized(bool success) {
    DCHECK(!initialized_);
    LOG_IF(ERROR, !success) << "Failed to initialize FFmpegAudioDecoder";
    if (success)
      initialized_ = true;

    if (success && !decode_queue_.empty()) {
      const auto& d = decode_queue_.front();
      DecodeNow(d.first, d.second);
      decode_queue_.pop();
    }

    if (!initialized_callback_.is_null())
      initialized_callback_.Run(initialized_);
  }

  void OnDecodeStatus(base::TimeDelta buffer_timestamp,
                      const DecodeCallback& decode_callback,
                      ::media::AudioDecoder::Status status) {
    Status result_status = kDecodeOk;
    scoped_refptr<media::DecoderBufferBase> decoded;
    if (status == ::media::AudioDecoder::kOk && !decoded_chunks_.empty()) {
      decoded = ConvertDecoded();
    } else {
      if (status != ::media::AudioDecoder::kOk)
        result_status = kDecodeError;
      decoded = new media::DecoderBufferAdapter(config_.id,
                                                new ::media::DecoderBuffer(0));
    }
    decoded_chunks_.clear();
    decoded->set_timestamp(buffer_timestamp);
    base::WeakPtr<CastAudioDecoderImpl> self = weak_factory_.GetWeakPtr();
    decode_callback.Run(result_status, decoded);
    if (!self.get())
      return;  // Return immediately if the decode callback deleted this.

    // Do not reset decode_pending_ to false until after the callback has
    // finished running because the callback may call Decode().
    decode_pending_ = false;

    if (decode_queue_.empty())
      return;

    const auto& d = decode_queue_.front();
    // Calling DecodeNow() here does not result in a loop, because
    // OnDecodeStatus() is always called asynchronously (guaranteed by the
    // AudioDecoder interface).
    DecodeNow(d.first, d.second);
    decode_queue_.pop();
  }

  void OnDecoderOutput(const scoped_refptr<::media::AudioBuffer>& decoded) {
    decoded_chunks_.push_back(decoded);
  }

  scoped_refptr<media::DecoderBufferBase> ConvertDecoded() {
    DCHECK(!decoded_chunks_.empty());
    int num_frames = 0;
    for (auto& chunk : decoded_chunks_)
      num_frames += chunk->frame_count();

    // Copy decoded data into an AudioBus for conversion.
    scoped_ptr<::media::AudioBus> decoded =
        ::media::AudioBus::Create(config_.channel_number, num_frames);
    int bus_frame_offset = 0;
    for (auto& chunk : decoded_chunks_) {
      chunk->ReadFrames(chunk->frame_count(), 0, bus_frame_offset,
                        decoded.get());
      bus_frame_offset += chunk->frame_count();
    }

    if (mixer_) {
      // Convert to stereo if necessary.
      scoped_ptr<::media::AudioBus> converted_to_stereo =
          ::media::AudioBus::Create(kStereoOutputChannelCount, num_frames);
      mixer_->Transform(decoded.get(), converted_to_stereo.get());
      decoded.swap(converted_to_stereo);
    }

    // TODO(tianyuwang): Remove this hack for 7_1 USB test speaker.
    if (mixer_7_1_) {
      // Convert to layout 7_1 if necessary.
      scoped_ptr<::media::AudioBus> converted_to_7_1 =
          ::media::AudioBus::Create(num_output_channels_, num_frames);
      mixer_7_1_->Transform(decoded.get(), converted_to_7_1.get());
      decoded.swap(converted_to_7_1);
    }

    // Convert to the desired output format.
    return FinishConversion(decoded.get());
  }

  scoped_refptr<media::DecoderBufferBase> FinishConversion(
      ::media::AudioBus* bus) {
    DCHECK_EQ(num_output_channels_, bus->channels());
    int size = bus->frames() * num_output_channels_ *
               OutputFormatSizeInBytes(output_format_);
    scoped_refptr<::media::DecoderBuffer> result(
        new ::media::DecoderBuffer(size));

    if (output_format_ == kOutputSigned16) {
      bus->ToInterleaved(bus->frames(), OutputFormatSizeInBytes(output_format_),
                         result->writable_data());
    } else if (output_format_ == kOutputPlanarFloat) {
      // Data in an AudioBus is already in planar float format; just copy each
      // channel into the result buffer in order.
      float* ptr = reinterpret_cast<float*>(result->writable_data());
      for (int c = 0; c < bus->channels(); ++c) {
        memcpy(ptr, bus->channel(c), bus->frames() * sizeof(float));
        ptr += bus->frames();
      }
    } else {
      NOTREACHED();
    }

    result->set_duration(base::TimeDelta::FromMicroseconds(
        bus->frames() * base::Time::kMicrosecondsPerSecond /
        config_.samples_per_second));
    return make_scoped_refptr(
        new media::DecoderBufferAdapter(config_.id, result));
  }

  const scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
  InitializedCallback initialized_callback_;
  OutputFormat output_format_;
  media::AudioConfig config_;
  scoped_ptr<::media::AudioDecoder> decoder_;
  std::queue<DecodeBufferCallbackPair> decode_queue_;
  bool initialized_;
  int num_output_channels_;
  scoped_ptr<::media::ChannelMixer> mixer_;
  scoped_ptr<::media::ChannelMixer> mixer_7_1_;
  bool decode_pending_;
  std::vector<scoped_refptr<::media::AudioBuffer>> decoded_chunks_;
  base::WeakPtrFactory<CastAudioDecoderImpl> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(CastAudioDecoderImpl);
};

}  // namespace

// static
scoped_ptr<CastAudioDecoder> CastAudioDecoder::Create(
    const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
    const media::AudioConfig& config,
    OutputFormat output_format,
    const InitializedCallback& initialized_callback) {
  scoped_ptr<CastAudioDecoderImpl> decoder(new CastAudioDecoderImpl(
      task_runner, initialized_callback, output_format));
  decoder->Initialize(config);
  return std::move(decoder);
}

// static
int CastAudioDecoder::OutputFormatSizeInBytes(
    CastAudioDecoder::OutputFormat format) {
  switch (format) {
    case CastAudioDecoder::OutputFormat::kOutputSigned16:
      return 2;
    case CastAudioDecoder::OutputFormat::kOutputPlanarFloat:
      return 4;
  }
  NOTREACHED();
  return 1;
}

}  // namespace media
}  // namespace chromecast


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <meta name="author" content="@renodesper">
    <meta name="description" content="Thoughts, stories and ideas.">
    <meta name="keywords" content="blog,developer,personal">

    <base href="https://renodesper.com">
    <title>
  Editing Stream like Merlin The Mighty with Sed · A Place to Remember
</title>

    <link rel="canonical" href="https://renodesper.com/blog/2014-12-18-editing-stream-like-merlin-the-mighty-with-sed/">

    <link href="https://fonts.googleapis.com/css?family=Lato:400,700|Merriweather:300,700|Source+Code+Pro:400,700" rel="stylesheet">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.0/normalize.min.css" integrity="sha256-oSrCnRYXvHG31SBifqP2PM1uje7SJUyX0nTwO2RJV54=" crossorigin="anonymous" />

      <link rel="stylesheet" href="https://renodesper.com/css/coder.min.4daad1498fb945968ce48059545027b5a31dbeea575449abe6098326206584e0.css" integrity="sha256-TarRSY+5RZaM5IBZVFAntaMdvupXVEmr5gmDJiBlhOA=" crossorigin="anonymous" media="screen" />

    <link rel="icon" type="image/png" href="https://renodesper.com/images/favicon-32x32.png" sizes="32x32">
    <link rel="icon" type="image/png" href="https://renodesper.com/images/favicon-16x16.png" sizes="16x16">

    <meta name="generator" content="Hugo 0.49.2" />

      A Place to Remember

    <input type="checkbox" id="menu-toggle" />

            Blog

            Tags

            About Me

Editing Stream like Merlin The Mighty with Sed

We already talk about Vim a couple of time. Let’s move to sed. Sed is a stream editor (we already know that) that I used today. This is the case, I have some file (php file) which is badly written by someone (maybe for pissing me off) by changing some characters on it. Let’s say they change *.php into .rrrr wherever possible. It’s not a big deal if the file is only have a few lines, but imagine if it has 2000 lines and I should edit every .rrrr into *.php. Let’s assume that I’m using a server, and even worse there many files that should be edited.

Enough with the long talk, this is how I roll:

sed -i 's/\.rrrr/\.php/g' file.php

I also found an interesting sed & find combo, it looks like this:

find folder_path -type f -exec sed -i 's/\.rrrr/\.php/g' {} \;

Neat, isn’t it? :)


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

<title>Base64FilterInputStream</title>
<meta name="date" content="2014-09-01">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.security.crypt.io

Class Base64FilterInputStream

java.lang.Object

java.io.InputStream

java.io.FilterInputStream

org.security.crypt.io.AbstractEncodingFilterInputStream

org.security.crypt.io.Base64FilterInputStream

All Implemented Interfaces:

java.io.Closeable, java.lang.AutoCloseable

public class Base64FilterInputStream
extends AbstractEncodingFilterInputStream

Converts an input stream of base-64 encoded character bytes into raw bytes.

Author:

shivam

Field Summary

Fields

Modifier and Type
Field and Description

static int
LINE_LENGTH_64

Wrap lines at 64 characters.

static int
LINE_LENGTH_76

Wrap lines at 76 characters.

Constructor Summary

Constructors

Constructor and Description

Base64FilterInputStream(java.io.InputStream in)

Creates a base-64 filter input stream around the given input stream.

Base64FilterInputStream(java.io.InputStream in,
                       int charsPerLine)

Creates a base-64 filter input stream around the given input stream.

Method Summary

Methods inherited from class org.security.crypt.io.AbstractEncodingFilterInputStream

read, read, read

Methods inherited from class java.io.FilterInputStream

available, close, mark, markSupported, reset, skip

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

LINE_LENGTH_64

public static final int LINE_LENGTH_64

Wrap lines at 64 characters.

See Also:

Constant Field Values

LINE_LENGTH_76

public static final int LINE_LENGTH_76

Wrap lines at 76 characters.

See Also:

Constant Field Values

Constructor Detail

Base64FilterInputStream

public Base64FilterInputStream(java.io.InputStream in)

Creates a base-64 filter input stream around the given input stream.

Parameters:

in - Input stream to wrap.

Base64FilterInputStream

public Base64FilterInputStream(java.io.InputStream in,
                               int charsPerLine)

Creates a base-64 filter input stream around the given input stream.

Parameters:

in - Input stream to wrap.

charsPerLine - Number of characters per line of encoded input. Must be one of
            LINE_LENGTH_64, LINE_LENGTH_76, or 0 to
            indicate no wrapping.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
{
  it("should mock calls to a mock function", () => {
    const mockFn = moduleMocker.fn();
    mockFn.mockImplementation(() => {
      return "Foo";
    });
    expect(typeof mockFn.getMockImplementation()).toBe("function");
    expect(mockFn.getMockImplementation()()).toBe("Foo");
  });
}


text:
<?php
namespace Crocos\SecurityBundle\Tests\Fixtures;

use Crocos\SecurityBundle\Annotation\Secure;
use Crocos\SecurityBundle\Annotation\SecureConfig;

/**
 * @Secure(allow={"admin"})
 * @SecureConfig(roleManager="in_memory", httpsRequired=true)
 */
class AdminController extends SecureController
{
    public function securedAction()
    {
    }

    /**
     * @SecureConfig(httpsRequired=false)
     * @Secure(disabled=true)
     */
    public function publicAction()
    {
    }

    public function loginAction()
    {
    }

    public function forward()
    {
    }
}


text:
namespace cobalt {
namespace overlay_info {

// This class allows register of arbitrary overlay information from anywhere
// inside Cobalt.  It also allows a consumer to retrieve and clear all
// registered info, such info will be displayed as overlay.  The data is stored
// as std::string internally.
// The class is thread safe and all its methods can be accessed from any thread.
// On average it expects to have less than 10 such info registered per frame.
//
// The info is stored in the following format:
//   name0,value0,name1,value1,...
// Binary data will be converted into hex string before storing.
class OverlayInfoRegistry {
 public:
  static const char kDelimiter = ',';  // ':' doesn't work with some scanners
  // The size of category and data combined should be less than or equal to
  // kMaxSizeOfData - 1.  The extra room of one byte is used by the delimiter.
  static const size_t kMaxSizeOfData = 255;
  // The app DCHECKs if the number of pending overlay exceeds the following
  // value.
  static const size_t kMaxNumberOfPendingOverlayInfo = 1024;

  static void Disable();

  // Both |category| and |data| cannot contain the delimiter.
  static void Register(const char* category, const char* data);
  // Both |category| and |data| cannot contain the delimiter.
  static void Register(const char* category, const void* data,
                       size_t data_size);
  // Both |category| and |data| cannot contain the delimiter.
  template <typename T>
  static void Register(const char* category, T data) {
    std::stringstream ss;
    ss << data;
    Register(category, ss.str().c_str());
  }

  static void RetrieveAndClear(std::string* infos);
};

}  // namespace overlay_info
}  // namespace cobalt

#endif  // COBALT_OVERLAY_INFO_OVERLAY_INFO_REGISTRY_H_


text:
Ext.define('Vegi.view.production.category.MainViewController', {
    extend: 'Ext.app.ViewController',
    alias: 'controller.productioncategorymain',

});


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

#ifndef TENSORFLOW_TEXT_CORE_KERNELS_NGRAMS_H_
#define TENSORFLOW_TEXT_CORE_KERNELS_NGRAMS_H_

#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "absl/strings/string_view.h"
#include "tensorflow/core/platform/tstring.h"
#include "tensorflow/lite/kernels/shim/op_kernel.h"
#include "tensorflow/lite/kernels/shim/status_macros.h"
#include "tensorflow/lite/kernels/shim/tensor_view.h"

namespace tensorflow {
namespace text {

// text.ngrams op kernel. See `kDoc` for more info.
template <tflite::shim::Runtime Rt>
class NGramsStrJoin : public tflite::shim::OpKernelShim<NGramsStrJoin, Rt> {
 protected:
  using Shape = tflite::shim::Shape;

 public:
  using typename tflite::shim::OpKernelShim<NGramsStrJoin, Rt>::InitContext;
  using typename tflite::shim::OpKernelShim<NGramsStrJoin, Rt>::InvokeContext;
  using typename tflite::shim::OpKernelShim<NGramsStrJoin,
                                            Rt>::ShapeInferenceContext;

  NGramsStrJoin() = default;
  static const char kOpName[];
  static const char kDoc[];

  // Attributes declaration
  static std::vector<std::string> Attrs() {
    return {"width: int32",           "axis: int",
            "reduction_type: string", "string_separator: string",
            "RAGGED_RANK: int >= 0",  "Tsplits: {int64} = DT_INT64"};
  }
  // Input tensors declaration
  static std::vector<std::string> Inputs() {
    return {"values: string", "row_splits: RAGGED_RANK * Tsplits"};
  }
  // Output tensors declaration
  static std::vector<std::string> Outputs() {
    return {"values: string", "row_splits: RAGGED_RANK * Tsplits"};
  }

  // Initializes the op
  absl::Status Init(InitContext* ctx) {
    absl::string_view reduction_type_val;
    SH_RETURN_IF_ERROR(ctx->GetAttr("reduction_type", &reduction_type_val));
    if (reduction_type_val != kStringJoin) {
      return absl::InternalError(
          absl::StrCat("Unsupported reduction_type: ", reduction_type_val));
    }
    int64_t axis;
    SH_RETURN_IF_ERROR(ctx->GetAttr("axis", &axis));
    if (axis != -1) {
      return absl::InternalError(absl::StrCat("axis != -1: ", axis));
    }
    SH_RETURN_IF_ERROR(ctx->GetAttr("width", &width_));
    absl::string_view string_separator;
    SH_RETURN_IF_ERROR(ctx->GetAttr("string_separator", &string_separator));
    string_separator_ = std::string(string_separator);
    return absl::OkStatus();
  }

  // Shape inference
  static absl::Status ShapeInference(ShapeInferenceContext* ctx) {
    if (ctx->NumOutputs() == 1) {
      // Tensor Output
      SH_ASSIGN_OR_RETURN(const auto input_shape, ctx->GetInputShape(kValues));
      int64_t width;
      SH_RETURN_IF_ERROR(ctx->GetAttr("width", &width));
      SH_RETURN_IF_ERROR(ctx->SetOutputShape(
          kValues, OutputValuesTensorShape(input_shape, width)));
    } else {
      // RaggedTensor Output
      SH_RETURN_IF_ERROR(ctx->SetOutputShape(kValues, Shape()));

      // The row_splits tensors maintain their shape, because only the
      // innermost dimension will change.
      for (int i = kRowSplitsStart; i < ctx->NumOutputs(); ++i) {
        SH_ASSIGN_OR_RETURN(const Shape input_row_splits_shape,
                            ctx->GetInputShape(i));
        if (input_row_splits_shape.Rank() != 1) {
          return absl::InvalidArgumentError(
              absl::StrCat("expected rank == 1 for input index: ", i));
        }
        SH_RETURN_IF_ERROR(ctx->SetOutputShape(i, input_row_splits_shape));
      }
    }
    return absl::OkStatus();
  }

  // Runs the operation
  absl::Status Invoke(InvokeContext* ctx) {
    using Tsplits = int64_t;
    // Storage for the dummy input and output row_splits used in the tensor
    // case.
    std::vector<Tsplits> tensor_input_row_splits;
    std::vector<Tsplits> tensor_output_row_splits;

    const Tsplits* input_row_splits;
    Tsplits* output_row_splits;
    int n_row_splits = 0;

    SH_ASSIGN_OR_RETURN(const auto input_values, ctx->GetInput(kValues));
    const Shape input_values_shape(input_values->Shape());

    // Tensor output
    if (ctx->NumOutputs() == 1) {
      // Generate mock input and output innermost row_splits.
      int64_t total_tokens =
          input_values->template Data<tensorflow::tstring>().size();
      int64_t tokens_per_element =
          input_values_shape->at(input_values_shape->size() - 1);
      tensor_output_row_splits.resize(total_tokens / tokens_per_element + 1);
      for (int64_t i = 0; i <= total_tokens; i += tokens_per_element) {
        tensor_input_row_splits.push_back(i);
      }
      input_row_splits = tensor_input_row_splits.data();
      output_row_splits = tensor_output_row_splits.data();
      n_row_splits = tensor_input_row_splits.size();
    } else {
      // RaggedTensor output
      int index = 0;
      const int num_row_splits = ctx->NumInputs() - kRowSplitsStart;
      while (index < num_row_splits - 1) {
        SH_ASSIGN_OR_RETURN(const auto input_tensor_row_splits,
                            ctx->GetInput(kRowSplitsStart + index));
        SH_ASSIGN_OR_RETURN(
            const auto output_tensor_row_splits,
            ctx->GetOutput(kRowSplitsStart + index,
                           Shape(input_tensor_row_splits->Shape())));
        const auto input_buffer =
            input_tensor_row_splits->template Data<Tsplits>();
        const auto output_buffer =
            output_tensor_row_splits->template Data<Tsplits>();
        std::memcpy(output_buffer.data(), input_buffer.data(),
                    input_buffer.size() * sizeof(Tsplits));
        ++index;
      }

      SH_ASSIGN_OR_RETURN(const auto input_tensor_row_splits,
                          ctx->GetInput(kRowSplitsStart + index));
      SH_ASSIGN_OR_RETURN(
          const auto output_tensor_row_splits,
          ctx->GetOutput(kRowSplitsStart + index,
                         Shape(input_tensor_row_splits->Shape())));
      input_row_splits =
          input_tensor_row_splits->template Data<Tsplits>().data();
      output_row_splits =
          output_tensor_row_splits->template Data<Tsplits>().data();
      n_row_splits = input_tensor_row_splits->Shape().at(0);
    }

    const auto input_values_data =
        input_values->template Data<tensorflow::tstring>();

    std::vector<std::string> buffer;
    for (int i = 0; i < n_row_splits - 1; ++i) {
      output_row_splits[i] = buffer.size();
      std::vector<tensorflow::tstring> tokens;
      for (int j = input_row_splits[i]; j < input_row_splits[i + 1]; ++j) {
        tokens.emplace_back(input_values_data.at(j));
        if (tokens.size() < width_)
          continue;
        tokens.erase(tokens.begin(), tokens.begin() + tokens.size() - width_);
        buffer.push_back(absl::StrJoin(tokens, string_separator_));
      }
    }
    output_row_splits[n_row_splits - 1] = buffer.size();

    tflite::shim::TensorViewOr output_values_or;
    if (ctx->NumOutputs() == 1) {
      output_values_or = ctx->GetOutput(
          kValues, OutputValuesTensorShape(input_values_shape, width_));
    } else {
      output_values_or =
          ctx->GetOutput(kValues, Shape({static_cast<int>(buffer.size())}));
    }
    if (!output_values_or.ok())
      return output_values_or.status();
    auto& output_buffer =
        output_values_or.value()->template Data<tensorflow::tstring>();
    int i = 0;
    for (const auto& v : buffer)
      output_buffer[i++] = v;
    return absl::OkStatus();
  }

 protected:
  inline static Shape OutputValuesTensorShape(const Shape& input_values_shape,
                                              const int64_t width) {
    Shape output_shape(input_values_shape);
    const int last_dim = output_shape->size() - 1;
    (*output_shape)[last_dim] =
        std::max(0, output_shape->at(last_dim) - static_cast<int>(width) + 1);
    return output_shape;
  }

  static const char kStringJoin[];
  // Both the input and output tensors use the same indices.
  static constexpr int kValues = 0;
  static constexpr int kRowSplitsStart = 1;

  int64_t width_;
  std::string string_separator_;
};

// Static member definitions.
// These can be inlined once the toolchain is bumped up to C++17

template <tflite::shim::Runtime Rt>
const char NGramsStrJoin<Rt>::kOpName[] = "TFText>Ngrams";

template <tflite::shim::Runtime Rt>
const char NGramsStrJoin<Rt>::kDoc[] = R"doc(
Description:
  This TFLite op implements the text.ngrams when reduction_type = STRING_JOIN.

Input:
* data: A string tensor, or a ragged string tensor (a 1D string value tensor
    and one or more 1D int64 row_split tensors).

Attributes:
* width:             scalar integer
    The width of the ngram window.
* axis:              scalar integer
    The axis to create ngrams along.  For STRING_JOIN, this must be -1.
* reduction_type:    scalar string
    A string corresponding to the name of an enum value of text.Reduction
    Currently, only STRING_JOIN is supported.
* string_separator:  scalar string
    The separator string used to join tokens together.

Output:
* output: A string tensor that matches the rank of 'data'.  Will be a ragged
    tensor if 'data' is a ragged tensor.
)doc";

template <tflite::shim::Runtime Rt>
const char NGramsStrJoin<Rt>::kStringJoin[] = "STRING_JOIN";

}  // namespace text
}  // namespace tensorflow

#endif  // TENSORFLOW_TEXT_CORE_KERNELS_NGRAMS_H_


text:
#region Licence

#endregion

using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace WmcSoft.Monitoring.Instruments
{
    /// <summary>
    /// Stores a value and the timestamp at which it was produced.
    /// </summary>
    /// <typeparam name="T">The type of value</typeparam>
    [DebuggerDisplay("{Value,nq}@{Timestamp.ToString(\"HH:mm:ss.fff\"), nq}")]
    public struct Timestamped<T> : IEquatable<T>
    {
        public Timestamped(T value, DateTime timestamp)
        {
            Value = value;
            Timestamp = timestamp;
        }

        public void Deconstruct(out T value, out DateTime timestamp)
        {
            value = Value;
            timestamp = Timestamp;
        }

        /// <summary>
        /// The value.
        /// </summary>
        public T Value { get; }

        /// <summary>
        /// The date and time when the value was produced.
        /// </summary>
        public DateTime Timestamp { get; }

        #region operators

        public static implicit operator T(Timestamped<T> value)
        {
            return value.Value;
        }

        #endregion

        #region IEquatable<T> members

        bool IEquatable<T>.Equals(T other)
        {
            return EqualityComparer<T>.Default.Equals(Value, other);
        }

        #endregion
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Annls Univ. Mariae Curie-Sklodowska, Sect. C, Biol. 31: 116 (1977)

#### Original name
Bryopogon crispus var. griseus Bystrek

### Remarks
null


text:
package com.github.weisj.darklaf.properties.parser;

class JoinedParser implements PropertyParser {
    private final PropertyParser first;
    private final PropertyParser second;

    JoinedParser(final PropertyParser first, final PropertyParser second) {
        this.first = first;
        this.second = second;
    }

    @Override
    public ParseResult doParse(final ParseResult parseResult, final ParserContext context) {
        return ParserUtil.apply(second, ParserUtil.apply(first, parseResult, context), context);
    }
}


text:
comically
=========

ComicAlly integrated webcomic viewer


text:
@interface RegistNextViewController : BaseViewController
@property(nonatomic,strong)NSString *phoneNum;
@property(nonatomic,strong)NSString *password;
@property(nonatomic,strong)NSString *invCode;

@end


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>J-Index</title>
<meta name="date" content="2013-09-05">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A C D E F G H I J L M N O P Q R S T U V

J

jfrmCompra - Class in com.puntodeventa.mvc.Views

jfrmCompra() - Constructor for class com.puntodeventa.mvc.Views.jfrmCompra

Creates new form jfrmCompra

jfrmLogin - Class in com.puntodeventa.mvc.Views

jfrmLogin() - Constructor for class com.puntodeventa.mvc.Views.jfrmLogin

jfrmProveedor - Class in com.puntodeventa.mvc.Views

jfrmProveedor() - Constructor for class com.puntodeventa.mvc.Views.jfrmProveedor

Creates new form jfrmCompra

jfrmReport - Class in com.puntodeventa.mvc.Views

jfrmReport() - Constructor for class com.puntodeventa.mvc.Views.jfrmReport

Creates new form jfrmReport

jfrmSplash - Class in com.puntodeventa.mvc.Views

jfrmSplash() - Constructor for class com.puntodeventa.mvc.Views.jfrmSplash

jtbpProduct - Static variable in class com.puntodeventa.mvc.Views.frmProduct

jtbpProduct - Static variable in class com.puntodeventa.mvc.Views.frmProduct_1

A C D E F G H I J L M N O P Q R S T U V

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
class DropNodeAdapter extends DropTargetAdapter{
    constructor(target){
        super(target);
    }

    dragging(source, event){

    }

    dragCommit(source){

    }
}


text:
// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using HtmlRenderer.Utils;

namespace HtmlRenderer
{
    ///
    ///
    ///
    internal sealed class WinGraphics : IGraphics
    {
        #region Fields and Consts

        ///
        /// used for <see cref="MeasureString(string,System.Drawing.Font,float,out int,out int)"/> calculation.
        ///
        private static readonly int[] _charFit = new int[1];

        ///
        /// used for <see cref="MeasureString(string,System.Drawing.Font,float,out int,out int)"/> calculation.
        ///
        private static readonly int[] _charFitWidth = new int[1000];

        ///
        /// Used for GDI+ measure string.
        ///
        private static readonly CharacterRange[] _characterRanges = new CharacterRange[1];

        ///
        /// The string format to use for measuring strings for GDI+ text rendering
        ///
        private static readonly StringFormat _stringFormat;

        ///
        /// The wrapped WinForms graphics object
        ///
        private readonly Graphics _g;

        ///
        /// Use GDI+ text rendering to measure/draw text.
        ///
        private readonly bool _useGdiPlusTextRendering;

        ///
        /// the initialized HDC used
        ///
        private IntPtr _hdc;

        #endregion

        ///
        /// Init static resources.
        ///
        static WinGraphics()
        {
            _stringFormat = new StringFormat(StringFormat.GenericDefault);
            _stringFormat.FormatFlags = StringFormatFlags.NoClip | StringFormatFlags.MeasureTrailingSpaces;
        }

        ///
        /// Init.
        ///
        /// <param name="g">the real graphics to use</param>
        /// <param name="useGdiPlusTextRendering">Use GDI+ text rendering to measure/draw text.</param>
        public WinGraphics(Graphics g, bool useGdiPlusTextRendering)
        {
            _g = g;
            _useGdiPlusTextRendering = useGdiPlusTextRendering;
        }

        ///
        /// Gets the bounding clipping region of this graphics.
        ///
        /// <returns>The bounding rectangle for the clipping region</returns>
        public RectangleF GetClip()
        {
            if( _hdc == IntPtr.Zero )
            {
                return _g.ClipBounds;
            }
            else
            {
                Rectangle lprc;
                Win32Utils.GetClipBox(_hdc, out lprc);
                return lprc;
            }
        }

        ///
        /// Sets the clipping region of this <see cref="T:System.Drawing.Graphics"/> to the result of the specified operation combining the current clip region and the rectangle specified by a <see cref="T:System.Drawing.RectangleF"/> structure.
        ///
        /// <param name="rect"><see cref="T:System.Drawing.RectangleF"/> structure to combine. </param>
        /// <param name="combineMode">Member of the <see cref="T:System.Drawing.Drawing2D.CombineMode"/> enumeration that specifies the combining operation to use. </param>
        public void SetClip(RectangleF rect, CombineMode combineMode = CombineMode.Replace)
        {
            ReleaseHdc();
            _g.SetClip(rect, combineMode);
        }

        ///
        /// Measure the width and height of string <paramref name="str"/> when drawn on device context HDC
        /// using the given font <paramref name="font"/>.
        ///
        /// <param name="str">the string to measure</param>
        /// <param name="font">the font to measure string with</param>
        /// <returns>the size of the string</returns>
        public Size MeasureString(string str, Font font)
        {
            if( _useGdiPlusTextRendering )
            {
                ReleaseHdc();
                _characterRanges[0] = new CharacterRange(0, str.Length);
                _stringFormat.SetMeasurableCharacterRanges(_characterRanges);
                var size = _g.MeasureCharacterRanges(str, font, RectangleF.Empty, _stringFormat)[0].GetBounds(_g).Size;
                return new Size((int)Math.Round(size.Width), (int)Math.Round(size.Height));
            }
            else
            {
                SetFont(font);

                var size = new Size();
                Win32Utils.GetTextExtentPoint32(_hdc, str, str.Length, ref size);
                return size;
            }
        }

        ///
        /// Measure the width and height of string <paramref name="str"/> when drawn on device context HDC
        /// using the given font <paramref name="font"/>.

        /// Restrict the width of the string and get the number of characters able to fit in the restriction and
        /// the width those characters take.
        ///
        /// <param name="str">the string to measure</param>
        /// <param name="font">the font to measure string with</param>
        /// <param name="maxWidth">the max width to render the string in</param>
        /// <param name="charFit">the number of characters that will fit under <see cref="maxWidth"/> restriction</param>
        /// <param name="charFitWidth"></param>
        /// <returns>the size of the string</returns>
        public Size MeasureString(string str, Font font, float maxWidth, out int charFit, out int charFitWidth)
        {
            if( _useGdiPlusTextRendering )
            {
                ReleaseHdc();
                throw new NotSupportedException("Char fit string measuring is not supported for GDI+ text rendering");
            }
            else
            {
                SetFont(font);

                var size = new Size();
                Win32Utils.GetTextExtentExPoint(_hdc, str, str.Length, (int)Math.Round(maxWidth), _charFit, _charFitWidth, ref size);
                charFit = _charFit[0];
                charFitWidth = charFit > 0 ? _charFitWidth[charFit - 1] : 0;
                return size;
            }
        }

        ///
        /// Draw the given string using the given font and foreground color at given location.
        ///
        /// <param name="str">the string to draw</param>
        /// <param name="font">the font to use to draw the string</param>
        /// <param name="color">the text color to set</param>
        /// <param name="point">the location to start string draw (top-left)</param>
        /// <param name="size">used to know the size of the rendered text for transparent text support</param>
        public void DrawString(String str, Font font, Color color, PointF point, SizeF size)
        {
            if( _useGdiPlusTextRendering )
            {
                ReleaseHdc();
                _g.DrawString(str, font, RenderUtils.GetSolidBrush(color), point.X - FontsUtils.GetFontLeftPadding(font)*.8f, point.Y);
            }
            else
            {
                if (color.A == 255)
                {
                    SetFont(font);
                    SetTextColor(color);

                    Win32Utils.TextOut(_hdc, (int)Math.Round(point.X), (int)Math.Round(point.Y), str, str.Length);
                }
                else
                {
                    InitHdc();
                    DrawTransparentText(_hdc, str, font, new Point((int)Math.Round(point.X), (int)Math.Round(point.Y)), Size.Round(size), color);
                }
            }
        }

        ///
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        ///
        public void Dispose()
        {
            ReleaseHdc();
        }

        #region Delegate graphics methods

        ///
        /// Gets or sets the rendering quality for this <see cref="T:System.Drawing.Graphics"/>.
        ///
        /// <returns>
        /// One of the <see cref="T:System.Drawing.Drawing2D.SmoothingMode"/> values.
        /// </returns>
        /// <PermissionSet><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence"/></PermissionSet>
        public SmoothingMode SmoothingMode
        {
            get
            {
                ReleaseHdc();
                return _g.SmoothingMode;
            }
            set
            {
                ReleaseHdc();
                _g.SmoothingMode = value;
            }
        }

        ///
        /// Draws a line connecting the two points specified by the coordinate pairs.
        ///
        /// <param name="pen"><see cref="T:System.Drawing.Pen"/> that determines the color, width, and style of the line. </param><param name="x1">The x-coordinate of the first point. </param><param name="y1">The y-coordinate of the first point. </param><param name="x2">The x-coordinate of the second point. </param><param name="y2">The y-coordinate of the second point. </param><exception cref="T:System.ArgumentNullException"><paramref name="pen"/> is null.</exception>
        public void DrawLine(Pen pen, float x1, float y1, float x2, float y2)
        {
            ReleaseHdc();
            _g.DrawLine(pen, x1, y1, x2, y2);
        }

        ///
        /// Draws a rectangle specified by a coordinate pair, a width, and a height.
        ///
        /// <param name="pen">A <see cref="T:System.Drawing.Pen"/> that determines the color, width, and style of the rectangle. </param><param name="x">The x-coordinate of the upper-left corner of the rectangle to draw. </param><param name="y">The y-coordinate of the upper-left corner of the rectangle to draw. </param><param name="width">The width of the rectangle to draw. </param><param name="height">The height of the rectangle to draw. </param><exception cref="T:System.ArgumentNullException"><paramref name="pen"/> is null.</exception>
        public void DrawRectangle(Pen pen, float x, float y, float width, float height)
        {
            ReleaseHdc();
            _g.DrawRectangle(pen, x, y, width, height);
        }

        public void FillRectangle(Brush getSolidBrush, float left, float top, float width, float height)
        {
            ReleaseHdc();
            _g.FillRectangle(getSolidBrush, left, top, width, height);
        }

        ///
        /// Draws the specified portion of the specified <see cref="T:System.Drawing.Image"/> at the specified location and with the specified size.
        ///
        /// <param name="image"><see cref="T:System.Drawing.Image"/> to draw. </param>
        /// <param name="destRect"><see cref="T:System.Drawing.RectangleF"/> structure that specifies the location and size of the drawn image. The image is scaled to fit the rectangle. </param>
        /// <param name="srcRect"><see cref="T:System.Drawing.RectangleF"/> structure that specifies the portion of the <paramref name="image"/> object to draw. </param>
        /// <exception cref="T:System.ArgumentNullException"><paramref name="image"/> is null.</exception>
        public void DrawImage(Image image, RectangleF destRect, RectangleF srcRect)
        {
            ReleaseHdc();
            _g.DrawImage(image, destRect, srcRect, GraphicsUnit.Pixel);
        }

        ///
        /// Draws the specified <see cref="T:System.Drawing.Image"/> at the specified location and with the specified size.
        ///
        /// <param name="image"><see cref="T:System.Drawing.Image"/> to draw. </param><param name="destRect"><see cref="T:System.Drawing.Rectangle"/> structure that specifies the location and size of the drawn image. </param><exception cref="T:System.ArgumentNullException"><paramref name="image"/> is null.</exception><PermissionSet><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence"/></PermissionSet>
        public void DrawImage(Image image, RectangleF destRect)
        {
            ReleaseHdc();
            _g.DrawImage(image, destRect);
        }

        ///
        /// Draws a <see cref="T:System.Drawing.Drawing2D.GraphicsPath"/>.
        ///
        /// <param name="pen"><see cref="T:System.Drawing.Pen"/> that determines the color, width, and style of the path. </param><param name="path"><see cref="T:System.Drawing.Drawing2D.GraphicsPath"/> to draw. </param><exception cref="T:System.ArgumentNullException"><paramref name="pen"/> is null.-or-<paramref name="path"/> is null.</exception><PermissionSet><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence"/></PermissionSet>
        public void DrawPath(Pen pen, GraphicsPath path)
        {
            _g.DrawPath(pen, path);
        }

        ///
        /// Fills the interior of a <see cref="T:System.Drawing.Drawing2D.GraphicsPath"/>.
        ///
        /// <param name="brush"><see cref="T:System.Drawing.Brush"/> that determines the characteristics of the fill. </param><param name="path"><see cref="T:System.Drawing.Drawing2D.GraphicsPath"/> that represents the path to fill. </param><exception cref="T:System.ArgumentNullException"><paramref name="brush"/> is null.-or-<paramref name="path"/> is null.</exception><PermissionSet><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence"/></PermissionSet>
        public void FillPath(Brush brush, GraphicsPath path)
        {
            ReleaseHdc();
            _g.FillPath(brush, path);
        }

        ///
        /// Fills the interior of a polygon defined by an array of points specified by <see cref="T:System.Drawing.PointF"/> structures.
        ///
        /// <param name="brush"><see cref="T:System.Drawing.Brush"/> that determines the characteristics of the fill. </param><param name="points">Array of <see cref="T:System.Drawing.PointF"/> structures that represent the vertices of the polygon to fill. </param><exception cref="T:System.ArgumentNullException"><paramref name="brush"/> is null.-or-<paramref name="points"/> is null.</exception>
        public void FillPolygon(Brush brush, PointF[] points)
        {
            ReleaseHdc();
            _g.FillPolygon(brush, points);
        }

        #endregion

        #region Private methods

        ///
        /// Init HDC for the current graphics object to be used to call GDI directly.
        ///
        private void InitHdc()
        {
            if(_hdc == IntPtr.Zero)
            {
                var clip = _g.Clip.GetHrgn(_g);

                _hdc = _g.GetHdc();
                Win32Utils.SetBkMode(_hdc, 1);

                Win32Utils.SelectClipRgn(_hdc, clip);

                Win32Utils.DeleteObject(clip);
            }
        }

        ///
        /// Release current HDC to be able to use <see cref="Graphics"/> methods.
        ///
        private void ReleaseHdc()
        {
            if (_hdc != IntPtr.Zero)
            {
                Win32Utils.SelectClipRgn(_hdc, IntPtr.Zero);
                _g.ReleaseHdc(_hdc);
                _hdc = IntPtr.Zero;
            }
        }

        ///
        /// Set a resource (e.g. a font) for the specified device context.
        /// WARNING: Calling Font.ToHfont() many times without releasing the font handle crashes the app.
        ///
        private void SetFont(Font font)
        {
            InitHdc();
            Win32Utils.SelectObject(_hdc, FontsUtils.GetCachedHFont(font));
        }

        ///
        /// Set the text color of the device context.
        ///
        private void SetTextColor(Color color)
        {
            InitHdc();
            int rgb = ( color.B & 0xFF ) << 16 | ( color.G & 0xFF ) << 8 | color.R;
            Win32Utils.SetTextColor(_hdc, rgb);
        }

        ///
        /// Special draw logic to draw transparent text using GDI.

        /// 1. Create in-memory DC

        /// 2. Copy background to in-memory DC

        /// 3. Draw the text to in-memory DC

        /// 4. Copy the in-memory DC to the proper location with alpha blend

        ///
        private static void DrawTransparentText(IntPtr hdc, string str, Font font, Point point, Size size, Color color)
        {
            IntPtr dib;
            var memoryHdc = Win32Utils.CreateMemoryHdc(hdc, size.Width, size.Height, out dib);

            try
            {
                // copy target background to memory HDC so when copied back it will have the proper background
                Win32Utils.BitBlt(memoryHdc, 0, 0, size.Width, size.Height, hdc, point.X, point.Y, Win32Utils.BitBltCopy);

                // Create and select font
                Win32Utils.SelectObject(memoryHdc, FontsUtils.GetCachedHFont(font));
                Win32Utils.SetTextColor(memoryHdc, (color.B & 0xFF) << 16 | (color.G & 0xFF) << 8 | color.R);

                // Draw text to memory HDC
                Win32Utils.TextOut(memoryHdc, 0, 0, str, str.Length);

                // copy from memory HDC to normal HDC with alpha blend so achieve the transparent text
                Win32Utils.AlphaBlend(hdc, point.X, point.Y, size.Width, size.Height, memoryHdc, 0, 0, size.Width, size.Height, new BlendFunction(color.A));
            }
            finally
            {
                Win32Utils.ReleaseMemoryHdc(memoryHdc, dib);
            }
        }

        #endregion
    }
}


text:
"""
Web resources and client for interacting with pubsub services.
"""

import mimetools
from time import gmtime, strftime
from StringIO import StringIO
import urllib
import urlparse

import simplejson

from twisted.application import service
from twisted.internet import defer, reactor
from twisted.python import log
from twisted.web import client, http, resource, server
from twisted.web.error import Error
from twisted.words.protocols.jabber.jid import JID
from twisted.words.protocols.jabber.error import StanzaError
from twisted.words.xish import domish

from wokkel.generic import parseXml
from wokkel.pubsub import Item
from wokkel.pubsub import PubSubClient

from idavoll import error

NS_ATOM = 'http://www.w3.org/2005/Atom'
MIME_ATOM_ENTRY = b'application/atom+xml;type=entry'
MIME_ATOM_FEED = b'application/atom+xml;type=feed'
MIME_JSON = b'application/json'

class XMPPURIParseError(ValueError):
    """
    Raised when a given XMPP URI couldn't be properly parsed.
    """

def getServiceAndNode(uri):
    """
    Given an XMPP URI, extract the publish subscribe service JID and node ID.
    """

    try:
        scheme, rest = uri.split(':', 1)
    except ValueError:
        raise XMPPURIParseError("No URI scheme component")

    if scheme != 'xmpp':
        raise XMPPURIParseError("Unknown URI scheme")

    if rest.startswith("//"):
        raise XMPPURIParseError("Unexpected URI authority component")

    try:
        entity, query = rest.split('?', 1)
    except ValueError:
        entity, query = rest, ''

    if not entity:
        raise XMPPURIParseError("Empty URI path component")

    try:
        service = JID(entity)
    except Exception, e:
        raise XMPPURIParseError("Invalid JID: %s" % e)

    params = urlparse.parse_qs(query)

    try:
        nodeIdentifier = params['node'][0]
    except (KeyError, ValueError):
        nodeIdentifier = ''

    return service, nodeIdentifier

def getXMPPURI(service, nodeIdentifier):
    """
    Construct an XMPP URI from a service JID and node identifier.
    """
    return "xmpp:%s?;node=%s" % (service.full(), nodeIdentifier or '')

def _parseContentType(header):
    """
    Parse a Content-Type header value to a L{mimetools.Message}.

    L{mimetools.Message} parses a Content-Type header and makes the
    components available with its C{getmaintype}, C{getsubtype}, C{gettype},
    C{getplist} and C{getparam} methods.
    """
    return mimetools.Message(StringIO(b'Content-Type: ' + header))

def _asyncResponse(render):
    """
    """
    def wrapped(self, request):
        def eb(failure):
            if failure.check(Error):
                err = failure.value
            else:
                log.err(failure)
                err = Error(500)
            request.setResponseCode(err.status, err.message)
            return err.response

        def finish(result):
            if result is server.NOT_DONE_YET:
                return

            if result:
                request.write(result)
            request.finish()

        d = defer.maybeDeferred(render, self, request)
        d.addErrback(eb)
        d.addCallback(finish)

        return server.NOT_DONE_YET

    return wrapped

class CreateResource(resource.Resource):
    """
    A resource to create a publish-subscribe node.
    """
    def __init__(self, backend, serviceJID, owner):
        self.backend = backend
        self.serviceJID = serviceJID
        self.owner = owner

    http_GET = None

    @_asyncResponse
    def render_POST(self, request):
        """
        Respond to a POST request to create a new node.
        """

        def toResponse(nodeIdentifier):
            uri = getXMPPURI(self.serviceJID, nodeIdentifier)
            body = simplejson.dumps({'uri': uri})
            request.setHeader(b'Content-Type', MIME_JSON)
            return body

        d = self.backend.createNode(None, self.owner)
        d.addCallback(toResponse)
        return d

class DeleteResource(resource.Resource):
    """
    A resource to create a publish-subscribe node.
    """
    def __init__(self, backend, serviceJID, owner):
        self.backend = backend
        self.serviceJID = serviceJID
        self.owner = owner

    render_GET = None

    @_asyncResponse
    def render_POST(self, request):
        """
        Respond to a POST request to create a new node.
        """
        def toResponse(result):
            request.setResponseCode(http.NO_CONTENT)

        def trapNotFound(failure):
            failure.trap(error.NodeNotFound)
            raise Error(http.NOT_FOUND, "Node not found")

        if not request.args.get('uri'):
            raise Error(http.BAD_REQUEST, "No URI given")

        try:
            jid, nodeIdentifier = getServiceAndNode(request.args['uri'][0])
        except XMPPURIParseError, e:
            raise Error(http.BAD_REQUEST, "Malformed XMPP URI: %s" % e)

        data = request.content.read()
        if data:
            params = simplejson.loads(data)
            redirectURI = params.get('redirect_uri', None)
        else:
            redirectURI = None

        d = self.backend.deleteNode(nodeIdentifier, self.owner,
                                    redirectURI)
        d.addCallback(toResponse)
        d.addErrback(trapNotFound)
        return d

class PublishResource(resource.Resource):
    """
    A resource to publish to a publish-subscribe node.
    """

    def __init__(self, backend, serviceJID, owner):
        self.backend = backend
        self.serviceJID = serviceJID
        self.owner = owner

    render_GET = None

    def checkMediaType(self, request):
        ctype = request.getHeader(b'content-type')

        if not ctype:
            request.setResponseCode(http.BAD_REQUEST)

            raise Error(http.BAD_REQUEST, b"No specified Media Type")

        message = _parseContentType(ctype)
        if (message.maintype != b'application' or
            message.subtype != b'atom+xml' or
            message.getparam(b'type') != b'entry' or
            (message.getparam(b'charset') or b'utf-8') != b'utf-8'):
            raise Error(http.UNSUPPORTED_MEDIA_TYPE,
                              b"Unsupported Media Type: %s" % ctype)

    @_asyncResponse
    def render_POST(self, request):
        """
        Respond to a POST request to create a new item.
        """

        def toResponse(nodeIdentifier):
            uri = getXMPPURI(self.serviceJID, nodeIdentifier)
            body = simplejson.dumps({'uri': uri})
            request.setHeader(b'Content-Type', MIME_JSON)
            return body

        def gotNode(nodeIdentifier, payload):
            item = Item(id='current', payload=payload)
            d = self.backend.publish(nodeIdentifier, [item], self.owner)
            d.addCallback(lambda _: nodeIdentifier)
            return d

        def getNode():
            if request.args.get('uri'):
                jid, nodeIdentifier = getServiceAndNode(request.args['uri'][0])
                return defer.succeed(nodeIdentifier)
            else:
                return self.backend.createNode(None, self.owner)

        def trapNotFound(failure):
            failure.trap(error.NodeNotFound)
            raise Error(http.NOT_FOUND, "Node not found")

        def trapXMPPURIParseError(failure):
            failure.trap(XMPPURIParseError)
            raise Error(http.BAD_REQUEST,
                        "Malformed XMPP URI: %s" % failure.value)

        self.checkMediaType(request)
        payload = parseXml(request.content.read())
        d = getNode()
        d.addCallback(gotNode, payload)
        d.addCallback(toResponse)
        d.addErrback(trapNotFound)
        d.addErrback(trapXMPPURIParseError)
        return d

class ListResource(resource.Resource):
    def __init__(self, service):
        self.service = service

    @_asyncResponse
    def render_GET(self, request):
        def responseFromNodes(nodeIdentifiers):
            body = simplejson.dumps(nodeIdentifiers)
            request.setHeader(b'Content-Type', MIME_JSON)
            return body

        d = self.service.getNodes()
        d.addCallback(responseFromNodes)
        return d

# Service for subscribing to remote XMPP Pubsub nodes and web resources

def extractAtomEntries(items):
    """
    Extract atom entries from a list of publish-subscribe items.

    @param items: List of L{domish.Element}s that represent publish-subscribe
        items.
    @type items: C{list}
    """

    atomEntries = []

    for item in items:
        # ignore non-items (i.e. retractions)
        if item.name != 'item':
            continue

        atomEntry = None
        for element in item.elements():
            # extract the first element that is an atom entry
            if element.uri == NS_ATOM and element.name == 'entry':
                atomEntry = element
                break

        if atomEntry:
            atomEntries.append(atomEntry)

    return atomEntries

def constructFeed(service, nodeIdentifier, entries, title):
    nodeURI = getXMPPURI(service, nodeIdentifier)
    now = strftime("%Y-%m-%dT%H:%M:%SZ", gmtime())

    # Collect the received entries in a feed
    feed = domish.Element((NS_ATOM, 'feed'))
    feed.addElement('title', content=title)
    feed.addElement('id', content=nodeURI)
    feed.addElement('updated', content=now)

    for entry in entries:
        feed.addChild(entry)

    return feed

class RemoteSubscriptionService(service.Service, PubSubClient):
    """
    Service for subscribing to remote XMPP Publish-Subscribe nodes.

    Subscriptions are created with a callback HTTP URI that is POSTed
    to with the received items in notifications.
    """

    def __init__(self, jid, storage):
        self.jid = jid
        self.storage = storage

    def trapNotFound(self, failure):
        failure.trap(StanzaError)

        if failure.value.condition == 'item-not-found':
            raise error.NodeNotFound()
        else:
            return failure

    def subscribeCallback(self, jid, nodeIdentifier, callback):
        """
        Subscribe a callback URI.

        This registers a callback URI to be called when a notification is
        received for the given node.

        If this is the first callback registered for this node, the gateway
        will subscribe to the node. Otherwise, the most recently published item
        for this node is retrieved and, if present, the newly registered
        callback will be called with that item.
        """

        def callbackForLastItem(items):
            atomEntries = extractAtomEntries(items)

            if not atomEntries:
                return

            self._postTo([callback], jid, nodeIdentifier, atomEntries[0],
                         MIME_ATOM_ENTRY)

        def subscribeOrItems(hasCallbacks):
            if hasCallbacks:
                if not nodeIdentifier:
                    return None
                d = self.items(jid, nodeIdentifier, 1)
                d.addCallback(callbackForLastItem)
            else:
                d = self.subscribe(jid, nodeIdentifier, self.jid)

            d.addErrback(self.trapNotFound)
            return d

        d = self.storage.hasCallbacks(jid, nodeIdentifier)
        d.addCallback(subscribeOrItems)
        d.addCallback(lambda _: self.storage.addCallback(jid, nodeIdentifier,
                                                         callback))
        return d

    def unsubscribeCallback(self, jid, nodeIdentifier, callback):
        """
        Unsubscribe a callback.

        If this was the last registered callback for this node, the
        gateway will unsubscribe from node.
        """

        def cb(last):
            if last:
                return self.unsubscribe(jid, nodeIdentifier, self.jid)

        d = self.storage.removeCallback(jid, nodeIdentifier, callback)
        d.addCallback(cb)
        return d

    def itemsReceived(self, event):
        """
        Fire up HTTP client to do callback
        """

        atomEntries = extractAtomEntries(event.items)
        service = event.sender
        nodeIdentifier = event.nodeIdentifier
        headers = event.headers

        # Don't notify if there are no atom entries
        if not atomEntries:
            return

        if len(atomEntries) == 1:
            contentType = MIME_ATOM_ENTRY
            payload = atomEntries[0]
        else:
            contentType = MIME_ATOM_FEED
            payload = constructFeed(service, nodeIdentifier, atomEntries,
                                    title='Received item collection')

        self.callCallbacks(service, nodeIdentifier, payload, contentType)

        if 'Collection' in headers:
            for collection in headers['Collection']:
                nodeIdentifier = collection or ''
                self.callCallbacks(service, nodeIdentifier, payload,
                                   contentType)

    def deleteReceived(self, event):
        """
        Fire up HTTP client to do callback
        """

        service = event.sender
        nodeIdentifier = event.nodeIdentifier
        redirectURI = event.redirectURI
        self.callCallbacks(service, nodeIdentifier, eventType='DELETED',
                           redirectURI=redirectURI)

    def _postTo(self, callbacks, service, nodeIdentifier,
                      payload=None, contentType=None, eventType=None,
                      redirectURI=None):

        if not callbacks:
            return

        postdata = None
        nodeURI = getXMPPURI(service, nodeIdentifier)
        headers = {'Referer': nodeURI.encode('utf-8'),
                   'PubSub-Service': service.full().encode('utf-8')}

        if payload:
            postdata = payload.toXml().encode('utf-8')
            if contentType:
                headers['Content-Type'] = "%s;charset=utf-8" % contentType

        if eventType:
            headers['Event'] = eventType

        if redirectURI:
            headers['Link'] = '<%s>; rel=alternate' % (
                              redirectURI.encode('utf-8'),
                              )

        def postNotification(callbackURI):
            f = getPageWithFactory(str(callbackURI),
                                   method='POST',
                                   postdata=postdata,
                                   headers=headers)
            d = f.deferred
            d.addErrback(log.err)

        for callbackURI in callbacks:
            reactor.callLater(0, postNotification, callbackURI)

    def callCallbacks(self, service, nodeIdentifier,
                            payload=None, contentType=None, eventType=None,
                            redirectURI=None):

        def eb(failure):
            failure.trap(error.NoCallbacks)

            # No callbacks were registered for this node. Unsubscribe?

        d = self.storage.getCallbacks(service, nodeIdentifier)
        d.addCallback(self._postTo, service, nodeIdentifier, payload,
                                    contentType, eventType, redirectURI)
        d.addErrback(eb)
        d.addErrback(log.err)

class RemoteSubscribeBaseResource(resource.Resource):
    """
    Base resource for remote pubsub node subscription and unsubscription.

    This resource accepts POST request with a JSON document that holds
    a dictionary with the keys C{uri} and C{callback} that respectively map
    to the XMPP URI of the publish-subscribe node and the callback URI.

    This class should be inherited with L{serviceMethod} overridden.

    @cvar serviceMethod: The name of the method to be called with
                         the JID of the pubsub service, the node identifier
                         and the callback URI as received in the HTTP POST
                         request to this resource.
    """
    serviceMethod = None
    errorMap = {
            error.NodeNotFound:
                (http.FORBIDDEN, "Node not found"),
            error.NotSubscribed:
                (http.FORBIDDEN, "No such subscription found"),
            error.SubscriptionExists:
                (http.FORBIDDEN, "Subscription already exists"),
    }

    def __init__(self, service):
        self.service = service
        self.params = None

    render_GET = None

    @_asyncResponse
    def render_POST(self, request):
        def trapNotFound(failure):
            err = failure.trap(*self.errorMap.keys())
            status, message = self.errorMap[err]
            raise Error(status, message)

        def toResponse(result):
            request.setResponseCode(http.NO_CONTENT)
            return b''

        def trapXMPPURIParseError(failure):
            failure.trap(XMPPURIParseError)
            raise Error(http.BAD_REQUEST,
                        "Malformed XMPP URI: %s" % failure.value)

        data = request.content.read()
        self.params = simplejson.loads(data)

        uri = self.params['uri']
        callback = self.params['callback']

        jid, nodeIdentifier = getServiceAndNode(uri)
        method = getattr(self.service, self.serviceMethod)
        d = method(jid, nodeIdentifier, callback)
        d.addCallback(toResponse)
        d.addErrback(trapNotFound)
        d.addErrback(trapXMPPURIParseError)
        return d

class RemoteSubscribeResource(RemoteSubscribeBaseResource):
    """
    Resource to subscribe to a remote publish-subscribe node.

    The passed C{uri} is the XMPP URI of the node to subscribe to and the
    C{callback} is the callback URI. Upon receiving notifications from the
    node, a POST request will be perfomed on the callback URI.
    """
    serviceMethod = 'subscribeCallback'

class RemoteUnsubscribeResource(RemoteSubscribeBaseResource):
    """
    Resource to unsubscribe from a remote publish-subscribe node.

    The passed C{uri} is the XMPP URI of the node to unsubscribe from and the
    C{callback} is the callback URI that was registered for it.
    """
    serviceMethod = 'unsubscribeCallback'

class RemoteItemsResource(resource.Resource):
    """
    Resource for retrieving items from a remote pubsub node.
    """

    def __init__(self, service):
        self.service = service

    @_asyncResponse
    def render_GET(self, request):
        try:
            maxItems = int(request.args.get('max_items', [0])[0]) or None
        except ValueError:
            raise Error(http.BAD_REQUEST,
                        "The argument max_items has an invalid value.")

        try:
            uri = request.args['uri'][0]
        except KeyError:
            raise Error(http.BAD_REQUEST,
                        "No URI for the remote node provided.")

        try:
            jid, nodeIdentifier = getServiceAndNode(uri)
        except XMPPURIParseError:
            raise Error(http.BAD_REQUEST,
                        "Malformed XMPP URI: %s" % uri)

        def toResponse(items):
            """
            Create a feed out the retrieved items.
            """
            atomEntries = extractAtomEntries(items)
            feed = constructFeed(jid, nodeIdentifier, atomEntries,
                                    "Retrieved item collection")
            body = feed.toXml().encode('utf-8')
            request.setHeader(b'Content-Type', MIME_ATOM_FEED)
            return body

        def trapNotFound(failure):
            failure.trap(StanzaError)
            if not failure.value.condition == 'item-not-found':
                raise failure
            raise Error(http.NOT_FOUND, "Node not found")

        d = self.service.items(jid, nodeIdentifier, maxItems)
        d.addCallback(toResponse)
        d.addErrback(trapNotFound)
        return d

# Client side code to interact with a service as provided above

def getPageWithFactory(url, contextFactory=None, *args, **kwargs):
    """Download a web page.

    Download a page. Return the factory that holds a deferred, which will
    callback with a page (as a string) or errback with a description of the
    error.

    See HTTPClientFactory to see what extra args can be passed.
    """

    factory = client.HTTPClientFactory(url, *args, **kwargs)
    factory.protocol.handleStatus_204 = lambda self: self.handleStatus_200()

    if factory.scheme == 'https':
        from twisted.internet import ssl
        if contextFactory is None:
            contextFactory = ssl.ClientContextFactory()
        reactor.connectSSL(factory.host, factory.port, factory, contextFactory)
    else:
        reactor.connectTCP(factory.host, factory.port, factory)
    return factory

class CallbackResource(resource.Resource):
    """
    Web resource for retrieving gateway notifications.
    """

    def __init__(self, callback):
        self.callback = callback

    http_GET = None

    def render_POST(self, request):
        if request.requestHeaders.hasHeader(b'Event'):
            payload = None
        else:
            payload = parseXml(request.content.read())

        self.callback(payload, request.requestHeaders)

        request.setResponseCode(http.NO_CONTENT)
        return b''

class GatewayClient(service.Service):
    """
    Service that provides client access to the HTTP Gateway into Idavoll.
    """

    agent = "Idavoll HTTP Gateway Client"

    def __init__(self, baseURI, callbackHost=None, callbackPort=None):
        self.baseURI = baseURI
        self.callbackHost = callbackHost or 'localhost'
        self.callbackPort = callbackPort or 8087
        root = resource.Resource()
        root.putChild('callback', CallbackResource(
                lambda *args, **kwargs: self.callback(*args, **kwargs)))
        self.site = server.Site(root)

    def startService(self):
        self.port = reactor.listenTCP(self.callbackPort,
                                      self.site)

    def stopService(self):
        return self.port.stopListening()

    def _makeURI(self, verb, query=None):
        uriComponents = urlparse.urlparse(self.baseURI)
        uri = urlparse.urlunparse((uriComponents[0],
                                   uriComponents[1],
                                   uriComponents[2] + verb,
                                   '',
                                   query and urllib.urlencode(query) or '',
                                   ''))
        return uri

    def callback(self, data, headers):
        pass

    def ping(self):
        f = getPageWithFactory(self._makeURI(''),
                               method='HEAD',
                               agent=self.agent)
        return f.deferred

    def create(self):
        f = getPageWithFactory(self._makeURI('create'),
                    method='POST',
                    agent=self.agent)
        return f.deferred.addCallback(simplejson.loads)

    def delete(self, xmppURI, redirectURI=None):
        query = {'uri': xmppURI}

        if redirectURI:
            params = {'redirect_uri': redirectURI}
            postdata = simplejson.dumps(params)
            headers = {'Content-Type': MIME_JSON}
        else:
            postdata = None
            headers = None

        f = getPageWithFactory(self._makeURI('delete', query),
                    method='POST',
                    postdata=postdata,
                    headers=headers,
                    agent=self.agent)
        return f.deferred

    def publish(self, entry, xmppURI=None):
        query = xmppURI and {'uri': xmppURI}

        f = getPageWithFactory(self._makeURI('publish', query),
                    method='POST',
                    postdata=entry.toXml().encode('utf-8'),
                    headers={'Content-Type': MIME_ATOM_ENTRY},
                    agent=self.agent)
        return f.deferred.addCallback(simplejson.loads)

    def listNodes(self):
        f = getPageWithFactory(self._makeURI('list'),
                    method='GET',
                    agent=self.agent)
        return f.deferred.addCallback(simplejson.loads)

    def subscribe(self, xmppURI):
        params = {'uri': xmppURI,
                  'callback': 'http://%s:%s/callback' % (self.callbackHost,
                                                         self.callbackPort)}
        f = getPageWithFactory(self._makeURI('subscribe'),
                    method='POST',
                    postdata=simplejson.dumps(params),
                    headers={'Content-Type': MIME_JSON},
                    agent=self.agent)
        return f.deferred

    def unsubscribe(self, xmppURI):
        params = {'uri': xmppURI,
                  'callback': 'http://%s:%s/callback' % (self.callbackHost,
                                                         self.callbackPort)}
        f = getPageWithFactory(self._makeURI('unsubscribe'),
                    method='POST',
                    postdata=simplejson.dumps(params),
                    headers={'Content-Type': MIME_JSON},
                    agent=self.agent)
        return f.deferred

    def items(self, xmppURI, maxItems=None):
        query = {'uri': xmppURI}
        if maxItems:
             query['max_items'] = int(maxItems)
        f = getPageWithFactory(self._makeURI('items', query),
                    method='GET',
                    agent=self.agent)
        return f.deferred