text:
Getting Started
***************

Application
===========

- Make sure the ``django.contrib.admin`` is installed in ``settings.py``:

  ::

    INSTALLED_APPS = (
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.sites',
    )

- Make sure that the following are uncommented, since the admin application
  depends on them:

  ::

    django.contrib.auth
    django.contrib.contenttypes
    django.contrib.sessions

Database
========

Create the database tables which are used by admin interface:

::

  python manage.py syncdb

**Note**:

- When you first run ``syncdb`` with ``django.contrib.auth`` in
  ``INSTALLED_APPS``, you'll be asked about creating a superuser.  If you
  didn't do so at that time, you'll need to run
  ``django/contrib/auth/bin/create_superuser.py`` to create an admin user.
  Otherwise, you won't be able to log in to the admin interface.

Models
======

Not all models can (or should) be editable by admin users.  You need to
create a ``ModelAdmin`` class for each model which you want included in
the admin interface.

Edit the ``app-name/admin.py`` file:

::

  from django.contrib import admin
  from myproject.myapp.models import Book

  class BookAdmin(admin.ModelAdmin):
      pass
  admin.site.register(Book, BookAdmin)

URL
===

Add (or uncomment) the ``autodiscover`` and URL pattern to ``urls.py``:

::

  from django.contrib import admin
  admin.autodiscover()

  urlpatterns = patterns('',
      (r'^admin/(.*)', admin.site.root),

Usage
=====

Start your development server:

::

  python manage.py runserver 0.0.0.0:8080

Visit the administration interface: http://127.0.0.1:8000/admin/.


text:
package org.zstack.testlib;

import com.sun.demo.jvmti.hprof.Tracker;
import org.apache.logging.log4j.ThreadContext;
import org.zstack.core.Platform;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.header.Constants;
import org.zstack.header.message.AbstractBeforeSendMessageInterceptor;
import org.zstack.header.message.CarrierMessage;
import org.zstack.header.message.Message;
import org.zstack.header.message.MessageReply;
import org.zstack.header.rest.BeforeAsyncJsonPostInterceptor;
import org.zstack.header.rest.RESTFacade;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Created by xing5 on 2017/3/24.
 */
public class ApiPathTracker {
    private CloudBus bus;
    private RESTFacade restf;

    List<Path> paths = new ArrayList<>();

    private enum Type {
        Message,
        HttpRPC,
    }

    private static class Path {
        Type type;
        String path;
    }

    public List<String> getApiPath() {
        return paths.stream().map(p -> String.format("(%s) %s", p.type, p.path)).collect(Collectors.toList());
    }

    public ApiPathTracker(String apiId) {
        bus = Platform.getComponentLoader().getComponent(CloudBus.class);
        restf = Platform.getComponentLoader().getComponent(RESTFacade.class);

        bus.installBeforeSendMessageInterceptor(new AbstractBeforeSendMessageInterceptor() {
            @Override
            public void beforeSendMessage(Message msg) {
                if (msg instanceof MessageReply || msg instanceof CarrierMessage) {
                    return;
                }

                String id = ThreadContext.get(Constants.THREAD_CONTEXT_API);

                if (id == null || !id.equals(apiId)) {
                    return;
                }

                Path p = new Path();
                p.type = Type.Message;
                p.path = msg.getClass().getName();
                paths.add(p);
            }
        });

        restf.installBeforeAsyncJsonPostInterceptor(new BeforeAsyncJsonPostInterceptor() {
            @Override
            public void beforeAsyncJsonPost(String url, Object body, TimeUnit unit, long timeout) {
                String id = ThreadContext.get(Constants.THREAD_CONTEXT_API);

                if (id == null || !id.equals(apiId)) {
                    return;
                }

                Path p = new Path();
                p.type = Type.HttpRPC;
                p.path = String.format("[url:%s, cmd: %s]", url, body.getClass().getName());
                paths.add(p);
            }

            @Override
            public void beforeAsyncJsonPost(String url, String body, TimeUnit unit, long timeout) {
                String id = ThreadContext.get(Constants.THREAD_CONTEXT_API);

                if (id == null || !id.equals(apiId)) {
                    return;
                }

                Path p = new Path();
                p.type = Type.HttpRPC;
                p.path = String.format("[url:%s, cmd body: %s]", url, body);
                paths.add(p);
            }
        });
    }
}

redpajama_set_name: RedPajamaGithub


text:
package edu.ur.metadata.marc;

import edu.ur.persistent.CommonPersistent;

/**
 * Represents a generic marc sub field.
 *
 * @author Nathan Sarr
 *
 */
public class MarcSubField extends CommonPersistent{

	/** eclipse generated id */
	private static final long serialVersionUID = -3387071569468295421L;

	/**  Default constructor */
	MarcSubField(){}

	/**
	 * Create a dublin core element with the given name.
	 *
	 * @param name
	 */
	public MarcSubField(String name)
	{
		this.setName(name);
	}

	public int hashCode()
	{
		int value = 0;
		value += name == null ? 0 : name.hashCode();
		return value;
	}

	public boolean equals(Object o)
	{
		if (this == o) return true;
		if (!(o instanceof MarcSubField)) return false;

		final MarcSubField other = (MarcSubField) o;

		if( ( name != null && !name.equals(other.getName()) ) ||
			( name == null && other.getName() != null ) ) return false;

		return true;
	}

	public String toString()
	{
		StringBuffer sb = new StringBuffer("[");
		sb.append(" id = " );
		sb.append(id);
		sb.append(" name = ");
		sb.append(name);
		sb.append(" description = ");
		sb.append( description );
		sb.append("]");
		return sb.toString();
	}

}


text:
#ifndef __TSMF_DECODER_H
#define __TSMF_DECODER_H

#include "drdynvc_types.h"
#include "tsmf_types.h"

typedef struct _ITSMFDecoder ITSMFDecoder;

struct _ITSMFDecoder
{
	/* Set the decoder format. Return true if supported. */
	boolean (*SetFormat) (ITSMFDecoder* decoder, TS_AM_MEDIA_TYPE* media_type);
	/* Decode a sample. */
	boolean (*Decode) (ITSMFDecoder* decoder, const uint8* data, uint32 data_size, uint32 extensions);
	/* Get the decoded data */
	uint8* (*GetDecodedData) (ITSMFDecoder* decoder, uint32* size);
	/* Get the pixel format of decoded video frame */
	uint32 (*GetDecodedFormat) (ITSMFDecoder* decoder);
	/* Get the width and height of decoded video frame */
	boolean (*GetDecodedDimension) (ITSMFDecoder* decoder, uint32* width, uint32* height);
	/* Free the decoder */
	void (*Free) (ITSMFDecoder* decoder);
};

#define TSMF_DECODER_EXPORT_FUNC_NAME "TSMFDecoderEntry"
typedef ITSMFDecoder* (*TSMF_DECODER_ENTRY) (void);

ITSMFDecoder* tsmf_load_decoder(const char* name, TS_AM_MEDIA_TYPE* media_type);

#endif


text:
import { Component, ViewChild } from '@angular/core';

import { Events, MenuController, Nav, Platform } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { Storage } from '@ionic/storage';

import { AboutPage } from '../pages/about/about';
import { AccountPage } from '../pages/account/account';
import { LoginPage } from '../pages/login/login';
import { MapPage } from '../pages/map/map';
import { TabsPage } from '../pages/tabs/tabs';
import { SchedulePage } from '../pages/schedule/schedule';
import { SpeakerListPage } from '../pages/speaker-list/speaker-list';
import { SupportPage } from '../pages/support/support';

import { ConferenceData } from '../providers/conference-data';
import { UserData } from '../providers/user-data';

export interface PageInterface {
  title: string;
  component: any;
  icon: string;
  logsOut?: boolean;
  index?: number;
  tabComponent?: any;
}

@Component({
  templateUrl: 'app.template.html'
})
export class ConferenceApp {
  // the root nav is a child of the root app component
  // @ViewChild(Nav) gets a reference to the app's root nav
  @ViewChild(Nav) nav: Nav;

  // List of pages that can be navigated to from the left menu
  // the left menu only works after login
  // the login page disables the left menu
  appPages: PageInterface[] = [
    { title: 'Schedule', component: TabsPage, tabComponent: SchedulePage, icon: 'calendar' },
    { title: 'Speakers', component: TabsPage, tabComponent: SpeakerListPage, index: 1, icon: 'contacts' },
    { title: 'Map', component: TabsPage, tabComponent: MapPage, index: 2, icon: 'map' },
    { title: 'About', component: TabsPage, tabComponent: AboutPage, index: 3, icon: 'information-circle' }
  ];
  studentPages: PageInterface[] = [
    { title: 'Schedule', component: TabsPage, tabComponent: SchedulePage, icon: 'calendar' },
    { title: 'Speakers', component: TabsPage, tabComponent: SpeakerListPage, index: 1, icon: 'contacts' },
    { title: 'Map', component: TabsPage, tabComponent: MapPage, index: 2, icon: 'map' },
    { title: 'About', component: TabsPage, tabComponent: AboutPage, index: 3, icon: 'information-circle' }
  ];
  teacherPages: PageInterface[] = [
    { title: 'Schedule', component: TabsPage, tabComponent: SchedulePage, icon: 'calendar' },
    { title: 'Speakers', component: TabsPage, tabComponent: SpeakerListPage, index: 1, icon: 'contacts' },
    { title: 'Map', component: TabsPage, tabComponent: MapPage, index: 2, icon: 'map' },
    { title: 'About', component: TabsPage, tabComponent: AboutPage, index: 3, icon: 'information-circle' }
  ];
  loggedInPages: PageInterface[] = [
    { title: 'Account', component: AccountPage, icon: 'person' },
    { title: 'Support', component: SupportPage, icon: 'help' },
    { title: 'Logout', component: TabsPage, icon: 'log-out', logsOut: true }
  ];
  loggedOutPages: PageInterface[] = [
    { title: 'Login', component: LoginPage, icon: 'log-in' },
    { title: 'Support', component: SupportPage, icon: 'help' },
  ];
  rootPage: any;

  constructor(
    public events: Events,
    public userData: UserData,
    public menu: MenuController,
    public platform: Platform,
    public confData: ConferenceData,
    public storage: Storage,
    public splashScreen: SplashScreen
  ) {
    this.platformReady()

    // load the conference data
    confData.load();

    // decide which menu items should be hidden by current login status stored in local storage
    this.userData.hasLoggedIn().then((hasLoggedIn) => {
        if(hasLoggedIn) {
            this.rootPage = TabsPage;
        } else {
            this.rootPage = LoginPage;
        }
      this.enableMenu(hasLoggedIn === true);
    });

    this.listenToLoginEvents();
  }

  openPage(page: PageInterface) {
    // the nav component was found using @ViewChild(Nav)
    // reset the nav to remove previous pages and only have this page
    // we wouldn't want the back button to show in this scenario
    if (page.index) {
      this.nav.setRoot(page.component, { tabIndex: page.index }).catch(() => {
        console.log("Didn't set nav root");
      });
    } else {
      this.nav.setRoot(page.component).catch(() => {
        console.log("Didn't set nav root");
      });
    }

    if (page.logsOut === true) {
      // Give the menu time to close before changing to logged out
      setTimeout(() => {
        this.userData.logout();
      }, 1000);
    }
  }

  listenToLoginEvents() {
    this.events.subscribe('user:login', () => {
      this.enableMenu(true);
    });

    this.events.subscribe('user:signup', () => {
      this.enableMenu(true);
    });

    this.events.subscribe('user:logout', () => {
      this.enableMenu(false);
    });
  }

  enableMenu(loggedIn: boolean) {
    this.menu.enable(loggedIn, 'loggedInMenu');
    this.menu.enable(!loggedIn, 'loggedOutMenu');
  }

  platformReady() {
    // Call any initial plugins when ready
    this.platform.ready().then(() => {
      this.splashScreen.hide();
    });
  }

  isActive(page: PageInterface) {
    let childNav = this.nav.getActiveChildNav();

    // Tabs are a special case because they have their own navigation
    if (childNav) {
      if (childNav.getSelected() && childNav.getSelected().root === page.tabComponent) {
        return 'primary';
      }
      return;
    }

    if (this.nav.getActive() && this.nav.getActive().component === page.component) {
      return 'primary';
    }
    return;
  }
}


text:
package vespa

import (
	"fmt"
	"os"
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestFindVespaUser(t *testing.T) {
	var uName string

	t.Setenv("VESPA_USER", "nobody")
	uName = FindVespaUser()
	assert.Equal(t, "nobody", uName)

	t.Setenv("VESPA_USER", "")
	uName = FindVespaUser()
	assert.NotEqual(t, "", uName)
}

func TestFindVespaUidAndGid(t *testing.T) {
	uid, gid := FindVespaUidAndGid()
	fmt.Fprintln(os.Stderr, "INFO: result from FindVespaUidAndGid() is", uid, "and", gid)
}


text:
package opennlp.tools.formats.ad;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

import opennlp.tools.cmdline.ArgumentParser;
import opennlp.tools.cmdline.ArgumentParser.OptionalParameter;
import opennlp.tools.cmdline.ArgumentParser.ParameterDescription;
import opennlp.tools.cmdline.CmdLineUtil;
import opennlp.tools.cmdline.StreamFactoryRegistry;
import opennlp.tools.formats.LanguageSampleStreamFactory;
import opennlp.tools.postag.POSSample;
import opennlp.tools.util.InputStreamFactory;
import opennlp.tools.util.ObjectStream;
import opennlp.tools.util.PlainTextByLineStream;

/**
 * <b>Note:</b> Do not use this class, internal use only!
 */
public class ADPOSSampleStreamFactory<P> extends
    LanguageSampleStreamFactory<POSSample, P> {

  interface Parameters {
    @ParameterDescription(valueName = "charsetName",
        description = "encoding for reading and writing text, if absent the system default is used.")
    Charset getEncoding();

    @ParameterDescription(valueName = "sampleData", description = "data to be used, usually a file name.")
    File getData();

    @ParameterDescription(valueName = "language", description = "language which is being processed.")
    String getLang();

    @ParameterDescription(valueName = "expandME", description = "expand multiword expressions.")
    @OptionalParameter(defaultValue = "false")
    Boolean getExpandME();

    @ParameterDescription(valueName = "includeFeatures",
        description = "combine POS Tags with word features, like number and gender.")
    @OptionalParameter(defaultValue = "false")
    Boolean getIncludeFeatures();
  }

  public static void registerFactory() {
    StreamFactoryRegistry.registerFactory(POSSample.class, "ad",
        new ADPOSSampleStreamFactory<>(Parameters.class));
  }

  protected ADPOSSampleStreamFactory(Class<P> params) {
    super(params);
  }

  public ObjectStream<POSSample> create(String[] args) {

    Parameters params = ArgumentParser.parse(args, Parameters.class);

    language = params.getLang();

    InputStreamFactory sampleDataIn = CmdLineUtil.createInputStreamFactory(params.getData());

    ObjectStream<String> lineStream = null;
    try {
      lineStream = new PlainTextByLineStream(sampleDataIn, params.getEncoding());
    } catch (IOException ex) {
      CmdLineUtil.handleCreateObjectStreamError(ex);
    }

    return new ADPOSSampleStream(lineStream,
        params.getExpandME(), params.getIncludeFeatures());
  }

}


text:
require 'test_helper'

class IndicatorResourceTest < ActiveSupport::TestCase
  should belong_to(:resource)
  should belong_to(:indicator)
  should validate_presence_of(:resource_id)
  should validate_presence_of(:indicator_id)

  context "With a proper context, " do
    setup do
        create_context
    end
    teardown do
        remove_context
    end

    should "have a name method" do
        assert_equal "Crocodile Dundee", @a3.name
    end
  end
end


text:
#include <boss.hpp>
#include <platform/boss_platform.hpp>
#include <service/boss_zay.hpp>

#include <resource.hpp>

bool PlatformInit()
{
    Platform::InitForGL();
    Platform::SetViewCreator(ZayView::Creator);

    Platform::SetWindowName("Boss2D Tools");
    Platform::SetWindowView("sourcetoolView"); //("toolsView");

    String InfoString = String::FromAsset("windowinfo.json");
    if(0 < InfoString.Length())
    {
        Context Info(ST_Json, SO_OnlyReference, InfoString, InfoString.Length());
        Platform::SetWindowRect(
            Info("x").GetInt(0), Info("y").GetInt(0),
            Info("w").GetInt(640), Info("h").GetInt(480));
    }
    else Platform::SetWindowSize(640, 480);

    String AtlasInfoString = String::FromAsset("atlasinfo.json");
    Context AtlasInfo(ST_Json, SO_OnlyReference, AtlasInfoString, AtlasInfoString.Length());
    R::SetAtlasDir("image");
    R::AddAtlas("ui_atlaskey.png", "atlas.png", AtlasInfo);
    if(R::IsAtlasUpdated())
        R::RebuildAll();

    Platform::AddWindowProcedure(WE_Tick,
        [](payload data)->void
        {
            static uint64 LastUpdateCheckTime = Platform::Utility::CurrentTimeMsec();
            uint64 CurUpdateCheckTime = Platform::Utility::CurrentTimeMsec();
            if(LastUpdateCheckTime + 1000 < CurUpdateCheckTime)
            {
                LastUpdateCheckTime = CurUpdateCheckTime;
                if(R::IsAtlasUpdated())
                {
                    R::RebuildAll();
                    Platform::UpdateAllViews();
                }
            }
        });
    return true;
}

void PlatformQuit()
{
    rect128 WindowRect = Platform::GetWindowRect(true);

    Context Info;
    Info.At("x").Set(String::FromInteger(WindowRect.l));
    Info.At("y").Set(String::FromInteger(WindowRect.t));
    Info.At("w").Set(String::FromInteger(WindowRect.r - WindowRect.l));
    Info.At("h").Set(String::FromInteger(WindowRect.b - WindowRect.t));
    Info.SaveJson().ToAsset("windowinfo.json");

    Context AtlasInfo;
    R::SaveAtlas(AtlasInfo);
    AtlasInfo.SaveJson().ToAsset("atlasinfo.json");
}


text:
class Film < ActiveRecord::Base
  belongs_to :artist
  has_many :links
  has_many :tags, through: :films_tags
  belongs_to :company
  belongs_to :designation

  def self.add_film(params = {})
    series = Series.where('upper(name) = ?', params[:designation_main].upcase).first || Series.create(name: params[:designation_main].upcase)

    designation = Designation.where('id = ?', series.id).where('upper(name) = ?', params[:designation_additional].upcase).first
    if designation
      return designation.film
    end
    designation = Designation.create(series_id: series.id, name: params[:designation_additional])

    params[:designation_id] = designation.id
    params.delete :designation_main
    params.delete :designation_additional

    Film.create(params)
  end
end


text:
<?php
App::uses('GenericAuthAppModel', 'GenericAuth.Model');
/**
 * UserSocialNetwork Model
 *
 * @property User $User
 */
class UserSocialNetwork extends GenericAuthAppModel {

/**
 * Validation rules
 *
 * @var array
 */
	public $validate = array(
		'type' => array(
			'notempty' => array(
				'rule' => array('notempty'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
	);

/**
 * belongsTo associations
 *
 * @var array
 */
	public $belongsTo = array(
		'User' => array(
			'className' => 'Users.User',
			'foreignKey' => 'user_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		)
	);

/**
 * Get details by auth id and provider
 */
	public function getDetailsByAuthIdAndProvider($authId, $provider){
		$this->Behaviors->attach('Containable');
		$this->contain();
		$userSocialNetwork = $this->find("first",array('conditions' => array('UserSocialNetwork.social_net_id' => $authId,'UserSocialNetwork.type' => $provider)));
		return $userSocialNetwork;
	}

/**
 * Get details by User Id and Provider
 */
	public function getDetailsByUserIdAndProvider($userId, $provider){
		$this->Behaviors->attach('Containable');
		$this->contain();
		$userSocialNetwork = $this->find("first",array('conditions' => array('UserSocialNetwork.user_id' => $userId, 'UserSocialNetwork.type' => $provider)));
		return $userSocialNetwork;
	}
}


text:
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper')

describe "Analytical::Modules::Mixpanel" do
  before(:each) do
    @parent = mock('api', :options=>{:google=>{:js_url_key=>'abc'}})
  end
  describe 'on initialize' do
    it 'should set the command_location' do
      a = Analytical::Modules::Mixpanel.new :parent=>@parent, :js_url_key=>'abc'
      a.tracking_command_location.should == :body_append
    end
    it 'should set the options' do
      a = Analytical::Modules::Mixpanel.new :parent=>@parent, :js_url_key=>'abc'
      a.options.should == {:js_url_key=>'abc', :parent=>@parent}
    end
  end
  describe '#identify' do
    it 'should return a js string' do
      @api = Analytical::Modules::Mixpanel.new :parent=>@parent, :js_url_key=>'abcdef'
      @api.identify('id', {:email=>'test@test.com'}).should == "mpmetrics.identify('id');"
    end
    it 'should return a js string with name if included' do
      @api = Analytical::Modules::Mixpanel.new :parent=>@parent, :js_url_key=>'abcdef'
      @api.identify('id', {:email=>'test@test.com', :name => "user_name"}).should == "mpmetrics.identify('id'); mpmetrics.name_tag('user_name');"
    end
  end
  describe '#track' do
    it 'should return the tracking javascript' do
      @api = Analytical::Modules::Mixpanel.new :parent=>@parent, :key=>'abcdef'
      @api.track('pagename', {:some=>'data'}).should == "mpmetrics.track(\"pagename\", {\"some\":\"data\"}, function(){});"
    end
    it 'should return the tracking javascript with a callback' do
      @api = Analytical::Modules::Mixpanel.new :parent=>@parent, :key=>'abcdef'
      @api.track('pagename', {:some=>'data', :callback=>'fubar'}).should == "mpmetrics.track(\"pagename\", {\"some\":\"data\"}, fubar);"
    end
  end
  describe '#event' do
    it 'should return a js string' do
      @api = Analytical::Modules::Mixpanel.new :parent=>@parent, :js_url_key=>'abcdef'
      @api.event('An event happened', { :item => 43 }).should == "mpmetrics.track(\"An event happened\", {\"item\":43});"
    end
  end
  describe '#init_javascript' do
    it 'should return the init javascript' do
      @api = Analytical::Modules::Mixpanel.new :parent=>@parent, :js_url_key=>'abcdef'
      @api.init_javascript(:head_prepend).should == ''
      @api.init_javascript(:head_append).should == ''
      @api.init_javascript(:body_prepend).should == ''
      @api.init_javascript(:body_append).should =~ /api\.mixpanel\.com\/site_media\/js\/api\/mixpanel\.js/
      @api.init_javascript(:body_append).should =~ /new MixpanelLib\('.*'\)/
    end
  end
end


text:
use rustc_serialize::base64::{self, ToBase64};

use std::fs::File;
use std::io::Read;

fn imgcat(buffer: Vec<u8>, size_key: &str, size_value: usize) -> String {
    let e = buffer.as_slice().to_base64(base64::STANDARD);
    return String::from(format!("\x1b]1337;File=inline=1;{size_key}={size_value};:{code}\x07", size_key = size_key, size_value = size_value, code = e));
}

pub fn imgcat_from_path(path: &str, width: usize) -> String {
    let mut f = match File::open(path) {
        Err(why) => panic!("couldn't open: {}", why),
        Ok(file) => file,
    };
    let mut buffer = Vec::new();
    f.read_to_end(&mut buffer).expect("fail to read image");

    return imgcat(buffer, &"width", width);
}

pub fn imgcat_from_url(url: &str, height: usize) -> Result<String, String> {
    let key = url.to_string().into_bytes().to_base64(base64::URL_SAFE);
    let path = format!("data/cache/img/{file_name}", file_name = key);

    let path2 = path.clone();

    return match File::open(path) {
        Err(why) => {
            error!("[imgcat from url error] url: {}, path: {}, reason: {}", url, path2, why);
            Err(format!("{:?}", why))
        },
        Ok(mut file) => {
            let mut buffer = Vec::new();
            file.read_to_end(&mut buffer).expect("fail to read image");
            Ok(imgcat(buffer, &"height", height))
        },
    };
}

pub fn reset_screen() {
    print!("{}{}{}", ::termion::clear::All, ::termion::style::Reset, ::termion::cursor::Show);
}

pub fn clear_screen () {
    print!("{}", ::termion::clear::All);
}


text:
class CreateAppeals < ActiveRecord::Migration[5.0]
  def up
    unless Appeal.table_exists?
      create_table :appeals do |t|
        t.timestamps
        t.references :appeal_type, foreign_key: { on_update: :cascade, on_delete: :nullify }
        t.references :user, foreign_key: { on_update: :cascade, on_delete: :nullify }
        t.references :agent, foreign_key: { on_update: :cascade, on_delete: :nullify }
        t.inet :ip
        t.integer :responder_id
        t.boolean :processed, default: false, null: false
        t.boolean :deleted, default: false, null: false
        t.string :name, default: '', null: false
        t.string :subject, null: false
        t.string :email, default: '', null: false
        t.string :phone, default: '', null: false
        t.string :attachment
        t.string :uuid
        t.text :body, null: false
        t.text :response
      end

      add_foreign_key :appeals, :users, column: :responder_id, on_update: :cascade, on_delete: :nullify
    end
  end

  def down
    if Appeal.table_exists?
      drop_table :appeals
    end
  end
end


text:
.. _version_1.0.2:

=============
Version 1.0.2
=============

Released on 2017/01/09.

.. NOTE::

    If you are upgrading a cluster, you must be running CrateDB 0.57.0 or
    higher before you upgrade to 1.0.2.

    If you want to perform a `rolling upgrade`_, your current CrateDB version
    number must be :ref:`version_1.0.0` or higher. If you want to upgrade from
    a version prior to this, the upgrade will introduce all of the breaking
    changes listed for :ref:`version_1.0.0`, and will require a `full restart
    upgrade`_.

.. WARNING::

    Before upgrading, you should `back up your data`_.

.. _rolling upgrade: https://crate.io/docs/crate/howtos/en/latest/admin/rolling-upgrade.html
.. _full restart upgrade: https://crate.io/docs/crate/howtos/en/latest/admin/full-restart-upgrade.html
.. _back up your data: https://crate.io/docs/crate/reference/en/latest/admin/snapshots.html

.. rubric:: Table of contents

.. contents::
   :local:

Changelog
=========

Changes
-------

- Do not display current statement in ``sys.jobs`` that disabled stats.

- It is not possible any more to circumvent ``NOT NULL`` column constraint by
  omitting the column in the ``INSERT`` statement.

- Updated crate-admin to 1.0.3 which includes the following change:

  - Added compatibility with future CrateDB versions which will serve the
    Admin UI from ``/admin/`` instead of ``/_plugins/crate-admin/``.

Fixes
-----

- Fixed a NPE when using a ``percentile`` aggregation in a multi-node
  environment.

- Fixed ``INDEX`` constraint validation. Defining it on complex data types like
  e.g. ``object`` was silently ignored instead of throwing an error.

- Fixed an issue that causes ``UnsupportedFeatureException`` for operations on
  a table where array access is used inside generated columns. e.g.::

      CREATE TABLE t1 (cola string, gencola AS (a[1]))

  Error thrown when: ``SELECT * from t1``, ``DROP TABLE t1``, etc.

- Fixed an issue that causes hanging queries if a data node disconnects from
  the cluster.

- CrateDB now throws a correct error if a user tries to create a table starting
  with ``_``.

- Fixed an issue that causes ``UnhandledServerException`` on joins when
  ``WHERE`` clause contains conditions on columns of array type of both tables
  which are separated with the ``OR`` :ref:`operator <gloss-operator>`. e.g.::

      SELECT * FROM t1 join t2 ON t1.id = t2.id
      WHERE 'foo' = ANY(a.strArray) OR 'bar' = ANY(b.strArray)

- :ref:`Scalar functions <scalar-functions>` ``longitude`` and ``latitude`` no
  longer show misleading results.

- Fixed an issue that causes ``ClassCastException`` on outer joins when
  ``WHERE`` clause contains a condition that prevents null values on the
  relation that may produce nulls. e.g.::

      SELECT * FROM t1 LEFT JOIN t2 ON t1.id = t2.id WHERE t2.txt = 'foo'

- Fixed NPE that occurred when an ``UPDATE`` statement inserted ``NULL`` value
  into a column that did not exist before.

- Fixed an issue that causes an error to be thrown if nested method calls are
  used in ``HAVING`` clause. e.g.::

      having sum(power(power(id, id), id)) > 1


text:
import React from 'react'
import logo from 'public/sir-edu_logo.png'
import './HomeView.scss'

export const HomeView = () => (

Sistema Integrado de Recursos - Educacional

)

export default HomeView


text:
/******************************************************************************
 *
 * Module Name: acapps - common include for ACPI applications/tools
 *
 *****************************************************************************/

/*
 * Copyright (C) 2000 - 2015, Intel Corp.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions, and the following disclaimer,
 *    without modification.
 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
 *    substantially similar to the "NO WARRANTY" disclaimer below
 *    ("Disclaimer") and any redistribution must be conditioned upon
 *    including a substantially similar Disclaimer requirement for further
 *    binary redistribution.
 * 3. Neither the names of the above-listed copyright holders nor the names
 *    of any contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * Alternatively, this software may be distributed under the terms of the
 * GNU General Public License ("GPL") version 2 as published by the Free
 * Software Foundation.
 *
 * NO WARRANTY
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGES.
 */

#ifndef _ACAPPS
#define _ACAPPS

/* Common info for tool signons */

#define ACPICA_NAME                 "Intel ACPI Component Architecture"
#define ACPICA_COPYRIGHT            "Copyright (c) 2000 - 2015 Intel Corporation"

#if ACPI_MACHINE_WIDTH == 64
#define ACPI_WIDTH          "-64"

#elif ACPI_MACHINE_WIDTH == 32
#define ACPI_WIDTH          "-32"

#else
#error unknown ACPI_MACHINE_WIDTH
#define ACPI_WIDTH          "-??"

#endif

/* Macros for signons and file headers */

#define ACPI_COMMON_SIGNON(utility_name) \
	"\n%s\n%s version %8.8X%s\n%s\n\n", \
	ACPICA_NAME, \
	utility_name, ((u32) ACPI_CA_VERSION), ACPI_WIDTH, \
	ACPICA_COPYRIGHT

#define ACPI_COMMON_HEADER(utility_name, prefix) \
	"%s%s\n%s%s version %8.8X%s\n%s%s\n%s\n", \
	prefix, ACPICA_NAME, \
	prefix, utility_name, ((u32) ACPI_CA_VERSION), ACPI_WIDTH, \
	prefix, ACPICA_COPYRIGHT, \
	prefix

/* Macros for usage messages */

#define ACPI_USAGE_HEADER(usage) \
	acpi_os_printf ("Usage: %s\nOptions:\n", usage);

#define ACPI_USAGE_TEXT(description) \
	acpi_os_printf (description);

#define ACPI_OPTION(name, description) \
	acpi_os_printf (" %-18s%s\n", name, description);

#define FILE_SUFFIX_DISASSEMBLY     "dsl"
#define FILE_SUFFIX_BINARY_TABLE    ".dat"	/* Needs the dot */

/*
 * getopt
 */
int acpi_getopt(int argc, char **argv, char *opts);

int acpi_getopt_argument(int argc, char **argv);

extern int acpi_gbl_optind;
extern int acpi_gbl_opterr;
extern int acpi_gbl_sub_opt_char;
extern char *acpi_gbl_optarg;

/*
 * cmfsize - Common get file size function
 */
u32 cm_get_file_size(ACPI_FILE file);

#ifndef ACPI_DUMP_APP
/*
 * adisasm
 */
acpi_status
ad_aml_disassemble(u8 out_to_file,
		   char *filename, char *prefix, char **out_filename);

void ad_print_statistics(void);

acpi_status ad_find_dsdt(u8 **dsdt_ptr, u32 *dsdt_length);

void ad_dump_tables(void);

acpi_status ad_get_local_tables(void);

acpi_status
ad_parse_table(struct acpi_table_header *table,
	       acpi_owner_id * owner_id, u8 load_table, u8 external);

acpi_status ad_display_tables(char *filename, struct acpi_table_header *table);

acpi_status ad_display_statistics(void);

/*
 * adwalk
 */
void
acpi_dm_cross_reference_namespace(union acpi_parse_object *parse_tree_root,
				  struct acpi_namespace_node *namespace_root,
				  acpi_owner_id owner_id);

void acpi_dm_dump_tree(union acpi_parse_object *origin);

void acpi_dm_find_orphan_methods(union acpi_parse_object *origin);

void
acpi_dm_finish_namespace_load(union acpi_parse_object *parse_tree_root,
			      struct acpi_namespace_node *namespace_root,
			      acpi_owner_id owner_id);

void
acpi_dm_convert_resource_indexes(union acpi_parse_object *parse_tree_root,
				 struct acpi_namespace_node *namespace_root);

/*
 * adfile
 */
acpi_status ad_initialize(void);

char *fl_generate_filename(char *input_filename, char *suffix);

acpi_status
fl_split_input_pathname(char *input_path,
			char **out_directory_path, char **out_filename);

char *ad_generate_filename(char *prefix, char *table_id);

void
ad_write_table(struct acpi_table_header *table,
	       u32 length, char *table_name, char *oem_table_id);
#endif

#endif				/* _ACAPPS */


text:
import { CLEAR_TRANSCRIPT, APPEND_TRANSCRIPT } from './constants'
import { concatTranscripts } from './utils'

const transcriptReducer = (state, action) => {
  switch (action.type) {
    case CLEAR_TRANSCRIPT:
      return {
        interimTranscript: '',
        finalTranscript: ''
      }
    case APPEND_TRANSCRIPT:
      return {
        interimTranscript: action.payload.interimTranscript,
        finalTranscript: concatTranscripts(state.finalTranscript, action.payload.finalTranscript)
      }
    default:
      throw new Error()
  }
}

export { transcriptReducer }


text:
@interface WaveView : UIView

@property (nonatomic, assign) CGFloat progress;
@property (nonatomic, strong) CADisplayLink *displayLink;
@property (nonatomic, assign) CGFloat wave_amplitude;//振幅a(y = asin(wx+φ) + k)
@property (nonatomic, assign) CGFloat wave_cycle;//周期w
@property (nonatomic, assign) CGFloat wave_h_distance;//两个波水平之间偏移
@property (nonatomic, assign) CGFloat wave_v_distance;//两个波竖直之间偏移
@property (nonatomic, assign) CGFloat wave_scale;//水波速率
@property (nonatomic, assign) CGFloat wave_offsety;//波峰所在位置的y坐标
@property (nonatomic, assign) CGFloat wave_move_width;//移动的距离,配合速率设置
@property (nonatomic, assign) CGFloat wave_offsetx;//偏移
@property (nonatomic, assign) CGFloat offsety_scale;//上升的速度

@end

@implementation WaveView

-(instancetype)initWithFrame:(CGRect)frame{

    if (self = [super initWithFrame:frame]) {

        self.backgroundColor = [UIColor blackColor];
        //初始化信息
        [self initInfo];
    }
    return self;
}

-(void)initInfo{

    //y=Asin(ωx+φ)+k
    _wave_amplitude = 5;

    _wave_cycle = M_PI*4/(self.frame.size.width);

    _wave_offsety = self.frame.size.height;

    self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(addProgress)];
    [self.displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
}

-(void)addProgress{

    NSLog(@"addProgress");
    _wave_offsetx += _wave_cycle*2;//速度
    _wave_offsety -= 0.1;
    if (_wave_offsety <= 0) {
        [self.displayLink invalidate];
        self.displayLink = nil;
    }
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect
{

    UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:rect];
    [[UIColor groupTableViewBackgroundColor] setFill];
    [path fill];
    [path addClip];
    CGFloat offsetx1 = 0;
    CGFloat offsetx2 = 2 * M_PI / _wave_cycle * 0.6;
    int offsety = _wave_offsety;
    //offsetx += 0.1;
    //绘制两个波形图
    [self drawWaveColor:[UIColor blueColor] offsetx:offsetx1 offsety:offsety];
    [self drawWaveColor:[UIColor cyanColor] offsetx:offsetx2 offsety:offsety];

}

- (void)drawWaveColor:(UIColor *)color offsetx:(CGFloat)offsetx offsety:(CGFloat)offsety
{

    UIBezierPath *wavePath = [UIBezierPath bezierPath];
    [wavePath moveToPoint:CGPointMake(0, _wave_offsety)];
    CGFloat y = _wave_offsety;
    for (float x = 0.0f; x <= self.frame.size.width ; x++) {

        //y=Asin(ωx+φ)+k
        //_wave_amplitude 表示波峰到波谷的间距
        //_wave_cycle 表示单位x内周期的个数(2π/width)表示在width宽度里面有一个周期
        //_wave_offsetx+offsetx 表示在x轴上的便宜量
        //表示距离原点的偏移量
        y = _wave_amplitude * sin(_wave_cycle * x+_wave_offsetx+offsetx)+offsety;
        [wavePath addLineToPoint:CGPointMake(x, y)];
    }
    [wavePath addLineToPoint:CGPointMake(self.frame.size.width, self.frame.size.height)];
    [wavePath addLineToPoint:CGPointMake(0, self.frame.size.height)];
    [wavePath closePath];
    [color set];
    [wavePath fill];
}

@end

#pragma mark - WaveViewViewController
@interface WaveViewViewController ()

@end

@implementation WaveViewViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blackColor];
    WaveView *view = [[WaveView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    view.layer.cornerRadius = 50;
    view.layer.masksToBounds = YES;
    [self.view addSubview:view];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
//===-- ClangTypeConverter.h - Converting Swift types to C types-*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
//  This file defines utilities for translating Swift types to C types.
//
//===----------------------------------------------------------------------===//

#ifndef SWIFT_AST_CLANG_TYPE_CONVERTER_H
#define SWIFT_AST_CLANG_TYPE_CONVERTER_H

#include "swift/AST/ASTContext.h"
#include "swift/AST/ClangModuleLoader.h"
#include "swift/AST/Type.h"
#include "swift/AST/TypeVisitor.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Type.h"

namespace swift {

/// Compute C types corresponding to Swift AST types.
class ClangTypeConverter :
    public TypeVisitor<ClangTypeConverter, clang::QualType> {

  using super = TypeVisitor<ClangTypeConverter, clang::QualType>;

  llvm::DenseMap<Type, clang::QualType> Cache;
  llvm::DenseMap<const clang::Decl *, swift::Decl *> ReversedExportMap;

  bool StdlibTypesAreCached = false;

  ASTContext &Context;

  clang::ASTContext &ClangASTContext;

  const llvm::Triple Triple;

  ClangTypeConverter(const ClangTypeConverter &) = delete;
  ClangTypeConverter &operator=(const ClangTypeConverter &) = delete;

public:

  /// Create a ClangTypeConverter.
  ClangTypeConverter(ASTContext &ctx, clang::ASTContext &clangCtx,
                     llvm::Triple triple)
    : Context(ctx), ClangASTContext(clangCtx), Triple(triple)
  {
  };

  /// Compute the C function type for a Swift function type.
  ///
  /// It is the caller's responsibility to make sure this method is only
  /// called in the appropriate context. For example, it makes sense to use
  /// this method for the output type of a @convention(c) function.
  ///
  /// Since we do not check the context, the translation is unconditional.
  /// For example, String will automatically get translated to NSString
  /// when bridging is available.
  ///
  /// Additionally, the API is expected to be used only from
  ///
  /// \returns The appropriate clang type on success, nullptr on failure.
  ///
  /// Precondition: The representation argument must be C-compatible.
  const clang::Type *getFunctionType(
    ArrayRef<AnyFunctionType::Param> params, Type resultTy,
    AnyFunctionType::Representation repr);

  /// Compute the C function type for a SIL function type.
  const clang::Type *getFunctionType(
    ArrayRef<SILParameterInfo> params, Optional<SILResultInfo> result,
    SILFunctionType::Representation repr);

  /// Check whether the given Clang declaration is an export of a Swift
  /// declaration introduced by this converter, and if so, return the original
  /// Swift declaration.
  Decl *getSwiftDeclForExportedClangDecl(const clang::Decl *decl) const;

  /// Translate Swift generic arguments to Clang C++ template arguments.
  ///
  /// \p templateArgs must be empty. \p templateParams and \p genericArgs must
  /// be equal in size.
  ///
  /// \returns nullptr if successful. If an error occors, returns a list of
  /// types that couldn't be converted.
  std::unique_ptr<TemplateInstantiationError> getClangTemplateArguments(
      const clang::TemplateParameterList *templateParams,
      ArrayRef<Type> genericArgs,
      SmallVectorImpl<clang::TemplateArgument> &templateArgs);

private:
  friend ASTContext; // HACK: expose `convert` method to ASTContext

  clang::QualType convert(Type type);

  clang::QualType convertMemberType(NominalTypeDecl *DC,
                                    StringRef memberName);

  void registerExportedClangDecl(Decl *swiftDecl,
                                 const clang::Decl *clangDecl);

  clang::QualType reverseBuiltinTypeMapping(StructType *type);

  friend TypeVisitor<ClangTypeConverter, clang::QualType>;

  clang::QualType visitStructType(StructType *type);
  clang::QualType visitTupleType(TupleType *type);
  clang::QualType visitMetatypeType(MetatypeType *type);
  clang::QualType visitExistentialMetatypeType(ExistentialMetatypeType *type);
  clang::QualType visitProtocolType(ProtocolType *type);
  clang::QualType visitClassType(ClassType *type);
  clang::QualType visitBoundGenericClassType(BoundGenericClassType *type);
  clang::QualType visitBoundGenericType(BoundGenericType *type);
  clang::QualType visitEnumType(EnumType *type);
  clang::QualType visitFunctionType(FunctionType *type);
  clang::QualType visitProtocolCompositionType(ProtocolCompositionType *type);
  clang::QualType visitExistentialType(ExistentialType *type);
  clang::QualType visitBuiltinRawPointerType(BuiltinRawPointerType *type);
  clang::QualType visitBuiltinIntegerType(BuiltinIntegerType *type);
  clang::QualType visitBuiltinFloatType(BuiltinFloatType *type);
  clang::QualType visitArchetypeType(ArchetypeType *type);
  clang::QualType visitDependentMemberType(DependentMemberType *type);
  clang::QualType visitSILFunctionType(SILFunctionType *type);
  clang::QualType visitGenericTypeParamType(GenericTypeParamType *type);
  clang::QualType visitDynamicSelfType(DynamicSelfType *type);
  clang::QualType visitSILBlockStorageType(SILBlockStorageType *type);
  clang::QualType visitSugarType(SugarType *type);
  clang::QualType visitType(TypeBase *type);
  clang::QualType visit(Type type);
};

} // end namespace swift

#endif /* SWIFT_AST_CLANG_TYPE_CONVERTER_H */


text:
package com.sebastian_daschner.jaxrs_analyzer.analysis.bytecode.collection.testclasses;

import com.sebastian_daschner.jaxrs_analyzer.model.Types;
import com.sebastian_daschner.jaxrs_analyzer.model.instructions.*;
import com.sebastian_daschner.jaxrs_analyzer.model.methods.MethodIdentifier;

import java.util.LinkedList;
import java.util.List;

public class TestClass4 {

    public int method(final int number) {
        try {
            return 3 * 2 / number;
        } finally {
            System.out.println("Computed");
        }
    }

    public static List<Instruction> getResult() {
        final List<Instruction> instructions = new LinkedList<>();

        // constant folding
        instructions.add(new PushInstruction(6, Types.PRIMITIVE_INT, null));
        instructions.add(new LoadInstruction(1, Types.PRIMITIVE_INT, "number", null, null));
        instructions.add(new SizeChangingInstruction("IDIV", 1, 2, null));
        instructions.add(new StoreInstruction(2, Types.OBJECT, null));
        instructions.add(new GetStaticInstruction("java/lang/System", "out", "Ljava/io/PrintStream;", System.out, null));
        instructions.add(new PushInstruction("Computed", Types.STRING, null));
        instructions.add(new InvokeInstruction(MethodIdentifier.ofNonStatic("java/io/PrintStream", "println", Types.PRIMITIVE_VOID, Types.STRING), null));
        instructions.add(new LoadInstruction(2, Types.OBJECT, null, null));
        instructions.add(new ReturnInstruction(null));

        instructions.add(new ExceptionHandlerInstruction(null));
        instructions.add(new StoreInstruction(3, Types.OBJECT, null));
        instructions.add(new GetStaticInstruction("java/lang/System", "out", "Ljava/io/PrintStream;", System.out, null));
        instructions.add(new PushInstruction("Computed", Types.STRING, null));
        instructions.add(new InvokeInstruction(MethodIdentifier.ofNonStatic("java/io/PrintStream", "println", Types.PRIMITIVE_VOID, Types.STRING), null));
        instructions.add(new LoadInstruction(3, Types.OBJECT, null, null));
        instructions.add(new ThrowInstruction(null));

        return instructions;
    }

}


text:
package message

import (
	"encoding/gob"
	"github.com/golang/snappy/snappy"
	"io"
	"time"
)

//Message ...
type Message struct {
	Action    string
	Key       string
	Value     []byte
	Timestamp int64
	Ttl       int64
}

//NewMessage returns a message object through the interface
func NewMessage(action string, key string, value string, ttl int64) *Message {

	/*var b bytes.Buffer
	w := snappy.NewWriter(&b)
	w.Write([]byte(value))
	compressedValue := b.Bytes()
	*/

	compressedValue, _ := snappy.Encode([]byte{}, []byte(value))

	timestamp := time.Now().Unix()

	return &Message{
		Action:     action,
		Key:       key,
		Value:     compressedValue,
		Timestamp: timestamp,
		Ttl:       ttl,
	}
}

//SetMessage sets message object from data
func SetMessage(action string, key string, compressedValue []byte, timestamp int64, ttl int64) *Message {

	return &Message{
		Action:     action,
		Key:       key,
		Value:     compressedValue,
		Timestamp: timestamp,
		Ttl:       ttl,
	}
}

//GetValue gets value payload of the message
func (m *Message) GetValue() *string {
	dst, _ := snappy.Decode([]byte{}, m.Value)
	value := string(dst)
	return &value
}

//WriteGob this writes the object to io.Writer interface
func (m *Message) WriteGob(conn io.Writer) error {
	encoder := gob.NewEncoder(conn)
	err := encoder.Encode(m)
	return err
}


text:
package io.flutter.plugins.camera;

import static io.flutter.plugins.camera.CameraUtils.computeBestPreviewSize;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCaptureSession.CaptureCallback;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.CaptureFailure;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.CaptureResult;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.MeteringRectangle;
import android.hardware.camera2.params.OutputConfiguration;
import android.hardware.camera2.params.SessionConfiguration;
import android.media.CamcorderProfile;
import android.media.Image;
import android.media.ImageReader;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.util.Range;
import android.util.Rational;
import android.util.Size;
import android.view.Surface;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.flutter.embedding.engine.systemchannels.PlatformChannel;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugins.camera.PictureCaptureRequest.State;
import io.flutter.plugins.camera.media.MediaRecorderBuilder;
import io.flutter.plugins.camera.types.ExposureMode;
import io.flutter.plugins.camera.types.FlashMode;
import io.flutter.plugins.camera.types.FocusMode;
import io.flutter.plugins.camera.types.ResolutionPreset;
import io.flutter.view.TextureRegistry.SurfaceTextureEntry;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.Executors;

@FunctionalInterface
interface ErrorCallback {
  void onError(String errorCode, String errorMessage);
}

public class Camera {
  private static final String TAG = "Camera";

  private final SurfaceTextureEntry flutterTexture;
  private final CameraManager cameraManager;
  private final DeviceOrientationManager deviceOrientationListener;
  private final boolean isFrontFacing;
  private final int sensorOrientation;
  private final String cameraName;
  private final Size captureSize;
  private final Size previewSize;
  private final boolean enableAudio;
  private final Context applicationContext;
  private final CamcorderProfile recordingProfile;
  private final DartMessenger dartMessenger;
  private final CameraZoom cameraZoom;
  private final CameraCharacteristics cameraCharacteristics;

  private CameraDevice cameraDevice;
  private CameraCaptureSession cameraCaptureSession;
  private ImageReader pictureImageReader;
  private ImageReader imageStreamReader;
  private CaptureRequest.Builder captureRequestBuilder;
  private MediaRecorder mediaRecorder;
  private boolean recordingVideo;
  private File videoRecordingFile;
  private FlashMode flashMode;
  private ExposureMode exposureMode;
  private FocusMode focusMode;
  private PictureCaptureRequest pictureCaptureRequest;
  private CameraRegions cameraRegions;
  private int exposureOffset;
  private boolean useAutoFocus = true;
  private Range<Integer> fpsRange;
  private PlatformChannel.DeviceOrientation lockedCaptureOrientation;

  private static final HashMap<String, Integer> supportedImageFormats;
  // Current supported outputs
  static {
    supportedImageFormats = new HashMap<>();
    supportedImageFormats.put("yuv420", 35);
    supportedImageFormats.put("jpeg", 256);
  }

  public Camera(
      final Activity activity,
      final SurfaceTextureEntry flutterTexture,
      final DartMessenger dartMessenger,
      final String cameraName,
      final String resolutionPreset,
      final boolean enableAudio)
      throws CameraAccessException {
    if (activity == null) {
      throw new IllegalStateException("No activity available!");
    }
    this.cameraName = cameraName;
    this.enableAudio = enableAudio;
    this.flutterTexture = flutterTexture;
    this.dartMessenger = dartMessenger;
    this.cameraManager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
    this.applicationContext = activity.getApplicationContext();
    this.flashMode = FlashMode.auto;
    this.exposureMode = ExposureMode.auto;
    this.focusMode = FocusMode.auto;
    this.exposureOffset = 0;

    cameraCharacteristics = cameraManager.getCameraCharacteristics(cameraName);
    initFps(cameraCharacteristics);
    sensorOrientation = cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
    isFrontFacing =
        cameraCharacteristics.get(CameraCharacteristics.LENS_FACING)
            == CameraMetadata.LENS_FACING_FRONT;
    ResolutionPreset preset = ResolutionPreset.valueOf(resolutionPreset);
    recordingProfile =
        CameraUtils.getBestAvailableCamcorderProfileForResolutionPreset(cameraName, preset);
    captureSize = new Size(recordingProfile.videoFrameWidth, recordingProfile.videoFrameHeight);
    previewSize = computeBestPreviewSize(cameraName, preset);
    cameraZoom =
        new CameraZoom(
            cameraCharacteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE),
            cameraCharacteristics.get(CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM));

    deviceOrientationListener =
        new DeviceOrientationManager(activity, dartMessenger, isFrontFacing, sensorOrientation);
    deviceOrientationListener.start();
  }

  private void initFps(CameraCharacteristics cameraCharacteristics) {
    try {
      Range<Integer>[] ranges =
          cameraCharacteristics.get(CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES);
      if (ranges != null) {
        for (Range<Integer> range : ranges) {
          int upper = range.getUpper();
          Log.i("Camera", "[FPS Range Available] is:" + range);
          if (upper >= 10) {
            if (fpsRange == null || upper > fpsRange.getUpper()) {
              fpsRange = range;
            }
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    Log.i("Camera", "[FPS Range] is:" + fpsRange);
  }

  private void prepareMediaRecorder(String outputFilePath) throws IOException {
    if (mediaRecorder != null) {
      mediaRecorder.release();
    }

    mediaRecorder =
        new MediaRecorderBuilder(recordingProfile, outputFilePath)
            .setEnableAudio(enableAudio)
            .setMediaOrientation(
                lockedCaptureOrientation == null
                    ? deviceOrientationListener.getMediaOrientation()
                    : deviceOrientationListener.getMediaOrientation(lockedCaptureOrientation))
            .build();
  }

  @SuppressLint("MissingPermission")
  public void open(String imageFormatGroup) throws CameraAccessException {
    pictureImageReader =
        ImageReader.newInstance(
            captureSize.getWidth(), captureSize.getHeight(), ImageFormat.JPEG, 2);

    Integer imageFormat = supportedImageFormats.get(imageFormatGroup);
    if (imageFormat == null) {
      Log.w(TAG, "The selected imageFormatGroup is not supported by Android. Defaulting to yuv420");
      imageFormat = ImageFormat.YUV_420_888;
    }

    // Used to steam image byte data to dart side.
    imageStreamReader =
        ImageReader.newInstance(previewSize.getWidth(), previewSize.getHeight(), imageFormat, 2);

    cameraManager.openCamera(
        cameraName,
        new CameraDevice.StateCallback() {
          @Override
          public void onOpened(@NonNull CameraDevice device) {
            cameraDevice = device;
            try {
              startPreview();
              dartMessenger.sendCameraInitializedEvent(
                  previewSize.getWidth(),
                  previewSize.getHeight(),
                  exposureMode,
                  focusMode,
                  isExposurePointSupported(),
                  isFocusPointSupported());
            } catch (CameraAccessException e) {
              dartMessenger.sendCameraErrorEvent(e.getMessage());
              close();
            }
          }

          @Override
          public void onClosed(@NonNull CameraDevice camera) {
            dartMessenger.sendCameraClosingEvent();
            super.onClosed(camera);
          }

          @Override
          public void onDisconnected(@NonNull CameraDevice cameraDevice) {
            close();
            dartMessenger.sendCameraErrorEvent("The camera was disconnected.");
          }

          @Override
          public void onError(@NonNull CameraDevice cameraDevice, int errorCode) {
            close();
            String errorDescription;
            switch (errorCode) {
              case ERROR_CAMERA_IN_USE:
                errorDescription = "The camera device is in use already.";
                break;
              case ERROR_MAX_CAMERAS_IN_USE:
                errorDescription = "Max cameras in use";
                break;
              case ERROR_CAMERA_DISABLED:
                errorDescription = "The camera device could not be opened due to a device policy.";
                break;
              case ERROR_CAMERA_DEVICE:
                errorDescription = "The camera device has encountered a fatal error";
                break;
              case ERROR_CAMERA_SERVICE:
                errorDescription = "The camera service has encountered a fatal error.";
                break;
              default:
                errorDescription = "Unknown camera error";
            }
            dartMessenger.sendCameraErrorEvent(errorDescription);
          }
        },
        null);
  }

  private void createCaptureSession(int templateType, Surface... surfaces)
      throws CameraAccessException {
    createCaptureSession(templateType, null, surfaces);
  }

  private void createCaptureSession(
      int templateType, Runnable onSuccessCallback, Surface... surfaces)
      throws CameraAccessException {
    // Close any existing capture session.
    closeCaptureSession();

    // Create a new capture builder.
    captureRequestBuilder = cameraDevice.createCaptureRequest(templateType);

    // Build Flutter surface to render to
    SurfaceTexture surfaceTexture = flutterTexture.surfaceTexture();
    surfaceTexture.setDefaultBufferSize(previewSize.getWidth(), previewSize.getHeight());
    Surface flutterSurface = new Surface(surfaceTexture);
    captureRequestBuilder.addTarget(flutterSurface);

    List<Surface> remainingSurfaces = Arrays.asList(surfaces);
    if (templateType != CameraDevice.TEMPLATE_PREVIEW) {
      // If it is not preview mode, add all surfaces as targets.
      for (Surface surface : remainingSurfaces) {
        captureRequestBuilder.addTarget(surface);
      }
    }

    cameraRegions = new CameraRegions(getRegionBoundaries());

    // Prepare the callback
    CameraCaptureSession.StateCallback callback =
        new CameraCaptureSession.StateCallback() {
          @Override
          public void onConfigured(@NonNull CameraCaptureSession session) {
            if (cameraDevice == null) {
              dartMessenger.sendCameraErrorEvent("The camera was closed during configuration.");
              return;
            }
            cameraCaptureSession = session;

            updateFpsRange();
            updateFocus(focusMode);
            updateFlash(flashMode);
            updateExposure(exposureMode);

            refreshPreviewCaptureSession(
                onSuccessCallback, (code, message) -> dartMessenger.sendCameraErrorEvent(message));
          }

          @Override
          public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
            dartMessenger.sendCameraErrorEvent("Failed to configure camera session.");
          }
        };

    // Start the session
    if (VERSION.SDK_INT >= VERSION_CODES.P) {
      // Collect all surfaces we want to render to.
      List<OutputConfiguration> configs = new ArrayList<>();
      configs.add(new OutputConfiguration(flutterSurface));
      for (Surface surface : remainingSurfaces) {
        configs.add(new OutputConfiguration(surface));
      }
      createCaptureSessionWithSessionConfig(configs, callback);
    } else {
      // Collect all surfaces we want to render to.
      List<Surface> surfaceList = new ArrayList<>();
      surfaceList.add(flutterSurface);
      surfaceList.addAll(remainingSurfaces);
      createCaptureSession(surfaceList, callback);
    }
  }

  @TargetApi(VERSION_CODES.P)
  private void createCaptureSessionWithSessionConfig(
      List<OutputConfiguration> outputConfigs, CameraCaptureSession.StateCallback callback)
      throws CameraAccessException {
    cameraDevice.createCaptureSession(
        new SessionConfiguration(
            SessionConfiguration.SESSION_REGULAR,
            outputConfigs,
            Executors.newSingleThreadExecutor(),
            callback));
  }

  @TargetApi(VERSION_CODES.LOLLIPOP)
  @SuppressWarnings("deprecation")
  private void createCaptureSession(
      List<Surface> surfaces, CameraCaptureSession.StateCallback callback)
      throws CameraAccessException {
    cameraDevice.createCaptureSession(surfaces, callback, null);
  }

  private void refreshPreviewCaptureSession(
      @Nullable Runnable onSuccessCallback, @NonNull ErrorCallback onErrorCallback) {
    if (cameraCaptureSession == null) {
      return;
    }

    try {
      cameraCaptureSession.setRepeatingRequest(
          captureRequestBuilder.build(),
          pictureCaptureCallback,
          new Handler(Looper.getMainLooper()));

      if (onSuccessCallback != null) {
        onSuccessCallback.run();
      }
    } catch (CameraAccessException | IllegalStateException | IllegalArgumentException e) {
      onErrorCallback.onError("cameraAccess", e.getMessage());
    }
  }

  private void writeToFile(ByteBuffer buffer, File file) throws IOException {
    try (FileOutputStream outputStream = new FileOutputStream(file)) {
      while (0 < buffer.remaining()) {
        outputStream.getChannel().write(buffer);
      }
    }
  }

  public void takePicture(@NonNull final Result result) {
    // Only take 1 picture at a time
    if (pictureCaptureRequest != null && !pictureCaptureRequest.isFinished()) {
      result.error("captureAlreadyActive", "Picture is currently already being captured", null);
      return;
    }
    // Store the result
    this.pictureCaptureRequest = new PictureCaptureRequest(result);

    // Create temporary file
    final File outputDir = applicationContext.getCacheDir();
    final File file;
    try {
      file = File.createTempFile("CAP", ".jpg", outputDir);
    } catch (IOException | SecurityException e) {
      pictureCaptureRequest.error("cannotCreateFile", e.getMessage(), null);
      return;
    }

    // Listen for picture being taken
    pictureImageReader.setOnImageAvailableListener(
        reader -> {
          try (Image image = reader.acquireLatestImage()) {
            ByteBuffer buffer = image.getPlanes()[0].getBuffer();
            writeToFile(buffer, file);
            pictureCaptureRequest.finish(file.getAbsolutePath());
          } catch (IOException e) {
            pictureCaptureRequest.error("IOError", "Failed saving image", null);
          }
        },
        null);

    if (useAutoFocus) {
      runPictureAutoFocus();
    } else {
      runPicturePreCapture();
    }
  }

  private final CameraCaptureSession.CaptureCallback pictureCaptureCallback =
      new CameraCaptureSession.CaptureCallback() {
        @Override
        public void onCaptureCompleted(
            @NonNull CameraCaptureSession session,
            @NonNull CaptureRequest request,
            @NonNull TotalCaptureResult result) {
          processCapture(result);
        }

        @Override
        public void onCaptureProgressed(
            @NonNull CameraCaptureSession session,
            @NonNull CaptureRequest request,
            @NonNull CaptureResult partialResult) {
          processCapture(partialResult);
        }

        @Override
        public void onCaptureFailed(
            @NonNull CameraCaptureSession session,
            @NonNull CaptureRequest request,
            @NonNull CaptureFailure failure) {
          if (pictureCaptureRequest == null || pictureCaptureRequest.isFinished()) {
            return;
          }
          String reason;
          boolean fatalFailure = false;
          switch (failure.getReason()) {
            case CaptureFailure.REASON_ERROR:
              reason = "An error happened in the framework";
              break;
            case CaptureFailure.REASON_FLUSHED:
              reason = "The capture has failed due to an abortCaptures() call";
              fatalFailure = true;
              break;
            default:
              reason = "Unknown reason";
          }
          Log.w("Camera", "pictureCaptureCallback.onCaptureFailed(): " + reason);
          if (fatalFailure) pictureCaptureRequest.error("captureFailure", reason, null);
        }

        private void processCapture(CaptureResult result) {
          if (pictureCaptureRequest == null) {
            return;
          }

          Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
          Integer afState = result.get(CaptureResult.CONTROL_AF_STATE);
          switch (pictureCaptureRequest.getState()) {
            case focusing:
              if (afState == null) {
                return;
              } else if (afState == CaptureResult.CONTROL_AF_STATE_FOCUSED_LOCKED
                  || afState == CaptureResult.CONTROL_AF_STATE_NOT_FOCUSED_LOCKED) {
                // Some devices might return null here, in which case we will also continue.
                if (aeState == null || aeState == CaptureResult.CONTROL_AE_STATE_CONVERGED) {
                  runPictureCapture();
                } else {
                  runPicturePreCapture();
                }
              }
              break;
            case preCapture:
              // Some devices might return null here, in which case we will also continue.
              if (aeState == null
                  || aeState == CaptureRequest.CONTROL_AE_STATE_PRECAPTURE
                  || aeState == CaptureRequest.CONTROL_AE_STATE_FLASH_REQUIRED
                  || aeState == CaptureRequest.CONTROL_AE_STATE_CONVERGED) {
                pictureCaptureRequest.setState(State.waitingPreCaptureReady);
              }
              break;
            case waitingPreCaptureReady:
              if (aeState == null || aeState != CaptureRequest.CONTROL_AE_STATE_PRECAPTURE) {
                runPictureCapture();
              }
          }
        }
      };

  private void runPictureAutoFocus() {
    assert (pictureCaptureRequest != null);

    pictureCaptureRequest.setState(PictureCaptureRequest.State.focusing);
    lockAutoFocus(pictureCaptureCallback);
  }

  private void runPicturePreCapture() {
    assert (pictureCaptureRequest != null);
    pictureCaptureRequest.setState(PictureCaptureRequest.State.preCapture);

    captureRequestBuilder.set(
        CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER,
        CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_START);

    refreshPreviewCaptureSession(
        () ->
            captureRequestBuilder.set(
                CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER,
                CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_IDLE),
        (code, message) -> pictureCaptureRequest.error(code, message, null));
  }

  private void runPictureCapture() {
    assert (pictureCaptureRequest != null);
    pictureCaptureRequest.setState(PictureCaptureRequest.State.capturing);
    try {
      final CaptureRequest.Builder captureBuilder =
          cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
      captureBuilder.addTarget(pictureImageReader.getSurface());
      captureBuilder.set(
          CaptureRequest.SCALER_CROP_REGION,
          captureRequestBuilder.get(CaptureRequest.SCALER_CROP_REGION));
      captureBuilder.set(
          CaptureRequest.JPEG_ORIENTATION,
          lockedCaptureOrientation == null
              ? deviceOrientationListener.getMediaOrientation()
              : deviceOrientationListener.getMediaOrientation(lockedCaptureOrientation));

      switch (flashMode) {
        case off:
          captureBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON);
          captureBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
          break;
        case auto:
          captureBuilder.set(
              CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
          break;
        case always:
        default:
          captureBuilder.set(
              CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_ALWAYS_FLASH);
          break;
      }
      cameraCaptureSession.stopRepeating();
      cameraCaptureSession.capture(
          captureBuilder.build(),
          new CameraCaptureSession.CaptureCallback() {
            @Override
            public void onCaptureCompleted(
                @NonNull CameraCaptureSession session,
                @NonNull CaptureRequest request,
                @NonNull TotalCaptureResult result) {
              unlockAutoFocus();
            }
          },
          null);
    } catch (CameraAccessException e) {
      pictureCaptureRequest.error("cameraAccess", e.getMessage(), null);
    }
  }

  private void lockAutoFocus(CaptureCallback callback) {
    captureRequestBuilder.set(
        CaptureRequest.CONTROL_AF_TRIGGER, CaptureRequest.CONTROL_AF_TRIGGER_START);

    refreshPreviewCaptureSession(
        null, (code, message) -> pictureCaptureRequest.error(code, message, null));
  }

  private void unlockAutoFocus() {
    captureRequestBuilder.set(
        CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_CANCEL);
    updateFocus(focusMode);
    try {
      cameraCaptureSession.capture(captureRequestBuilder.build(), null, null);
    } catch (CameraAccessException ignored) {
    }
    captureRequestBuilder.set(
        CaptureRequest.CONTROL_AF_TRIGGER, CaptureRequest.CONTROL_AF_TRIGGER_IDLE);

    refreshPreviewCaptureSession(
        null,
        (errorCode, errorMessage) -> pictureCaptureRequest.error(errorCode, errorMessage, null));
  }

  public void startVideoRecording(Result result) {
    final File outputDir = applicationContext.getCacheDir();
    try {
      videoRecordingFile = File.createTempFile("REC", ".mp4", outputDir);
    } catch (IOException | SecurityException e) {
      result.error("cannotCreateFile", e.getMessage(), null);
      return;
    }

    try {
      prepareMediaRecorder(videoRecordingFile.getAbsolutePath());
      recordingVideo = true;
      createCaptureSession(
          CameraDevice.TEMPLATE_RECORD, () -> mediaRecorder.start(), mediaRecorder.getSurface());
      result.success(null);
    } catch (CameraAccessException | IOException e) {
      recordingVideo = false;
      videoRecordingFile = null;
      result.error("videoRecordingFailed", e.getMessage(), null);
    }
  }

  public void stopVideoRecording(@NonNull final Result result) {
    if (!recordingVideo) {
      result.success(null);
      return;
    }

    try {
      recordingVideo = false;

      try {
        cameraCaptureSession.abortCaptures();
        mediaRecorder.stop();
      } catch (CameraAccessException | IllegalStateException e) {
        // Ignore exceptions and try to continue (changes are camera session already aborted capture)
      }

      mediaRecorder.reset();
      startPreview();
      result.success(videoRecordingFile.getAbsolutePath());
      videoRecordingFile = null;
    } catch (CameraAccessException | IllegalStateException e) {
      result.error("videoRecordingFailed", e.getMessage(), null);
    }
  }

  public void pauseVideoRecording(@NonNull final Result result) {
    if (!recordingVideo) {
      result.success(null);
      return;
    }

    try {
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        mediaRecorder.pause();
      } else {
        result.error("videoRecordingFailed", "pauseVideoRecording requires Android API +24.", null);
        return;
      }
    } catch (IllegalStateException e) {
      result.error("videoRecordingFailed", e.getMessage(), null);
      return;
    }

    result.success(null);
  }

  public void resumeVideoRecording(@NonNull final Result result) {
    if (!recordingVideo) {
      result.success(null);
      return;
    }

    try {
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        mediaRecorder.resume();
      } else {
        result.error(
            "videoRecordingFailed", "resumeVideoRecording requires Android API +24.", null);
        return;
      }
    } catch (IllegalStateException e) {
      result.error("videoRecordingFailed", e.getMessage(), null);
      return;
    }

    result.success(null);
  }

  public void setFlashMode(@NonNull final Result result, FlashMode mode)
      throws CameraAccessException {
    // Get the flash availability
    Boolean flashAvailable =
        cameraManager
            .getCameraCharacteristics(cameraDevice.getId())
            .get(CameraCharacteristics.FLASH_INFO_AVAILABLE);

    // Check if flash is available.
    if (flashAvailable == null || !flashAvailable) {
      result.error("setFlashModeFailed", "Device does not have flash capabilities", null);
      return;
    }

    // If switching directly from torch to auto or on, make sure we turn off the torch.
    if (flashMode == FlashMode.torch && mode != FlashMode.torch && mode != FlashMode.off) {
      updateFlash(FlashMode.off);

      this.cameraCaptureSession.setRepeatingRequest(
          captureRequestBuilder.build(),
          new CaptureCallback() {
            private boolean isFinished = false;

            @Override
            public void onCaptureCompleted(
                @NonNull CameraCaptureSession session,
                @NonNull CaptureRequest request,
                @NonNull TotalCaptureResult captureResult) {
              if (isFinished) {
                return;
              }

              updateFlash(mode);
              refreshPreviewCaptureSession(
                  () -> {
                    result.success(null);
                    isFinished = true;
                  },
                  (code, message) ->
                      result.error("setFlashModeFailed", "Could not set flash mode.", null));
            }

            @Override
            public void onCaptureFailed(
                @NonNull CameraCaptureSession session,
                @NonNull CaptureRequest request,
                @NonNull CaptureFailure failure) {
              if (isFinished) {
                return;
              }

              result.error("setFlashModeFailed", "Could not set flash mode.", null);
              isFinished = true;
            }
          },
          null);
    } else {
      updateFlash(mode);

      refreshPreviewCaptureSession(
          () -> result.success(null),
          (code, message) -> result.error("setFlashModeFailed", "Could not set flash mode.", null));
    }
  }

  public void setExposureMode(@NonNull final Result result, ExposureMode mode)
      throws CameraAccessException {
    updateExposure(mode);
    cameraCaptureSession.setRepeatingRequest(captureRequestBuilder.build(), null, null);
    result.success(null);
  }

  public void setExposurePoint(@NonNull final Result result, Double x, Double y)
      throws CameraAccessException {
    // Check if exposure point functionality is available.
    if (!isExposurePointSupported()) {
      result.error(
          "setExposurePointFailed", "Device does not have exposure point capabilities", null);
      return;
    }
    // Check if the current region boundaries are known
    if (cameraRegions.getMaxBoundaries() == null) {
      result.error("setExposurePointFailed", "Could not determine max region boundaries", null);
      return;
    }
    // Set the metering rectangle
    if (x == null || y == null) cameraRegions.resetAutoExposureMeteringRectangle();
    else cameraRegions.setAutoExposureMeteringRectangleFromPoint(x, y);
    // Apply it
    updateExposure(exposureMode);
    refreshPreviewCaptureSession(
        () -> result.success(null), (code, message) -> result.error("CameraAccess", message, null));
  }

  public void setFocusMode(@NonNull final Result result, FocusMode mode)
      throws CameraAccessException {
    this.focusMode = mode;

    updateFocus(mode);

    switch (mode) {
      case auto:
        refreshPreviewCaptureSession(
            null, (code, message) -> result.error("setFocusMode", message, null));
        break;
      case locked:
        lockAutoFocus(
            new CaptureCallback() {
              @Override
              public void onCaptureCompleted(
                  @NonNull CameraCaptureSession session,
                  @NonNull CaptureRequest request,
                  @NonNull TotalCaptureResult result) {
                unlockAutoFocus();
              }
            });
        break;
    }
    result.success(null);
  }

  public void setFocusPoint(@NonNull final Result result, Double x, Double y)
      throws CameraAccessException {
    // Check if focus point functionality is available.
    if (!isFocusPointSupported()) {
      result.error("setFocusPointFailed", "Device does not have focus point capabilities", null);
      return;
    }

    // Check if the current region boundaries are known
    if (cameraRegions.getMaxBoundaries() == null) {
      result.error("setFocusPointFailed", "Could not determine max region boundaries", null);
      return;
    }

    // Set the metering rectangle
    if (x == null || y == null) {
      cameraRegions.resetAutoFocusMeteringRectangle();
    } else {
      cameraRegions.setAutoFocusMeteringRectangleFromPoint(x, y);
    }

    // Apply the new metering rectangle
    setFocusMode(result, focusMode);
  }

  @TargetApi(VERSION_CODES.P)
  private boolean supportsDistortionCorrection() throws CameraAccessException {
    int[] availableDistortionCorrectionModes =
        cameraManager
            .getCameraCharacteristics(cameraDevice.getId())
            .get(CameraCharacteristics.DISTORTION_CORRECTION_AVAILABLE_MODES);
    if (availableDistortionCorrectionModes == null) availableDistortionCorrectionModes = new int[0];
    long nonOffModesSupported =
        Arrays.stream(availableDistortionCorrectionModes)
            .filter((value) -> value != CaptureRequest.DISTORTION_CORRECTION_MODE_OFF)
            .count();
    return nonOffModesSupported > 0;
  }

  private Size getRegionBoundaries() throws CameraAccessException {
    // No distortion correction support
    if (android.os.Build.VERSION.SDK_INT < VERSION_CODES.P || !supportsDistortionCorrection()) {
      return cameraManager
          .getCameraCharacteristics(cameraDevice.getId())
          .get(CameraCharacteristics.SENSOR_INFO_PIXEL_ARRAY_SIZE);
    }
    // Get the current distortion correction mode
    Integer distortionCorrectionMode =
        captureRequestBuilder.get(CaptureRequest.DISTORTION_CORRECTION_MODE);
    // Return the correct boundaries depending on the mode
    android.graphics.Rect rect;
    if (distortionCorrectionMode == null
        || distortionCorrectionMode == CaptureRequest.DISTORTION_CORRECTION_MODE_OFF) {
      rect =
          cameraManager
              .getCameraCharacteristics(cameraDevice.getId())
              .get(CameraCharacteristics.SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE);
    } else {
      rect =
          cameraManager
              .getCameraCharacteristics(cameraDevice.getId())
              .get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE);
    }
    return rect == null ? null : new Size(rect.width(), rect.height());
  }

  private boolean isExposurePointSupported() throws CameraAccessException {
    Integer supportedRegions =
        cameraManager
            .getCameraCharacteristics(cameraDevice.getId())
            .get(CameraCharacteristics.CONTROL_MAX_REGIONS_AE);
    return supportedRegions != null && supportedRegions > 0;
  }

  private boolean isFocusPointSupported() throws CameraAccessException {
    Integer supportedRegions =
        cameraManager
            .getCameraCharacteristics(cameraDevice.getId())
            .get(CameraCharacteristics.CONTROL_MAX_REGIONS_AF);
    return supportedRegions != null && supportedRegions > 0;
  }

  public double getMinExposureOffset() throws CameraAccessException {
    Range<Integer> range =
        cameraManager
            .getCameraCharacteristics(cameraDevice.getId())
            .get(CameraCharacteristics.CONTROL_AE_COMPENSATION_RANGE);
    double minStepped = range == null ? 0 : range.getLower();
    double stepSize = getExposureOffsetStepSize();
    return minStepped * stepSize;
  }

  public double getMaxExposureOffset() throws CameraAccessException {
    Range<Integer> range =
        cameraManager
            .getCameraCharacteristics(cameraDevice.getId())
            .get(CameraCharacteristics.CONTROL_AE_COMPENSATION_RANGE);
    double maxStepped = range == null ? 0 : range.getUpper();
    double stepSize = getExposureOffsetStepSize();
    return maxStepped * stepSize;
  }

  public double getExposureOffsetStepSize() throws CameraAccessException {
    Rational stepSize =
        cameraManager
            .getCameraCharacteristics(cameraDevice.getId())
            .get(CameraCharacteristics.CONTROL_AE_COMPENSATION_STEP);
    return stepSize == null ? 0.0 : stepSize.doubleValue();
  }

  public void setExposureOffset(@NonNull final Result result, double offset)
      throws CameraAccessException {
    // Set the exposure offset
    double stepSize = getExposureOffsetStepSize();
    exposureOffset = (int) (offset / stepSize);
    // Apply it
    updateExposure(exposureMode);
    this.cameraCaptureSession.setRepeatingRequest(captureRequestBuilder.build(), null, null);
    result.success(offset);
  }

  public float getMaxZoomLevel() {
    return cameraZoom.maxZoom;
  }

  public float getMinZoomLevel() {
    return CameraZoom.DEFAULT_ZOOM_FACTOR;
  }

  public void setZoomLevel(@NonNull final Result result, float zoom) throws CameraAccessException {
    float maxZoom = cameraZoom.maxZoom;
    float minZoom = CameraZoom.DEFAULT_ZOOM_FACTOR;

    if (zoom > maxZoom || zoom < minZoom) {
      String errorMessage =
          String.format(
              Locale.ENGLISH,
              "Zoom level out of bounds (zoom level should be between %f and %f).",
              minZoom,
              maxZoom);
      result.error("ZOOM_ERROR", errorMessage, null);
      return;
    }

    //Zoom area is calculated relative to sensor area (activeRect)
    if (captureRequestBuilder != null) {
      final Rect computedZoom = cameraZoom.computeZoom(zoom);
      captureRequestBuilder.set(CaptureRequest.SCALER_CROP_REGION, computedZoom);
      cameraCaptureSession.setRepeatingRequest(captureRequestBuilder.build(), null, null);
    }

    result.success(null);
  }

  public void lockCaptureOrientation(PlatformChannel.DeviceOrientation orientation) {
    this.lockedCaptureOrientation = orientation;
  }

  public void unlockCaptureOrientation() {
    this.lockedCaptureOrientation = null;
  }

  private void updateFpsRange() {
    if (fpsRange == null) {
      return;
    }

    captureRequestBuilder.set(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE, fpsRange);
  }

  private void updateFocus(FocusMode mode) {
    if (useAutoFocus) {
      int[] modes = cameraCharacteristics.get(CameraCharacteristics.CONTROL_AF_AVAILABLE_MODES);
      // Auto focus is not supported
      if (modes == null
          || modes.length == 0
          || (modes.length == 1 && modes[0] == CameraCharacteristics.CONTROL_AF_MODE_OFF)) {
        useAutoFocus = false;
        captureRequestBuilder.set(
            CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_OFF);
      } else {
        // Applying auto focus
        switch (mode) {
          case locked:
            captureRequestBuilder.set(
                CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_AUTO);
            break;
          case auto:
            captureRequestBuilder.set(
                CaptureRequest.CONTROL_AF_MODE,
                recordingVideo
                    ? CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_VIDEO
                    : CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
          default:
            break;
        }
        MeteringRectangle afRect = cameraRegions.getAFMeteringRectangle();
        captureRequestBuilder.set(
            CaptureRequest.CONTROL_AF_REGIONS,
            afRect == null ? null : new MeteringRectangle[] {afRect});
      }
    } else {
      captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_OFF);
    }
  }

  private void updateExposure(ExposureMode mode) {
    exposureMode = mode;

    // Applying auto exposure
    MeteringRectangle aeRect = cameraRegions.getAEMeteringRectangle();
    captureRequestBuilder.set(
        CaptureRequest.CONTROL_AE_REGIONS,
        aeRect == null ? null : new MeteringRectangle[] {cameraRegions.getAEMeteringRectangle()});

    switch (mode) {
      case locked:
        captureRequestBuilder.set(CaptureRequest.CONTROL_AE_LOCK, true);
        break;
      case auto:
      default:
        captureRequestBuilder.set(CaptureRequest.CONTROL_AE_LOCK, false);
        break;
    }

    captureRequestBuilder.set(CaptureRequest.CONTROL_AE_EXPOSURE_COMPENSATION, exposureOffset);
  }

  private void updateFlash(FlashMode mode) {
    // Get flash
    flashMode = mode;

    // Applying flash modes
    switch (flashMode) {
      case off:
        captureRequestBuilder.set(
            CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON);
        captureRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
        break;
      case auto:
        captureRequestBuilder.set(
            CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
        captureRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
        break;
      case always:
        captureRequestBuilder.set(
            CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_ALWAYS_FLASH);
        captureRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
        break;
      case torch:
      default:
        captureRequestBuilder.set(
            CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON);
        captureRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH);
        break;
    }
  }

  public void startPreview() throws CameraAccessException {
    if (pictureImageReader == null || pictureImageReader.getSurface() == null) return;

    createCaptureSession(CameraDevice.TEMPLATE_PREVIEW, pictureImageReader.getSurface());
  }

  public void startPreviewWithImageStream(EventChannel imageStreamChannel)
      throws CameraAccessException {
    createCaptureSession(CameraDevice.TEMPLATE_RECORD, imageStreamReader.getSurface());

    imageStreamChannel.setStreamHandler(
        new EventChannel.StreamHandler() {
          @Override
          public void onListen(Object o, EventChannel.EventSink imageStreamSink) {
            setImageStreamImageAvailableListener(imageStreamSink);
          }

          @Override
          public void onCancel(Object o) {
            imageStreamReader.setOnImageAvailableListener(null, null);
          }
        });
  }

  private void setImageStreamImageAvailableListener(final EventChannel.EventSink imageStreamSink) {
    imageStreamReader.setOnImageAvailableListener(
        reader -> {
          Image img = reader.acquireLatestImage();
          if (img == null) return;

          List<Map<String, Object>> planes = new ArrayList<>();
          for (Image.Plane plane : img.getPlanes()) {
            ByteBuffer buffer = plane.getBuffer();

            byte[] bytes = new byte[buffer.remaining()];
            buffer.get(bytes, 0, bytes.length);

            Map<String, Object> planeBuffer = new HashMap<>();
            planeBuffer.put("bytesPerRow", plane.getRowStride());
            planeBuffer.put("bytesPerPixel", plane.getPixelStride());
            planeBuffer.put("bytes", bytes);

            planes.add(planeBuffer);
          }

          Map<String, Object> imageBuffer = new HashMap<>();
          imageBuffer.put("width", img.getWidth());
          imageBuffer.put("height", img.getHeight());
          imageBuffer.put("format", img.getFormat());
          imageBuffer.put("planes", planes);

          imageStreamSink.success(imageBuffer);
          img.close();
        },
        null);
  }

  public void stopImageStream() throws CameraAccessException {
    if (imageStreamReader != null) {
      imageStreamReader.setOnImageAvailableListener(null, null);
    }
    startPreview();
  }

  private void closeCaptureSession() {
    if (cameraCaptureSession != null) {
      cameraCaptureSession.close();
      cameraCaptureSession = null;
    }
  }

  public void close() {
    closeCaptureSession();

    if (cameraDevice != null) {
      cameraDevice.close();
      cameraDevice = null;
    }
    if (pictureImageReader != null) {
      pictureImageReader.close();
      pictureImageReader = null;
    }
    if (imageStreamReader != null) {
      imageStreamReader.close();
      imageStreamReader = null;
    }
    if (mediaRecorder != null) {
      mediaRecorder.reset();
      mediaRecorder.release();
      mediaRecorder = null;
    }
  }

  public void dispose() {
    close();
    flutterTexture.release();
    deviceOrientationListener.stop();
  }
}


text:
<?php

namespace danaketh\CIBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

/**
 * Class danakethCIExtension
 *
 * @package danaketh\CIBundle\DependencyInjection
 */
class danakethCIExtension extends Extension
{
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');

        $container->setParameter('danaketh_ci.services', $config['services']);
        $container->setParameter('danaketh_ci.plugins', $config['plugins']);
        $container->setParameter('danaketh_ci.env', $config['env']);
    }
}


text:
file(REMOVE_RECURSE
  "CMakeFiles/myRRT.dir/myRRT.cpp.o"
  "libmyRRT.pdb"
  "libmyRRT.so"
  "libmyRRT.pdb"
  "CMakeFiles/CMakeRelink.dir/libmyRRT.so"
)

# Per-language clean rules from dependency scanning.
foreach(lang CXX)
  include(CMakeFiles/myRRT.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()


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

namespace WebProjectArchitecture
{
    public class Logger : ILogger
    {
        public Logger()
        {

        }
        public void Error(string message)
        {
            Console.WriteLine(message);
        }
    }
}


text:
using System;

namespace Tfs.TransitionSpecs
{
    public abstract class Expression : IEquatable<Expression>
    {
        public abstract bool Equals(Expression other);

        public override bool Equals(object obj)
        {
            var expr = obj as Expression;

            return expr != null && this.Equals(expr);
        }

        public abstract object Evalute(EvaluationContext context);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#660000</color>
    <color name="colorPrimaryDark">#4d660000</color>
    <color name="colorAccent">#4CAF50</color>
    <color name="lightPrimary">#FFCdd2</color>
    <color name="textColor">#FFFFFF</color>
    <color name="primaryText">#212121</color>
    <color name="secondaryText">#727272</color>
    <color name="dividerColor">#B6B6B6</color>
    <color name="gray">#d3d3d3</color>
    <color name="gray_50_opacity">#4D8a8a8a</color>
    <color name="transparent">#00FFFFFF</color>
</resources>


text:
package com.deobfuscation.visitors;

import org.apache.commons.lang3.StringUtils;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.TypeDeclaration;

public class PublicClassNameVisitor extends ASTVisitor {
	private String className;

	@Override
	public void endVisit(TypeDeclaration node) {
		if(StringUtils.isEmpty(className)){
			className = node.getName().getIdentifier();
		}

		if(Modifier.isPublic(node.getModifiers())){
			className = node.getName().getIdentifier();
		}
		super.endVisit(node);
	}

	public String getClassName() {
		return className + ".java";
	}

}


text:
var express = require('express');
var router = express.Router();
var app = module.parent.exports;
var passport = app.get('passport');

router.get('/twitter', passport.authenticate('twitter'));

router.get('/twitter/callback', passport.authenticate('twitter', {
    successRedirect: '/',
    failureRedirect: '/login?false=1'
}));

module.exports = router;


text:
project_euler
=============

My solutions to the great problems


text:
package com.bt.pi.app.volumemanager;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import com.bt.pi.app.common.entities.Volume;
import com.bt.pi.app.common.entities.VolumeState;
import com.bt.pi.app.common.resource.PiQueue;
import com.bt.pi.app.volumemanager.handlers.DetachVolumeHandler;
import com.bt.pi.core.application.MessageContextFactory;
import com.bt.pi.core.application.watcher.task.TaskProcessingQueueContinuation;
import com.bt.pi.core.continuation.UpdateResolvingPiContinuation;
import com.bt.pi.core.dht.DhtWriter;
import com.bt.pi.core.id.PId;

@Component
public class DetachVolumeTaskProcessingQueueContinuation extends AbstractVolumeTaskProcessingQueueContinuation implements TaskProcessingQueueContinuation {
    private static final String UNABLE_TO_GET_VOLUME_S = "Unable to get Volume: %s";
    private static final Log LOG = LogFactory.getLog(DetachVolumeTaskProcessingQueueContinuation.class);
    @Resource
    private DetachVolumeHandler detachHandler;
    @Resource(type = VolumeManagerApplication.class)
    private MessageContextFactory messageContextFactory;

    public DetachVolumeTaskProcessingQueueContinuation() {
        this.detachHandler = null;
        this.messageContextFactory = null;
    }

    @Override
    public void receiveResult(final String url, final String nodeId) {
        LOG.debug(String.format("receiveResult(%s, %s)", url, nodeId));
        PId id = getPiIdbuilder().getPIdForEc2AvailabilityZone(url);
        DhtWriter writer = getDhtClientFactory().createWriter();
        final List<VolumeState> volumeStateCache = new ArrayList<VolumeState>();

        writer.update(id, new UpdateResolvingPiContinuation<Volume>() {
            @Override
            public Volume update(Volume existingEntity, Volume requestedEntity) {
                if (null == existingEntity) {
                    LOG.warn(String.format(UNABLE_TO_GET_VOLUME_S, url));
                    return null;
                }

                if (VolumeState.AVAILABLE.equals(existingEntity.getStatus())) {
                    LOG.warn(String.format("volume status is %s, so assuming already detached", existingEntity.getStatus()));
                    PId detachVolumeQueueId = getPiIdbuilder().getPiQueuePId(PiQueue.DETACH_VOLUME).forLocalScope(PiQueue.DETACH_VOLUME.getNodeScope());
                    getTaskProcessingQueueHelper().removeUrlFromQueue(detachVolumeQueueId, url);
                    return null;
                }

                volumeStateCache.clear();
                volumeStateCache.add(existingEntity.getStatus());

                LOG.info(String.format("setting volume %s state to %s to allow re-processing", existingEntity.getUrl(), VolumeState.IN_USE));
                existingEntity.setStatus(VolumeState.IN_USE);
                return existingEntity;
            }

            @Override
            public void handleResult(Volume result) {
                if (null == result) {
                    LOG.warn(String.format(UNABLE_TO_GET_VOLUME_S, url));
                    return;
                }
                if (!VolumeState.AVAILABLE.equals(result.getStatus()) && null != result.getInstanceId()) {
                    result.setStatus(volumeStateCache.get(0));
                    detachHandler.detachVolume(result, messageContextFactory.newMessageContext(), nodeId);
                } else {
                    LOG.debug("Not detaching volume as VolumeState is " + result.getStatus());
                }
            }
        });
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<lldp label="LLDP neighbors">
    <interface label="Interface" name="eno1" via="LLDP" rid="2" age="0 day, 00:00:02">
        <chassis label="Chassis">
            <id label="ChassisID" type="mac">58:f3:9c:4b:b9:9e</id>
            <name label="SysName">My-Terrible-Name</name>
            <descr label="SysDescr">Cisco Nexus Operating System (NX-OS) Software 6.0(2)U4(1)
                TAC support: http://www.cisco.com/tac
                Copyright (c) 2002-2020, Cisco Systems, Inc. All rights reserved.</descr>
            <capability label="Capability" type="Bridge" enabled="on"/>
            <capability label="Capability" type="Router" enabled="on"/>
        </chassis>
        <port label="Port">
            <id label="PortID" type="ifname">Ethernet1/23</id>
            <descr label="PortDescr">Description</descr>
        </port>
        <vlan label="VLAN" vlan-id="500" pvid="yes"/>
    </interface>
    <interface label="Interface" name="eno2" via="LLDP" rid="1" age="0 day, 00:00:08">
        <chassis label="Chassis">
            <id label="ChassisID" type="mac">1c:6a:7a:4c:e3:1e</id>
            <name label="SysName">My-Terrible-Name</name>
            <descr label="SysDescr">Cisco Nexus Operating System (NX-OS) Software 6.0(2)U4(1)
                TAC support: http://www.cisco.com/tac
                Copyright (c) 2002-2020, Cisco Systems, Inc. All rights reserved.</descr>
            <capability label="Capability" type="Bridge" enabled="on"/>
            <capability label="Capability" type="Router" enabled="on"/>
        </chassis>
        <port label="Port">
            <id label="PortID" type="ifname">Ethernet1/23</id>
            <descr label="PortDescr">Description</descr>
        </port>
        <vlan label="VLAN" vlan-id="500" pvid="yes"/>
    </interface>
</lldp>