file_name
stringlengths 3
137
| prefix
stringlengths 0
918k
| suffix
stringlengths 0
962k
| middle
stringlengths 0
812k
|
---|---|---|---|
0008_ci_text.py | # Generated by Django 4.0 on 2022-01-10 15:42
from django.contrib.postgres.operations import CITextExtension
from django.db import migrations
class Migration(migrations.Migration):
| dependencies = [
("core", "0007_ltree"),
]
operations = [CITextExtension()] |
|
rename.go | package keys
import (
"bufio"
"fmt"
"github.com/spf13/cobra"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/input"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
)
// RenameKeyCommand renames a key from the key store.
func RenameKeyCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "rename <old_name> <new_name>",
Short: "Rename an existing key",
Long: `Rename a key from the Keybase backend.
Note that renaming offline or ledger keys will rename
only the public key references stored locally, i.e.
private keys stored in a ledger device cannot be renamed with the CLI.
`,
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
buf := bufio.NewReader(cmd.InOrStdin())
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
oldName, newName := args[0], args[1]
k, err := clientCtx.Keyring.Key(oldName)
if err != nil {
return err
}
// confirm rename, unless -y is passed
if skip, _ := cmd.Flags().GetBool(flagYes); !skip {
prompt := fmt.Sprintf("Key reference will be renamed from %s to %s. Continue?", args[0], args[1])
if yes, err := input.GetConfirmation(prompt, buf, cmd.ErrOrStderr()); err != nil {
return err
} else if !yes {
return nil
}
}
if err := clientCtx.Keyring.Rename(oldName, newName); err != nil {
return err
}
if k.GetType() == keyring.TypeLedger || k.GetType() == keyring.TypeOffline |
cmd.PrintErrln(fmt.Sprintf("Key was successfully renamed from %s to %s", oldName, newName))
return nil
},
}
cmd.Flags().BoolP(flagYes, "y", false, "Skip confirmation prompt when renaming offline or ledger key references")
return cmd
}
| {
cmd.PrintErrln("Public key reference renamed")
return nil
} |
midleware_test.go | package handler
import (
"errors"
"fmt"
"github.com/gin-gonic/gin"
"github.com/golang/mock/gomock"
"github.com/oneils/todo-app/pkg/service"
mock_service "github.com/oneils/todo-app/pkg/service/mocks"
"github.com/stretchr/testify/assert"
"net/http/httptest"
"testing" |
func TestHandler_userIdentity(t *testing.T) {
type mockBehavior func(s *mock_service.MockAuthorization, token string)
testTable := []struct {
name string
headerName string
headerValue string
token string
mockBehavior mockBehavior
expectedStatusCode int
expectedResponseBody string
}{
{
name: "Ok",
headerName: "Authorization",
headerValue: "Bearer token",
token: "token",
mockBehavior: func(s *mock_service.MockAuthorization, token string) {
s.EXPECT().ParseToken(token).Return(1, nil)
},
expectedStatusCode: 200,
expectedResponseBody: "1",
},
{
name: "Missed token",
headerName: "",
token: "token",
mockBehavior: func(s *mock_service.MockAuthorization, token string) {},
expectedStatusCode: 401,
expectedResponseBody: `{"message":"empty auth header"}`,
},
{
name: "Invalid Bearer",
headerName: "Authorization",
headerValue: "Beerer token",
token: "token",
mockBehavior: func(s *mock_service.MockAuthorization, token string) {},
expectedStatusCode: 401,
expectedResponseBody: `{"message":"invalid auth header"}`,
},
{
name: "No token after bearer",
headerName: "Authorization",
headerValue: "Bearer ",
token: "token",
mockBehavior: func(s *mock_service.MockAuthorization, token string) {},
expectedStatusCode: 401,
expectedResponseBody: `{"message":"token is empty"}`,
},
{
name: "Service error",
headerName: "Authorization",
headerValue: "Bearer token",
token: "token",
mockBehavior: func(s *mock_service.MockAuthorization, token string) {
s.EXPECT().ParseToken(token).Return(1, errors.New("some error"))
},
expectedStatusCode: 401,
expectedResponseBody: `{"message":"some error"}`,
},
}
for _, testCase := range testTable {
t.Run(testCase.name, func(t *testing.T) {
c := gomock.NewController(t)
defer c.Finish()
auth := mock_service.NewMockAuthorization(c)
testCase.mockBehavior(auth, testCase.token)
services := &service.Service{Authorization: auth}
handler := NewHandler(services)
r := gin.New()
r.GET("/protected", handler.userIdentity, func(c *gin.Context) {
id, _ := c.Get(userCtx)
c.String(200, fmt.Sprintf("%d", id.(int)))
})
w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/protected", nil)
req.Header.Set(testCase.headerName, testCase.headerValue)
r.ServeHTTP(w, req)
assert.Equal(t, testCase.expectedStatusCode, w.Code)
assert.Equal(t, testCase.expectedResponseBody, w.Body.String())
})
}
} | ) |
keys.py | #!/usr/bin/python
#
# Copyright 2002-2021 Barcelona Supercomputing Center (www.bsc.es)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# -*- coding: utf-8 -*-
"""
PyCOMPSs runtime - MPI - Keys
============================
This file contains the MPI Collection layout keys.
"""
| """
Strings used in MPI layout for collections
"""
block_count = 'block_count'
block_length = 'block_length'
stride = 'stride' | class MPILayoutKeys(object): |
c_card_m_selectable_hover_BoxShadow.js | module.exports = {"name":"--pf-c-card--m-selectable--hover--BoxShadow","value":"0 0.1875rem 0.4375rem 0.1875rem rgba(3,3,3,0.13),0 0.6875rem 1.5rem 1rem rgba(3,3,3,0.12)","var":"var(--pf-c-card--m-selectable--hover--BoxShadow)"} |
||
speed_dial_item.js | import $ from '../../core/renderer';
import { extend } from '../../core/utils/extend';
import eventsEngine from '../../events/core/events_engine';
import { addNamespace } from '../../events/utils/index';
import { name as clickEventName } from '../../events/click';
import { getImageContainer } from '../../core/utils/icon';
import Overlay from '../overlay/ui.overlay';
import { render } from '../widget/utils.ink_ripple';
import { isMaterial } from '../themes';
const FAB_CLASS = 'dx-fa-button';
const FAB_ICON_CLASS = 'dx-fa-button-icon';
const FAB_LABEL_CLASS = 'dx-fa-button-label';
const FAB_LABEL_WRAPPER_CLASS = 'dx-fa-button-label-wrapper';
const FAB_CONTENT_REVERSE_CLASS = 'dx-fa-button-content-reverse';
const OVERLAY_CONTENT_SELECTOR = '.dx-overlay-content';
class SpeedDialItem extends Overlay {
_getDefaultOptions() {
return extend(super._getDefaultOptions(), {
shading: false,
useInkRipple: false,
callOverlayRenderShading: false,
width: 'auto',
zIndex: 1500
});
}
_defaultOptionsRules() {
return super._defaultOptionsRules().concat([
{
device() {
return isMaterial();
},
options: {
useInkRipple: true
}
}
]);
}
_render() {
this.$element().addClass(FAB_CLASS);
this._renderIcon();
this._renderLabel();
super._render(); | this._renderClick();
}
_renderLabel() {
!!this._$label && this._$label.remove();
const labelText = this.option('label');
if(!labelText) {
this._$label = null;
return;
}
const $element = $('<div>').addClass(FAB_LABEL_CLASS);
const $wrapper = $('<div>').addClass(FAB_LABEL_WRAPPER_CLASS);
this._$label = $wrapper
.prependTo(this.$content())
.append($element.text(labelText));
this.$content().toggleClass(FAB_CONTENT_REVERSE_CLASS, this._isPositionLeft(this.option('parentPosition')));
}
_isPositionLeft(position) {
const currentLocation = position ?
(position.at ?
(position.at.x ? position.at.x : position.at) :
(typeof position === 'string' ? position : '')) :
'';
return currentLocation.split(' ')[0] === 'left';
}
_renderButtonIcon($element, icon, iconClass) {
!!$element && $element.remove();
$element = $('<div>').addClass(iconClass);
const $iconElement = getImageContainer(icon);
$element
.append($iconElement)
.appendTo(this.$content());
return $element;
}
_renderIcon() {
this._$icon = this._renderButtonIcon(
this._$icon,
this._options.silent('icon'),
FAB_ICON_CLASS);
}
_renderWrapper() {
if(this._options.silent('callOverlayRenderShading')) {
super._renderWrapper();
}
}
_getVisibleActions(actions) {
const currentActions = actions || this.option('actions') || [];
return currentActions.filter((action) => action.option('visible'));
}
_getActionComponent() {
if(this._getVisibleActions().length === 1) {
return this._getVisibleActions()[0];
} else {
return this.option('actionComponent') || this.option('actions')[0];
}
}
_initContentReadyAction() {
this._contentReadyAction = this._getActionComponent()._createActionByOption('onContentReady', {
excludeValidators: ['disabled', 'readOnly']
}, true);
}
_fireContentReadyAction() {
this._contentReadyAction({ actionElement: this.$element() });
}
_updateZIndexStackPosition() {
const zIndex = this.option('zIndex');
this._$wrapper.css('zIndex', zIndex);
this._$content.css('zIndex', zIndex);
}
_fixWrapperPosition() {
const $wrapper = this._$wrapper;
const $container = this._getContainer();
$wrapper.css('position', this._isWindow($container) ? 'fixed' : 'absolute');
}
_setClickAction() {
const eventName = addNamespace(clickEventName, this.NAME);
const overlayContent = this.$element().find(OVERLAY_CONTENT_SELECTOR);
eventsEngine.off(overlayContent, eventName);
eventsEngine.on(overlayContent, eventName, (e) => {
const clickActionArgs = {
event: e,
actionElement: this.element(),
element: this._getActionComponent().$element()
};
this._clickAction(clickActionArgs);
});
}
_defaultActionArgs() {
return {
component: this._getActionComponent()
};
}
_renderClick() {
this._clickAction = this._getActionComponent()._createActionByOption('onClick');
this._setClickAction();
}
_renderInkRipple() {
this._inkRipple = render();
}
_getInkRippleContainer() {
return this._$icon;
}
_toggleActiveState($element, value, e) {
super._toggleActiveState.apply(this, arguments);
if(!this._inkRipple) {
return;
}
const config = {
element: this._getInkRippleContainer(),
event: e
};
if(value) {
this._inkRipple.showWave(config);
} else {
this._inkRipple.hideWave(config);
}
}
_optionChanged(args) {
switch(args.name) {
case 'icon':
this._renderIcon();
break;
case 'onClick':
this._renderClick();
break;
case 'label':
this._renderLabel();
break;
case 'visible':
this._currentVisible = args.previousValue;
args.value ?
this._show() :
this._hide();
break;
case 'useInkRipple':
this._render();
break;
default:
super._optionChanged(args);
}
}
}
export default SpeedDialItem; | this.option('useInkRipple') && this._renderInkRipple(); |
author.xo.go | // Package mysql contains generated code for schema 'booktest'.
package mysql
// Code generated by xo. DO NOT EDIT.
import (
"context"
)
// Author represents a row from 'booktest.authors'.
type Author struct {
AuthorID int `json:"author_id"` // author_id
Name string `json:"name"` // name
// xo fields
_exists, _deleted bool
}
// Exists returns true when the Author exists in the database.
func (a *Author) Exists() bool {
return a._exists
}
// Deleted returns true when the Author has been marked for deletion from
// the database.
func (a *Author) Deleted() bool {
return a._deleted
}
// Insert inserts the Author to the database.
func (a *Author) Insert(ctx context.Context, db DB) error {
switch {
case a._exists: // already exists
return logerror(&ErrInsertFailed{ErrAlreadyExists})
case a._deleted: // deleted
return logerror(&ErrInsertFailed{ErrMarkedForDeletion})
}
// insert (primary key generated and returned by database)
const sqlstr = `INSERT INTO booktest.authors (` +
`name` +
`) VALUES (` +
`?` +
`)`
// run
logf(sqlstr, a.Name)
res, err := db.ExecContext(ctx, sqlstr, a.Name)
if err != nil {
return logerror(err)
}
// retrieve id
id, err := res.LastInsertId()
if err != nil {
return logerror(err)
} // set primary key
a.AuthorID = int(id)
// set exists
a._exists = true
return nil
}
// Update updates a Author in the database.
func (a *Author) Update(ctx context.Context, db DB) error {
switch {
case !a._exists: // doesn't exist
return logerror(&ErrUpdateFailed{ErrDoesNotExist})
case a._deleted: // deleted
return logerror(&ErrUpdateFailed{ErrMarkedForDeletion})
}
// update with primary key
const sqlstr = `UPDATE booktest.authors SET ` +
`name = ? ` +
`WHERE author_id = ?`
// run
logf(sqlstr, a.Name, a.AuthorID)
if _, err := db.ExecContext(ctx, sqlstr, a.Name, a.AuthorID); err != nil {
return logerror(err)
}
return nil
}
// Save saves the Author to the database.
func (a *Author) Save(ctx context.Context, db DB) error {
if a.Exists() {
return a.Update(ctx, db)
}
return a.Insert(ctx, db)
}
// Upsert performs an upsert for Author.
func (a *Author) Upsert(ctx context.Context, db DB) error {
switch {
case a._deleted: // deleted
return logerror(&ErrUpsertFailed{ErrMarkedForDeletion})
}
// upsert
const sqlstr = `INSERT INTO booktest.authors (` +
`author_id, name` +
`) VALUES (` +
`?, ?` +
`)` +
` ON DUPLICATE KEY UPDATE ` +
`name = VALUES(name)`
// run
logf(sqlstr, a.AuthorID, a.Name)
if _, err := db.ExecContext(ctx, sqlstr, a.AuthorID, a.Name); err != nil {
return logerror(err)
}
// set exists
a._exists = true
return nil
}
// Delete deletes the Author from the database.
func (a *Author) Delete(ctx context.Context, db DB) error {
switch {
case !a._exists: // doesn't exist
return nil
case a._deleted: // deleted
return nil
}
// delete with single primary key
const sqlstr = `DELETE FROM booktest.authors ` +
`WHERE author_id = ?`
// run
logf(sqlstr, a.AuthorID)
if _, err := db.ExecContext(ctx, sqlstr, a.AuthorID); err != nil {
return logerror(err)
}
// set deleted
a._deleted = true
return nil
}
// AuthorByAuthorID retrieves a row from 'booktest.authors' as a Author.
//
// Generated from index 'authors_author_id_pkey'.
func AuthorByAuthorID(ctx context.Context, db DB, authorID int) (*Author, error) {
// query
const sqlstr = `SELECT ` +
`author_id, name ` +
`FROM booktest.authors ` +
`WHERE author_id = ?`
// run
logf(sqlstr, authorID)
a := Author{
_exists: true,
}
if err := db.QueryRowContext(ctx, sqlstr, authorID).Scan(&a.AuthorID, &a.Name); err != nil {
return nil, logerror(err)
}
return &a, nil
}
// AuthorsByName retrieves a row from 'booktest.authors' as a Author.
//
// Generated from index 'authors_name_idx'.
func AuthorsByName(ctx context.Context, db DB, name string) ([]*Author, error) | {
// query
const sqlstr = `SELECT ` +
`author_id, name ` +
`FROM booktest.authors ` +
`WHERE name = ?`
// run
logf(sqlstr, name)
rows, err := db.QueryContext(ctx, sqlstr, name)
if err != nil {
return nil, logerror(err)
}
defer rows.Close()
// process
var res []*Author
for rows.Next() {
a := Author{
_exists: true,
}
// scan
if err := rows.Scan(&a.AuthorID, &a.Name); err != nil {
return nil, logerror(err)
}
res = append(res, &a)
}
if err := rows.Err(); err != nil {
return nil, logerror(err)
}
return res, nil
} |
|
dielectric.rs | use super::utils::*;
use super::{Material, PartialScatterResult, ScatterResult};
use crate::utils::*;
use crate::{math::*, GeometryHitResult};
use crate::{IntersectResult, Ray};
#[derive(Clone, Debug)]
pub struct Dielectric(FloatType);
impl Dielectric {
pub fn new(ri: FloatType) -> Self {
Self(ri)
}
pub fn | (&self) -> FloatType {
self.0
}
}
impl Material for Dielectric {
fn scatter(&self, ray_in: &Ray, hit_record: GeometryHitResult) -> Option<ScatterResult> {
let etai_over_etat = if hit_record.front_face() {
1.0 / self.refractive_index()
} else {
self.refractive_index()
};
let unit_ray_direction = ray_in.direction().normalize();
let cos_theta = -unit_ray_direction.dot(hit_record.surface_normal()).min(1.0);
let sin_theta = (1.0 - cos_theta * cos_theta).sqrt();
if etai_over_etat * sin_theta > 1.0
|| random_in_range(0.0, 1.0) < schlick(cos_theta, etai_over_etat)
{
let reflected = reflect(unit_ray_direction, hit_record.surface_normal());
Some(ScatterResult {
partial: PartialScatterResult {
attenuation: vec3(1.0, 1.0, 1.0),
},
scattered: Ray::new(hit_record.hit_point(), reflected, ray_in.time()),
})
} else {
let refracted = refract(
unit_ray_direction,
hit_record.surface_normal(),
etai_over_etat,
);
Some(ScatterResult {
partial: PartialScatterResult {
attenuation: vec3(1.0, 1.0, 1.0),
},
scattered: Ray::new(hit_record.hit_point(), refracted, ray_in.time()),
})
}
}
}
pub mod factories {
use super::*;
pub fn dielectric(ri: FloatType) -> Dielectric {
Dielectric::new(ri)
}
}
| refractive_index |
words.go | package japanese
import "fmt"
type Word struct {
Kanji string
Kana string
}
// LastKana returns the last kana in a word.
func (w *Word) LastKana() string {
k := []rune(w.Kana)
return string(k[len(k)-1:])
}
func (v *Verb) addEnd(end string) Word {
r, k := v.AllButLast()
return Word{r + end, k + end}
}
// AllButLast returns the kanji and kana readings of
// a word without the last character.
func (w *Word) AllButLast() (kanji, kana string) {
kr := []rune(w.Kanji)
kar := []rune(w.Kana)
return string(kr[:len(kr)-1]), string(kar[:len(kar)-1]) | type Verb struct {
Type string
Word
}
func (v *Verb) stem(u map[string]string) (w Word, err error) {
switch v.Kanji {
case "する":
return Word{"し", "し"}, nil
}
r, k := v.AllButLast()
switch v.Type {
case "る":
return Word{r, k}, nil
case "う":
lastKana := v.LastKana()
val, ok := u[lastKana]
if !ok {
return w, fmt.Errorf("Attempt to get stem of U verb with invalid ending %s. Valid endings: %v", lastKana, u)
}
return v.addEnd(val), nil
}
return w, fmt.Errorf("Attempt to get stem of verb with invalid ending.")
}
// Stem returns the stem of a verb.
// (食べる: 食べ; 言う: 言い)
func (v *Verb) Stem() (w Word, err error) {
switch v.Kanji {
case "来る":
return Word{"来", "き"}, nil
case "ある":
return Word{"あり", "あり"}, nil
}
m := map[string]string{
"す": "し",
"く": "き",
"ぐ": "ぎ",
"む": "み",
"ぶ": "び",
"ぬ": "に",
"る": "り",
"う": "い",
"つ": "ち",
}
word, err := v.stem(m)
if err != nil {
return w, err
}
return word, nil
}
// ShortStem returns the short stem of a verb.
// (食べる: 食べ; 言う: 言わ)
func (v *Verb) ShortStem() (w Word, err error) {
switch v.Kanji {
case "来る":
return Word{"来", "こ"}, nil
}
m := map[string]string{
"す": "さ",
"く": "か",
"ぐ": "が",
"む": "ま",
"ぶ": "ば",
"ぬ": "な",
"る": "ら",
"う": "わ",
"つ": "た",
}
word, err := v.stem(m)
if err != nil {
return w, err
}
return word, nil
}
// TeForm returns the te-form of a verb.
func (v *Verb) TeForm() (word Word, err error) {
switch v.Kanji {
case "する":
return Word{"して", "して"}, nil
case "来る":
return Word{"来て", "きて"}, nil
case "行く":
return v.addEnd("って"), nil
}
switch v.Type {
case "る":
return v.addEnd("て"), nil
case "う":
l := v.LastKana()
switch l {
case "す":
return v.addEnd("して"), nil
case "く":
return v.addEnd("いて"), nil
case "ぐ":
return v.addEnd("いで"), nil
case "む", "ぶ", "ぬ":
return v.addEnd("んで"), nil
case "る", "う", "つ":
return v.addEnd("って"), nil
default:
return word, fmt.Errorf("Attempt to get te form of verb with invalid ending %s.", l)
}
}
return word, fmt.Errorf("Attempt to get te form of verb with invalid ending")
}
// Negative returns the negative form of a Verb.
func (v *Verb) Negative() (word Word, err error) {
switch v.Kanji {
case "ある":
return Word{"ない", "ない"}, nil
}
w, err := v.ShortStem()
if err != nil {
return word, err
}
return Word{w.Kanji + "ない", w.Kana + "ない"}, nil
}
// NegativePast returns the negative past form of a Verb.
func (v *Verb) NegativePast() (word Word, err error) {
switch v.Kanji {
case "ある":
return Word{"なかった", "なかった"}, nil
}
w, err := v.ShortStem()
if err != nil {
return word, err
}
return Word{w.Kanji + "なかった", w.Kana + "なかった"}, nil
}
// NegativePolite returns the negative polite form of a Verb.
func (v *Verb) NegativePolite() (word Word, err error) {
w, err := v.Stem()
if err != nil {
return word, err
}
return Word{w.Kanji + "ません", w.Kana + "ません"}, nil
}
// NegativePastPolite returns the negative past polite form of a Verb.
func (v *Verb) NegativePastPolite() (word Word, err error) {
w, err := v.Stem()
if err != nil {
return word, err
}
return Word{w.Kanji + "ませんでした", w.Kana + "ませんでした"}, nil
}
// Past returns the past tense of a Verb.
func (v *Verb) Past() (word Word, err error) {
switch v.Kanji {
case "ある":
return Word{"あった", "あった"}, nil
case "する":
return Word{"した", "した"}, nil
case "来る":
return Word{"来た", "きた"}, nil
case "行く":
return v.addEnd("った"), nil
}
switch v.Type {
case "る":
return v.addEnd("た"), nil
case "う":
lastKana := v.LastKana()
switch lastKana {
case "す":
return v.addEnd("した"), nil
case "く":
return v.addEnd("いた"), nil
case "ぐ":
return v.addEnd("いだ"), nil
case "む", "ぶ", "ぬ":
return v.addEnd("んだ"), nil
case "る", "う", "つ":
return v.addEnd("った"), nil
}
}
return v.Word, fmt.Errorf("Attempt to get past tense of non-verb")
}
// PastPolite returns the past polite tense of a Verb.
func (v *Verb) PastPolite() (word Word, err error) {
w, err := v.Stem()
if err != nil {
return word, err
}
return Word{w.Kanji + "ました", w.Kana + "ました"}, nil
}
func (v *Verb) te(end string) (word Word, err error) {
w, err := v.TeForm()
if err != nil {
return word, err
}
return Word{w.Kanji + end, w.Kana + end}, nil
}
// Progressive returns the te positive
// form of a Verb.
func (v *Verb) Progressive() (word Word, err error) {
w, err := v.te("いる")
if err != nil {
return word, err
}
return w, nil
}
// ProgressiveNegative returns the te negative
// form of a Verb.
func (v *Verb) ProgressiveNegative() (word Word, err error) {
w, err := v.te("いない")
if err != nil {
return word, err
}
return w, nil
}
// ProgressivePolite returns the te positive
// polite form of a Verb.
func (v *Verb) ProgressivePolite() (word Word, err error) {
w, err := v.te("います")
if err != nil {
return word, err
}
return w, nil
}
// ProgressiveNegativePolite returns the te negative
// polite form of a Verb.
func (v *Verb) ProgressiveNegativePolite() (word Word, err error) {
w, err := v.te("いません")
if err != nil {
return word, err
}
return w, nil
}
// ProgressiveShort returns the shortened
// te positive form of a Verb.
func (v *Verb) ProgressiveShort() (word Word, err error) {
w, err := v.te("る")
if err != nil {
return word, err
}
return w, nil
}
// ProgressiveShortNegative returns the shortened
// te negative form of a Verb.
func (v *Verb) ProgressiveShortNegative() (word Word, err error) {
w, err := v.te("ない")
if err != nil {
return word, err
}
return w, nil
}
// PotentialStem returns the potential stem of a verb.
func (v *Verb) PotentialStem() (word Word, err error) {
switch v.Kanji {
case "する":
return Word{"でき", "でき"}, nil
case "来る":
return Word{"来られ", "こられ"}, nil
}
switch v.Type {
case "る":
return v.addEnd("られ"), nil
case "う":
lastKana := v.LastKana()
switch lastKana {
case "す":
return v.addEnd("せ"), nil
case "く":
return v.addEnd("け"), nil
case "ぐ":
return v.addEnd("げ"), nil
case "む":
return v.addEnd("め"), nil
case "ぶ":
return v.addEnd("べ"), nil
case "ぬ":
return v.addEnd("ね"), nil
case "る":
return v.addEnd("れ"), nil
case "う":
return v.addEnd("え"), nil
case "つ":
return v.addEnd("て"), nil
}
}
return word, fmt.Errorf("Attempt to get potential stem of verb with invalid ending.")
}
func (v *Verb) Potential() (word Word, err error) {
w, err := v.PotentialStem()
if err != nil {
return word, err
}
return Word{w.Kanji + "る", w.Kana + "る"}, nil
}
func (v *Verb) PotentialNegative() (word Word, err error) {
w, err := v.PotentialStem()
if err != nil {
return word, err
}
return Word{w.Kanji + "ない", w.Kana + "ない"}, nil
}
func (v *Verb) PotentialPolite() (word Word, err error) {
w, err := v.PotentialStem()
if err != nil {
return word, err
}
return Word{w.Kanji + "ます", w.Kana + "ます"}, nil
}
func (v *Verb) PotentialNegativePolite() (word Word, err error) {
w, err := v.PotentialStem()
if err != nil {
return word, err
}
return Word{w.Kanji + "ません", w.Kana + "ません"}, nil
}
type Adjective struct {
Word
}
type NaAdjective struct {
Adjective
} | }
// A Verb is a Japanese verb. |
State_force.py | #
# Copyright (C) [2020] Futurewei Technologies, Inc.
#
# FORCE-RISCV is licensed under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES
# OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
# NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import RandomUtils
from Enums import EStateElementDuplicateMode
from State import State
from base.Sequence import Sequence
from riscv.EnvRISCV import EnvRISCV
from riscv.GenThreadRISCV import GenThreadRISCV
# This test attempts to add StateElements to a State. There is no direct
# mechanism for retrieving the StateElements after they have been added, so
# this test merely ensures the method calls don't crash or fail.
class MainSequence(Sequence):
def generate(self, **kargs):
state = State()
state.setDuplicateMode(EStateElementDuplicateMode.Replace)
mem_start_addr = (RandomUtils.random64(0, 0xFFFFFFFFFFFF) >> 3) << 3
mem_val = RandomUtils.random64()
state.addMemoryStateElement(mem_start_addr, 8, mem_val)
mem_values = []
for _ in range(RandomUtils.random32(1, 64)):
mem_values.append(RandomUtils.random32(0, 0xFF))
mem_start_addr = RandomUtils.random64(0, 0xFFFFFFFFFFFF)
state.addMemoryStateElementsAsBytes(mem_start_addr, mem_values)
gpr_name = "x%d" % RandomUtils.random32(0, 31)
state.addRegisterStateElement(gpr_name, (RandomUtils.random64(),))
fp_reg_name = "D%d" % RandomUtils.random32(0, 31)
state.addRegisterStateElement(fp_reg_name, (RandomUtils.random64(),))
state.addSystemRegisterStateElementByField("sstatus", "FS", 0x3)
state.addVmContextStateElement("mstatus", "MPRV", 0x1)
state.addPcStateElement(RandomUtils.random64(0, 0xFFFFFFFFFFFF))
# Test creating duplicate StateElements
state.addVmContextStateElement("mstatus", "MPRV", 0x0)
state.setDuplicateMode(EStateElementDuplicateMode.Ignore)
state.addRegisterStateElement("sstatus", (RandomUtils.random64(),))
# Test merging two StateElements
mem_start_addr = (RandomUtils.random64(0, 0xFFFFFFFFFFFF) >> 3) << 3
mem_val = RandomUtils.random32()
state.addMemoryStateElement(mem_start_addr, 4, mem_val)
mem_start_addr += 4
mem_values = []
for _ in range(4):
mem_values.append(RandomUtils.random32(0, 0xFF)) | MainSequenceClass = MainSequence
GenThreadClass = GenThreadRISCV
EnvClass = EnvRISCV |
state.addMemoryStateElementsAsBytes(mem_start_addr, mem_values)
|
chain.rs | #![cfg(feature = "util")]
use futures::Async::*;
use tokio_buf::{BufStream, BufStreamExt};
mod support;
use support::*;
#[test]
fn | () {
// Chain one with one
//
let mut bs = one("hello").chain(one("world"));
assert_buf_eq!(bs.poll_buf(), "hello");
assert_buf_eq!(bs.poll_buf(), "world");
assert_none!(bs.poll_buf());
// Chain multi with multi
let mut bs = list(&["foo", "bar"]).chain(list(&["baz", "bok"]));
assert_buf_eq!(bs.poll_buf(), "foo");
assert_buf_eq!(bs.poll_buf(), "bar");
assert_buf_eq!(bs.poll_buf(), "baz");
assert_buf_eq!(bs.poll_buf(), "bok");
assert_none!(bs.poll_buf());
// Chain includes a not ready call
//
let mut bs = new_mock(&[Ok(Ready("foo")), Ok(NotReady), Ok(Ready("bar"))]).chain(one("baz"));
assert_buf_eq!(bs.poll_buf(), "foo");
assert_not_ready!(bs.poll_buf());
assert_buf_eq!(bs.poll_buf(), "bar");
assert_buf_eq!(bs.poll_buf(), "baz");
assert_none!(bs.poll_buf());
}
| chain |
forms.py | from flask_wtf import FlaskForm
from wtforms import StringField, TextAreaField, SubmitField
from wtforms.validators import Length, DataRequired
from anon_scriber import datetime
class PostForm(FlaskForm):
| title = StringField(label='Title: ', validators=[Length(min=1, max=60), DataRequired()])
post_text = TextAreaField(label='Your Post: ', validators=[Length(min=1, max=1024), DataRequired()])
time_stamp_of_post = StringField(label="Posted on: ", default=datetime.utcnow)
submit = SubmitField(label='Share') |
|
app.py | import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import numpy as np
import fileutility
app = dash.Dash(__name__, suppress_callback_exceptions=True)
app.title = 'Tunnusluvut'
# For Heroku
server = app.server
#######################################
# Global variables
#######################################
df, units = fileutility.prepare_data()
yhtiot = sorted(df['Yhtiö'].unique())
tunnusluvut = {
'Sijoitukset': sorted((df.columns[[6, 7, 13, 14, 15, 16, 17, 18, 19]])),
'Muut': sorted((df.columns[[4, 5, 8, 9, 10, 11, 12, 20, 21, 22, 23, 24, 25]]))
}
vuodet = sorted(df['Vuosi'].unique())
# Companies' own colors for Elo, Etera, Ilmarinen, Varma, and Veritas
colors = {
'Alandia': '#b97454',
'Elo': '#FFD200',
'Etera': '#9ACD68',
'Fennia': '#69BDD1',
'Ilmarinen': '#003975',
'Varma': '#D10168',
'Veritas': '#00990F',
'background': '#F9FBFD'
}
#######################################
# Modals
#######################################
tietoa_yhtioista = html.Div(children=[
html.Section([
html.H6('Sulautumiset'),
html.P(['Nykyiset yhtiöt ovat Elo, Ilmarinen, Varma ja Veritas.',
html.Br(),
'Alandia sulautui Veritakseen 1.1.2019.',
html.Br(),
'Etera sulautui Ilmariseen 1.1.2018.',
html.Br(),
'Fennia sulautui Eloon 1.1.2014.'
])
]),
html.Section([
html.H6('Viralliset nimet'),
html.P(['Försäkringsaktiebolaget Pensions-Alandia',
html.Br(),
'Keskinäinen Työeläkevakuutusyhtiö Elo',
html.Br(),
'Keskinäinen Eläkevakuutusyhtiö Etera',
html.Br(),
'Keskinäinen vakuutusyhtiö Eläke-Fennia',
html.Br(),
'Keskinäinen Eläkevakuutusyhtiö Ilmarinen',
html.Br(),
'Keskinäinen työeläkevakuutusyhtiö Varma',
html.Br(),
'Pensionsförsäkringsaktiebolaget Veritas'
]),
html.P('''Elo toimi vuonna 2013 nimellä LähiTapiola Keskinäinen Eläkevakuutusyhtiö
ja sitä ennen nimellä Keskinäinen Eläkevakuutusyhtiö Tapiola.''')
])
])
tietoa_sivusta = html.Div(children=[
html.P('''Sivulla voit luoda kaavioita työeläkevakuutusyhtiöiden tunnusluvuista.
Hiirellä tai kaavion painikkeilla voit esimerkiksi suurentaa tai vierittää kaavioita.
Osaa tunnusluvuista ei ole kaikilta vuosilta.'''),
html.P(['Luvut ovat Finanssivalvonnan julkaisemista ',
html.A('tilastoista', href='https://www.finanssivalvonta.fi/tilastot/vakuutus/elakevakuutus/'),
' ja yhtiöiden tilinpäätöksistä. Kunkin vuoden luvut ovat tilanne 31.12. ',
'Lukujen pyöristystarkkuus vaihtelee.']),
html.P(['Sivun lähdekoodi on ',
html.A('GitHubissa', href='https://github.com/mikkomaa/tunnusluvut'),
'.']),
html.P('''Kysymyksiä ja kommentteja voit lähettää sähköpostilla mkkmatis at hotmail.com.''')
])
yhtio_info_button = dbc.Button('Tietoa yhtiöistä',
id='open-yhtio-modal',
outline=True,
style={
'margin-top': 20,
})
sivu_info_button = dbc.Button('Tietoa sivusta',
id='open-sivu-modal',
outline=True,
style={
'margin-top': 20,
'margin-left': 20,
})
yhtio_modal = html.Div(
[
yhtio_info_button,
dbc.Modal(
[
dbc.ModalHeader('Tietoa yhtiöistä'),
dbc.ModalBody(
children=[
tietoa_yhtioista,
]
),
dbc.ModalFooter(
dbc.Button('Sulje',
id='close-yhtio-modal',
outline=True)
),
],
id='yhtio-modal',
),
]
)
sivu_modal = html.Div(
[
sivu_info_button,
dbc.Modal(
[
dbc.ModalHeader('Tietoa sivusta'),
dbc.ModalBody(
children=[
tietoa_sivusta,
]
),
dbc.ModalFooter(
dbc.Button('Sulje',
id='close-sivu-modal',
outline=True)
),
],
id='sivu-modal',
),
]
)
#######################################
# Options for the user
#######################################
yhtio_checklist = html.Div([
html.H6('Yhtiöt'),
dcc.Checklist(
id='yhtio-checklist',
options=[{'label': i, 'value': i} for i in yhtiot],
value=['Elo', 'Ilmarinen', 'Varma', 'Veritas'],
labelStyle={'display': 'inline-block', 'margin-right': 10},
inputStyle={'margin-right': 2},
),
])
sijoitukset_dropdown = html.Div([
html.H6('Sijoitusluvut'),
dcc.Dropdown(
id='sijoitukset-dropdown',
options=[{'label': i, 'value': i} for i in tunnusluvut['Sijoitukset']],
value=[tunnusluvut['Sijoitukset'][0]],
placeholder='Valitse...',
multi=True,
style={'width': 450}
)
])
muut_dropdown = html.Div([
html.H6('Muut luvut'),
dcc.Dropdown(
id='muut-dropdown',
options=[{'label': i, 'value': i} for i in tunnusluvut['Muut']],
value=[tunnusluvut['Muut'][0]],
placeholder='Valitse...',
multi=True,
style={'width': 450}
)
])
vuosi_slider = html.Div([
html.H6('Vuodet'),
dcc.RangeSlider(
id='vuosi-slider',
min=vuodet[0],
max=vuodet[-1],
value=[vuodet[-5], vuodet[-1]],
marks={str(year): str(year) for year in vuodet},
step=None,
)],
style={'width': 450}
)
kaavio_radioitems = html.Div([
html.H6('Kaavio'),
dcc.RadioItems(
id='kaavio-radioitems',
className='radio-group',
options=[{'label': 'Pylväs', 'value': 'bar'},
{'label': 'Viiva', 'value': 'line'}],
value='bar',
labelStyle={'display': 'inline-block', 'margin-right': 10},
inputStyle={'margin-right': 2},
)
])
#######################################
# Page layout
#######################################
app.layout = html.Div(
html.Div([
# Header
html.Div([
html.H2('Työeläkevakuutusyhtiöiden tunnusluvut',
style={'margin-left': 20},
),
html.Div([yhtio_modal],
style={'margin-left': 50},
),
html.Div([sivu_modal],
),
], className='row'),
# Options: yhtiöt, kaavio, vuodet
html.Div([
html.Div([yhtio_checklist],
style={'margin-left': 20}
),
html.Div([kaavio_radioitems],
style={'margin-left': 20}
),
html.Div([vuosi_slider],
style={'margin-left': 20}
)
], className='row'),
# Options: sijoitusluvut, muut luvut
html.Div([
html.Div([sijoitukset_dropdown],
style={'margin-left': 20},
),
html.Div([muut_dropdown],
style={'margin-left': 20},
)
], className='row'),
# Graphs, from create_graphs-method
html.Div(id='container'),
])
)
#######################################
# Callbacks
#######################################
@app.callback(
Output('container', 'children'),
[Input('yhtio-checklist', 'value'),
Input('sijoitukset-dropdown', 'value'),
Input('muut-dropdown', 'value'),
Input('vuosi-slider', 'value'),
Input('kaavio-radioitems', 'value')]
)
def create_graphs(yhtiot, sijoitusluvut, muutluvut, vuodet, kaavio | ate graphs to display"""
yhtiot.sort()
tunnusluvut = sorted(sijoitusluvut + muutluvut)
vuodet = [i for i in range(vuodet[0], vuodet[1] + 1)]
dff = df[df['Vuosi'].isin(vuodet)]
graphs = []
for t in tunnusluvut:
graphs.append(dcc.Graph(
id='graph-{}'.format(t),
figure=create_figure(t, yhtiot, kaavio, dff),
))
return html.Div(graphs,
className='row')
def create_figure(tunnusluku, yhtiot, kaavio, df):
"""Create a figure for a graph"""
data = []
for yhtio in yhtiot:
dff = df[(df['Yhtiö'] == yhtio) & (df[tunnusluku] != np.nan)]
if dff.empty:
continue
data.append({'x': dff['Vuosi'], 'y': dff[tunnusluku],
'type': kaavio, 'name': yhtio,
'marker': {'color': colors[yhtio]},
'hovertemplate': '%{y}',
'hoverlabel': {'bgcolor': 'white'},
}
)
return {
'data': data,
'layout': dict(
title=get_figure_title(tunnusluku),
xaxis={
'title': 'Vuosi',
'dtick': 1
},
height=550,
width=get_figure_width(yhtiot, kaavio, df),
hovermode='closest',
paper_bgcolor=colors['background'],
plot_bgcolor=colors['background'])
}
def get_figure_title(tunnusluku):
"""Return a figure title"""
if units[tunnusluku] in ['euroa', 'kpl', '%']:
return f'{tunnusluku} ({units[tunnusluku]})'
return tunnusluku
def get_figure_width(yhtiot, kaavio, df):
years = len(df['Vuosi'].unique())
if kaavio == 'bar':
width = max(550, 37 * years * len(yhtiot))
return min(1200, width)
return max(550, 75 * years)
# Modal callbacks
@app.callback(
Output('sivu-modal', 'is_open'),
[Input('open-sivu-modal', 'n_clicks'), Input('close-sivu-modal', 'n_clicks')],
[State('sivu-modal', 'is_open')]
)
def toggle_modal(n1, n2, is_open):
if n1 or n2:
return not is_open
return is_open
@app.callback(
Output('yhtio-modal', 'is_open'),
[Input('open-yhtio-modal', 'n_clicks'), Input('close-yhtio-modal', 'n_clicks')],
[State('yhtio-modal', 'is_open')]
)
def toggle_modal(n1, n2, is_open):
if n1 or n2:
return not is_open
return is_open
if __name__ == '__main__':
app.run_server(debug=False) # Set debug=False for the production server
| ):
"""Cre |
bam.py | execfile('<%= @tmp_dir %>/common.py')
# weblogic node params
WLHOME = '<%= @weblogic_home_dir %>'
JAVA_HOME = '<%= @java_home_dir %>'
WEBLOGIC_VERSION = '<%= @version %>'
# domain params
DOMAIN_PATH = '<%= @domain_dir %>'
DOMAIN = '<%= @domain_name %>'
APP_PATH = '<%= @app_dir %>'
# adminserver params
ADMIN_SERVER_NAME = '<%= @adminserver_name %>'
ADMIN_SERVER_LISTEN_ADDRESS = '<%= @adminserver_listen_address %>'
MACHINE_NAME = 'LocalMachine'
NODEMANAGER_LISTEN_PORT = <%= scope.lookupvar("fmw_domain::nodemanager_port") %>
BAM_SERVER_STARTUP_ARGUMENTS = '<%= @bam_server_startup_arguments %>'
BAM_SERVER_LISTEN_PORT = 9001
ESS_CLUSTER = '<%= @ess_cluster %>'
SOA_CLUSTER = '<%= @soa_cluster %>'
OSB_CLUSTER = '<%= @osb_cluster %>'
BAM_CLUSTER = '<%= @bam_cluster %>'
# templates
WLS_EM_TEMPLATE = '<%= @wls_em_template %>'
WLS_BAM_TEMPLATE = '<%= @wls_bam_template %>'
# repository
REPOS_DBURL = '<%= @repository_database_url %>'
REPOS_DBUSER_PREFIX = '<%= @repository_prefix %>'
REPOS_DBPASSWORD = sys.argv[2]
BPM_ENABLED=<%= @bpm_enabled %>
readDomain(DOMAIN_PATH)
cd('/')
setOption( "AppDir", APP_PATH )
print 'Adding EM Template'
try:
addTemplate(WLS_EM_TEMPLATE)
except:
print "Probably already added error:", sys.exc_info()[0]
print 'Adding BAM Template'
addTemplate(WLS_BAM_TEMPLATE)
if WEBLOGIC_VERSION == '10.3.6':
cd('/')
# destroy the normal one
delete('LocalMachine','Machine')
print('change the default machine LocalMachine with type Machine')
createMachine('UnixMachine', MACHINE_NAME, ADMIN_SERVER_LISTEN_ADDRESS, NODEMANAGER_LISTEN_PORT)
print 'Change AdminServer'
cd('/Servers/'+ADMIN_SERVER_NAME)
set('Machine','LocalMachine')
if BAM_CLUSTER:
pass
else:
print 'change bam_server1'
cd('/')
changeManagedServer('bam_server1', MACHINE_NAME, ADMIN_SERVER_LISTEN_ADDRESS, BAM_SERVER_LISTEN_PORT, BAM_SERVER_STARTUP_ARGUMENTS, JAVA_HOME)
if WEBLOGIC_VERSION == '10.3.6':
print 'Change datasources'
changeDatasource('OraSDPMDataSource', REPOS_DBUSER_PREFIX+'_ORASDPM', REPOS_DBPASSWORD, REPOS_DBURL)
changeDatasource('mds-owsm', REPOS_DBUSER_PREFIX+'_MDS', REPOS_DBPASSWORD, REPOS_DBURL)
changeDatasource('BAMDataSource', REPOS_DBUSER_PREFIX+'_ORABAM', REPOS_DBPASSWORD, REPOS_DBURL)
if BAM_CLUSTER:
bamServers = getClusterServers(BAM_CLUSTER, ADMIN_SERVER_NAME)
if 'bam_server1' in bamServers:
pass
else:
print "delete bam_server1"
cd('/')
delete('bam_server1', 'Server')
change11gFMWTargets(ADMIN_SERVER_NAME, SOA_CLUSTER, OSB_CLUSTER, BAM_CLUSTER, BPM_ENABLED)
updateDomain()
dumpStack()
closeDomain()
readDomain(DOMAIN_PATH)
cleanJMS('BAMJmsSystemResource', 'BAMJMSServer_auto', None)
if WEBLOGIC_VERSION != '10.3.6':
print 'Change datasources'
print 'Change datasource LocalScvTblDataSource'
changeDatasource('LocalSvcTblDataSource', REPOS_DBUSER_PREFIX+'_STB', REPOS_DBPASSWORD, REPOS_DBURL)
print 'Call getDatabaseDefaults which reads the service table'
getDatabaseDefaults()
changeDatasourceToXA('OraSDPMDataSource')
changeDatasourceToXA('BamDataSource')
print 'end datasources'
print 'Add server groups WSM-CACHE-SVR WSMPM-MAN-SVR JRF-MAN-SVR to AdminServer'
serverGroup = ["WSM-CACHE-SVR" , "WSMPM-MAN-SVR" , "JRF-MAN-SVR"]
setServerGroups(ADMIN_SERVER_NAME, serverGroup)
serverGroup = ["BAM12-MGD-SVRS"]
if BAM_CLUSTER:
if WEBLOGIC_VERSION == '12.2.1':
cleanJMS('UMSJMSSystemResource', 'UMSJMSServer_auto', 'UMSJMSFileStore_auto')
print 'Add server group BAM-MGD-SVRS to cluster' | cd('/')
for i in range(len(bamServers)):
print "Add server group BAM-MGD-SVRS to " + bamServers[i]
setServerGroups(bamServers[i] , serverGroup)
print 'Assign cluster to defaultCoherenceCluster'
cd('/')
assign('Cluster',BAM_CLUSTER,'CoherenceClusterSystemResource','defaultCoherenceCluster')
cd('/CoherenceClusterSystemResource/defaultCoherenceCluster')
AllArray = []
if SOA_CLUSTER:
AllArray.append(SOA_CLUSTER)
if BAM_CLUSTER:
AllArray.append(BAM_CLUSTER)
if OSB_CLUSTER:
AllArray.append(OSB_CLUSTER)
if ESS_CLUSTER:
AllArray.append(ESS_CLUSTER)
All = ','.join(AllArray)
set('Target', All)
if 'bam_server1' in bamServers:
pass
else:
print "delete bam_server1"
cd('/')
delete('bam_server1', 'Server')
updateDomain()
dumpStack()
closeDomain()
readDomain(DOMAIN_PATH)
if WEBLOGIC_VERSION == '12.2.1':
cd('/')
cleanJMS('UMSJMSSystemResource', 'UMSJMSServer_auto', 'UMSJMSFileStore_auto')
recreateUMSJms12c(ADMIN_SERVER_NAME, SOA_CLUSTER, OSB_CLUSTER, BAM_CLUSTER, ESS_CLUSTER, All)
updateDomain()
dumpStack()
closeDomain()
readDomain(DOMAIN_PATH)
cleanJMS('BamCQServiceJmsSystemResource', 'BamCQServiceJmsServer', 'BamCQServiceJmsFileStore')
updateDomain()
dumpStack()
closeDomain()
readDomain(DOMAIN_PATH)
BAMJms12c(BAM_CLUSTER)
else:
print 'Add server group BAM-MGD-SVRS to bam_server1'
setServerGroups('bam_server1', serverGroup)
print 'end server groups'
updateDomain()
dumpStack()
closeDomain()
print('Exiting...')
exit() | cd('/')
setServerGroups('bam_server1', [])
bamServers = getClusterServers(BAM_CLUSTER, ADMIN_SERVER_NAME) |
parse.go | package utils
import (
"encoding/json"
"fmt"
"github.com/BurntSushi/toml"
"github.com/caarlos0/env"
"gopkg.in/yaml.v3"
"path/filepath"
"reflect"
"strings"
)
func parseConfig(config *Config, i interface{}, paths ...string) error {
if config.Debug {
fmt.Println("start parse config")
}
if len(paths) <= 0 {
return nil
}
items, err := Waits(len(paths), func(i int) (interface{}, error) {
item := paths[i]
if strings.HasPrefix(item, "http") {
return readAsHttp(item)
}
p, err := filepath.Abs(item)
if err != nil {
return nil, err
}
return readAsFile(p)
})
if err != nil {
return err
}
for _, item := range items {
err := Parse(i, item.([]byte), config.Debug)
if err != nil {
return err
}
}
if config.Debug {
fmt.Println("end parse config")
}
return nil
}
func ParseConfig(config *Config, i interface{}, paths ...string) error {
value := reflect.Indirect(reflect.ValueOf(i))
if !value.CanAddr() {
return fmt.Errorf("data %v err", i)
}
err := parseConfig(config, i, paths...)
if err != nil {
return err
}
if config.Reload == true && config.Interval != 0 {
Auto(config.Interval, func() (bool, error) {
defer func() {
if config.CallBack != nil {
config.CallBack()
}
}()
//set default value at parse before
reflectPtr := reflect.New(reflect.ValueOf(i).Elem().Type())
reflectPtr.Elem().Set(value)
err := parseConfig(config, i, paths...)
return true, err
}, config.Debug)
}
return nil
}
func parseBase(i interface{}, content []byte, debug bool) error {
err := json.Unmarshal(content, i)
if err == nil {
return nil
}
err = yaml.Unmarshal(content, i)
if err == nil {
return nil
}
err = toml.Unmarshal(content, i)
if err == nil {
return nil
}
if debug {
Failure(err, "parse error")
}
return err
}
// 解析配置文件
func Parse(i interface{}, content []byte, debug bool) error {
err := pa | rseBase(i, content, debug)
if err != nil {
return err
}
_ = env.Parse(i)
return nil
}
|
|
message_raw.rs | // Copyright 2020-2021 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
use crate::endpoints::{
config::ROUTE_MESSAGE_RAW, filters::with_tangle, path_params::message_id, permission::has_permission,
rejection::CustomRejection, storage::StorageBackend,
};
use bee_common::packable::Packable;
use bee_message::MessageId;
use bee_runtime::resource::ResourceHandle;
use bee_tangle::Tangle;
use warp::{filters::BoxedFilter, http::Response, reject, Filter, Rejection, Reply};
use std::net::IpAddr;
fn path() -> impl Filter<Extract = (MessageId,), Error = warp::Rejection> + Clone {
super::path()
.and(warp::path("messages"))
.and(message_id())
.and(warp::path("raw"))
.and(warp::path::end())
}
pub(crate) fn | <B: StorageBackend>(
public_routes: Box<[String]>,
allowed_ips: Box<[IpAddr]>,
tangle: ResourceHandle<Tangle<B>>,
) -> BoxedFilter<(impl Reply,)> {
self::path()
.and(warp::get())
.and(has_permission(ROUTE_MESSAGE_RAW, public_routes, allowed_ips))
.and(with_tangle(tangle))
.and_then(message_raw)
.boxed()
}
pub async fn message_raw<B: StorageBackend>(
message_id: MessageId,
tangle: ResourceHandle<Tangle<B>>,
) -> Result<impl Reply, Rejection> {
match tangle.get(&message_id).await.map(|m| (*m).clone()) {
Some(message) => Ok(Response::builder()
.header("Content-Type", "application/octet-stream")
.body(message.pack_new())),
None => Err(reject::custom(CustomRejection::NotFound(
"can not find message".to_string(),
))),
}
}
| filter |
table.component.ts | import {
Component, EventEmitter, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChanges, Type,
ViewChild
} from '@angular/core'; |
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import { Page, Sort } from './page';
import { SharkColumn } from './column';
import { SharkPageChangeEvent } from './page.change.event';
import { SharkCurrentSort, SharkSortType } from './sort.type';
import { SharkTableUtils } from './table.utils';
import { SharkDynamicContents } from './dynamic/dynamic.contents';
import { SharkHeaderFilterChange, SharkTableHeaderComponent } from './table.header.component';
import { CellStyleFunction, RowStyleFunction } from './table.body.component';
import { SharkTableFooterComponent } from './table.footer.component';
import { SharkTableInfoHeaderComponent } from './table.info.header.component';
import { NotifierService } from './notifier/notifier.service';
import { SharkTableCurrentDataEvent } from './current.data.event';
@Component({
selector: 'shark-table',
template: `
<shark-table-aria-notifier [notifierService]="notifierService"></shark-table-aria-notifier>
<div class="table-wrapper" *ngIf="page">
<shark-table-info-header *ngIf="(serverSideData || (filterable && !columnFiltering) || columnPicker)"
[serverSideData]="serverSideData"
[filterable]="filterable"
[columnFiltering]="columnFiltering"
[columnPicker]="columnPicker"
[columns]="currentColumns"
[allColumns]="columns"
[filter]="filter"
[showFilterPlaceholders]="showFilterPlaceholders"
[localPagingSize]="localPagingSize"
[notifierService]="notifierService"
(filterChange)="headerChange($event)"
(columnChange)="updateCurrentColumns($event)"
></shark-table-info-header>
<table>
<caption [ngClass]="{'screen-reader': hideCaption}">{{ caption }}</caption>
<thead shark-table-header
[sortable]="sortable"
[columns]="currentColumns"
[columnOrdering]="columnOrdering"
[childRows]="childRows"
[page]="page"
[filterable]="filterable"
[columnFiltering]="columnFiltering"
[localPagingSize]="localPagingSize"
[filter]="filter"
[showFilterPlaceholders]="showFilterPlaceholders"
[notifierService]="notifierService"
(sortChange)="changeSort($event.property, $event.sortType)"
(filterChange)="headerChange($event)"
(columnChange)="updateCurrentColumns($event)"
></thead>
<tbody shark-table-body
[currentColumns]="currentColumns"
[columns]="columns"
[localFilter]="localFilter"
[localPaging]="localPaging"
[columnFiltering]="columnFiltering"
[filter]="filter"
[childRows]="childRows"
[childComponent]="childComponent"
[linkTarget]="linkTarget" [linkKey]="linkKey"
[page]="page"
[tableEmptyMessage]="tableEmptyMessage"
[rowStylingFunction]="rowStylingFunction"
[cellStylingFunction]="cellStylingFunction"
></tbody>
</table>
<shark-table-footer *ngIf="footer && currentColumns.length > 0"
[page]="page"
[columns]="currentColumns"
[filter]="filter"
[localPaging]="localPaging"
[localPagingSize]="localPagingSize"
[localPagingOptions]="localPagingOptions"
[showLocalPagingOptions]="showLocalPagingOptions"
[notifierService]="notifierService"
(filterChange)="headerChange($event)"
(paginationChange)="changePage($event)"
></shark-table-footer>
</div>
`
})
export class SharkTableComponent implements OnInit, OnChanges, OnDestroy {
@ViewChild(SharkTableInfoHeaderComponent)
headerInfoComponent: SharkTableInfoHeaderComponent;
@ViewChild(SharkTableHeaderComponent)
headerComponent: SharkTableHeaderComponent;
@ViewChild(SharkTableFooterComponent)
footerComponent: SharkTableFooterComponent;
notifierService = new NotifierService();
/**
* The raw table data
*/
@Input()
data: Page | Observable<Page | any[]> | any[];
/**
* The table column definitions
*/
@Input()
columns: SharkColumn[];
currentColumns: SharkColumn[] = [];
/**
* The <caption> text for this table
* @type {string}
*/
@Input()
caption = 'A Data Table';
/**
* Whether or not the table <caption> should be hidden (screen-reader) only.
* @type {boolean}
*/
@Input()
hideCaption = false;
/**
* Allow users to turn columns on and off
* @type {boolean}
*/
@Input()
columnPicker = false;
/**
* Allow users to reorder columns with header buttons
* @type {boolean}
*/
@Input()
columnOrdering = false;
/**
* The destination page for the call to `router.navigate` when the row is clicked.
*/
@Input()
linkTarget: string;
/**
* The property name from the data object to pass to `router.navigate` when the rows is clicked.
*/
@Input()
linkKey: string;
/**
* Enables the sorting headers
* @type {boolean}
*/
@Input()
sortable = true;
/**
* Enables the global filter text box
* @type {boolean}
*/
@Input()
filterable = true;
/**
* Enables column specific filter boxes
* @type {boolean}
*/
@Input()
columnFiltering = false;
/**
* Enables client-side filtering as opposed to just emitting a `SharkPageChangeEvent`
* @type {boolean}
*/
@Input()
localFilter = true;
/**
* Enables the placeholder text for the filter boxes
* @type {boolean}
*/
@Input()
showFilterPlaceholders = true;
/**
* Enables client-side pagination as opposed to just emitting a `SharkPageChangeEvent`
* @type {boolean}
*/
@Input()
localPaging = true;
/**
* The size of each page
* @type {number}
*/
@Input()
localPagingSize: number = 10;
/**
* The supported page sizes
* @type {number[]}
*/
@Input()
localPagingOptions: number[] = [ 10, 20, 100 ];
/**
* Enables the drop down for changing the page size
* @type {boolean}
*/
@Input()
showLocalPagingOptions = true;
/**
* Shows a button that when clicked, emits a `SharkPageChangeEvent`
* @type {boolean}
*/
@Input()
serverSideData = false;
/**
* The initial sortString
*/
@Input()
initialSort: string;
@Input()
rowStylingFunction: RowStyleFunction = row => { return {}; };
@Input()
cellStylingFunction: CellStyleFunction;
/**
* Enables children rows
* @type {boolean}
*/
@Input()
childRows = false;
/**
* Your custom component which extends {@link SharkDynamicContents} that will be used
* to render each child row. Your custom component needs to be registered in your NgModule
* as an `entryComponent` and in the `declarations` section.
*
* The easiest way to specify this component in your HTML template is to create an instance variable
* and assign it, eg:
*
* ```typescript
* @Component({
* template: `
* <shark-table
* [data]="testData"
* [columns]="tableColumns"
* [childRows]="true"
* [childComponent]="childComponent"
* >
* </shark-table>
* `
* })
* export class MyComponent {
* childComponent = MyChildComponent
* }
*
* ```
*/
@Input()
childComponent?: Type<SharkDynamicContents>;
/**
* {@link SharkPageChangeEvent} events are emitted from here
* @type {EventEmitter<SharkPageChangeEvent>}
*/
@Output()
pageChange = new EventEmitter<SharkPageChangeEvent>();
/**
* The current filter value
*/
@Input()
filter: string;
/**
* Show the footer with 'Showing x through y of z rows`
*
* @type {boolean}
*/
@Input()
footer = true;
/**
* Message to show when the table is empty
*/
@Input()
tableEmptyMessage = 'This table contains no rows';
page: Page;
private dataSubscription: Subscription;
private localSubscription: Subscription;
constructor(private router: Router, private tableUtils: SharkTableUtils) {}
ngOnInit(): void {
this.updatePage();
}
ngOnChanges(changes: SimpleChanges): void {
const dataChange = changes['data'];
const columnChange = changes['columns'];
if (columnChange && columnChange.isFirstChange()) {
this.columns = columnChange.currentValue;
this.columns.forEach((column: SharkColumn) => column.displayed = true);
this.currentColumns = this.columns;
}
if (dataChange && !dataChange.isFirstChange()) {
this.updatePage();
} else if (columnChange && !columnChange.isFirstChange()) {
this.currentColumns = columnChange.currentValue;
this.emitCurrent();
}
}
ngOnDestroy(): void {
if (this.dataSubscription) {
this.dataSubscription.unsubscribe();
}
if (this.localSubscription) {
this.localSubscription.unsubscribe();
}
}
updateCurrentColumns(newColumns: SharkColumn[]) {
this.currentColumns = newColumns.filter((value: SharkColumn) => value.displayed);
this.emitCurrent();
}
/**
* Emits a {@link SharkPageChangeEvent} with the current information. This event should be consumed by the host
* component and sent to a REST endpoint to update the data.
*/
emitCurrent(): void {
this.pageChange.emit({
pageNo: this.page.number,
columns: this.currentColumns,
sortString: this.generateSortString(),
sorts: this.generateSortArray(),
filter: this.filter
});
}
headerChange(event: SharkHeaderFilterChange): void {
this.columns = event.columns;
this.currentColumns = this.columns.filter((value: SharkColumn) => value.displayed);
this.filter = event.filter;
this.localPagingSize = event.localPagingSize;
this.emitCurrent();
}
changePage(pageNo: number): void {
this.pageChange.emit({
pageNo: pageNo,
columns: this.currentColumns,
sortString: this.generateSortString(),
sorts: this.generateSortArray(),
filter: this.filter
});
}
changeSort(columnProperty: string, sortType: SharkSortType): void {
if (this.sortable) {
this.currentColumns.forEach((column: SharkColumn) => {
if (column.property === columnProperty) {
// State Machine
// ASC -> DESC -> NONE -> ASC
switch (sortType) {
case SharkSortType.ASC: {
// -> DESC
column.sortType = SharkSortType.DESC;
break;
}
case SharkSortType.DESC: {
// -> NONE
column.sortType = SharkSortType.NONE;
break;
}
case SharkSortType.NONE:
default: {
// -> ASC
column.sortType = SharkSortType.ASC;
break;
}
}
this.notifierService.postMessage((column.sortType === SharkSortType.DESC ? 'sorted descending' : column.sortType === SharkSortType.ASC ? 'sorted ascending' : 'unsorted'));
}
});
const sorts = this.generateSortArray();
if (!this.serverSideData) {
// sort internally
this.sort(this.page.content, sorts);
}
this.pageChange.emit({
pageNo: this.page.number,
columns: this.currentColumns,
sortString: this.generateSortString(),
sorts: sorts,
filter: this.filter
});
}
}
/**
* Currently only works if your input is an any[], returns the current "view" into the table with filtering/column selection
* @param {boolean} rendered If you would like inline pipes to be applied to the exported data
*
* @returns {SharkTableCurrentDataEvent}
*/
exportCurrentData(rendered: boolean = true): SharkTableCurrentDataEvent {
let currentData: any[];
if (this.localFilter && (this.columnFiltering && this.tableUtils.hasFilter(this.currentColumns) || (this.filter && this.filter.length > 0))) {
currentData = this.tableUtils.filter(this.data, this.currentColumns, this.columnFiltering, this.filter);
this.sort(currentData, this.generateSortArray());
} else {
currentData = this.data as any[];
}
if (this.currentColumns.length === 0) {
return {
data: [],
columns: []
}
}
return {
data: currentData.map(row => this.tableUtils.exportRow(row, this.currentColumns, rendered)),
columns: this.currentColumns
};
}
private generateSortString(): string {
let sortString = '';
this.currentColumns.forEach((column: SharkColumn) => {
switch (column.sortType) {
case SharkSortType.ASC: {
sortString += '' + column.property + ';';
break;
}
case SharkSortType.DESC: {
sortString += '-' + column.property + ';';
break;
}
case SharkSortType.NONE: {
break;
}
}
});
return sortString;
}
private generateSortArray(): SharkCurrentSort[] {
const currentSorts: SharkCurrentSort[] = [];
this.currentColumns.forEach((column: SharkColumn) => {
switch (column.sortType) {
case SharkSortType.ASC:
case SharkSortType.DESC: {
currentSorts.push({property: column.property, sortType: column.sortType});
break;
}
}
});
return currentSorts;
}
private sort(content: any[], sorts: SharkCurrentSort[]): void {
const columnCache = {};
this.columns.forEach(column => columnCache[column.property] = column);
content.sort((a, b) => {
let result = 0;
sorts.forEach((sort: SharkCurrentSort) => {
if ( result === 0 ) {
const aVal = this.tableUtils.findValue(a, sort.property);
const bVal = this.tableUtils.findValue(b, sort.property);
const sortFunction = columnCache[sort.property].ascendingSortFunction;
if (!!sortFunction) {
result = sortFunction(aVal, bVal);
} else if (!isNaN(Number(aVal)) && !isNaN(Number(bVal))) {
result = aVal - bVal;
} else {
result = (aVal < bVal) ? -1 : (aVal > bVal) ? 1 : 0;
}
result *= (sort.sortType === SharkSortType.DESC) ? -1 : 1;
}
});
return result;
});
}
private updatePage(): void {
if (this.data) {
if (this.data.constructor === Array) {
this.setupPageArray();
} else if (this.data.constructor === Observable) {
this.setupPageSubscription();
} else {
this.page = this.data as Page;
if (!this.page.number) {
this.page.number = 0;
}
}
this.setupInitialSort();
}
}
private createLocalPage(data?: any[]): Page {
const total = (data ? data : this.data as any[]).length;
return {
number: 0,
totalPages: 1,
totalElements: total,
first: true,
last: true,
numberOfElements: total,
content: data ? data : this.data as any[]
};
}
private setupPageArray(): void {
if (this.localPaging) {
const total = (this.data as any[]).length;
const pageCount = Math.ceil(total / this.localPagingSize);
this.page = {
number: 0,
totalPages: pageCount,
totalElements: total,
first: true,
last: false,
numberOfElements: this.localPagingSize,
content: (this.data as any[]).slice(0, this.localPagingSize)
};
if (this.localSubscription) {
this.localSubscription.unsubscribe();
}
this.localSubscription = this.pageChange.subscribe((event) => this.calculateLocalPage(event));
} else if (this.localFilter) {
this.page = this.createLocalPage();
if (this.localSubscription) {
this.localSubscription.unsubscribe();
}
this.localSubscription = this.pageChange.subscribe((event) => this.calculateLocalPageNoPagination(event));
} else {
this.page = this.createLocalPage();
}
}
private calculateLocalPageNoPagination(event: SharkPageChangeEvent): void {
if (((event.filter && event.filter.length > 0)) || this.tableUtils.hasFilter(event.columns)) {
const filteredContent = this.tableUtils.filter(this.data, this.currentColumns, this.columnFiltering, event.filter);
this.page = {
number: 0,
totalPages: 1,
totalElements: filteredContent.length,
first: true,
last: false,
numberOfElements: filteredContent.length,
content: filteredContent
};
} else {
this.page = this.createLocalPage();
}
}
private calculateLocalPage(event: SharkPageChangeEvent): void {
let content;
if (this.localFilter && ((event.filter && event.filter.length > 0)) || this.tableUtils.hasFilter(event.columns)) {
content = this.tableUtils.filter(this.data, this.currentColumns, this.columnFiltering, event.filter);
} else {
content = (this.data as any[]);
}
this.sort(content, this.generateSortArray());
const total = content.length;
// IntelliJ claims this * 1 call is useless, but we need to make sure it's a number
const pageSize: number = (this.localPagingSize > content.length ? content.length : this.localPagingSize) * 1;
const pageCount = total === 0 ? 0 : Math.ceil(total / pageSize);
const pageNo = event.pageNo > pageCount || content.length <= pageSize ? 0 : event.pageNo;
const sliceRange = pageSize * pageNo + pageSize;
const displayedContent = content.slice((pageSize * pageNo), sliceRange);
this.page = {
number: pageNo,
totalPages: pageCount,
totalElements: total,
first: pageNo === 0,
last: pageNo === pageCount,
numberOfElements: pageSize,
content: displayedContent
};
}
private setupPageSubscription(): void {
// Fix potential memory leak, by unsubscribing to previous subscription if exists
if (this.dataSubscription) {
this.dataSubscription.unsubscribe();
}
this.dataSubscription = (this.data as Observable<Page | any[]>).subscribe((data: Page | any[]) => {
if (data.constructor === Array) {
this.page = this.createLocalPage(data as any[]);
} else {
this.page = data as Page;
}
});
}
private setupInitialSort() {
if (this.initialSort) {
const sorts = this.initialSort.split(';');
sorts.forEach((sort: string) => {
this.columns.forEach((column: SharkColumn) => {
let type = SharkSortType.NONE;
let property = sort;
if (sort.startsWith('-')) {
type = SharkSortType.DESC;
property = property.substr(1);
} else {
type = SharkSortType.ASC;
}
if (property === column.property) {
column.sortType = type;
}
});
});
this.changeSort('', undefined);
}
if (this.page.sorts && this.page.sorts.length > 0) {
this.columns.forEach((column: SharkColumn) => {
this.page.sorts.forEach((sort: Sort) => {
if (column.property === sort.property) {
column.sortType = SharkSortType.NONE;
if (sort.ascending) {
column.sortType = SharkSortType.ASC;
} else if (sort.descending) {
column.sortType = SharkSortType.DESC;
}
}
});
});
if (!this.serverSideData) {
this.changeSort('', undefined);
}
}
}
} | import { Router } from '@angular/router'; |
standalone.rs | // Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
use crate::deno_dir::DenoDir;
use crate::flags::CheckFlag;
use crate::flags::DenoSubcommand;
use crate::flags::Flags;
use crate::flags::RunFlags;
use crate::standalone::Metadata;
use crate::standalone::MAGIC_TRAILER;
use crate::ProcState;
use deno_core::anyhow::bail;
use deno_core::anyhow::Context;
use deno_core::error::AnyError;
use deno_core::serde_json;
use deno_core::url::Url;
use deno_graph::ModuleSpecifier;
use deno_runtime::permissions::Permissions;
use std::env;
use std::fs::read;
use std::fs::File;
use std::io::Read;
use std::io::Seek;
use std::io::SeekFrom;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
pub async fn get_base_binary(
deno_dir: &DenoDir,
target: Option<String>,
) -> Result<Vec<u8>, AnyError> {
if target.is_none() {
let path = std::env::current_exe()?;
return Ok(tokio::fs::read(path).await?);
} |
let target = target.unwrap_or_else(|| env!("TARGET").to_string());
let binary_name = format!("deno-{}.zip", target);
let binary_path_suffix = if crate::version::is_canary() {
format!("canary/{}/{}", crate::version::GIT_COMMIT_HASH, binary_name)
} else {
format!("release/v{}/{}", env!("CARGO_PKG_VERSION"), binary_name)
};
let download_directory = deno_dir.root.join("dl");
let binary_path = download_directory.join(&binary_path_suffix);
if !binary_path.exists() {
download_base_binary(&download_directory, &binary_path_suffix).await?;
}
let archive_data = tokio::fs::read(binary_path).await?;
let base_binary_path =
crate::tools::upgrade::unpack(archive_data, target.contains("windows"))?;
let base_binary = tokio::fs::read(base_binary_path).await?;
Ok(base_binary)
}
async fn download_base_binary(
output_directory: &Path,
binary_path_suffix: &str,
) -> Result<(), AnyError> {
let download_url = format!("https://dl.deno.land/{}", binary_path_suffix);
let client_builder = Client::builder();
let client = client_builder.build()?;
println!("Checking {}", &download_url);
let res = client.get(&download_url).send().await?;
let binary_content = if res.status().is_success() {
println!("Download has been found");
res.bytes().await?.to_vec()
} else {
println!("Download could not be found, aborting");
std::process::exit(1)
};
std::fs::create_dir_all(&output_directory)?;
let output_path = output_directory.join(binary_path_suffix);
std::fs::create_dir_all(&output_path.parent().unwrap())?;
tokio::fs::write(output_path, binary_content).await?;
Ok(())
}
/// This functions creates a standalone deno binary by appending a bundle
/// and magic trailer to the currently executing binary.
pub async fn create_standalone_binary(
mut original_bin: Vec<u8>,
eszip: eszip::EszipV2,
entrypoint: ModuleSpecifier,
flags: Flags,
ps: ProcState,
) -> Result<Vec<u8>, AnyError> {
let mut eszip_archive = eszip.into_bytes();
let ca_data = match &flags.ca_file {
Some(ca_file) => Some(read(ca_file)?),
None => None,
};
let maybe_import_map: Option<(Url, String)> = match flags
.import_map_path
.as_ref()
{
None => None,
Some(import_map_url) => {
let import_map_specifier = deno_core::resolve_url_or_path(import_map_url)
.context(format!("Bad URL (\"{}\") for import map.", import_map_url))?;
let file = ps
.file_fetcher
.fetch(&import_map_specifier, &mut Permissions::allow_all())
.await
.context(format!(
"Unable to load '{}' import map",
import_map_specifier
))?;
Some((import_map_specifier, file.source.to_string()))
}
};
let metadata = Metadata {
argv: flags.argv.clone(),
unstable: flags.unstable,
seed: flags.seed,
location: flags.location.clone(),
permissions: flags.permissions_options(),
v8_flags: flags.v8_flags.clone(),
unsafely_ignore_certificate_errors: flags
.unsafely_ignore_certificate_errors
.clone(),
log_level: flags.log_level,
ca_stores: flags.ca_stores,
ca_data,
entrypoint,
maybe_import_map,
};
let mut metadata = serde_json::to_string(&metadata)?.as_bytes().to_vec();
let eszip_pos = original_bin.len();
let metadata_pos = eszip_pos + eszip_archive.len();
let mut trailer = MAGIC_TRAILER.to_vec();
trailer.write_all(&eszip_pos.to_be_bytes())?;
trailer.write_all(&metadata_pos.to_be_bytes())?;
let mut final_bin = Vec::with_capacity(
original_bin.len() + eszip_archive.len() + trailer.len(),
);
final_bin.append(&mut original_bin);
final_bin.append(&mut eszip_archive);
final_bin.append(&mut metadata);
final_bin.append(&mut trailer);
Ok(final_bin)
}
/// This function writes out a final binary to specified path. If output path
/// is not already standalone binary it will return error instead.
pub async fn write_standalone_binary(
output: PathBuf,
target: Option<String>,
final_bin: Vec<u8>,
) -> Result<(), AnyError> {
let output = match target {
Some(target) => {
if target.contains("windows") {
output.with_extension("exe")
} else {
output
}
}
None => {
if cfg!(windows) && output.extension().unwrap_or_default() != "exe" {
output.with_extension("exe")
} else {
output
}
}
};
if output.exists() {
// If the output is a directory, throw error
if output.is_dir() {
bail!("Could not compile: {:?} is a directory.", &output);
}
// Make sure we don't overwrite any file not created by Deno compiler.
// Check for magic trailer in last 24 bytes.
let mut has_trailer = false;
let mut output_file = File::open(&output)?;
// This seek may fail because the file is too small to possibly be
// `deno compile` output.
if output_file.seek(SeekFrom::End(-24)).is_ok() {
let mut trailer = [0; 24];
output_file.read_exact(&mut trailer)?;
let (magic_trailer, _) = trailer.split_at(8);
has_trailer = magic_trailer == MAGIC_TRAILER;
}
if !has_trailer {
bail!("Could not compile: cannot overwrite {:?}.", &output);
}
// Remove file if it was indeed a deno compiled binary, to avoid corruption
// (see https://github.com/denoland/deno/issues/10310)
std::fs::remove_file(&output)?;
} else {
let output_base = &output.parent().unwrap();
if output_base.exists() && output_base.is_file() {
bail!("Could not compile: {:?} is a file.", &output_base);
}
tokio::fs::create_dir_all(output_base).await?;
}
tokio::fs::write(&output, final_bin).await?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let perms = std::fs::Permissions::from_mode(0o777);
tokio::fs::set_permissions(output, perms).await?;
}
Ok(())
}
/// Transform the flags passed to `deno compile` to flags that would be used at
/// runtime, as if `deno run` were used.
/// - Flags that affect module resolution, loading, type checking, etc. aren't
/// applicable at runtime so are set to their defaults like `false`.
/// - Other flags are inherited.
pub fn compile_to_runtime_flags(
flags: &Flags,
baked_args: Vec<String>,
) -> Result<Flags, AnyError> {
// IMPORTANT: Don't abbreviate any of this to `..flags` or
// `..Default::default()`. That forces us to explicitly consider how any
// change to `Flags` should be reflected here.
Ok(Flags {
argv: baked_args,
subcommand: DenoSubcommand::Run(RunFlags {
script: "placeholder".to_string(),
}),
allow_all: flags.allow_all,
allow_env: flags.allow_env.clone(),
allow_hrtime: flags.allow_hrtime,
allow_net: flags.allow_net.clone(),
allow_ffi: flags.allow_ffi.clone(),
allow_read: flags.allow_read.clone(),
allow_run: flags.allow_run.clone(),
allow_write: flags.allow_write.clone(),
ca_stores: flags.ca_stores.clone(),
ca_file: flags.ca_file.clone(),
cache_blocklist: vec![],
cache_path: None,
cached_only: false,
config_path: None,
coverage_dir: flags.coverage_dir.clone(),
enable_testing_features: false,
ignore: vec![],
import_map_path: flags.import_map_path.clone(),
inspect_brk: None,
inspect: None,
location: flags.location.clone(),
lock_write: false,
lock: None,
log_level: flags.log_level,
check: CheckFlag::All,
compat: flags.compat,
unsafely_ignore_certificate_errors: flags
.unsafely_ignore_certificate_errors
.clone(),
no_remote: false,
no_prompt: flags.no_prompt,
reload: false,
repl: false,
seed: flags.seed,
unstable: flags.unstable,
v8_flags: flags.v8_flags.clone(),
version: false,
watch: None,
no_clear_screen: false,
})
} | |
prefer-explicit-assert.ts | import { TSESTree, ASTUtils } from '@typescript-eslint/experimental-utils';
import { PRESENCE_MATCHERS, ABSENCE_MATCHERS } from '../utils';
import { findClosestCallNode, isMemberExpression } from '../node-utils';
import { createTestingLibraryRule } from '../create-testing-library-rule';
export const RULE_NAME = 'prefer-explicit-assert';
export type MessageIds =
| 'preferExplicitAssert'
| 'preferExplicitAssertAssertion';
type Options = [
{
assertion?: string;
}
];
const isAtTopLevel = (node: TSESTree.Node) =>
!!node?.parent?.parent && node.parent.parent.type === 'ExpressionStatement';
export default createTestingLibraryRule<Options, MessageIds>({
name: RULE_NAME, | docs: {
description:
'Suggest using explicit assertions rather than just `getBy*` queries',
category: 'Best Practices',
recommendedConfig: {
dom: false,
angular: false,
react: false,
vue: false,
},
},
messages: {
preferExplicitAssert:
'Wrap stand-alone `getBy*` query with `expect` function for better explicit assertion',
preferExplicitAssertAssertion:
'`getBy*` queries must be asserted with `{{assertion}}`',
},
schema: [
{
type: 'object',
additionalProperties: false,
properties: {
assertion: {
type: 'string',
enum: PRESENCE_MATCHERS,
},
},
},
],
},
defaultOptions: [{}],
create(context, [options], helpers) {
const { assertion } = options;
const getQueryCalls: TSESTree.Identifier[] = [];
return {
'CallExpression Identifier'(node: TSESTree.Identifier) {
if (helpers.isGetQueryVariant(node)) {
getQueryCalls.push(node);
}
},
'Program:exit'() {
getQueryCalls.forEach((queryCall) => {
const node = isMemberExpression(queryCall.parent)
? queryCall.parent
: queryCall;
if (isAtTopLevel(node)) {
context.report({
node: queryCall,
messageId: 'preferExplicitAssert',
});
}
if (assertion) {
const expectCallNode = findClosestCallNode(node, 'expect');
if (!expectCallNode) return;
const expectStatement = expectCallNode.parent as TSESTree.MemberExpression;
const property = expectStatement.property as TSESTree.Identifier;
let matcher = property.name;
let isNegatedMatcher = false;
if (
matcher === 'not' &&
isMemberExpression(expectStatement.parent) &&
ASTUtils.isIdentifier(expectStatement.parent.property)
) {
isNegatedMatcher = true;
matcher = expectStatement.parent.property.name;
}
const shouldEnforceAssertion =
(!isNegatedMatcher && PRESENCE_MATCHERS.includes(matcher)) ||
(isNegatedMatcher && ABSENCE_MATCHERS.includes(matcher));
if (shouldEnforceAssertion && matcher !== assertion) {
context.report({
node: property,
messageId: 'preferExplicitAssertAssertion',
data: {
assertion,
},
});
}
}
});
},
};
},
}); | meta: {
type: 'suggestion', |
static.go | package main
import (
"bytes"
"flag"
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"os"
"path"
"path/filepath"
"strings"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/extension"
"github.com/yuin/goldmark/parser"
"github.com/yuin/goldmark/renderer/html"
)
var markdownTemplate, _ = template.New("markdown").Parse(`<!doctype html>
<html>
<head>
<link rel="shortcut icon"type="image/x-icon" href="data:image/x-icon;,">
<title>{{.Name}}</title>
{{- if .CSS}}
<link rel="stylesheet" href="{{.CSS}}">
{{- else}}
<style>
html {
-ms-text-size-adjust: 100%;
-webkit-text-size-adjust: 100%;
font-family: sans-serif;
}
body {
margin: 0;
padding: 30px;
/*min-width: 1020px;*/
background-color: #fff;
color: #333333;
font: 13px Helvetica, arial, freesans, clean, sans-serif;
line-height: 1.4;
}
body > *:first-child {
margin-top: 0 !important;
}
body > *:last-child {
margin-bottom: 0 !important;
}
a {
color: #4183c4;
text-decoration: none;
}
a:hover {
outline: 0;
text-decoration: underline;
}
a:focus {
outline: thin dotted;
text-decoration: underline;
}
a:active {
outline: 0;
text-decoration: underline;
}
h1, h2, h3, h4, h5, h6 {
position: relative;
margin: 1em 0 15px;
padding: 0;
font-weight: bold;
line-height: 1.7;
cursor: text;
}
/*h1:hover a.anchor, h2:hover a.anchor, h3:hover a.anchor, h4:hover a.anchor, h5:hover a.anchor, h6:hover a.anchor {
top: 15%;
margin-left: -30px;
padding-left: 8px;
text-decoration: none;
line-height: 1;
}*/
h1 code, h2 code, h3 code, h4 code, h5 code, h6 code {
font-size: inherit;
}
h1 {
border-bottom: 1px solid #ddd;
font-size: 2.5em;
}
h2 {
border-bottom: 1px solid #eee;
font-size: 2em;
}
h3 {
font-size: 1.5em;
}
h4 {
font-size: 1.2em;
}
h5 {
font-size: 1em;
}
h6 {
color: #777;
font-size: 1em;
}
b, strong {
font-weight: bold;
}
hr:before, hr:after {
display: table;
content: " ";
}
hr:after {
clear: both;
}
sub, sup {
position: relative;
vertical-align: baseline;
font-size: 75%;
line-height: 0;
}
sup {
top: -0.5em;
}
sub {
bottom: -0.25em;
}
img {
-moz-box-sizing: border-box;
box-sizing: border-box;
max-width: 100%;
border: 0;
}
code, pre {
font-size: 12px;
font-family: Consolas, "Liberation Mono", Courier, monospace;
}
pre {
margin-top: 0;
margin-bottom: 0;
}
a.anchor:focus {
outline: none;
}
p, blockquote, ul, ol, dl, table, pre {
margin: 15px 0;
}
ul, ol {
margin-top: 0;
margin-bottom: 0;
padding: 0;
padding-left: 30px;
}
ul.no-list, ol.no-list {
padding: 0;
list-style-type: none;
}
ul ul, ul ol, ol ol, ol ul {
margin-top: 0;
margin-bottom: 0;
}
dl {
padding: 0;
}
blockquote {
padding: 0 15px;
border-left: 4px solid #DDD;
color: #777;
}
table {
display: block;
overflow: auto;
width: 100%;
border-collapse: collapse;
}
table th, table td {
padding: 6px 13px;
border: 1px solid #ddd;
}
table tr:nth-child(2n) {
background-color: #f8f8f8;
}
/* TODO: Something in here is stripping line-breaks */
code {
display: inline-block;
overflow: auto;
margin: 0;
padding: 0;
max-width: 100%;
border: 1px solid #ddd;
border-radius: 3px;
background-color: #f8f8f8;
vertical-align: middle;
/*white-space: nowrap;*/
line-height: 1.3;
}
code:before, code:after {
content: "\00a0";
letter-spacing: -0.2em;
}
pre {
overflow: auto;
/*padding: 6px 10px;*/
padding: 2px 3px;
border: 1px solid #ddd;
border-radius: 3px;
background-color: #f8f8f8;
word-wrap: normal;
font-size: 13px;
line-height: 1.2em;
}
pre code {
display: inline;
overflow: initial;
margin: 0;
padding: 0;
max-width: initial;
border: none;
background-color: transparent;
word-wrap: normal;
line-height: inherit;
}
pre code:before, pre code:after {
content: normal;
}
/* breadcrumbs */
nav {
position: fixed;
width: 100%;
top: 0;
left: 0;
padding: 0 15px;
border-bottom: 1px solid rgb(220, 220, 220);
background: rgb(235, 235, 235);
color: rgb(120, 120, 120);
z-index: 9999;
}
nav ol {
list-style-type: none;
padding: 0;
}
nav ol li {
display: inline;
}
nav ol li+li::before {
content: ' | ';
margin: 5px;
}
nav a:visited {
color: #4183c4;
}
</style>{{end}}
<!--<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.10/styles/default.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.10/highlight.min.js"></script>-->
</head>
<body>
{{.Content}}
<script>
~function (d) {
'use strict';
//var pres = d.querySelectorAll('div.highlight > pre');
var codes = d.querySelectorAll('pre > code');
console.log(codes.length)
if (codes.length > 0) {
var css = d.createElement('link'),
js = d.createElement('script');
//css.setAttribute('rel', 'stylesheet');
//css.setAttribute('href', '//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.10/styles/default.min.css');
//js.setAttribute('src', '//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.10/highlight.min.js');
css.async = true;
css.rel = 'stylesheet';
//css.href = '//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/styles/default.min.css';
css.href = '/_/highlightjs/styles/github-gist.css';
js.async = true;
//js.src = '//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/highlight.min.js';
js.src = '/_/highlightjs/highlight.pack.js';
js.onreadystatechange = js.onload = function () {
if (!js.readyState || /loaded|complete/.test(js.readyState)) {
Array.prototype.forEach.call(codes, function (block) { hljs.highlightBlock(block); });
}
}
d.head.appendChild(css);
d.head.appendChild(js);
}
}(document);
// breadcrumbs
~function (d) {
'use strict';
function pathElem(path, name, isCurrent) {
var elem = document.createElement('li'),
text;
if (isCurrent) {
text = document.createElement('span');
} else {
text = document.createElement('a');
//text.href = path == '/' ? '/index.md' : path + '/index.md';
text.href = path
}
text.textContent = name;
elem.appendChild(text);
return elem;
}
function breadcrumbElem(paths) {
var elem = d.createElement('ol'),
path;
elem.appendChild(pathElem('/', 'home'));
for (var i=0; i<paths.length; i++) {
path = [path, paths[i]].join('/');
elem.appendChild(pathElem(path, paths[i], i == paths.length-1));
}
return elem;
}
var paths = d.location.pathname.split('/'),
breadcrumb = breadcrumbElem(paths.slice(1)),
nav = d.createElement('nav');
nav.appendChild(breadcrumb);
d.body.insertBefore(nav, d.body.firstChild);
//hljs.initHighlightingOnLoad();
}(document);
</script>
</body>
</html>
`)
type variables struct {
Name, CSS string
Content template.HTML
}
func markdownToHTML(file string) ([]byte, error) {
cwd, err := os.Getwd()
if err != nil {
return nil, err
}
data, err := ioutil.ReadFile(path.Join(cwd, file))
if err != nil {
return nil, err
}
md := goldmark.New(
goldmark.WithExtensions(
extension.GFM,
extension.Footnote,
extension.Linkify,
extension.Strikethrough,
extension.Table,
extension.TaskList,
extension.Typographer,
),
goldmark.WithParserOptions(
parser.WithAutoHeadingID(),
parser.WithBlockParsers(),
),
goldmark.WithRendererOptions(
html.WithUnsafe(),
),
)
var buf bytes.Buffer
err = md.Convert(data, &buf)
if err != nil {
return nil, err
}
return buf.Bytes(), err
}
func writeMarkDown(w http.ResponseWriter, name, css string, md []byte) error {
content := template.HTML(md)
return markdownTemplate.Execute(w, variables{name, css, content})
}
func handleFileError(w http.ResponseWriter, err error) bool {
if err == nil {
return false
}
status := 500
if err.Error() == "no such file or directory" {
status = 404
}
http.Error(w, err.Error(), status)
return true
}
func | (r *http.Request) string {
p := r.URL.Path
if !strings.HasPrefix(p, "/") {
p = "/" + p
r.URL.Path = p
}
return path.Clean(p)
}
func markdownHandler(root string) http.Handler {
svr := http.FileServer(http.Dir(root))
fn := func(w http.ResponseWriter, r *http.Request) {
p := cleanRequestPath(r)
_, isRaw := r.URL.Query()["raw"]
if filepath.Ext(p) != ".md" || isRaw {
svr.ServeHTTP(w, r)
return
}
md, err := markdownToHTML(p)
if handleFileError(w, err) {
return
}
css := r.URL.Query().Get("css")
writeMarkDown(w, p, css, md)
}
return http.HandlerFunc(fn)
}
func singlePageHandler(root string) http.Handler {
indexPath := path.Join(root, "index.html")
svr := http.FileServer(http.Dir(root))
fn := func(w http.ResponseWriter, r *http.Request) {
p := cleanRequestPath(r)
if filepath.Ext(p) != "" {
svr.ServeHTTP(w, r)
return
}
b, err := ioutil.ReadFile(indexPath)
if handleFileError(w, err) {
return
}
w.Header().Set("Content-type", "text/html")
w.Write(b)
}
return http.HandlerFunc(fn)
}
func main() {
d, err := os.Getwd()
if err != nil {
log.Fatalln(err)
}
p := flag.Int("port", 9000, "Port number")
path := flag.String("path", d, "Content path")
isSinglePage := flag.Bool("single", false, "Whether this is a single page site or not (eg. react-router)")
flag.Parse()
port := fmt.Sprintf(":%d", *p)
fmt.Printf("static listener on \"%s\" at path \"%s\"\n", port, *path)
var handler http.Handler
if *isSinglePage {
handler = singlePageHandler(*path)
} else {
http.Handle("/", markdownHandler(*path))
}
err = http.ListenAndServe(port, handler)
log.Fatalln(err)
}
| cleanRequestPath |
step_functions.py | import os
from collections import defaultdict
import sys
import hashlib
import json
import time
import string
import random
import uuid
from metaflow.exception import MetaflowException, MetaflowInternalError
from metaflow.plugins import ResourcesDecorator, BatchDecorator, RetryDecorator
from metaflow.parameters import deploy_time_eval
from metaflow.decorators import flow_decorators
from metaflow.util import compress_list, dict_to_cli_options, to_pascalcase
from metaflow.metaflow_config import (
SFN_IAM_ROLE,
EVENTS_SFN_ACCESS_IAM_ROLE,
SFN_DYNAMO_DB_TABLE,
SFN_EXECUTION_LOG_GROUP_ARN,
)
from metaflow import R
from .step_functions_client import StepFunctionsClient
from .event_bridge_client import EventBridgeClient
from ..batch.batch import Batch
class StepFunctionsException(MetaflowException):
headline = "AWS Step Functions error"
class StepFunctionsSchedulingException(MetaflowException):
headline = "AWS Step Functions scheduling error"
class StepFunctions(object):
def __init__(
self,
name,
graph,
flow,
code_package_sha,
code_package_url,
production_token,
metadata,
flow_datastore,
environment,
event_logger,
monitor,
tags=None,
namespace=None,
username=None,
max_workers=None,
workflow_timeout=None,
is_project=False,
):
self.name = name
self.graph = graph
self.flow = flow
self.code_package_sha = code_package_sha
self.code_package_url = code_package_url
self.production_token = production_token
self.metadata = metadata
self.flow_datastore = flow_datastore
self.environment = environment
self.event_logger = event_logger
self.monitor = monitor
self.tags = tags
self.namespace = namespace
self.username = username
self.max_workers = max_workers
self.workflow_timeout = workflow_timeout
self._client = StepFunctionsClient()
self._workflow = self._compile()
self._cron = self._cron()
self._state_machine_arn = None
def to_json(self):
return self._workflow.to_json(pretty=True)
def trigger_explanation(self):
if self._cron:
# Sometime in the future, we should vendor (or write) a utility
# that can translate cron specifications into a human readable
# format and push to the user for a better UX, someday.
return (
"This workflow triggers automatically "
"via a cron schedule *%s* defined in AWS EventBridge."
% self.event_bridge_rule
)
else:
return "No triggers defined. " "You need to launch this workflow manually."
def deploy(self, log_execution_history):
if SFN_IAM_ROLE is None:
raise StepFunctionsException(
"No IAM role found for AWS Step "
"Functions. You can create one "
"following the instructions listed at "
"*https://admin-docs.metaflow.org/meta"
"flow-on-aws/deployment-guide/manual-d"
"eployment#scheduling* and "
"re-configure Metaflow using "
"*metaflow configure aws* on your "
"terminal."
)
if log_execution_history:
if SFN_EXECUTION_LOG_GROUP_ARN is None:
raise StepFunctionsException(
"No AWS CloudWatch Logs log "
"group ARN found for emitting "
"state machine execution logs for "
"your workflow. You can set it in "
"your environment by using the "
"METAFLOW_SFN_EXECUTION_LOG_GROUP_ARN "
"environment variable."
)
try:
self._state_machine_arn = self._client.push(
name=self.name,
definition=self.to_json(),
role_arn=SFN_IAM_ROLE,
log_execution_history=log_execution_history,
)
except Exception as e:
raise StepFunctionsException(repr(e))
def schedule(self):
# Scheduling is currently enabled via AWS Event Bridge.
if EVENTS_SFN_ACCESS_IAM_ROLE is None:
raise StepFunctionsSchedulingException(
"No IAM role found for AWS "
"Events Bridge. You can "
"create one following the "
"instructions listed at "
"*https://admin-docs.metaflo"
"w.org/metaflow-on-aws/deplo"
"yment-guide/manual-deployme"
"nt#scheduling* and "
"re-configure Metaflow "
"using *metaflow configure "
"aws* on your terminal."
)
try:
self.event_bridge_rule = (
EventBridgeClient(self.name)
.cron(self._cron)
.role_arn(EVENTS_SFN_ACCESS_IAM_ROLE)
.state_machine_arn(self._state_machine_arn)
.schedule()
)
except Exception as e:
raise StepFunctionsSchedulingException(repr(e))
@classmethod
def trigger(cls, name, parameters):
try:
state_machine = StepFunctionsClient().get(name)
except Exception as e:
raise StepFunctionsException(repr(e))
if state_machine is None:
raise StepFunctionsException(
"The workflow *%s* doesn't exist "
"on AWS Step Functions. Please "
"deploy your flow first." % name
)
# Dump parameters into `Parameters` input field.
input = json.dumps({"Parameters": json.dumps(parameters)})
# AWS Step Functions limits input to be 32KiB, but AWS Batch
# has it's own limitation of 30KiB for job specification length.
# Reserving 10KiB for rest of the job sprecification leaves 20KiB
# for us, which should be enough for most use cases for now.
if len(input) > 20480:
raise StepFunctionsException(
"Length of parameter names and "
"values shouldn't exceed 20480 as "
"imposed by AWS Step Functions."
)
try:
state_machine_arn = state_machine.get("stateMachineArn")
return StepFunctionsClient().trigger(state_machine_arn, input)
except Exception as e:
raise StepFunctionsException(repr(e))
@classmethod
def list(cls, name, states):
try:
state_machine = StepFunctionsClient().get(name)
except Exception as e:
raise StepFunctionsException(repr(e))
if state_machine is None:
raise StepFunctionsException(
"The workflow *%s* doesn't exist " "on AWS Step Functions." % name
)
try:
state_machine_arn = state_machine.get("stateMachineArn")
return StepFunctionsClient().list_executions(state_machine_arn, states)
except Exception as e:
raise StepFunctionsException(repr(e))
@classmethod
def get_existing_deployment(cls, name):
workflow = StepFunctionsClient().get(name)
if workflow is not None:
try:
start = json.loads(workflow["definition"])["States"]["start"]
parameters = start["Parameters"]["Parameters"]
return parameters.get("metaflow.owner"), parameters.get(
"metaflow.production_token"
)
except KeyError as e:
raise StepFunctionsException(
"An existing non-metaflow "
"workflow with the same name as "
"*%s* already exists in AWS Step "
"Functions. Please modify the "
"name of this flow or delete your "
"existing workflow on AWS Step "
"Functions." % name
)
return None
def _compile(self):
# Visit every node of the flow and recursively build the state machine.
def _visit(node, workflow, exit_node=None):
# Assign an AWS Batch job to the AWS Step Functions state
# and pass the intermediate state by exposing `JobId` and
# `Parameters` to the child job(s) as outputs. `Index` and
# `SplitParentTaskId` are populated optionally, when available.
# We can't modify the names of keys in AWS Step Functions aside
# from a blessed few which are set as `Parameters` for the Map
# state. That's why even though `JobId` refers to the parent task
# id, we can't call it as such. Similar situation for `Parameters`.
state = (
State(node.name)
.batch(self._batch(node))
.output_path(
"$.['JobId', " "'Parameters', " "'Index', " "'SplitParentTaskId']"
)
)
# End the (sub)workflow if we have reached the end of the flow or
# the parent step of matching_join of the sub workflow.
if node.type == "end" or exit_node in node.out_funcs:
workflow.add_state(state.end())
# Continue linear assignment within the (sub)workflow if the node
# doesn't branch or fork.
elif node.type in ("linear", "join"):
workflow.add_state(state.next(node.out_funcs[0]))
_visit(self.graph[node.out_funcs[0]], workflow, exit_node)
# Create a `Parallel` state and assign sub workflows if the node
# branches out.
elif node.type == "split-and":
branch_name = hashlib.sha224(
"&".join(node.out_funcs).encode("utf-8")
).hexdigest()
workflow.add_state(state.next(branch_name))
branch = Parallel(branch_name).next(node.matching_join)
# Generate as many sub workflows as branches and recurse.
for n in node.out_funcs:
branch.branch(
_visit(
self.graph[n], Workflow(n).start_at(n), node.matching_join
)
)
workflow.add_state(branch)
# Continue the traversal from the matching_join.
_visit(self.graph[node.matching_join], workflow, exit_node)
# Create a `Map` state and assign sub workflow if the node forks.
elif node.type == "foreach":
# Fetch runtime cardinality via an AWS DynamoDb Get call before
# configuring the node
cardinality_state_name = "#%s" % node.out_funcs[0]
workflow.add_state(state.next(cardinality_state_name))
cardinality_state = (
State(cardinality_state_name)
.dynamo_db(SFN_DYNAMO_DB_TABLE, "$.JobId", "for_each_cardinality")
.result_path("$.Result")
)
iterator_name = "*%s" % node.out_funcs[0]
workflow.add_state(cardinality_state.next(iterator_name))
workflow.add_state(
Map(iterator_name)
.items_path("$.Result.Item.for_each_cardinality.NS")
.parameter("JobId.$", "$.JobId")
.parameter("SplitParentTaskId.$", "$.JobId")
.parameter("Parameters.$", "$.Parameters")
.parameter("Index.$", "$$.Map.Item.Value")
.next(node.matching_join)
.iterator(
_visit(
self.graph[node.out_funcs[0]],
Workflow(node.out_funcs[0]).start_at(node.out_funcs[0]),
node.matching_join,
)
)
.max_concurrency(self.max_workers)
.output_path("$.[0]")
)
# Continue the traversal from the matching_join.
_visit(self.graph[node.matching_join], workflow, exit_node)
# We shouldn't ideally ever get here.
else:
raise StepFunctionsException(
"Node type *%s* for step *%s* "
"is not currently supported by "
"AWS Step Functions." % (node.type, node.name)
)
return workflow
workflow = Workflow(self.name).start_at("start")
if self.workflow_timeout:
workflow.timeout_seconds(self.workflow_timeout)
return _visit(self.graph["start"], workflow)
def _cron(self):
schedule = self.flow._flow_decorators.get("schedule")
if schedule:
return schedule.schedule
return None
def _process_parameters(self):
parameters = []
has_schedule = self._cron() is not None
seen = set()
for var, param in self.flow._get_parameters():
# Throw an exception if the parameter is specified twice.
norm = param.name.lower()
if norm in seen:
raise MetaflowException(
"Parameter *%s* is specified twice. "
"Note that parameter names are "
"case-insensitive." % param.name
)
seen.add(norm)
is_required = param.kwargs.get("required", False)
# Throw an exception if a schedule is set for a flow with required
# parameters with no defaults. We currently don't have any notion
# of data triggers in AWS Event Bridge.
if "default" not in param.kwargs and is_required and has_schedule:
raise MetaflowException(
"The parameter *%s* does not have a "
"default and is required. Scheduling "
"such parameters via AWS Event Bridge "
"is not currently supported." % param.name
)
value = deploy_time_eval(param.kwargs.get("default"))
parameters.append(dict(name=param.name, value=value))
return parameters
def _batch(self, node):
attrs = {
# metaflow.user is only used for setting the AWS Job Name.
# Since job executions are no longer tied to a specific user
# identity, we will just set their user to `SFN`. We still do need
# access to the owner of the workflow for production tokens, which
# we can stash in metaflow.owner.
"metaflow.user": "SFN",
"metaflow.owner": self.username,
"metaflow.flow_name": self.flow.name,
"metaflow.step_name": node.name,
"metaflow.run_id.$": "$$.Execution.Name",
# Unfortunately we can't set the task id here since AWS Step
# Functions lacks any notion of run-scoped task identifiers. We
# instead co-opt the AWS Batch job id as the task id. This also
# means that the AWS Batch job name will have missing fields since
# the job id is determined at job execution, but since the job id is
# part of the job description payload, we don't lose much except for
# a few ugly looking black fields in the AWS Batch UI.
# Also, unfortunately we can't set the retry count since
# `$$.State.RetryCount` resolves to an int dynamically and
# AWS Batch job specification only accepts strings. We handle
# retries/catch within AWS Batch to get around this limitation.
"metaflow.version": self.environment.get_environment_info()[
"metaflow_version"
],
# We rely on step names and task ids of parent steps to construct
# input paths for a task. Since the only information we can pass
# between states (via `InputPath` and `ResultPath`) in AWS Step
# Functions is the job description, we run the risk of exceeding
# 32K state size limit rather quickly if we don't filter the job
# description to a minimal set of fields. Unfortunately, the partial
# `JsonPath` implementation within AWS Step Functions makes this
# work a little non-trivial; it doesn't like dots in keys, so we
# have to add the field again.
# This pattern is repeated in a lot of other places, where we use
# AWS Batch parameters to store AWS Step Functions state
# information, since this field is the only field in the AWS Batch
# specification that allows us to set key-values.
"step_name": node.name,
}
# Store production token within the `start` step, so that subsequent
# `step-functions create` calls can perform a rudimentary authorization
# check.
if node.name == "start":
attrs["metaflow.production_token"] = self.production_token
# Add env vars from the optional @environment decorator.
env_deco = [deco for deco in node.decorators if deco.name == "environment"]
env = {}
if env_deco:
env = env_deco[0].attributes["vars"]
if node.name == "start":
# Initialize parameters for the flow in the `start` step.
parameters = self._process_parameters()
if parameters:
# Get user-defined parameters from State Machine Input.
# Since AWS Step Functions doesn't allow for optional inputs
# currently, we have to unfortunately place an artificial
# constraint that every parameterized workflow needs to include
# `Parameters` as a key in the input to the workflow.
# `step-functions trigger` already takes care of this
# requirement, but within the UI, the users will be required to
# specify an input with key as `Parameters` and value as a
# stringified json of the actual parameters -
# {"Parameters": "{\"alpha\": \"beta\"}"}
env["METAFLOW_PARAMETERS"] = "$.Parameters"
default_parameters = {}
for parameter in parameters:
if parameter["value"] is not None:
default_parameters[parameter["name"]] = parameter["value"]
# Dump the default values specified in the flow.
env["METAFLOW_DEFAULT_PARAMETERS"] = json.dumps(default_parameters)
# `start` step has no upstream input dependencies aside from
# parameters.
input_paths = None
else:
# We need to rely on the `InputPath` of the AWS Step Functions
# specification to grab task ids and the step names of the parent
# to properly construct input_paths at runtime. Thanks to the
# JsonPath-foo embedded in the parent states, we have this
# information easily available.
# Handle foreach join.
if (
node.type == "join"
and self.graph[node.split_parents[-1]].type == "foreach"
):
input_paths = (
"sfn-${METAFLOW_RUN_ID}/%s/:"
"${METAFLOW_PARENT_TASK_IDS}" % node.in_funcs[0]
)
# Unfortunately, AWS Batch only allows strings as value types
# in it's specification and we don't have any way to concatenate
# the task ids array from the parent steps within AWS Step
# Functions and pass it down to AWS Batch. We instead have to
# rely on publishing the state to DynamoDb and fetching it back
# in within the AWS Batch entry point to set
# `METAFLOW_PARENT_TASK_IDS`. The state is scoped to the parent
# foreach task `METAFLOW_SPLIT_PARENT_TASK_ID`. We decided on
# AWS DynamoDb and not AWS Lambdas, because deploying and
# debugging Lambdas would be a nightmare as far as OSS support
# is concerned.
env["METAFLOW_SPLIT_PARENT_TASK_ID"] = (
"$.Parameters.split_parent_task_id_%s" % node.split_parents[-1]
)
else:
# Set appropriate environment variables for runtime replacement.
if len(node.in_funcs) == 1:
input_paths = (
"sfn-${METAFLOW_RUN_ID}/%s/${METAFLOW_PARENT_TASK_ID}"
% node.in_funcs[0]
)
env["METAFLOW_PARENT_TASK_ID"] = "$.JobId"
else:
# Generate the input paths in a quasi-compressed format.
# See util.decompress_list for why this is written the way
# it is.
input_paths = "sfn-${METAFLOW_RUN_ID}:" + ",".join(
"/${METAFLOW_PARENT_%s_STEP}/"
"${METAFLOW_PARENT_%s_TASK_ID}" % (idx, idx)
for idx, _ in enumerate(node.in_funcs)
)
for idx, _ in enumerate(node.in_funcs):
env["METAFLOW_PARENT_%s_TASK_ID" % idx] = "$.[%s].JobId" % idx
env["METAFLOW_PARENT_%s_STEP" % idx] = (
"$.[%s].Parameters.step_name" % idx
)
env["METAFLOW_INPUT_PATHS"] = input_paths
if node.is_inside_foreach:
# Set the task id of the parent job of the foreach split in
# our favorite dumping ground, the AWS Batch attrs. For
# subsequent descendent tasks, this attrs blob becomes the
# input to those descendent tasks. We set and propagate the
# task ids pointing to split_parents through every state.
if any(self.graph[n].type == "foreach" for n in node.in_funcs):
attrs[
"split_parent_task_id_%s.$" % node.split_parents[-1]
] = "$.SplitParentTaskId"
for parent in node.split_parents[:-1]:
if self.graph[parent].type == "foreach":
attrs["split_parent_task_id_%s.$" % parent] = (
"$.Parameters.split_parent_task_id_%s" % parent
)
elif node.type == "join":
if self.graph[node.split_parents[-1]].type == "foreach":
# A foreach join only gets one set of input from the
# parent tasks. We filter the Map state to only output
# `$.[0]`, since we don't need any of the other outputs,
# that information is available to us from AWS DynamoDB.
# This has a nice side-effect of making our foreach
# splits infinitely scalable because otherwise we would
# be bounded by the 32K state limit for the outputs. So,
# instead of referencing `Parameters` fields by index
# (like in `split-and`), we can just reference them
# directly.
attrs["split_parent_task_id_%s.$" % node.split_parents[-1]] = (
"$.Parameters.split_parent_task_id_%s"
% node.split_parents[-1]
)
for parent in node.split_parents[:-1]:
if self.graph[parent].type == "foreach":
attrs["split_parent_task_id_%s.$" % parent] = (
"$.Parameters.split_parent_task_id_%s" % parent
)
else:
for parent in node.split_parents:
if self.graph[parent].type == "foreach":
attrs["split_parent_task_id_%s.$" % parent] = (
"$.[0].Parameters.split_parent_task_id_%s" % parent
)
else:
for parent in node.split_parents:
if self.graph[parent].type == "foreach":
attrs["split_parent_task_id_%s.$" % parent] = (
"$.Parameters.split_parent_task_id_%s" % parent
)
# Set `METAFLOW_SPLIT_PARENT_TASK_ID_FOR_FOREACH_JOIN` if the
# next transition is to a foreach join, so that the
# stepfunctions decorator can write the mapping for input path
# to DynamoDb.
if any(
self.graph[n].type == "join"
and self.graph[self.graph[n].split_parents[-1]].type == "foreach"
for n in node.out_funcs
):
env["METAFLOW_SPLIT_PARENT_TASK_ID_FOR_FOREACH_JOIN"] = attrs[
"split_parent_task_id_%s.$"
% self.graph[node.out_funcs[0]].split_parents[-1]
]
# Set ttl for the values we set in AWS DynamoDB.
if node.type == "foreach":
if self.workflow_timeout:
env["METAFLOW_SFN_WORKFLOW_TIMEOUT"] = self.workflow_timeout
# Handle split index for for-each.
if any(self.graph[n].type == "foreach" for n in node.in_funcs):
env["METAFLOW_SPLIT_INDEX"] = "$.Index"
env["METAFLOW_CODE_URL"] = self.code_package_url
env["METAFLOW_FLOW_NAME"] = attrs["metaflow.flow_name"]
env["METAFLOW_STEP_NAME"] = attrs["metaflow.step_name"]
env["METAFLOW_RUN_ID"] = attrs["metaflow.run_id.$"]
env["METAFLOW_PRODUCTION_TOKEN"] = self.production_token
env["SFN_STATE_MACHINE"] = self.name
env["METAFLOW_OWNER"] = attrs["metaflow.owner"]
# Can't set `METAFLOW_TASK_ID` due to lack of run-scoped identifiers.
# We will instead rely on `AWS_BATCH_JOB_ID` as the task identifier.
# Can't set `METAFLOW_RETRY_COUNT` either due to integer casting issue.
metadata_env = self.metadata.get_runtime_environment("step-functions")
env.update(metadata_env)
metaflow_version = self.environment.get_environment_info()
metaflow_version["flow_name"] = self.graph.name
metaflow_version["production_token"] = self.production_token
env["METAFLOW_VERSION"] = json.dumps(metaflow_version)
# Set AWS DynamoDb Table Name for state tracking for for-eaches.
# There are three instances when metaflow runtime directly interacts
# with AWS DynamoDB.
# 1. To set the cardinality of foreaches (which are subsequently)
# read prior to the instantiation of the Map state by AWS Step
# Functions.
# 2. To set the input paths from the parent steps of a foreach join.
# 3. To read the input paths in a foreach join.
if (
node.type == "foreach"
or (
node.is_inside_foreach
and any(
self.graph[n].type == "join"
and self.graph[self.graph[n].split_parents[-1]].type == "foreach"
for n in node.out_funcs
)
)
or (
node.type == "join"
and self.graph[node.split_parents[-1]].type == "foreach"
)
):
if SFN_DYNAMO_DB_TABLE is None:
raise StepFunctionsException(
"An AWS DynamoDB table is needed "
"to support foreach in your flow. "
"You can create one following the "
"instructions listed at *https://a"
"dmin-docs.metaflow.org/metaflow-o"
"n-aws/deployment-guide/manual-dep"
"loyment#scheduling* and "
"re-configure Metaflow using "
"*metaflow configure aws* on your "
"terminal."
)
env["METAFLOW_SFN_DYNAMO_DB_TABLE"] = SFN_DYNAMO_DB_TABLE
# Resolve AWS Batch resource requirements.
batch_deco = [deco for deco in node.decorators if deco.name == "batch"][0]
resources = batch_deco.attributes
# Resolve retry strategy.
user_code_retries, total_retries = self._get_retries(node)
task_spec = {
"flow_name": attrs["metaflow.flow_name"],
"step_name": attrs["metaflow.step_name"],
"run_id": "sfn-$METAFLOW_RUN_ID",
# Use AWS Batch job identifier as the globally unique
# task identifier.
"task_id": "$AWS_BATCH_JOB_ID",
# Since retries are handled by AWS Batch, we can rely on
# AWS_BATCH_JOB_ATTEMPT as the job counter.
"retry_count": "$((AWS_BATCH_JOB_ATTEMPT-1))",
}
return (
Batch(self.metadata, self.environment)
.create_job(
step_name=node.name,
step_cli=self._step_cli(
node, input_paths, self.code_package_url, user_code_retries
),
task_spec=task_spec,
code_package_sha=self.code_package_sha,
code_package_url=self.code_package_url,
code_package_ds=self.flow_datastore.TYPE,
image=resources["image"],
queue=resources["queue"],
iam_role=resources["iam_role"],
execution_role=resources["execution_role"],
cpu=resources["cpu"],
gpu=resources["gpu"],
memory=resources["memory"],
run_time_limit=batch_deco.run_time_limit,
shared_memory=resources["shared_memory"],
max_swap=resources["max_swap"],
swappiness=resources["swappiness"],
env=env,
attrs=attrs,
host_volumes=resources["host_volumes"],
)
.attempts(total_retries + 1)
)
def _get_retries(self, node):
max_user_code_retries = 0
max_error_retries = 0
# Different decorators may have different retrying strategies, so take
# the max of them.
for deco in node.decorators:
user_code_retries, error_retries = deco.step_task_retry_count()
max_user_code_retries = max(max_user_code_retries, user_code_retries)
max_error_retries = max(max_error_retries, error_retries)
return max_user_code_retries, max_user_code_retries + max_error_retries
def _step_cli(self, node, paths, code_package_url, user_code_retries):
cmds = []
script_name = os.path.basename(sys.argv[0])
executable = self.environment.executable(node.name)
if R.use_r():
entrypoint = [R.entrypoint()]
else:
entrypoint = [executable, script_name]
# Use AWS Batch job identifier as the globally unique task identifier.
task_id = "${AWS_BATCH_JOB_ID}"
# FlowDecorators can define their own top-level options. They are
# responsible for adding their own top-level options and values through
# the get_top_level_options() hook. See similar logic in runtime.py.
top_opts_dict = {}
for deco in flow_decorators():
top_opts_dict.update(deco.get_top_level_options())
top_opts = list(dict_to_cli_options(top_opts_dict))
if node.name == "start":
# We need a separate unique ID for the special _parameters task
task_id_params = "%s-params" % task_id
# Export user-defined parameters into runtime environment
param_file = "".join(
random.choice(string.ascii_lowercase) for _ in range(10)
)
export_params = (
"python -m "
"metaflow.plugins.aws.step_functions.set_batch_environment "
"parameters %s && . `pwd`/%s" % (param_file, param_file)
)
params = (
entrypoint
+ top_opts
+ [
"--quiet",
"--metadata=%s" % self.metadata.TYPE,
"--environment=%s" % self.environment.TYPE,
"--datastore=s3",
"--event-logger=%s" % self.event_logger.logger_type,
"--monitor=%s" % self.monitor.monitor_type,
"--no-pylint",
"init",
"--run-id sfn-$METAFLOW_RUN_ID",
"--task-id %s" % task_id_params,
]
)
# Assign tags to run objects.
if self.tags:
params.extend("--tag %s" % tag for tag in self.tags)
# If the start step gets retried, we must be careful not to
# regenerate multiple parameters tasks. Hence we check first if
# _parameters exists already.
exists = entrypoint + [
"dump",
"--max-value-size=0",
"sfn-${METAFLOW_RUN_ID}/_parameters/%s" % (task_id_params),
]
cmd = "if ! %s >/dev/null 2>/dev/null; then %s && %s; fi" % (
" ".join(exists),
export_params,
" ".join(params),
)
cmds.append(cmd)
paths = "sfn-${METAFLOW_RUN_ID}/_parameters/%s" % (task_id_params)
if node.type == "join" and self.graph[node.split_parents[-1]].type == "foreach":
parent_tasks_file = "".join(
random.choice(string.ascii_lowercase) for _ in range(10)
)
export_parent_tasks = (
"python -m "
"metaflow.plugins.aws.step_functions.set_batch_environment "
"parent_tasks %s && . `pwd`/%s" % (parent_tasks_file, parent_tasks_file)
)
cmds.append(export_parent_tasks)
top_level = top_opts + [
"--quiet",
"--metadata=%s" % self.metadata.TYPE,
"--environment=%s" % self.environment.TYPE,
"--datastore=%s" % self.flow_datastore.TYPE,
"--datastore-root=%s" % self.flow_datastore.datastore_root,
"--event-logger=%s" % self.event_logger.logger_type,
"--monitor=%s" % self.monitor.monitor_type,
"--no-pylint",
"--with=step_functions_internal",
]
step = [
"step",
node.name,
"--run-id sfn-$METAFLOW_RUN_ID",
"--task-id %s" % task_id,
# Since retries are handled by AWS Batch, we can rely on
# AWS_BATCH_JOB_ATTEMPT as the job counter.
"--retry-count $((AWS_BATCH_JOB_ATTEMPT-1))",
"--max-user-code-retries %d" % user_code_retries,
"--input-paths %s" % paths,
# Set decorator to batch to execute `task_*` hooks for batch
# decorator.
"--with=batch",
]
if any(self.graph[n].type == "foreach" for n in node.in_funcs):
# We set the `METAFLOW_SPLIT_INDEX` through JSONPath-foo
# to pass the state from the parent DynamoDb state for for-each.
step.append("--split-index $METAFLOW_SPLIT_INDEX")
if self.tags:
step.extend("--tag %s" % tag for tag in self.tags)
if self.namespace is not None:
step.append("--namespace=%s" % self.namespace)
cmds.append(" ".join(entrypoint + top_level + step))
return " && ".join(cmds)
class Workflow(object):
def __init__(self, name):
self.name = name
tree = lambda: defaultdict(tree)
self.payload = tree()
def start_at(self, start_at):
self.payload["StartAt"] = start_at
return self
def add_state(self, state):
self.payload["States"][state.name] = state.payload
return self
def timeout_seconds(self, timeout_seconds):
self.payload["TimeoutSeconds"] = timeout_seconds
return self
def to_json(self, pretty=False):
return json.dumps(self.payload, indent=4 if pretty else None)
class State(object):
def __init__(self, name):
self.name = name
tree = lambda: defaultdict(tree)
self.payload = tree()
self.payload["Type"] = "Task"
def resource(self, resource):
self.payload["Resource"] = resource
return self
def next(self, state):
self.payload["Next"] = state
return self
def end(self):
self.payload["End"] = True
return self
def parameter(self, name, value):
self.payload["Parameters"][name] = value
return self
def output_path(self, output_path):
self.payload["OutputPath"] = output_path
return self
def result_path(self, result_path):
self.payload["ResultPath"] = result_path
return self
def _partition(self):
# This is needed to support AWS Gov Cloud and AWS CN regions
return SFN_IAM_ROLE.split(":")[1]
def batch(self, job):
self.resource(
"arn:%s:states:::batch:submitJob.sync" % self._partition()
).parameter("JobDefinition", job.payload["jobDefinition"]).parameter(
"JobName", job.payload["jobName"]
).parameter(
"JobQueue", job.payload["jobQueue"]
).parameter(
"Parameters", job.payload["parameters"]
).parameter(
"ContainerOverrides", to_pascalcase(job.payload["containerOverrides"])
).parameter(
"RetryStrategy", to_pascalcase(job.payload["retryStrategy"])
).parameter(
"Timeout", to_pascalcase(job.payload["timeout"])
)
# tags may not be present in all scenarios
if "tags" in job.payload:
self.parameter("Tags", job.payload["tags"])
return self
def dynamo_db(self, table_name, primary_key, values):
self.resource("arn:%s:states:::dynamodb:getItem" % self._partition()).parameter(
"TableName", table_name
).parameter("Key", {"pathspec": {"S.$": primary_key}}).parameter(
"ConsistentRead", True
).parameter(
"ProjectionExpression", values
)
return self
class Parallel(object):
def __init__(self, name):
self.name = name
tree = lambda: defaultdict(tree)
self.payload = tree()
self.payload["Type"] = "Parallel"
def branch(self, workflow):
if "Branches" not in self.payload:
self.payload["Branches"] = []
self.payload["Branches"].append(workflow.payload)
return self
def next(self, state):
self.payload["Next"] = state
return self
def output_path(self, output_path):
self.payload["OutputPath"] = output_path
return self
def result_path(self, result_path):
self.payload["ResultPath"] = result_path
return self
class Map(object):
def __init__(self, name):
self.name = name
tree = lambda: defaultdict(tree)
self.payload = tree()
self.payload["Type"] = "Map"
self.payload["MaxConcurrency"] = 0
def | (self, workflow):
self.payload["Iterator"] = workflow.payload
return self
def next(self, state):
self.payload["Next"] = state
return self
def items_path(self, items_path):
self.payload["ItemsPath"] = items_path
return self
def parameter(self, name, value):
self.payload["Parameters"][name] = value
return self
def max_concurrency(self, max_concurrency):
self.payload["MaxConcurrency"] = max_concurrency
return self
def output_path(self, output_path):
self.payload["OutputPath"] = output_path
return self
def result_path(self, result_path):
self.payload["ResultPath"] = result_path
return self
| iterator |
handler.go | package pcf_handler
import (
"gofree5gc/lib/openapi/models"
"gofree5gc/src/pcf/logger"
"gofree5gc/src/pcf/pcf_handler/pcf_message"
"gofree5gc/src/pcf/pcf_producer"
"time"
"github.com/sirupsen/logrus"
)
var HandlerLog *logrus.Entry
func init() {
// init Pool
HandlerLog = logger.HandlerLog
}
func Handle() {
for {
select {
case msg, ok := <-pcf_message.PCFChannel:
if ok {
switch msg.Event {
case pcf_message.EventBDTPolicyCreate:
pcf_producer.CreateBDTPolicyContext(msg.HttpChannel, msg.HTTPRequest.Body.(models.BdtReqData))
case pcf_message.EventBDTPolicyGet:
bdtPolicyId := msg.HTTPRequest.Params["bdtPolicyId"]
pcf_producer.GetBDTPolicyContext(msg.HttpChannel, bdtPolicyId)
case pcf_message.EventBDTPolicyUpdate:
bdtPolicyId := msg.HTTPRequest.Params["bdtPolicyId"]
pcf_producer.UpdateBDTPolicyContext(msg.HttpChannel, bdtPolicyId, msg.HTTPRequest.Body.(models.BdtPolicyDataPatch))
case pcf_message.EventPostAppSessions:
pcf_producer.PostAppSessionsContext(msg.HttpChannel, msg.HTTPRequest.Body.(models.AppSessionContext))
case pcf_message.EventGetAppSession:
appSessionId := msg.HTTPRequest.Params["appSessionId"]
pcf_producer.GetAppSessionContext(msg.HttpChannel, appSessionId)
case pcf_message.EventDeleteAppSession:
appSessionId := msg.HTTPRequest.Params["appSessionId"]
pcf_producer.DeleteAppSessionContext(msg.HttpChannel, appSessionId, msg.HTTPRequest.Body.(*models.EventsSubscReqData))
case pcf_message.EventModAppSession:
appSessionId := msg.HTTPRequest.Params["appSessionId"]
pcf_producer.ModAppSessionContext(msg.HttpChannel, appSessionId, msg.HTTPRequest.Body.(models.AppSessionContextUpdateData))
case pcf_message.EventDeleteEventsSubsc:
appSessionId := msg.HTTPRequest.Params["appSessionId"]
pcf_producer.DeleteEventsSubscContext(msg.HttpChannel, appSessionId)
case pcf_message.EventUpdateEventsSubsc:
appSessionId := msg.HTTPRequest.Params["appSessionId"]
pcf_producer.UpdateEventsSubscContext(msg.HttpChannel, appSessionId, msg.HTTPRequest.Body.(models.EventsSubscReqData))
case pcf_message.EventAMPolicyGet:
PolAssoId := msg.HTTPRequest.Params["polAssoId"]
pcf_producer.GetPoliciesPolAssoId(msg.HttpChannel, PolAssoId)
case pcf_message.EventAMPolicyDelete:
PolAssoId := msg.HTTPRequest.Params["polAssoId"]
pcf_producer.DeletePoliciesPolAssoId(msg.HttpChannel, PolAssoId)
case pcf_message.EventAMPolicyCreate:
pcf_producer.PostPolicies(msg.HttpChannel, msg.HTTPRequest.Body.(models.PolicyAssociationRequest)) | case pcf_message.EventSMPolicyCreate:
pcf_producer.CreateSmPolicy(msg.HttpChannel, msg.HTTPRequest.Body.(models.SmPolicyContextData))
case pcf_message.EventSMPolicyGet:
smPolicyId := msg.HTTPRequest.Params["smPolicyId"]
pcf_producer.GetSmPolicyContext(msg.HttpChannel, smPolicyId)
case pcf_message.EventSMPolicyUpdate:
smPolicyId := msg.HTTPRequest.Params["smPolicyId"]
pcf_producer.UpdateSmPolicyContext(msg.HttpChannel, smPolicyId, msg.HTTPRequest.Body.(models.SmPolicyUpdateContextData))
case pcf_message.EventSMPolicyDelete:
smPolicyId := msg.HTTPRequest.Params["smPolicyId"]
pcf_producer.DeleteSmPolicyContext(msg.HttpChannel, smPolicyId)
case pcf_message.EventSMPolicyNotify:
ReqURI := msg.HTTPRequest.Params["ReqURI"]
pcf_producer.HandleSmPolicyNotify(msg.HttpChannel, ReqURI, msg.HTTPRequest.Body.(models.PolicyDataChangeNotification))
// TODO: http event dispatcher
default:
HandlerLog.Warnf("Event[%s] has not implemented", msg.Event)
}
} else {
HandlerLog.Errorln("Channel closed!")
}
case <-time.After(time.Second * 1):
}
}
} | case pcf_message.EventAMPolicyUpdate:
PolAssoId := msg.HTTPRequest.Params["polAssoId"]
pcf_producer.UpdatePostPoliciesPolAssoId(msg.HttpChannel, PolAssoId, msg.HTTPRequest.Body.(models.PolicyAssociationUpdateRequest)) |
sprite.go | package gfx
import (
"korok.io/korok/math/f32"
"korok.io/korok/engi"
)
// Sprite is Tex2D
type Sprite Tex2D
// SpriteComp & SpriteTable
// Usually, sprite can be rendered with a BatchRenderer
type SpriteComp struct {
engi.Entity
Sprite
zOrder
batchId
color uint32
flipX uint16
flipY uint16
width float32
height float32
gravity struct{
x, y float32
}
visible bool
}
func (sc *SpriteComp) SetSprite(spt Sprite) {
sc.Sprite = spt
sc.batchId.value = spt.Tex()
// optional size
if sc.width == 0 || sc.height == 0 {
size := spt.Size()
sc.width = size.Width
sc.height = size.Height
}
}
func (sc *SpriteComp) SetSize(w, h float32) {
sc.width, sc.height = w, h
}
func (sc *SpriteComp) Size() (w, h float32) {
w, h = sc.width, sc.height
return
}
func (sc *SpriteComp) SetGravity(x, y float32) {
sc.gravity.x = x
sc.gravity.y = y
}
func (sc *SpriteComp) Gravity() (x, y float32) {
return sc.gravity.x, sc.gravity.y
}
func (sc *SpriteComp) SetVisible(v bool) {
sc.visible = v
}
func (sc *SpriteComp) Visible() bool {
return sc.visible
}
func (sc *SpriteComp) Color() Color {
return U32Color(sc.color)
}
func (sc *SpriteComp) SetColor(c Color) {
sc.color = c.U32()
}
func (sc *SpriteComp) Flip(flipX, flipY bool) {
if flipX {
sc.flipX = 1
} else {
sc.flipX = 0
}
if flipY {
sc.flipY = 1
} else {
sc.flipY = 0
}
}
type SpriteTable struct {
comps []SpriteComp
_map map[uint32]int
index, cap int
}
func NewSpriteTable(cap int) *SpriteTable {
return &SpriteTable{
cap:cap,
_map:make(map[uint32]int),
}
}
func (st *SpriteTable) NewComp(entity engi.Entity) (sc *SpriteComp) {
if size := len(st.comps); st.index >= size {
st.comps = spriteResize(st.comps, size + STEP)
}
ei := entity.Index()
if v, ok := st._map[ei]; ok {
sc = &st.comps[v]
return
}
sc = &st.comps[st.index]
sc.Entity = entity
sc.gravity.x, sc.gravity.y = .5, .5
sc.color = 0xFFFFFFFF
sc.visible = true
st._map[ei] = st.index
st.index ++
return
}
// New SpriteComp with parameter
func (st *SpriteTable) NewCompX(entity engi.Entity, spt Tex2D) (sc *SpriteComp) {
sc = st.NewComp(entity)
sc.SetSprite(spt)
return
}
func (st *SpriteTable) Alive(entity engi.Entity) bool {
ei := entity.Index()
if v, ok := st._map[ei]; ok {
return st.comps[v].Entity != 0
}
return false
}
func (st *SpriteTable) Comp(entity engi.Entity) (sc *SpriteComp) {
ei := entity.Index()
if v, ok := st._map[ei]; ok {
sc = &st.comps[v]
}
return
}
func (st *SpriteTable) Delete(entity engi.Entity) {
ei := entity.Index()
if v, ok := st._map[ei]; ok {
if tail := st.index -1; v != tail && tail > 0 {
st.comps[v] = st.comps[tail]
// remap index
tComp := st.comps[tail]
ei := tComp.Entity.Index()
st._map[ei] = v
st.comps[tail] = SpriteComp{}
} else {
st.comps[tail] = SpriteComp{}
}
st.index -= 1
delete(st._map, ei)
}
}
func (st *SpriteTable) Size() (size, cap int) {
return st.index, st.cap
}
func (st *SpriteTable) Destroy() {
st.comps = make([]SpriteComp, 0)
st._map = make(map[uint32]int)
st.index = 0
}
func spriteResize(slice []SpriteComp, size int) []SpriteComp |
/////
type SpriteRenderFeature struct {
Stack *StackAllocator
id int
R *BatchRender
st *SpriteTable
xt *TransformTable
}
func (f *SpriteRenderFeature) SetRender(render *BatchRender) {
f.R = render
}
func (f *SpriteRenderFeature) SetTable(st *SpriteTable, xt *TransformTable) {
f.st, f.xt = st, xt
}
// 此处初始化所有的依赖
func (f *SpriteRenderFeature) Register(rs *RenderSystem) {
// init render
for _, r := range rs.RenderList {
switch br := r.(type) {
case *BatchRender:
f.R = br; break
}
}
// init table
for _, t := range rs.TableList {
switch table := t.(type){
case *SpriteTable:
f.st = table
case *TransformTable:
f.xt = table
}
}
// add new feature, use the index as id
f.id = rs.Accept(f)
}
func (f *SpriteRenderFeature) Extract(v *View) {
var (
camera = v.Camera
xt = f.xt
fi = uint32(f.id) << 16
)
for i, spr := range f.st.comps[:f.st.index] {
xf := xt.Comp(spr.Entity)
sz := f32.Vec2{spr.width, spr.height}
g := f32.Vec2{spr.gravity.x, spr.gravity.y}
if spr.visible && camera.InView(xf,sz , g) {
sid := PackSortId(spr.zOrder.value, spr.batchId.value)
val := fi + uint32(i)
v.RenderNodes = append(v.RenderNodes, SortObject{sid, val})
}
}
}
func (f *SpriteRenderFeature) Draw(nodes RenderNodes) {
var (
st, xt = f.st, f.xt
sortId = uint32(0xFFFFFFFF)
begin = false
render = f.R
)
// batch draw!
var spriteBatchObject = spriteBatchObject{}
for _, b := range nodes {
ii := b.Value & 0xFFFF
if sid := b.SortId & 0xFFFF; sortId != sid {
if begin {
render.End()
}
sortId = sid
begin = true
tex2d := st.comps[ii].Sprite.Tex()
depth, _ := UnpackSortId(b.SortId)
render.Begin(tex2d, depth)
}
spriteBatchObject.SpriteComp = &st.comps[ii]
spriteBatchObject.Transform = xt.Comp(st.comps[ii].Entity)
render.Draw(spriteBatchObject)
}
if begin {
render.End()
}
render.Flush()
}
func (f *SpriteRenderFeature) Flush() {
}
type spriteBatchObject struct {
*SpriteComp
*Transform
}
// batch system winding order
//
// 3----------2
// | . |
// | . |
// | . |
// | . |
// 0----------1
// 1 * 1 quad for each char
// order: 3 0 1 3 1 2
//
// Transform Method:
//
// |
// |
// |
func (sbo spriteBatchObject) Fill(buf []PosTexColorVertex) {
var (
srt = sbo.Transform.world
p = srt.Position
c = sbo.SpriteComp
w = sbo.width
h = sbo.height
)
// Texture
rg := c.Sprite.Region()
if rg.Rotated {
if c.flipX == 1 {
rg.Y1, rg.Y2 = rg.Y2, rg.Y1
}
if c.flipY == 1 {
rg.X1, rg.X2 = rg.X2, rg.X1
}
buf[1].U, buf[1].V = rg.X1, rg.Y2
buf[2].U, buf[2].V = rg.X2, rg.Y2
buf[3].U, buf[3].V = rg.X2, rg.Y1
buf[0].U, buf[0].V = rg.X1, rg.Y1
} else {
if c.flipY == 1 {
rg.Y1, rg.Y2 = rg.Y2, rg.Y1
}
if c.flipX == 1 {
rg.X1, rg.X2 = rg.X2, rg.X1
}
buf[0].U, buf[0].V = rg.X1, rg.Y2
buf[1].U, buf[1].V = rg.X2, rg.Y2
buf[2].U, buf[2].V = rg.X2, rg.Y1
buf[3].U, buf[3].V = rg.X1, rg.Y1
}
// Color
buf[0].RGBA = c.color
buf[1].RGBA = c.color
buf[2].RGBA = c.color
buf[3].RGBA = c.color
// Center of model
ox := w * c.gravity.x
oy := h * c.gravity.y
// Transform matrix
m := f32.Mat3{}; m.Initialize(p[0], p[1], srt.Rotation, srt.Scale[0], srt.Scale[1], ox, oy, 0,0)
// Let's go!
buf[0].X, buf[0].Y = m.Transform(0, 0)
buf[1].X, buf[1].Y = m.Transform(w, 0)
buf[2].X, buf[2].Y = m.Transform(w, h)
buf[3].X, buf[3].Y = m.Transform(0, h)
}
func (sbo spriteBatchObject) Size() int {
return 4
}
| {
newSlice := make([]SpriteComp, size)
copy(newSlice, slice)
return newSlice
} |
utils.rs | use std::{
fs::File,
io::{Read, Write},
};
pub fn read_file_as_bytes(filename: &str) -> Result<Vec<u8>, String> {
let mut f = File::open(&filename).expect("no file found");
let mut buffer = Vec::<u8>::new();
match f.read_to_end(&mut buffer) {
Ok(_) => Ok(buffer),
Err(_) => Err("Error with reading ROM file".to_string()),
}
}
pub fn | (from: &[u8], mut to: &mut [u8]) -> usize {
to.write(from).unwrap()
}
| byte_copy |
volume_backup.go | package storage
import (
"context"
"fmt"
"io"
"os"
"google.golang.org/grpc"
"github.com/chrislusf/seaweedfs/weed/operation"
"github.com/chrislusf/seaweedfs/weed/pb/volume_server_pb"
"github.com/chrislusf/seaweedfs/weed/storage/idx"
"github.com/chrislusf/seaweedfs/weed/storage/needle"
"github.com/chrislusf/seaweedfs/weed/storage/super_block"
. "github.com/chrislusf/seaweedfs/weed/storage/types"
)
func (v *Volume) GetVolumeSyncStatus() *volume_server_pb.VolumeSyncStatusResponse {
v.dataFileAccessLock.RLock()
defer v.dataFileAccessLock.RUnlock()
var syncStatus = &volume_server_pb.VolumeSyncStatusResponse{}
if datSize, _, err := v.DataBackend.GetStat(); err == nil {
syncStatus.TailOffset = uint64(datSize)
}
syncStatus.Collection = v.Collection
syncStatus.IdxFileSize = v.nm.IndexFileSize()
syncStatus.CompactRevision = uint32(v.SuperBlock.CompactionRevision)
syncStatus.Ttl = v.SuperBlock.Ttl.String()
syncStatus.Replication = v.SuperBlock.ReplicaPlacement.String()
return syncStatus
}
// The volume sync with a master volume via 2 steps:
// 1. The slave checks master side to find subscription checkpoint
// to setup the replication.
// 2. The slave receives the updates from master
/*
Assume the slave volume needs to follow the master volume.
The master volume could be compacted, and could be many files ahead of
slave volume.
Step 0: // implemented in command/backup.go, to avoid dat file size overflow.
0.1 If slave compact version is less than the master, do a local compaction, and set
local compact version the same as the master.
0.2 If the slave size is still bigger than the master, discard local copy and do a full copy.
Step 1:
The slave volume ask the master by the last modification time t.
The master do a binary search in volume (use .idx as an array, and check the appendAtNs in .dat file),
to find the first entry with appendAtNs > t.
Step 2:
The master send content bytes to the slave. The bytes are not chunked by needle.
Step 3:
The slave generate the needle map for the new bytes. (This may be optimized to incrementally
update needle map when receiving new .dat bytes. But seems not necessary now.)
*/
func (v *Volume) IncrementalBackup(volumeServer string, grpcDialOption grpc.DialOption) error {
| return err
}
writeOffset := int64(startFromOffset)
err = operation.WithVolumeServerClient(volumeServer, grpcDialOption, func(client volume_server_pb.VolumeServerClient) error {
stream, err := client.VolumeIncrementalCopy(context.Background(), &volume_server_pb.VolumeIncrementalCopyRequest{
VolumeId: uint32(v.Id),
SinceNs: appendAtNs,
})
if err != nil {
return err
}
for {
resp, recvErr := stream.Recv()
if recvErr != nil {
if recvErr == io.EOF {
break
} else {
return recvErr
}
}
n, writeErr := v.DataBackend.WriteAt(resp.FileContent, writeOffset)
if writeErr != nil {
return writeErr
}
writeOffset += int64(n)
}
return nil
})
if err != nil {
return err
}
// add to needle map
return ScanVolumeFileFrom(v.Version(), v.DataBackend, int64(startFromOffset), &VolumeFileScanner4GenIdx{v: v})
}
func (v *Volume) findLastAppendAtNs() (uint64, error) {
offset, err := v.locateLastAppendEntry()
if err != nil {
return 0, err
}
if offset.IsZero() {
return 0, nil
}
return v.readAppendAtNs(offset)
}
func (v *Volume) locateLastAppendEntry() (Offset, error) {
indexFile, e := os.OpenFile(v.FileName()+".idx", os.O_RDONLY, 0644)
if e != nil {
return Offset{}, fmt.Errorf("cannot read %s.idx: %v", v.FileName(), e)
}
defer indexFile.Close()
fi, err := indexFile.Stat()
if err != nil {
return Offset{}, fmt.Errorf("file %s stat error: %v", indexFile.Name(), err)
}
fileSize := fi.Size()
if fileSize%NeedleMapEntrySize != 0 {
return Offset{}, fmt.Errorf("unexpected file %s size: %d", indexFile.Name(), fileSize)
}
if fileSize == 0 {
return Offset{}, nil
}
bytes := make([]byte, NeedleMapEntrySize)
n, e := indexFile.ReadAt(bytes, fileSize-NeedleMapEntrySize)
if n != NeedleMapEntrySize {
return Offset{}, fmt.Errorf("file %s read error: %v", indexFile.Name(), e)
}
_, offset, _ := idx.IdxFileEntry(bytes)
return offset, nil
}
func (v *Volume) readAppendAtNs(offset Offset) (uint64, error) {
n, _, bodyLength, err := needle.ReadNeedleHeader(v.DataBackend, v.SuperBlock.Version, offset.ToAcutalOffset())
if err != nil {
return 0, fmt.Errorf("ReadNeedleHeader: %v", err)
}
_, err = n.ReadNeedleBody(v.DataBackend, v.SuperBlock.Version, offset.ToAcutalOffset()+int64(NeedleHeaderSize), bodyLength)
if err != nil {
return 0, fmt.Errorf("ReadNeedleBody offset %d, bodyLength %d: %v", offset.ToAcutalOffset(), bodyLength, err)
}
return n.AppendAtNs, nil
}
// on server side
func (v *Volume) BinarySearchByAppendAtNs(sinceNs uint64) (offset Offset, isLast bool, err error) {
indexFile, openErr := os.OpenFile(v.FileName()+".idx", os.O_RDONLY, 0644)
if openErr != nil {
err = fmt.Errorf("cannot read %s.idx: %v", v.FileName(), openErr)
return
}
defer indexFile.Close()
fi, statErr := indexFile.Stat()
if statErr != nil {
err = fmt.Errorf("file %s stat error: %v", indexFile.Name(), statErr)
return
}
fileSize := fi.Size()
if fileSize%NeedleMapEntrySize != 0 {
err = fmt.Errorf("unexpected file %s size: %d", indexFile.Name(), fileSize)
return
}
bytes := make([]byte, NeedleMapEntrySize)
entryCount := fileSize / NeedleMapEntrySize
l := int64(0)
h := entryCount
for l < h {
m := (l + h) / 2
if m == entryCount {
return Offset{}, true, nil
}
// read the appendAtNs for entry m
offset, err = v.readAppendAtNsForIndexEntry(indexFile, bytes, m)
if err != nil {
return
}
mNs, nsReadErr := v.readAppendAtNs(offset)
if nsReadErr != nil {
err = nsReadErr
return
}
// move the boundary
if mNs <= sinceNs {
l = m + 1
} else {
h = m
}
}
if l == entryCount {
return Offset{}, true, nil
}
offset, err = v.readAppendAtNsForIndexEntry(indexFile, bytes, l)
return offset, false, err
}
// bytes is of size NeedleMapEntrySize
func (v *Volume) readAppendAtNsForIndexEntry(indexFile *os.File, bytes []byte, m int64) (Offset, error) {
if _, readErr := indexFile.ReadAt(bytes, m*NeedleMapEntrySize); readErr != nil && readErr != io.EOF {
return Offset{}, readErr
}
_, offset, _ := idx.IdxFileEntry(bytes)
return offset, nil
}
// generate the volume idx
type VolumeFileScanner4GenIdx struct {
v *Volume
}
func (scanner *VolumeFileScanner4GenIdx) VisitSuperBlock(superBlock super_block.SuperBlock) error {
return nil
}
func (scanner *VolumeFileScanner4GenIdx) ReadNeedleBody() bool {
return false
}
func (scanner *VolumeFileScanner4GenIdx) VisitNeedle(n *needle.Needle, offset int64, needleHeader, needleBody []byte) error {
if n.Size > 0 && n.Size != TombstoneFileSize {
return scanner.v.nm.Put(n.Id, ToOffset(offset), n.Size)
}
return scanner.v.nm.Delete(n.Id, ToOffset(offset))
} | startFromOffset, _, _ := v.FileStat()
appendAtNs, err := v.findLastAppendAtNs()
if err != nil { |
groupadd.rs | #![deny(warnings)]
#[macro_use]
extern crate clap;
extern crate extra;
extern crate redox_users;
|
use redox_users::{AllGroups, UsersError};
const _MAN_PAGE: &'static str = /* @MANSTART{groupadd} */ r#"
NAME
groupadd - add a user group
SYNOPSIS
groupadd [ -f | --force ] GROUP
groupadd [ -h | --help ]
DESCRIPTION
The groupadd utility adds a new user group using values
passed on the command line and system defaults.
OPTIONS
-f, --force
Simply forces the exit status of the program to 0
even if the group already exists. A message is still
printed to stdout.
-g, --gid GID
The group id to use. This value must not be used and must
be non-negative. The default is to pick the smallest available
group id (between values defined in redox_users).
-h, --help
Display this help and exit.
AUTHOR
Written by Wesley Hershberger.
"#; /* @MANEND */
fn main() {
let args = clap_app!(groupadd =>
(author: "Wesley Hershberger")
(about: "Add groups based on the system's redox_users backend")
(@arg GROUP: +required "Add group GROUP")
(@arg FORCE: -f --force "Force the status of the program to be 0 even if the group exists")
(@arg GID: -g --gid +takes_value "Group id. Positive integer and must not be in use")
).get_matches();
let mut sys_groups = AllGroups::new().unwrap_or_exit(1);
let groupname = args.value_of("GROUP").unwrap();
let gid = match args.value_of("GID") {
Some(gid) => {
let id = gid.parse::<usize>().unwrap_or_exit(1);
if let Some(_group) = sys_groups.get_by_id(id) {
eprintln!("groupadd: group already exists");
exit(1);
}
id
},
None => sys_groups.get_unique_id().unwrap_or_else(|| {
eprintln!("groupadd: no available gid");
exit(1);
})
};
match sys_groups.add_group(groupname, gid, &[""]) {
Ok(_) => { },
Err(ref err) if err.downcast_ref::<UsersError>() == Some(&UsersError::AlreadyExists) && args.is_present("FORCE") => {
exit(0);
},
Err(err) => {
eprintln!("groupadd: {}", err);
exit(1);
}
}
sys_groups.save().unwrap_or_exit(1);
} | use extra::option::OptionalExt;
use std::process::exit; |
run_manager.py | # Once for All: Train One Network and Specialize it for Efficient Deployment
# Han Cai, Chuang Gan, Tianzhe Wang, Zhekai Zhang, Song Han
# International Conference on Learning Representations (ICLR), 2020.
import os
import time
import json
import math
from tqdm import tqdm
import numpy as np
import copy
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torchvision
# from imagenet_codebase.utils import *
from ofa.imagenet_codebase.utils import count_parameters, count_net_flops, measure_net_latency, \
cross_entropy_loss_with_soft_target, cross_entropy_with_label_smoothing
from ofa.utils import AverageMeter, accuracy
class RunConfig:
def __init__(self, n_epochs, init_lr, lr_schedule_type, lr_schedule_param,
dataset, train_batch_size, test_batch_size, valid_size,
opt_type, opt_param, weight_decay, label_smoothing, no_decay_keys,
mixup_alpha,
model_init, validation_frequency, print_frequency):
self.n_epochs = n_epochs
self.init_lr = init_lr
self.lr_schedule_type = lr_schedule_type
self.lr_schedule_param = lr_schedule_param
self.dataset = dataset
self.train_batch_size = train_batch_size
self.test_batch_size = test_batch_size
self.valid_size = valid_size
self.opt_type = opt_type
self.opt_param = opt_param
self.weight_decay = weight_decay
self.label_smoothing = label_smoothing
self.no_decay_keys = no_decay_keys
self.mixup_alpha = mixup_alpha
self.model_init = model_init
self.validation_frequency = validation_frequency
self.print_frequency = print_frequency
@property
def config(self):
config = {}
for key in self.__dict__:
if not key.startswith('_'):
config[key] = self.__dict__[key]
return config
def copy(self):
return RunConfig(**self.config)
""" learning rate """
def calc_learning_rate(self, epoch, batch=0, nBatch=None):
if self.lr_schedule_type == 'cosine':
T_total = self.n_epochs * nBatch
T_cur = epoch * nBatch + batch
lr = 0.5 * self.init_lr * (1 + math.cos(math.pi * T_cur / T_total))
elif self.lr_schedule_type is None:
lr = self.init_lr
else:
raise ValueError('do not support: %s' % self.lr_schedule_type)
return lr
def adjust_learning_rate(self, optimizer, epoch, batch=0, nBatch=None):
""" adjust learning of a given optimizer and return the new learning rate """
new_lr = self.calc_learning_rate(epoch, batch, nBatch)
for param_group in optimizer.param_groups:
param_group['lr'] = new_lr
return new_lr
def warmup_adjust_learning_rate(self, optimizer, T_total, nBatch, epoch, batch=0, warmup_lr=0):
T_cur = epoch * nBatch + batch + 1
new_lr = T_cur / T_total * (self.init_lr - warmup_lr) + warmup_lr
for param_group in optimizer.param_groups:
param_group['lr'] = new_lr
return new_lr
""" data provider """
@property
def data_provider(self):
raise NotImplementedError
def train_FL_loader(self, _):
return self.data_provider.train_splits[_]
@property
def train_loader(self):
return self.data_provider.train
@property
def valid_loader(self):
return self.data_provider.valid
@property
def test_loader(self):
return self.data_provider.test
def random_sub_train_loader(self, n_images, batch_size, num_worker=None, num_replicas=None, rank=None, tag_FL=-1):
return self.data_provider.build_sub_train_loader(n_images, batch_size, num_worker, num_replicas, rank, tag_FL)
""" optimizer """
def build_optimizer(self, net_params):
if self.no_decay_keys is not None:
assert isinstance(net_params, list) and len(net_params) == 2
net_params = [
{'params': net_params[0], 'weight_decay': self.weight_decay},
{'params': net_params[1], 'weight_decay': 0},
]
else:
net_params = [{'params': net_params, 'weight_decay': self.weight_decay}]
if self.opt_type == 'sgd':
opt_param = {} if self.opt_param is None else self.opt_param
momentum, nesterov = opt_param.get('momentum', 0.9), opt_param.get('nesterov', True)
optimizer = torch.optim.SGD(net_params, self.init_lr, momentum=momentum, nesterov=nesterov)
elif self.opt_type == 'adam':
optimizer = torch.optim.Adam(net_params, self.init_lr)
else:
raise NotImplementedError
return optimizer
def get_net_info(net, input_shape=(3, 224, 224), measure_latency=None, print_info=True):
net_info = {}
if isinstance(net, nn.DataParallel):
net = net.module
# parameters
net_info['params'] = count_parameters(net)
# flops
net_info['flops'] = count_net_flops(net, [2] + list(input_shape))/2
# latencies
latency_types = [] if measure_latency is None else measure_latency.split('#')
for l_type in latency_types:
latency, measured_latency = measure_net_latency(net, l_type, fast=False, input_shape=input_shape)
net_info['%s latency' % l_type] = {
'val': latency,
'hist': measured_latency
}
if print_info:
print(net)
print('Total training params: %.2fM' % (net_info['params'] / 1e6))
print('Total FLOPs: %.2fM' % (net_info['flops'] / 1e6))
for l_type in latency_types:
print('Estimated %s latency: %.3fms' % (l_type, net_info['%s latency' % l_type]['val']))
return net_info
class RunManager:
def __init__(self, path, net, run_config: RunConfig, init=True, measure_latency=None, no_gpu=False, mix_prec=None):
self.path = path
self.net = net
self.run_config = run_config
self.mix_prec = mix_prec
self.best_acc = 0
self.start_epoch = 0
os.makedirs(self.path, exist_ok=True)
# move network to GPU if available
if torch.cuda.is_available() and (not no_gpu):
self.device = torch.device('cuda:0')
self.net = self.net.to(self.device)
cudnn.benchmark = True
else:
self.device = torch.device('cpu')
# initialize model (default)
if init:
self.network.init_model(run_config.model_init)
# net info
net_info = get_net_info(self.net, self.run_config.data_provider.data_shape, measure_latency, True)
with open('%s/net_info.txt' % self.path, 'w') as fout:
fout.write(json.dumps(net_info, indent=4) + '\n')
try:
fout.write(self.network.module_str)
except Exception:
pass
# criterion
if isinstance(self.run_config.mixup_alpha, float):
self.train_criterion = cross_entropy_loss_with_soft_target
elif self.run_config.label_smoothing > 0:
self.train_criterion = lambda pred, target: \
cross_entropy_with_label_smoothing(pred, target, self.run_config.label_smoothing)
else:
self.train_criterion = nn.CrossEntropyLoss()
self.test_criterion = nn.CrossEntropyLoss()
# optimizer
if self.run_config.no_decay_keys:
keys = self.run_config.no_decay_keys.split('#')
net_params = [
self.network.get_parameters(keys, mode='exclude'), # parameters with weight decay
self.network.get_parameters(keys, mode='include'), # parameters without weight decay
]
else:
try:
net_params = self.network.weight_parameters()
except Exception:
net_params = self.network.parameters()
self.optimizer = self.run_config.build_optimizer(net_params)
if mix_prec is not None:
from apex import amp
self.network, self.optimizer = amp.initialize(self.network, self.optimizer, opt_level=mix_prec)
self.net = torch.nn.DataParallel(self.net)
def init_FL(self, flag_reset_running_statistics):
""" FL """
if self.run_config.flag_FL:
self.nets_FL = []
self.optimizers_FL = []
for _ in range(self.run_config.size_FL):
self.nets_FL.append(copy.deepcopy(self.net))
if flag_reset_running_statistics:
self.reset_running_statistics(self.network_FL(_), _)
for _ in range(self.run_config.size_FL):
if self.run_config.no_decay_keys:
keys = self.run_config.no_decay_keys.split('#')
net_params = [
self.network_FL(_).get_parameters(keys, mode='exclude'), # parameters with weight decay
self.network_FL(_).get_parameters(keys, mode='include'), # parameters without weight decay
]
else:
try:
net_params = self.network_FL(_).weight_parameters()
except Exception:
net_params = self.network_FL(_).parameters()
self.optimizers_FL.append(self.run_config.build_optimizer(net_params))
""" save path and log path """
@property
def save_path(self):
if self.__dict__.get('_save_path', None) is None:
save_path = os.path.join(self.path, 'checkpoint')
os.makedirs(save_path, exist_ok=True)
self.__dict__['_save_path'] = save_path
return self.__dict__['_save_path']
@property
def logs_path(self):
if self.__dict__.get('_logs_path', None) is None:
logs_path = os.path.join(self.path, 'logs')
os.makedirs(logs_path, exist_ok=True)
self.__dict__['_logs_path'] = logs_path
return self.__dict__['_logs_path']
def network_FL(self, _):
if isinstance(self.nets_FL[_], nn.DataParallel):
return self.nets_FL[_].module
else:
return self.nets_FL[_]
@property
def network(self):
if isinstance(self.net, nn.DataParallel):
return self.net.module
else:
return self.net
@network.setter
def network(self, new_val):
if isinstance(self.net, nn.DataParallel):
self.net.module = new_val
else:
self.net = new_val
def write_log(self, log_str, prefix='valid', should_print=True):
""" prefix: valid, train, test """
if prefix in ['valid', 'test']:
with open(os.path.join(self.logs_path, 'valid_console.txt'), 'a') as fout:
fout.write(log_str + '\n')
fout.flush()
if prefix in ['valid', 'test', 'train']:
with open(os.path.join(self.logs_path, 'train_console.txt'), 'a') as fout:
if prefix in ['valid', 'test']:
fout.write('=' * 10)
fout.write(log_str + '\n')
fout.flush()
else:
with open(os.path.join(self.logs_path, '%s.txt' % prefix), 'a') as fout:
fout.write(log_str + '\n')
fout.flush()
if should_print:
print(log_str)
""" save and load models """
def save_model(self, checkpoint=None, is_best=False, model_name=None):
if checkpoint is None:
checkpoint = {'state_dict': self.network.state_dict()}
if model_name is None:
model_name = 'checkpoint.pth.tar'
if self.mix_prec is not None:
from apex import amp
checkpoint['amp'] = amp.state_dict()
checkpoint['dataset'] = self.run_config.dataset # add `dataset` info to the checkpoint
latest_fname = os.path.join(self.save_path, 'latest.txt')
model_path = os.path.join(self.save_path, model_name)
with open(latest_fname, 'w') as fout:
fout.write(model_path + '\n')
torch.save(checkpoint, model_path)
if is_best:
best_path = os.path.join(self.save_path, 'model_best.pth.tar')
torch.save({'state_dict': checkpoint['state_dict']}, best_path)
def load_model(self, model_fname=None):
latest_fname = os.path.join(self.save_path, 'latest.txt')
if model_fname is None and os.path.exists(latest_fname):
with open(latest_fname, 'r') as fin:
model_fname = fin.readline()
if model_fname[-1] == '\n':
model_fname = model_fname[:-1]
try:
if model_fname is None or not os.path.exists(model_fname):
model_fname = '%s/checkpoint.pth.tar' % self.save_path
with open(latest_fname, 'w') as fout:
fout.write(model_fname + '\n')
print("=> loading checkpoint '{}'".format(model_fname))
if torch.cuda.is_available():
checkpoint = torch.load(model_fname)
else:
checkpoint = torch.load(model_fname, map_location='cpu')
self.network.load_state_dict(checkpoint['state_dict'])
if 'epoch' in checkpoint:
self.start_epoch = checkpoint['epoch'] + 1 | self.optimizer.load_state_dict(checkpoint['optimizer'])
if self.mix_prec is not None and 'amp' in checkpoint:
from apex import amp
amp.load_state_dict(checkpoint['amp'])
print("=> loaded checkpoint '{}'".format(model_fname))
except Exception:
print('fail to load checkpoint from %s' % self.save_path)
def save_config(self):
""" dump run_config and net_config to the model_folder """
net_save_path = os.path.join(self.path, 'net.config')
json.dump(self.network.config, open(net_save_path, 'w'), indent=4)
print('Network configs dump to %s' % net_save_path)
run_save_path = os.path.join(self.path, 'run.config')
json.dump(self.run_config.config, open(run_save_path, 'w'), indent=4)
print('Run configs dump to %s' % run_save_path)
""" train and test """
def validate(self, epoch=0, is_test=True, run_str='', net=None, data_loader=None, no_logs=False):
if net is None:
net = self.net
if not isinstance(net, nn.DataParallel):
net = nn.DataParallel(net)
if data_loader is None:
if is_test:
data_loader = self.run_config.test_loader
else:
data_loader = self.run_config.valid_loader
net.eval()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
with torch.no_grad():
with tqdm(total=len(data_loader),
desc='Validate Epoch #{} {}'.format(epoch + 1, run_str), disable=no_logs) as t:
for i, (images, labels) in enumerate(data_loader):
images, labels = images.to(self.device), labels.to(self.device)
# compute output
output = net(images)
loss = self.test_criterion(output, labels.long())
# measure accuracy and record loss
acc1 = accuracy(output, labels, topk=(1,))
losses.update(loss.item(), images.size(0))
top1.update(acc1[0].item(), images.size(0))
t.set_postfix({
'loss': losses.avg,
'top1': top1.avg,
'img_size': images.size(2),
})
t.update(1)
return losses.avg, top1.avg
def validate_all_resolution(self, epoch=0, is_test=True, net=None):
if net is None:
net = self.network
if isinstance(self.run_config.data_provider.image_size, list):
img_size_list, loss_list, top1_list, top5_list = [], [], [], []
for img_size in self.run_config.data_provider.image_size:
img_size_list.append(img_size)
self.run_config.data_provider.assign_active_img_size(img_size)
if not self.run_config.flag_FL:
self.reset_running_statistics(net=net)
else:
self.reset_running_statistics(net=None, tag_FL=self.run_config.size_FL)
loss, top1 = self.validate(epoch, is_test, net=net)
loss_list.append(loss)
top1_list.append(top1)
return img_size_list, loss_list, top1_list
else:
loss, top1 = self.validate(epoch, is_test, net=net)
return [self.run_config.data_provider.active_img_size], [loss], [top1]
def train_one_epoch(self, args, epoch, warmup_epochs=0, warmup_lr=0, tag_FL=-1):
# switch to train mode
if tag_FL >= 0:
self.nets_FL[tag_FL].train()
else:
self.net.train()
if tag_FL >= 0:
data_loader = self.run_config.train_FL_loader(tag_FL)
else:
data_loader = self.run_config.train_loader
nBatch = len(data_loader)
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
data_time = AverageMeter()
with tqdm(total=nBatch,
desc='Train Epoch #{}'.format(epoch + 1)) as t:
end = time.time()
for i, (images, labels) in enumerate(data_loader):
data_time.update(time.time() - end)
if tag_FL >= 0:
if epoch < warmup_epochs:
new_lr = self.run_config.warmup_adjust_learning_rate(
self.optimizers_FL[tag_FL], warmup_epochs * nBatch, nBatch, epoch, i, warmup_lr,
)
else:
new_lr = self.run_config.adjust_learning_rate(self.optimizers_FL[tag_FL], epoch - warmup_epochs, i, nBatch)
else:
if epoch < warmup_epochs:
new_lr = self.run_config.warmup_adjust_learning_rate(
self.optimizer, warmup_epochs * nBatch, nBatch, epoch, i, warmup_lr,
)
else:
new_lr = self.run_config.adjust_learning_rate(self.optimizer, epoch - warmup_epochs, i, nBatch)
images, labels = images.to(self.device), labels.to(self.device)
target = labels
# soft target
if args.teacher_model is not None:
args.teacher_model.train()
with torch.no_grad():
soft_logits = args.teacher_model(images).detach()
soft_label = F.softmax(soft_logits, dim=1)
# compute output
if isinstance(self.network, torchvision.models.Inception3):
if tag_FL >= 0:
output, aux_outputs = self.nets_FL[tag_FL](images)
else:
output, aux_outputs = self.net(images)
loss1 = self.train_criterion(output, labels.long())
loss2 = self.train_criterion(aux_outputs, labels.long())
loss = loss1 + 0.4 * loss2
else:
if tag_FL >= 0:
output = self.nets_FL[tag_FL](images)
else:
output = self.net(images)
loss = self.train_criterion(output, labels.long())
if args.teacher_model is None:
loss_type = 'ce'
else:
if args.kd_type == 'ce':
kd_loss = cross_entropy_loss_with_soft_target(output, soft_label)
else:
kd_loss = F.mse_loss(output, soft_logits)
loss = args.kd_ratio * kd_loss + loss
loss_type = '%.1fkd-%s & ce' % (args.kd_ratio, args.kd_type)
# compute gradient and do SGD step
if tag_FL >= 0:
self.nets_FL[tag_FL].zero_grad() # or self.optimizer.zero_grad()
else:
self.net.zero_grad() # or self.optimizer.zero_grad()
if self.mix_prec is not None:
from apex import amp
if tag_FL >= 0:
with amp.scale_loss(loss, self.optimizers_FL[tag_FL]) as scaled_loss:
scaled_loss.backward()
else:
with amp.scale_loss(loss, self.optimizer) as scaled_loss:
scaled_loss.backward()
else:
loss.backward()
if tag_FL >= 0:
self.optimizers_FL[tag_FL].step()
else:
self.optimizer.step()
# measure accuracy and record loss
acc1 = accuracy(output, target, topk=(1,))
losses.update(loss.item(), images.size(0))
top1.update(acc1[0].item(), images.size(0))
t.set_postfix({
'loss': losses.avg,
'top1': top1.avg,
'img_size': images.size(2),
'lr': new_lr,
'loss_type': loss_type,
'data_time': data_time.avg,
})
t.update(1)
end = time.time()
return losses.avg, top1.avg
def FedAvg(self):
if self.run_config.flag_FL:
with torch.no_grad():
base_state = self.network.state_dict()
all_states = []
for _ in range(self.run_config.size_FL):
model = self.network_FL(_)
all_states.append(model.state_dict())
for name in base_state:
for _ in range(self.run_config.size_FL):
# print(all_states[_][name].shape)
# print(all_states[_][name])
tmp_state = (all_states[_][name] / self.run_config.size_FL) if _ == 0 else \
tmp_state + (all_states[_][name] / self.run_config.size_FL)
base_state[name].copy_(tmp_state)
self.network.load_state_dict(base_state)
for _ in range(self.run_config.size_FL):
self.network_FL(_).load_state_dict(base_state)
def train(self, args, warmup_epoch=0, warmup_lr=0, flag_reset_running_statistics=False):
self.init_FL(flag_reset_running_statistics)
for epoch in range(self.start_epoch, self.run_config.n_epochs + warmup_epoch):
if not self.run_config.flag_FL:
train_loss, train_top1 = self.train_one_epoch(args, epoch, warmup_epoch, warmup_lr)
else:
train_loss, train_top1 = [], []
for _ in range(self.run_config.size_FL):
loss, top1 = self.train_one_epoch(args, epoch, warmup_epoch, warmup_lr, _)
train_loss.append(loss)
train_top1.append(top1)
train_loss = np.mean(train_loss)
train_top1 = np.mean(train_top1)
self.FedAvg()
if (epoch + 1) % self.run_config.validation_frequency == 0:
img_size, val_loss, val_acc = self.validate_all_resolution(epoch=epoch, is_test=False)
is_best = np.mean(val_acc) > self.best_acc
self.best_acc = max(self.best_acc, np.mean(val_acc))
val_log = 'Valid [{0}/{1}]\tloss {2:.3f}\ttop-1 acc {3:.3f} ({4:.3f})'. \
format(epoch + 1 - warmup_epoch, self.run_config.n_epochs,
np.mean(val_loss), np.mean(val_acc), self.best_acc)
val_log += '\tTrain top-1 {top1:.3f}\tloss {train_loss:.3f}\t'. \
format(top1=train_top1, train_loss=train_loss)
for i_s, v_a in zip(img_size, val_acc):
val_log += '(%d, %.3f), ' % (i_s, v_a)
self.write_log(val_log, prefix='valid', should_print=False)
else:
is_best = False
self.save_model({
'epoch': epoch,
'best_acc': self.best_acc,
'optimizer': self.optimizer.state_dict(),
'state_dict': self.network.state_dict(),
}, is_best=is_best)
return self.network
def reset_running_statistics(self, net=None, tag_FL=-1):
from ofa.elastic_nn.utils import set_running_statistics
if tag_FL == -1:
if net is None:
net = self.network
sub_train_loader = self.run_config.random_sub_train_loader(2000, 100)
set_running_statistics(net, sub_train_loader)
elif tag_FL == self.run_config.size_FL:
if not self.run_config.flag_FL:
print('Wrong FL client ID')
import sys
sys.exit()
for _ in range(tag_FL):
self.reset_running_statistics(self.network_FL(_), _)
self.FedAvg()
else:
if tag_FL < 0 or tag_FL >= self.run_config.size_FL or not self.run_config.flag_FL:
print('Wrong FL client ID')
import sys
sys.exit()
if net is None:
net = self.network_FL(tag_FL)
sub_train_loader = self.run_config.random_sub_train_loader(2000, 100, tag_FL=tag_FL)
set_running_statistics(net, sub_train_loader) | if 'best_acc' in checkpoint:
self.best_acc = checkpoint['best_acc']
if 'optimizer' in checkpoint: |
memory_store.go | package configsvc
import (
"context"
"d7y.io/dragonfly/v2/pkg/dfcodes"
"d7y.io/dragonfly/v2/pkg/dferrors"
"sort"
"sync"
)
type memoryStore struct {
mu sync.Mutex
configs map[string]*Config
objects map[string]*Config
}
func | () Store {
return &memoryStore{
configs: make(map[string]*Config),
objects: make(map[string]*Config),
}
}
func (memory *memoryStore) AddConfig(ctx context.Context, id string, config *Config) (*Config, error) {
memory.mu.Lock()
defer memory.mu.Unlock()
if _, exist := memory.configs[id]; exist {
return nil, dferrors.Newf(dfcodes.ManagerStoreError, "add config error: id %s", id)
} else {
config.ID = id
memory.configs[id] = config
if objConfig, exist := memory.objects[config.Object]; exist {
if config.Version > objConfig.Version {
delete(memory.objects, config.Object)
memory.objects[config.Object] = config
}
} else {
memory.objects[config.Object] = config
}
return config, nil
}
}
func (memory *memoryStore) DeleteConfig(ctx context.Context, id string) (*Config, error) {
memory.mu.Lock()
defer memory.mu.Unlock()
if config, exist := memory.configs[id]; !exist {
return nil, nil
} else {
delete(memory.configs, id)
if objConfig, exist := memory.objects[config.Object]; exist {
if objConfig.Version == config.Version {
delete(memory.objects, config.Object)
}
}
return config, nil
}
}
func (memory *memoryStore) UpdateConfig(ctx context.Context, id string, config *Config) (*Config, error) {
memory.mu.Lock()
defer memory.mu.Unlock()
if _, exist := memory.configs[id]; !exist {
return nil, dferrors.Newf(dfcodes.ManagerConfigNotFound, "update config error: id %s", id)
} else {
config.ID = id
memory.configs[id] = config
if objConfig, exist := memory.objects[config.Object]; exist {
if objConfig.Version <= config.Version {
memory.objects[config.Object] = config
}
}
return config, nil
}
}
func (memory *memoryStore) GetConfig(ctx context.Context, id string) (*Config, error) {
memory.mu.Lock()
defer memory.mu.Unlock()
if config, exist := memory.configs[id]; exist {
return config, nil
} else {
return nil, dferrors.Newf(dfcodes.ManagerConfigNotFound, "get config error: id %s", id)
}
}
func (memory *memoryStore) ListConfigs(ctx context.Context, object string) ([]*Config, error) {
memory.mu.Lock()
defer memory.mu.Unlock()
return memory.listSortedConfig(ctx, object, 0)
}
func (memory *memoryStore) LatestConfig(ctx context.Context, object string, objType string) (*Config, error) {
memory.mu.Lock()
defer memory.mu.Unlock()
if config, exist := memory.objects[object]; !exist {
configs, err := memory.listSortedConfig(ctx, object, 1)
if err != nil {
return nil, err
}
memory.objects[object] = configs[0]
return configs[0], nil
} else {
if config.Type == objType {
return config, nil
} else {
return nil, dferrors.Newf(dfcodes.ManagerStoreError, "latest config error: object %s, objType %s", object, objType)
}
}
}
func (memory *memoryStore) listSortedConfig(ctx context.Context, object string, maxLen uint32) ([]*Config, error) {
configs := make([]*Config, 0)
for _, config := range memory.configs {
if config.Object == object {
configs = append(configs, config)
}
}
if len(configs) <= 0 {
return nil, dferrors.Newf(dfcodes.ManagerConfigNotFound, "list sorted config error: object %s, maxLen %d", object, maxLen)
}
sort.Sort(SortConfig(configs))
len := uint32(len(configs))
if maxLen == 0 || len <= maxLen {
return configs, nil
} else {
return configs[0:maxLen], nil
}
}
| NewMemoryStore |
test_parallel.py | # flake8: noqa
from typing import Any, Dict, List
import logging
from tempfile import TemporaryDirectory
from pytest import mark
import torch
from torch.utils.data import DataLoader
from catalyst.callbacks import CheckpointCallback, CriterionCallback, OptimizerCallback
from catalyst.core.runner import IRunner
from catalyst.engines import DataParallelEngine
from catalyst.engines.torch import DeviceEngine
from catalyst.loggers import ConsoleLogger, CSVLogger
from catalyst.runners.config import SupervisedConfigRunner
from catalyst.settings import IS_CUDA_AVAILABLE, NUM_CUDA_DEVICES
from .misc import DataParallelTypeChecker, DummyDataset, DummyModel, LossMinimizationCallback
logger = logging.getLogger(__name__)
class CustomRunner(IRunner):
def __init__(self, logdir):
super().__init__()
self._logdir = logdir
def get_engine(self):
return DataParallelEngine()
def get_callbacks(self, stage: str):
return {
"criterion": CriterionCallback(
metric_key="loss", input_key="logits", target_key="targets"
),
"optimizer": OptimizerCallback(metric_key="loss"),
# "scheduler": dl.SchedulerCallback(loader_key="valid", metric_key="loss"),
"checkpoint": CheckpointCallback(
self._logdir, loader_key="valid", metric_key="loss", minimize=True, save_n_best=3
),
"test_nn_parallel_data_parallel": DataParallelTypeChecker(),
"test_loss_minimization": LossMinimizationCallback("loss", logger=logger),
}
@property
def stages(self) -> "Iterable[str]":
return ["train"]
def get_stage_len(self, stage: str) -> int:
return 10
def | (self, stage: str) -> "OrderedDict[str, DataLoader]":
dataset = DummyDataset(6)
loader = DataLoader(dataset, batch_size=4)
return {"train": loader, "valid": loader}
def get_model(self, stage: str):
return DummyModel(4, 2)
def get_criterion(self, stage: str):
return torch.nn.MSELoss()
def get_optimizer(self, model, stage: str):
return torch.optim.Adam(model.parameters())
def get_scheduler(self, optimizer, stage: str):
return None
def get_trial(self):
return None
def get_loggers(self):
return {"console": ConsoleLogger(), "csv": CSVLogger(logdir=self._logdir)}
def handle_batch(self, batch):
x, y = batch
logits = self.model(x)
self.batch = {"features": x, "targets": y, "logits": logits}
def train_from_runner():
with TemporaryDirectory() as logdir:
runner = CustomRunner(logdir)
runner.run()
def train_from_config():
with TemporaryDirectory() as logdir:
dataset = DummyDataset(6)
runner = SupervisedConfigRunner(
config={
"args": {"logdir": logdir},
"model": {"_target_": "DummyModel", "in_features": 4, "out_features": 2},
"engine": {"_target_": "DataParallelEngine"},
"args": {"logdir": logdir},
"stages": {
"stage1": {
"num_epochs": 10,
"loaders": {"batch_size": 4, "num_workers": 0},
"criterion": {"_target_": "MSELoss"},
"optimizer": {"_target_": "Adam", "lr": 1e-3},
"callbacks": {
"criterion": {
"_target_": "CriterionCallback",
"metric_key": "loss",
"input_key": "logits",
"target_key": "targets",
},
"optimizer": {"_target_": "OptimizerCallback", "metric_key": "loss"},
"test_nn_parallel_data_parallel": {
"_target_": "DataParallelTypeChecker"
},
"test_loss_minimization": {
"_target_": "LossMinimizationCallback",
"key": "loss",
},
},
},
},
}
)
runner.get_datasets = lambda *args, **kwargs: {
"train": dataset,
"valid": dataset,
}
runner.run()
@mark.skipif(not IS_CUDA_AVAILABLE, reason="CUDA device is not available")
def test_experiment_parallel_engine_with_cuda():
train_from_runner()
# @mark.skip("Config experiment is in development phase!")
@mark.skipif(not IS_CUDA_AVAILABLE, reason="CUDA device is not available")
def test_config_experiment_engine_with_cuda():
train_from_config()
| get_loaders |
getBalamsatData.py | from cansat import ReadLog
import re
import math as m
temperatura = []
presion = []
aceleracion = []
ax = []
ay = []
az = []
orientacion = []
orientacionFloat =[]
oy = []
oz =[]
alt = []
cont = 0
#Esta funcion valida que los datos del documento sean numeros
#Si no lo son retorna un string Nan
#NOTA IMPORTANTE: Solo funciona en las banderas T P y A debido al formato con que estas llegan
def validateData(i):
try:
value = re.split('=',i)
values = float(value[1])
except ValueError as e:
values = 'Nan'
except IndexError as e:
values = 'No data'
return values
def getTempData(testLogLineString):
temperaturaFloat = []
temperatura = []
cont = 0
#En estas linea se genera una lista que elimina los \n \r y ; de los inicios de cada string
testLogLineStringSplit = re.split('\r|\n|;',testLogLineString)
#En este for se separa la informacion segun la bandera de su línea
for i in testLogLineStringSplit:
if i.startswith('T'):
temperatura.append(validateData(i))
| temperaturaFloat.append(i)
return temperaturaFloat
def getPresData(testLogLineString):
presionFloat = []
presion = []
testLogLineStringSplit = re.split('\r|\n|;',testLogLineString)
for i in testLogLineStringSplit:
if i.startswith('P'):
presion.append(validateData(i))
for i in presion:
if isinstance(i, float):
i = i/100
presionFloat.append(i)
return presionFloat
def getAcData(testLogLineString, n):
aceleracion = []
acFloat = []
testLogLineStringSplit = re.split('\r|\n|;',testLogLineString)
for i in testLogLineStringSplit:
if i.startswith('Ac'):
#Se separa cada valor segun el formato en el que venga y se guardan esos valores en acvalues
acvalues = re.split(' |:Xa=|:Ya=|:Za=|;',i)
#acvalues = re.split(' Xa= | Ya= | Za= ',i)
#Valido que el formato de la linea sea el correcto, a partir de la longitud de acvalues
if len(acvalues) == 4:
try:
aceleracion.append([float(acvalues[1]),float(acvalues[2]),float(acvalues[3])])
except ValueError as e:
aceleracion.append(['Nan','Nan','Nan'])
except IndexError as e:
aceleracion.append(['No data','No data','No data'])
for i in aceleracion:
if isinstance(i[0], float):
acFloat.append(i[n])
return acFloat
def getVelData(aceleracion):
vi = 0
velocidades = []
for i in aceleracion:
vx = vi + (i*50e-3*9.81)
vi = vx
velocidades.append(vx)
return velocidades
def getAlData(testLogLineString):
alt = []
altFloat = []
testLogLineStringSplit = re.split('\r|\n|;',testLogLineString)
for i in testLogLineStringSplit:
if i.startswith('Al'):
try:
value = re.split('=',i)
if len(value) == 2 and float(value[1])>1000:
alt.append(float(value[1]))
except ValueError as e:
alt.append('Nan')
except IndexError as e:
alt.append('Nan')
for i in alt:
if isinstance(i, float):
altFloat.append(i)
return altFloat
def getOrData(testLogLineString,n):
orientacion = []
orientacionFloatx =[]
orientacionFloaty = []
orientacionFloatz = []
testLogLineStringSplit = re.split('\r|\n|;',testLogLineString)
for i in testLogLineStringSplit:
if i.startswith('O'):
orvalues = re.split(':x=|:y=|:z=|;',i)
#orvalues = re.split('x: | y: | z: ',i)
if len(orvalues) >= 4:
try:
if float(orvalues[1]) < 1 and float(orvalues[2]) < 1 and float(orvalues[3]) < 1:
orientacion.append([float(orvalues[1]),float(orvalues[2]),float(orvalues[3])])
except ValueError as e:
orientacion.append(['Nan','Nan','Nan'])
else:
orientacion.append(['No data','No data','No data'])
for i in orientacion:
if isinstance(i[0],float):
orientacionFloatx.append(i[n])
return orientacionFloatx | for i in temperatura:
if isinstance(i, float):
|
ModifyDialog.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ModifyDialogUI.ui'
#
# Created by: PyQt5 UI code generator 5.15.4
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_ModifyDialog(object):
def setupUi(self, ModifyDialog):
ModifyDialog.setObjectName("ModifyDialog")
ModifyDialog.resize(400, 300)
font = QtGui.QFont()
font.setFamily("微软雅黑")
font.setPointSize(13)
ModifyDialog.setFont(font)
self.verticalLayout = QtWidgets.QVBoxLayout(ModifyDialog)
self.verticalLayout.setObjectName("verticalLayout")
self.verticalLayout_4 = QtWidgets.QVBoxLayout()
self.verticalLayout_4.setSpacing(4)
self.verticalLayout_4.setObjectName("verticalLayout_4")
self.horizontalLayout_5 = QtWidgets.QHBoxLayout()
self.horizontalLayout_5.setObjectName("horizontalLayout_5")
self.pic_label = QtWidgets.QLabel(ModifyDialog)
self.pic_label.setMinimumSize(QtCore.QSize(140, 140))
self.pic_label.setMaximumSize(QtCore.QSize(140, 140))
self.pic_label.setObjectName("pic_label")
self.horizontalLayout_5.addWidget(self.pic_label)
self.verticalLayout_2 = QtWidgets.QVBoxLayout()
self.verticalLayout_2.setSpacing(16)
self.verticalLayout_2.setObjectName("verticalLayout_2")
self.horizontalLayout_9 = QtWidgets.QHBoxLayout()
self.horizontalLayout_9.setSpacing(2)
self.horizontalLayout_9.setObjectName("horizontalLayout_9")
self.label_9 = QtWidgets.QLabel(ModifyDialog)
self.label_9.setMaximumSize(QtCore.QSize(45, 16777215))
self.label_9.setBaseSize(QtCore.QSize(0, 0))
font = QtGui.QFont()
font.setFamily("Adobe 黑体 Std R")
font.setPointSize(13)
self.label_9.setFont(font)
self.label_9.setObjectName("label_9")
self.horizontalLayout_9.addWidget(self.label_9)
self.year_lineEdit = QtWidgets.QLineEdit(ModifyDialog)
font = QtGui.QFont()
font.setFamily("微软雅黑")
font.setPointSize(13)
self.year_lineEdit.setFont(font)
self.year_lineEdit.setObjectName("year_lineEdit")
self.horizontalLayout_9.addWidget(self.year_lineEdit)
self.verticalLayout_2.addLayout(self.horizontalLayout_9)
self.horizontalLayout_8 = QtWidgets.QHBoxLayout()
self.horizontalLayout_8.setSpacing(2)
self.horizontalLayout_8.setObjectName("horizontalLayout_8")
self.label_8 = QtWidgets.QLabel(ModifyDialog)
self.label_8.setMaximumSize(QtCore.QSize(45, 16777215))
self.label_8.setBaseSize(QtCore.QSize(0, 0))
font = QtGui.QFont()
font.setFamily("Adobe 黑体 Std R")
font.setPointSize(13)
self.label_8.setFont(font)
self.label_8.setObjectName("label_8")
self.horizontalLayout_8.addWidget(self.label_8)
self.track_number_lineEdit = QtWidgets.QLineEdit(ModifyDialog)
font = QtGui.QFont()
font.setFamily("微软雅黑")
font.setPointSize(13) | self.verticalLayout_2.addLayout(self.horizontalLayout_8)
self.horizontalLayout_7 = QtWidgets.QHBoxLayout()
self.horizontalLayout_7.setSpacing(2)
self.horizontalLayout_7.setObjectName("horizontalLayout_7")
self.label_7 = QtWidgets.QLabel(ModifyDialog)
self.label_7.setMaximumSize(QtCore.QSize(45, 16777215))
self.label_7.setBaseSize(QtCore.QSize(0, 0))
font = QtGui.QFont()
font.setFamily("Adobe 黑体 Std R")
font.setPointSize(13)
self.label_7.setFont(font)
self.label_7.setObjectName("label_7")
self.horizontalLayout_7.addWidget(self.label_7)
self.genre_lineEdit = QtWidgets.QLineEdit(ModifyDialog)
font = QtGui.QFont()
font.setFamily("微软雅黑")
font.setPointSize(13)
self.genre_lineEdit.setFont(font)
self.genre_lineEdit.setObjectName("genre_lineEdit")
self.horizontalLayout_7.addWidget(self.genre_lineEdit)
self.verticalLayout_2.addLayout(self.horizontalLayout_7)
self.horizontalLayout_5.addLayout(self.verticalLayout_2)
self.verticalLayout_4.addLayout(self.horizontalLayout_5)
self.verticalLayout_3 = QtWidgets.QVBoxLayout()
self.verticalLayout_3.setSpacing(4)
self.verticalLayout_3.setObjectName("verticalLayout_3")
self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
self.horizontalLayout_2.setSpacing(2)
self.horizontalLayout_2.setObjectName("horizontalLayout_2")
self.label_3 = QtWidgets.QLabel(ModifyDialog)
self.label_3.setMaximumSize(QtCore.QSize(45, 16777215))
font = QtGui.QFont()
font.setFamily("Adobe 黑体 Std R")
font.setPointSize(12)
self.label_3.setFont(font)
self.label_3.setObjectName("label_3")
self.horizontalLayout_2.addWidget(self.label_3)
self.song_name_lineEdit = QtWidgets.QLineEdit(ModifyDialog)
font = QtGui.QFont()
font.setFamily("微软雅黑")
font.setPointSize(12)
self.song_name_lineEdit.setFont(font)
self.song_name_lineEdit.setObjectName("song_name_lineEdit")
self.horizontalLayout_2.addWidget(self.song_name_lineEdit)
self.verticalLayout_3.addLayout(self.horizontalLayout_2)
self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
self.horizontalLayout_3.setSpacing(2)
self.horizontalLayout_3.setObjectName("horizontalLayout_3")
self.label = QtWidgets.QLabel(ModifyDialog)
self.label.setMaximumSize(QtCore.QSize(45, 16777215))
font = QtGui.QFont()
font.setFamily("Adobe 黑体 Std R")
font.setPointSize(12)
self.label.setFont(font)
self.label.setObjectName("label")
self.horizontalLayout_3.addWidget(self.label)
self.singer_lineEdit = QtWidgets.QLineEdit(ModifyDialog)
font = QtGui.QFont()
font.setFamily("微软雅黑")
font.setPointSize(12)
self.singer_lineEdit.setFont(font)
self.singer_lineEdit.setObjectName("singer_lineEdit")
self.horizontalLayout_3.addWidget(self.singer_lineEdit)
self.verticalLayout_3.addLayout(self.horizontalLayout_3)
self.horizontalLayout_6 = QtWidgets.QHBoxLayout()
self.horizontalLayout_6.setSpacing(2)
self.horizontalLayout_6.setObjectName("horizontalLayout_6")
self.label_6 = QtWidgets.QLabel(ModifyDialog)
self.label_6.setMaximumSize(QtCore.QSize(45, 16777215))
self.label_6.setBaseSize(QtCore.QSize(0, 0))
font = QtGui.QFont()
font.setFamily("Adobe 黑体 Std R")
font.setPointSize(12)
self.label_6.setFont(font)
self.label_6.setObjectName("label_6")
self.horizontalLayout_6.addWidget(self.label_6)
self.album_lineEdit = QtWidgets.QLineEdit(ModifyDialog)
font = QtGui.QFont()
font.setFamily("微软雅黑")
font.setPointSize(12)
self.album_lineEdit.setFont(font)
self.album_lineEdit.setObjectName("album_lineEdit")
self.horizontalLayout_6.addWidget(self.album_lineEdit)
self.verticalLayout_3.addLayout(self.horizontalLayout_6)
self.verticalLayout_4.addLayout(self.verticalLayout_3)
self.verticalLayout.addLayout(self.verticalLayout_4)
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem)
self.upload_pic_button = QtWidgets.QPushButton(ModifyDialog)
font = QtGui.QFont()
font.setFamily("微软雅黑")
font.setPointSize(12)
self.upload_pic_button.setFont(font)
self.upload_pic_button.setObjectName("upload_pic_button")
self.horizontalLayout.addWidget(self.upload_pic_button)
self.buttonBox = QtWidgets.QDialogButtonBox(ModifyDialog)
font = QtGui.QFont()
font.setFamily("微软雅黑")
font.setPointSize(12)
self.buttonBox.setFont(font)
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
self.buttonBox.setObjectName("buttonBox")
self.horizontalLayout.addWidget(self.buttonBox)
spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout.addItem(spacerItem1)
self.verticalLayout.addLayout(self.horizontalLayout)
self.retranslateUi(ModifyDialog)
self.buttonBox.accepted.connect(ModifyDialog.accept)
self.buttonBox.rejected.connect(ModifyDialog.reject)
QtCore.QMetaObject.connectSlotsByName(ModifyDialog)
def retranslateUi(self, ModifyDialog):
_translate = QtCore.QCoreApplication.translate
ModifyDialog.setWindowTitle(_translate("ModifyDialog", "Dialog"))
self.pic_label.setText(_translate("ModifyDialog", "N/A"))
self.label_9.setText(_translate("ModifyDialog", "年份"))
self.label_8.setText(_translate("ModifyDialog", "序号"))
self.label_7.setText(_translate("ModifyDialog", "流派"))
self.label_3.setText(_translate("ModifyDialog", "曲名"))
self.label.setText(_translate("ModifyDialog", "歌手"))
self.label_6.setText(_translate("ModifyDialog", "专辑"))
self.upload_pic_button.setText(_translate("ModifyDialog", "上传专辑图片")) | self.track_number_lineEdit.setFont(font)
self.track_number_lineEdit.setObjectName("track_number_lineEdit")
self.horizontalLayout_8.addWidget(self.track_number_lineEdit) |
conftest.py | import pytest
from naturalnets.brains.i_layer_based_brain import ILayerBasedBrainCfg
from tests.pytorch_brains import IPytorchBrainCfg
@pytest.fixture
def | () -> IPytorchBrainCfg:
return IPytorchBrainCfg(type="GRU_PyTorch", num_layers=3,
hidden_size=8,
use_bias=False)
@pytest.fixture
def numpy_config() -> ILayerBasedBrainCfg:
return ILayerBasedBrainCfg(type="GRULayered", hidden_layer_structure=[8, 8, 8], diagonal_hidden_to_hidden=False,
use_bias=False)
| torch_config |
loadbalancers.go | package network
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
import (
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"net/http"
"net/url"
)
// LoadBalancersClient is the the Microsoft Azure Network management API
// provides a RESTful set of web services that interact with Microsoft Azure
// Networks service to manage your network resrources. The API has entities
// that capture the relationship between an end user and the Microsoft Azure
// Networks service.
type LoadBalancersClient struct {
ManagementClient
}
// NewLoadBalancersClient creates an instance of the LoadBalancersClient
// client.
func NewLoadBalancersClient(subscriptionID string) LoadBalancersClient |
// NewLoadBalancersClientWithBaseURI creates an instance of the
// LoadBalancersClient client.
func NewLoadBalancersClientWithBaseURI(baseURI string, subscriptionID string) LoadBalancersClient {
return LoadBalancersClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// CreateOrUpdate the Put LoadBalancer operation creates/updates a
// LoadBalancer This method may poll for completion. Polling can be canceled
// by passing the cancel channel argument. The channel will be used to cancel
// polling and any outstanding HTTP requests.
//
// resourceGroupName is the name of the resource group. loadBalancerName is
// the name of the loadBalancer. parameters is parameters supplied to the
// create/delete LoadBalancer operation
func (client LoadBalancersClient) CreateOrUpdate(resourceGroupName string, loadBalancerName string, parameters LoadBalancer, cancel <-chan struct{}) (result autorest.Response, err error) {
req, err := client.CreateOrUpdatePreparer(resourceGroupName, loadBalancerName, parameters, cancel)
if err != nil {
return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "CreateOrUpdate", nil, "Failure preparing request")
}
resp, err := client.CreateOrUpdateSender(req)
if err != nil {
result.Response = resp
return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "CreateOrUpdate", resp, "Failure sending request")
}
result, err = client.CreateOrUpdateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "CreateOrUpdate", resp, "Failure responding to request")
}
return
}
// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
func (client LoadBalancersClient) CreateOrUpdatePreparer(resourceGroupName string, loadBalancerName string, parameters LoadBalancer, cancel <-chan struct{}) (*http.Request, error) {
pathParameters := map[string]interface{}{
"loadBalancerName": url.QueryEscape(loadBalancerName),
"resourceGroupName": url.QueryEscape(resourceGroupName),
"subscriptionId": url.QueryEscape(client.SubscriptionID),
}
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
return autorest.Prepare(&http.Request{Cancel: cancel},
autorest.AsJSON(),
autorest.AsPut(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPath("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}"),
autorest.WithJSON(parameters),
autorest.WithPathParameters(pathParameters),
autorest.WithQueryParameters(queryParameters))
}
// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the
// http.Response Body if it receives an error.
func (client LoadBalancersClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client,
req,
azure.DoPollForAsynchronous(client.PollingDelay))
}
// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always
// closes the http.Response Body.
func (client LoadBalancersClient) CreateOrUpdateResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusCreated, http.StatusOK),
autorest.ByClosing())
result.Response = resp
return
}
// Delete the delete loadbalancer operation deletes the specified
// loadbalancer. This method may poll for completion. Polling can be canceled
// by passing the cancel channel argument. The channel will be used to cancel
// polling and any outstanding HTTP requests.
//
// resourceGroupName is the name of the resource group. loadBalancerName is
// the name of the loadBalancer.
func (client LoadBalancersClient) Delete(resourceGroupName string, loadBalancerName string, cancel <-chan struct{}) (result autorest.Response, err error) {
req, err := client.DeletePreparer(resourceGroupName, loadBalancerName, cancel)
if err != nil {
return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Delete", nil, "Failure preparing request")
}
resp, err := client.DeleteSender(req)
if err != nil {
result.Response = resp
return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Delete", resp, "Failure sending request")
}
result, err = client.DeleteResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Delete", resp, "Failure responding to request")
}
return
}
// DeletePreparer prepares the Delete request.
func (client LoadBalancersClient) DeletePreparer(resourceGroupName string, loadBalancerName string, cancel <-chan struct{}) (*http.Request, error) {
pathParameters := map[string]interface{}{
"loadBalancerName": url.QueryEscape(loadBalancerName),
"resourceGroupName": url.QueryEscape(resourceGroupName),
"subscriptionId": url.QueryEscape(client.SubscriptionID),
}
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
return autorest.Prepare(&http.Request{Cancel: cancel},
autorest.AsJSON(),
autorest.AsDelete(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPath("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}"),
autorest.WithPathParameters(pathParameters),
autorest.WithQueryParameters(queryParameters))
}
// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client LoadBalancersClient) DeleteSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client,
req,
azure.DoPollForAsynchronous(client.PollingDelay))
}
// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client LoadBalancersClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusNoContent, http.StatusAccepted, http.StatusOK),
autorest.ByClosing())
result.Response = resp
return
}
// Get the Get ntework interface operation retreives information about the
// specified network interface.
//
// resourceGroupName is the name of the resource group. loadBalancerName is
// the name of the loadBalancer. expand is expand references resources.
func (client LoadBalancersClient) Get(resourceGroupName string, loadBalancerName string, expand string) (result LoadBalancer, err error) {
req, err := client.GetPreparer(resourceGroupName, loadBalancerName, expand)
if err != nil {
return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Get", nil, "Failure preparing request")
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Get", resp, "Failure sending request")
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "Get", resp, "Failure responding to request")
}
return
}
// GetPreparer prepares the Get request.
func (client LoadBalancersClient) GetPreparer(resourceGroupName string, loadBalancerName string, expand string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"loadBalancerName": url.QueryEscape(loadBalancerName),
"resourceGroupName": url.QueryEscape(resourceGroupName),
"subscriptionId": url.QueryEscape(client.SubscriptionID),
}
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
if len(expand) > 0 {
queryParameters["$expand"] = expand
}
return autorest.Prepare(&http.Request{},
autorest.AsJSON(),
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPath("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}"),
autorest.WithPathParameters(pathParameters),
autorest.WithQueryParameters(queryParameters))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client LoadBalancersClient) GetSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req)
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client LoadBalancersClient) GetResponder(resp *http.Response) (result LoadBalancer, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// List the List loadBalancer opertion retrieves all the loadbalancers in a
// resource group.
//
// resourceGroupName is the name of the resource group.
func (client LoadBalancersClient) List(resourceGroupName string) (result LoadBalancerListResult, err error) {
req, err := client.ListPreparer(resourceGroupName)
if err != nil {
return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "List", nil, "Failure preparing request")
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "List", resp, "Failure sending request")
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "List", resp, "Failure responding to request")
}
return
}
// ListPreparer prepares the List request.
func (client LoadBalancersClient) ListPreparer(resourceGroupName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": url.QueryEscape(resourceGroupName),
"subscriptionId": url.QueryEscape(client.SubscriptionID),
}
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
return autorest.Prepare(&http.Request{},
autorest.AsJSON(),
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPath("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers"),
autorest.WithPathParameters(pathParameters),
autorest.WithQueryParameters(queryParameters))
}
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client LoadBalancersClient) ListSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req)
}
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client LoadBalancersClient) ListResponder(resp *http.Response) (result LoadBalancerListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListNextResults retrieves the next set of results, if any.
func (client LoadBalancersClient) ListNextResults(lastResults LoadBalancerListResult) (result LoadBalancerListResult, err error) {
req, err := lastResults.LoadBalancerListResultPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "List", nil, "Failure preparing next results request request")
}
if req == nil {
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "List", resp, "Failure sending next results request request")
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "List", resp, "Failure responding to next results request request")
}
return
}
// ListAll the List loadBalancer opertion retrieves all the loadbalancers in a
// subscription.
func (client LoadBalancersClient) ListAll() (result LoadBalancerListResult, err error) {
req, err := client.ListAllPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "ListAll", nil, "Failure preparing request")
}
resp, err := client.ListAllSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "ListAll", resp, "Failure sending request")
}
result, err = client.ListAllResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "ListAll", resp, "Failure responding to request")
}
return
}
// ListAllPreparer prepares the ListAll request.
func (client LoadBalancersClient) ListAllPreparer() (*http.Request, error) {
pathParameters := map[string]interface{}{
"subscriptionId": url.QueryEscape(client.SubscriptionID),
}
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
return autorest.Prepare(&http.Request{},
autorest.AsJSON(),
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPath("/subscriptions/{subscriptionId}/providers/Microsoft.Network/loadBalancers"),
autorest.WithPathParameters(pathParameters),
autorest.WithQueryParameters(queryParameters))
}
// ListAllSender sends the ListAll request. The method will close the
// http.Response Body if it receives an error.
func (client LoadBalancersClient) ListAllSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req)
}
// ListAllResponder handles the response to the ListAll request. The method always
// closes the http.Response Body.
func (client LoadBalancersClient) ListAllResponder(resp *http.Response) (result LoadBalancerListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListAllNextResults retrieves the next set of results, if any.
func (client LoadBalancersClient) ListAllNextResults(lastResults LoadBalancerListResult) (result LoadBalancerListResult, err error) {
req, err := lastResults.LoadBalancerListResultPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "ListAll", nil, "Failure preparing next results request request")
}
if req == nil {
return
}
resp, err := client.ListAllSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "network.LoadBalancersClient", "ListAll", resp, "Failure sending next results request request")
}
result, err = client.ListAllResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "network.LoadBalancersClient", "ListAll", resp, "Failure responding to next results request request")
}
return
}
| {
return NewLoadBalancersClientWithBaseURI(DefaultBaseURI, subscriptionID)
} |
de.rs | use criterion::{black_box, criterion_group, criterion_main, Criterion};
use serenity_voice_model::Event;
pub fn json_deser(c: &mut Criterion) {
let json_data = r#"{
"op": 2,
"d": {
"ssrc": 1,
"ip": "127.0.0.1",
"port": 1234,
"modes": ["xsalsa20_poly1305", "xsalsa20_poly1305_suffix", "xsalsa20_poly1305_lite"],
"heartbeat_interval": 1
}
}"#;
let wonky_json_data = r#"{
"d": {
"ssrc": 1,
"ip": "127.0.0.1",
"port": 1234,
"modes": ["xsalsa20_poly1305", "xsalsa20_poly1305_suffix", "xsalsa20_poly1305_lite"],
"heartbeat_interval": 1
},
"op": 2
}"#; |
c.bench_function("Ready event (bad order)", |b| {
b.iter(|| serde_json::from_str::<Event>(black_box(wonky_json_data)))
});
}
criterion_group!(benches, json_deser);
criterion_main!(benches); |
c.bench_function("Ready event", |b| {
b.iter(|| serde_json::from_str::<Event>(black_box(json_data)))
}); |
luareader.go | // SPDX-License-Identifier: ISC
// Copyright (c) 2014-2020 Bitmark Inc.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package configuration
import (
"net"
"runtime"
"github.com/yuin/gluamapper"
lua "github.com/yuin/gopher-lua"
)
// ParseConfigurationFile - read and execute a Lua files and assign
// the results to a configuration structure
func ParseConfigurationFile(fileName string, config interface{}) error | {
L := lua.NewState()
defer L.Close()
L.OpenLibs()
// create the global "arg" table
// arg[0] = config file
arg := &lua.LTable{}
arg.Insert(0, lua.LString(fileName))
L.SetGlobal("arg", arg)
// prepare global "interface_public_ips" table
addrList, err := net.InterfaceAddrs()
if nil == err {
// RFC 1918 (Address Allocation for Private Internets) [/8 /12 and /16]
rfc1918_8 := net.ParseIP("10.0.0.0")
rfc1918_12 := net.ParseIP("172.16.0.0")
rfc1918_16 := net.ParseIP("192.168.0.0")
// RFC 3927 (Dynamic Configuration of IPv4 Link-Local Addresses) [/16]
rfc3927_16 := net.ParseIP("169.254.0.0")
// RFC 4193 (Unique Local IPv6 Unicast Addresses) [/7]
rfc4193_7 := net.ParseIP("fc00::")
// table for the list of addresses
addr := &lua.LTable{}
j := 1 // lua indices start at 1
ip_loop:
for _, a := range addrList {
ip, _, err := net.ParseCIDR(a.String())
if nil != err || !ip.IsGlobalUnicast() {
// exclude most non-routable addresses
// like loopback and IPv6 link local
continue ip_loop
}
if ip4 := ip.To4(); nil != ip4 {
// mask to specific IPv4 network sizes
ip4_8 := ip4.Mask(net.CIDRMask(8, 32))
ip4_12 := ip4.Mask(net.CIDRMask(12, 32))
ip4_16 := ip4.Mask(net.CIDRMask(16, 32))
// check if IPv4 non-routable addresses
if ip4_8.Equal(rfc1918_8) ||
ip4_12.Equal(rfc1918_12) ||
ip4_16.Equal(rfc1918_16) ||
ip4_16.Equal(rfc3927_16) {
continue ip_loop
}
} else { // IPv6
// mask to specific IPv6 network sizes
ip6_7 := ip.Mask(net.CIDRMask(7, 128))
// check if IPv6 non-routable addresses
if ip6_7.Equal(rfc4193_7) {
continue ip_loop
}
}
addr.Insert(j, lua.LString(ip.String()))
j += 1
}
L.SetGlobal("interface_public_ips", addr)
}
// some information about the platform
L.SetGlobal("arch_name", lua.LString(runtime.GOARCH))
L.SetGlobal("os_name", lua.LString(runtime.GOOS))
// execute configuration
if err := L.DoFile(fileName); err != nil {
return err
}
mapperOption := gluamapper.Option{
NameFunc: func(s string) string {
return s
},
TagName: "gluamapper",
}
mapper := gluamapper.Mapper{Option: mapperOption}
err = mapper.Map(L.Get(L.GetTop()).(*lua.LTable), config)
return err
} |
|
mod.rs | // -*- mode: rust; -*-
//
// This file is part of curve25519-dalek.
// Copyright (c) 2016-2019 Isis Lovecruft, Henry de Valence
// See LICENSE for licensing information.
//
// Authors:
// - Isis Agora Lovecruft <[email protected]>
// - Henry de Valence <[email protected]>
//! Pluggable implementations for different architectures.
//!
//! The backend code is split into two parts: a serial backend,
//! and a vector backend.
//!
//! The [`serial`] backend contains 32- and 64-bit implementations of | //!
//! The [`vector`] backend contains implementations of vectorized
//! field arithmetic, used to implement point operations using a novel
//! implementation strategy derived from parallel formulas of Hisil,
//! Wong, Carter, and Dawson.
//!
//! Because the two strategies give rise to different curve models,
//! it's not possible to reuse exactly the same scalar multiplication
//! code (or to write it generically), so both serial and vector
//! backends contain matching implementations of scalar multiplication
//! algorithms. These are intended to be selected by a `#[cfg]`-based
//! type alias.
//!
//! The [`vector`] backend is selected by the `simd_backend` cargo
//! feature; it uses the [`serial`] backend for non-vectorized operations.
#[cfg(not(any(
feature = "u32_backend",
feature = "u64_backend",
feature = "simd_backend",
)))]
compile_error!(
"no curve25519-dalek backend cargo feature enabled! \
please enable one of: u32_backend, u64_backend, simd_backend"
);
pub mod serial;
#[cfg(any(
all(
feature = "simd_backend",
any(target_feature = "avx2", target_feature = "avx512ifma")
),
all(feature = "nightly", rustdoc)
))]
#[cfg_attr(
feature = "nightly",
doc(cfg(any(all(
feature = "simd_backend",
any(target_feature = "avx2", target_feature = "avx512ifma")
))))
)]
pub mod vector; | //! field arithmetic and scalar arithmetic, as well as implementations
//! of point operations using the mixed-model strategy (passing
//! between different curve models depending on the operation). |
file.rs | use clap::Clap;
/// Writes a file on the server
#[derive(Clap, Debug)]
pub struct WriteFileCommand {
/// Path to the file
#[clap(parse(try_from_str))]
pub path: String,
/// Content to write to the file
#[clap(parse(try_from_str))]
pub contents: String,
}
/// Reads a file on the server
#[derive(Clap, Debug)]
pub struct ReadFileCommand {
/// Path to the file
#[clap(parse(try_from_str))]
pub path: String,
}
/// Moves a file at the specified path on the server to the new path
#[derive(Clap, Debug)]
pub struct MoveFileCommand {
/// Origin path of the file to move
#[clap(parse(try_from_str))]
pub from: String,
/// Destination path of the file to move
#[clap(parse(try_from_str))] | pub to: String,
}
/// Removes a file at the specified path on the server
#[derive(Clap, Debug)]
pub struct RemoveFileCommand {
/// Path of the file to remove
#[clap(parse(try_from_str))]
pub path: String,
} | |
utils.py | from tqdm import tqdm
import numpy as np
import torch
import torch.nn as nn
def build_mlp(input_dim, output_dim, hidden_units=[64, 64],
hidden_activation=nn.Tanh(), output_activation=None):
layers = []
units = input_dim
for next_units in hidden_units:
layers.append(nn.Linear(units, next_units))
layers.append(hidden_activation)
units = next_units
layers.append(nn.Linear(units, output_dim))
if output_activation is not None: | return nn.Sequential(*layers)
def dict_concat(x):
return torch.cat([value for key, value in x.items()], dim=0)
def dict_config_concat(x):
return torch.cat([torch.cat((value, key.repeat(value.size(0),1)), dim=1) for key, value in x.items()], dim=0) | layers.append(output_activation) |
dom.js | import * as Util from './util';
const docStyle = window.document.documentElement.style;
function testProp(props) {
if (!docStyle) return props[0];
for (let i = 0; i < props.length; i++) {
if (props[i] in docStyle) {
return props[i];
}
}
return props[0];
}
export function create(tagName, className, container) {
const el = document.createElement(tagName);
el.className = className || '';
if (container) {
container.appendChild(el);
}
return el;
}
// @function remove(el: HTMLElement)
// Removes `el` from its parent element
export function remove(el) {
const parent = el.parentNode;
if (parent) {
parent.removeChild(el);
}
}
// @function addClass(el: HTMLElement, name: String)
// Adds `name` to the element's class attribute.
export function addClass(el, name) {
if (el.classList !== undefined) {
const classes = Util.splitWords(name);
for (let i = 0, len = classes.length; i < len; i++) {
el.classList.add(classes[i]);
}
} else if (!hasClass(el, name)) {
const className = getClass(el);
setClass(el, (className ? className + ' ' : '') + name);
}
}
// @function removeClass(el: HTMLElement, name: String)
// Removes `name` from the element's class attribute.
export function removeClass(el, name) {
if (el.classList !== undefined) {
el.classList.remove(name);
} else {
setClass(el, Util.trim((' ' + getClass(el) + ' ').replace(' ' + name + ' ', ' '))); | // @function hasClass(el: HTMLElement, name: String): Boolean
// Returns `true` if the element's class attribute contains `name`.
export function hasClass(el, name) {
if (el.classList !== undefined) {
return el.classList.contains(name);
}
const className = getClass(el);
return className.length > 0 && new RegExp('(^|\\s)' + name + '(\\s|$)').test(className);
}
// @function setClass(el: HTMLElement, name: String)
// Sets the element's class.
export function setClass(el, name) {
if (el.className.baseVal === undefined) {
el.className = name;
} else {
// in case of SVG element
el.className.baseVal = name;
}
}
// @function getClass(el: HTMLElement): String
// Returns the element's class.
export function getClass(el) {
// Check if the element is an SVGElementInstance and use the correspondingElement instead
// (Required for linked SVG elements in IE11.)
if (el.correspondingElement) {
el = el.correspondingElement;
}
return el.className.baseVal === undefined ? el.className : el.className.baseVal;
}
export function empty(el) {
while (el.firstChild) {
el.removeChild(el.firstChild);
}
}
const transformProp = testProp([ 'transform', 'WebkitTransform' ]);
export function setTransform(el, value) {
el.style[transformProp] = value;
} | }
}
|
table.go | // Copyright 2019 Dolthub, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package doltdb
import (
"context"
"errors"
"fmt"
"regexp"
"strings"
"unicode"
"github.com/dolthub/go-mysql-server/sql"
"github.com/dolthub/dolt/go/libraries/doltcore/conflict"
"github.com/dolthub/dolt/go/libraries/doltcore/doltdb/durable"
"github.com/dolthub/dolt/go/libraries/doltcore/schema"
"github.com/dolthub/dolt/go/libraries/doltcore/schema/typeinfo"
"github.com/dolthub/dolt/go/store/hash"
"github.com/dolthub/dolt/go/store/types"
)
const (
// TableNameRegexStr is the regular expression that valid tables must match.
TableNameRegexStr = `^[a-zA-Z]{1}$|^[a-zA-Z_]+[-_0-9a-zA-Z]*[0-9a-zA-Z]+$`
// ForeignKeyNameRegexStr is the regular expression that valid foreign keys must match.
// From the unquoted identifiers: https://dev.mysql.com/doc/refman/8.0/en/identifiers.html
// We also allow the '-' character from quoted identifiers.
ForeignKeyNameRegexStr = `^[-$_0-9a-zA-Z]+$`
// IndexNameRegexStr is the regular expression that valid indexes must match.
// From the unquoted identifiers: https://dev.mysql.com/doc/refman/8.0/en/identifiers.html
// We also allow the '-' character from quoted identifiers.
IndexNameRegexStr = `^[-$_0-9a-zA-Z]+$`
)
var (
tableNameRegex = regexp.MustCompile(TableNameRegexStr)
foreignKeyNameRegex = regexp.MustCompile(ForeignKeyNameRegexStr)
indexNameRegex = regexp.MustCompile(IndexNameRegexStr)
ErrNoConflictsResolved = errors.New("no conflicts resolved")
)
// IsValidTableName returns true if the name matches the regular expression TableNameRegexStr.
// Table names must be composed of 1 or more letters and non-initial numerals, as well as the characters _ and -
func IsValidTableName(name string) bool {
// Ignore all leading digits
name = strings.TrimLeftFunc(name, unicode.IsDigit)
return tableNameRegex.MatchString(name)
}
// IsValidForeignKeyName returns true if the name matches the regular expression ForeignKeyNameRegexStr.
func IsValidForeignKeyName(name string) bool {
return foreignKeyNameRegex.MatchString(name)
}
// IsValidIndexName returns true if the name matches the regular expression IndexNameRegexStr.
func IsValidIndexName(name string) bool {
return indexNameRegex.MatchString(name)
}
// Table is a struct which holds row data, as well as a reference to its schema.
type Table struct {
table durable.Table
}
// NewNomsTable creates a noms Struct which stores row data, index data, and schema.
func NewNomsTable(ctx context.Context, vrw types.ValueReadWriter, sch schema.Schema, rows types.Map, indexes durable.IndexSet, autoIncVal types.Value) (*Table, error) {
dt, err := durable.NewNomsTable(ctx, vrw, sch, rows, indexes, autoIncVal)
if err != nil {
return nil, err
}
return &Table{table: dt}, nil
}
// NewTable creates a durable object which stores row data, index data, and schema.
func NewTable(ctx context.Context, vrw types.ValueReadWriter, sch schema.Schema, rows durable.Index, indexes durable.IndexSet, autoIncVal types.Value) (*Table, error) {
dt, err := durable.NewTable(ctx, vrw, sch, rows, indexes, autoIncVal)
if err != nil {
return nil, err
}
return &Table{table: dt}, nil
}
// Format returns the NomsBinFormat for this table.
func (t *Table) Format() *types.NomsBinFormat {
return t.ValueReadWriter().Format()
}
// ValueReadWriter returns the ValueReadWriter for this table.
func (t *Table) ValueReadWriter() types.ValueReadWriter {
return durable.VrwFromTable(t.table)
}
// SetConflicts sets the merge conflicts for this table.
func (t *Table) SetConflicts(ctx context.Context, schemas conflict.ConflictSchema, conflictData types.Map) (*Table, error) {
table, err := t.table.SetConflicts(ctx, schemas, conflictData)
if err != nil {
return nil, err
}
return &Table{table: table}, nil
}
// GetConflicts returns a map built from ValueReadWriter when there are no conflicts in table.
func (t *Table) GetConflicts(ctx context.Context) (conflict.ConflictSchema, types.Map, error) {
return t.table.GetConflicts(ctx)
}
// HasConflicts returns true if this table contains merge conflicts.
func (t *Table) HasConflicts(ctx context.Context) (bool, error) {
return t.table.HasConflicts(ctx)
}
// NumRowsInConflict returns the number of rows with merge conflicts for this table.
func (t *Table) NumRowsInConflict(ctx context.Context) (uint64, error) {
ok, err := t.table.HasConflicts(ctx)
if err != nil {
return 0, err
}
if !ok {
return 0, nil
}
_, cons, err := t.table.GetConflicts(ctx)
if err != nil {
return 0, err
}
return cons.Len(), nil
}
// ClearConflicts deletes all merge conflicts for this table.
func (t *Table) ClearConflicts(ctx context.Context) (*Table, error) {
table, err := t.table.ClearConflicts(ctx)
if err != nil {
return nil, err
}
return &Table{table: table}, nil
}
// GetConflictSchemas returns the merge conflict schemas for this table.
func (t *Table) GetConflictSchemas(ctx context.Context) (base, sch, mergeSch schema.Schema, err error) {
cs, _, err := t.table.GetConflicts(ctx)
if err != nil {
return nil, nil, nil, err
}
return cs.Base, cs.Schema, cs.MergeSchema, nil
}
// GetConstraintViolationsSchema returns this table's dolt_constraint_violations system table schema.
func (t *Table) GetConstraintViolationsSchema(ctx context.Context) (schema.Schema, error) {
sch, err := t.GetSchema(ctx)
if err != nil {
return nil, err
}
typeType, err := typeinfo.FromSqlType(
sql.MustCreateEnumType([]string{"foreign key", "unique index", "check constraint"}, sql.Collation_Default))
if err != nil {
return nil, err
}
typeCol, err := schema.NewColumnWithTypeInfo("violation_type", schema.DoltConstraintViolationsTypeTag, typeType, true, "", false, "")
if err != nil {
return nil, err
}
infoCol, err := schema.NewColumnWithTypeInfo("violation_info", schema.DoltConstraintViolationsInfoTag, typeinfo.JSONType, false, "", false, "")
if err != nil {
return nil, err
}
colColl := schema.NewColCollection()
colColl = colColl.Append(typeCol)
colColl = colColl.Append(sch.GetAllCols().GetColumns()...)
colColl = colColl.Append(infoCol)
return schema.SchemaFromCols(colColl)
}
// GetConstraintViolations returns a map of all constraint violations for this table, along with a bool indicating
// whether the table has any violations.
func (t *Table) GetConstraintViolations(ctx context.Context) (types.Map, error) {
return t.table.GetConstraintViolations(ctx)
}
// SetConstraintViolations sets this table's violations to the given map. If the map is empty, then the constraint
// violations entry on the embedded struct is removed.
func (t *Table) SetConstraintViolations(ctx context.Context, violationsMap types.Map) (*Table, error) {
table, err := t.table.SetConstraintViolations(ctx, violationsMap)
if err != nil {
return nil, err
}
return &Table{table: table}, nil
}
// GetSchema will retrieve the schema being referenced from the table in noms and unmarshal it.
func (t *Table) GetSchema(ctx context.Context) (schema.Schema, error) {
return t.table.GetSchema(ctx)
}
// GetSchemaHash returns the hash of this table's schema.
func (t *Table) GetSchemaHash(ctx context.Context) (hash.Hash, error) {
return t.table.GetSchemaHash(ctx)
}
// UpdateSchema updates the table with the schema given and returns the updated table. The original table is unchanged.
// This method only updates the schema of a table; the row data is unchanged. Schema alterations that require rebuilding
// the table (e.g. adding a column in the middle, adding a new non-null column, adding a column in the middle of a
// schema) must account for these changes separately.
func (t *Table) UpdateSchema(ctx context.Context, sch schema.Schema) (*Table, error) {
table, err := t.table.SetSchema(ctx, sch)
if err != nil {
return nil, err
}
return &Table{table: table}, nil
}
// HashOf returns the hash of the underlying table struct.
func (t *Table) HashOf() (hash.Hash, error) {
return t.table.HashOf()
}
// UpdateNomsRows replaces the current row data and returns and updated Table.
// Calls to UpdateNomsRows will not be written to the database. The root must
// be updated with the updated table, and the root must be committed or written.
func (t *Table) UpdateNomsRows(ctx context.Context, updatedRows types.Map) (*Table, error) {
table, err := t.table.SetTableRows(ctx, durable.IndexFromNomsMap(updatedRows, t.ValueReadWriter()))
if err != nil {
return nil, err
}
return &Table{table: table}, nil
}
// UpdateRows replaces the current row data and returns and updated Table.
// Calls to UpdateRows will not be written to the database. The root must
// be updated with the updated table, and the root must be committed or written.
func (t *Table) UpdateRows(ctx context.Context, updatedRows durable.Index) (*Table, error) {
table, err := t.table.SetTableRows(ctx, updatedRows)
if err != nil {
return nil, err
}
return &Table{table: table}, nil
}
// GetNomsRowData retrieves the underlying map which is a map from a primary key to a list of field values.
func (t *Table) GetNomsRowData(ctx context.Context) (types.Map, error) {
idx, err := t.table.GetTableRows(ctx)
if err != nil {
return types.Map{}, err
}
return durable.NomsMapFromIndex(idx), nil
}
// GetRowData retrieves the underlying map which is a map from a primary key to a list of field values.
func (t *Table) GetRowData(ctx context.Context) (durable.Index, error) {
return t.table.GetTableRows(ctx)
}
// ResolveConflicts resolves conflicts for this table.
func (t *Table) ResolveConflicts(ctx context.Context, pkTuples []types.Value) (invalid, notFound []types.Value, tbl *Table, err error) {
removed := 0
conflictSchema, confData, err := t.GetConflicts(ctx)
if err != nil {
return nil, nil, nil, err
}
confEdit := confData.Edit()
for _, pkTupleVal := range pkTuples {
if has, err := confData.Has(ctx, pkTupleVal); err != nil {
return nil, nil, nil, err
} else if has {
removed++
confEdit.Remove(pkTupleVal)
} else {
notFound = append(notFound, pkTupleVal)
}
}
if removed == 0 {
return invalid, notFound, tbl, ErrNoConflictsResolved
}
conflicts, err := confEdit.Map(ctx)
if err != nil {
return nil, nil, nil, err
}
if conflicts.Len() == 0 {
table, err := t.table.ClearConflicts(ctx)
if err != nil {
return nil, nil, nil, err
}
return invalid, notFound, &Table{table: table}, nil
}
table, err := t.table.SetConflicts(ctx, conflictSchema, conflicts)
if err != nil {
return nil, nil, nil, err
}
return invalid, notFound, &Table{table: table}, nil
}
// GetIndexSet returns the internal index map which goes from index name to a ref of the row data map.
func (t *Table) GetIndexSet(ctx context.Context) (durable.IndexSet, error) {
return t.table.GetIndexes(ctx)
}
// SetIndexSet replaces the current internal index map, and returns an updated Table.
func (t *Table) SetIndexSet(ctx context.Context, indexes durable.IndexSet) (*Table, error) {
table, err := t.table.SetIndexes(ctx, indexes)
if err != nil {
return nil, err
}
return &Table{table: table}, nil
}
// GetNomsIndexRowData retrieves the underlying map of an index, in which the primary key consists of all indexed columns.
func (t *Table) GetNomsIndexRowData(ctx context.Context, indexName string) (types.Map, error) {
sch, err := t.GetSchema(ctx)
if err != nil {
return types.EmptyMap, err
}
indexes, err := t.GetIndexSet(ctx)
if err != nil {
return types.EmptyMap, err
}
idx, err := indexes.GetIndex(ctx, sch, indexName)
if err != nil {
return types.EmptyMap, err
}
return durable.NomsMapFromIndex(idx), nil
}
// GetIndexRowData retrieves the underlying map of an index, in which the primary key consists of all indexed columns.
func (t *Table) GetIndexRowData(ctx context.Context, indexName string) (durable.Index, error) {
sch, err := t.GetSchema(ctx)
if err != nil {
return nil, err
}
indexes, err := t.GetIndexSet(ctx)
if err != nil {
return nil, err
}
return indexes.GetIndex(ctx, sch, indexName)
}
// SetIndexRows replaces the current row data for the given index and returns an updated Table.
func (t *Table) SetIndexRows(ctx context.Context, indexName string, idx durable.Index) (*Table, error) {
indexes, err := t.GetIndexSet(ctx)
if err != nil {
return nil, err
}
indexes, err = indexes.PutIndex(ctx, indexName, idx)
if err != nil {
return nil, err
}
return t.SetIndexSet(ctx, indexes)
}
// SetNomsIndexRows replaces the current row data for the given index and returns an updated Table.
func (t *Table) SetNomsIndexRows(ctx context.Context, indexName string, idx types.Map) (*Table, error) {
indexes, err := t.GetIndexSet(ctx)
if err != nil {
return nil, err
}
indexes, err = indexes.PutNomsIndex(ctx, indexName, idx)
if err != nil {
return nil, err
}
return t.SetIndexSet(ctx, indexes)
} | // DeleteIndexRowData removes the underlying map of an index, along with its key entry. This should only be used
// when removing an index altogether. If the intent is to clear an index's data, then use SetNomsIndexRows with
// an empty map.
func (t *Table) DeleteIndexRowData(ctx context.Context, indexName string) (*Table, error) {
indexes, err := t.GetIndexSet(ctx)
if err != nil {
return nil, err
}
indexes, err = indexes.DropIndex(ctx, indexName)
if err != nil {
return nil, err
}
return t.SetIndexSet(ctx, indexes)
}
// RenameIndexRowData changes the name for the index data. Does not verify that the new name is unoccupied. If the old
// name does not exist, then this returns the called table without error.
func (t *Table) RenameIndexRowData(ctx context.Context, oldIndexName, newIndexName string) (*Table, error) {
indexes, err := t.GetIndexSet(ctx)
if err != nil {
return nil, err
}
indexes, err = indexes.RenameIndex(ctx, oldIndexName, newIndexName)
if err != nil {
return nil, err
}
return t.SetIndexSet(ctx, indexes)
}
// VerifyIndexRowData verifies that the index with the given name's data matches what the index expects.
func (t *Table) VerifyIndexRowData(ctx context.Context, indexName string) error {
sch, err := t.GetSchema(ctx)
if err != nil {
return err
}
index := sch.Indexes().GetByName(indexName)
if index == nil {
return fmt.Errorf("index `%s` does not exist", indexName)
}
indexes, err := t.GetIndexSet(ctx)
if err != nil {
return err
}
idx, err := indexes.GetIndex(ctx, sch, indexName)
if err != nil {
return err
}
im := durable.NomsMapFromIndex(idx)
iter, err := im.Iterator(ctx)
if err != nil {
return err
}
return index.VerifyMap(ctx, iter, im.Format())
}
// GetAutoIncrementValue returns the current AUTO_INCREMENT value for this table.
func (t *Table) GetAutoIncrementValue(ctx context.Context) (uint64, error) {
return t.table.GetAutoIncrement(ctx)
}
// SetAutoIncrementValue sets the current AUTO_INCREMENT value for this table.
func (t *Table) SetAutoIncrementValue(ctx context.Context, val uint64) (*Table, error) {
table, err := t.table.SetAutoIncrement(ctx, val)
if err != nil {
return nil, err
}
return &Table{table: table}, nil
}
// AddColumnToRows adds the column named to row data as necessary and returns the resulting table.
func (t *Table) AddColumnToRows(ctx context.Context, newCol string, newSchema schema.Schema) (*Table, error) {
idx, err := t.table.GetTableRows(ctx)
if err != nil {
return nil, err
}
newIdx, err := idx.AddColumnToRows(ctx, newCol, newSchema)
if err != nil {
return nil, err
}
newTable, err := t.table.SetTableRows(ctx, newIdx)
if err != nil {
return nil, err
}
return &Table{table: newTable}, nil
} | |
getSavedPlots.ts | import { MODELURL } from '..';
const getSavedPlots = async (fileId: string) => {
try {
const data = await fetch(`${MODELURL}/get_save_plots/${fileId}`, {
method: 'GET',
}).then((res) => res.json());
console.log('[SUCCESS] GET saved plots', data);
return data;
} catch (err) {
console.log('[FAIL] GET saved plots', err);
alert('저장된 플랏 로딩에 실패하였습니다.');
return null; | }
};
export default getSavedPlots; |
|
setting_tol.py | from sciapp.action import Measure
from sciapp.action import Free
from imagepy.app import ConfigManager
class Plugin(Free):
| title = "Measure Setting"
para = Measure.default.copy()
view = [
("color", "color", "line", "color"),
("color", "fcolor", "face", "color"),
("color", "tcolor", "text", "color"),
(int, "lw", (1, 10), 0, "width", "pix"),
(int, "size", (1, 30), 0, "text", "size"),
(bool, "fill", "solid fill"),
]
def run(self, para=None):
for i in para:
Measure.default[i] = para[i]
ConfigManager.set("mea_style", para) |
|
test_bugdown.py | import copy
import os
import re
from typing import Any, Dict, List, Optional, Set, Tuple
from unittest import mock
import ujson
from django.conf import settings
from django.test import TestCase, override_settings
from zerver.lib import bugdown, mdiff
from zerver.lib.actions import (
do_add_alert_words,
do_remove_realm_emoji,
do_set_realm_property,
do_set_user_display_setting,
)
from zerver.lib.alert_words import get_alert_word_automaton
from zerver.lib.create_user import create_user
from zerver.lib.emoji import get_emoji_url
from zerver.lib.exceptions import BugdownRenderingException
from zerver.lib.mention import possible_mentions, possible_user_group_mentions
from zerver.lib.message import render_markdown
from zerver.lib.request import JsonableError
from zerver.lib.test_classes import ZulipTestCase
from zerver.lib.test_runner import slow
from zerver.lib.tex import render_tex
from zerver.lib.user_groups import create_user_group
from zerver.models import (
MAX_MESSAGE_LENGTH,
Message,
Realm,
RealmEmoji,
RealmFilter,
Stream,
UserGroup,
UserMessage,
UserProfile,
flush_per_request_caches,
flush_realm_filter,
get_client,
get_realm,
get_stream,
realm_filters_for_realm,
realm_in_local_realm_filters_cache,
)
class FencedBlockPreprocessorTest(TestCase):
def test_simple_quoting(self) -> None:
processor = bugdown.fenced_code.FencedBlockPreprocessor(None)
markdown = [
'~~~ quote',
'hi',
'bye',
'',
'',
]
expected = [
'',
'> hi',
'> bye',
'',
'',
'',
]
lines = processor.run(markdown)
self.assertEqual(lines, expected)
def test_serial_quoting(self) -> None:
processor = bugdown.fenced_code.FencedBlockPreprocessor(None)
markdown = [
'~~~ quote',
'hi',
'~~~',
'',
'~~~ quote',
'bye',
'',
'',
]
expected = [
'',
'> hi',
'',
'',
'',
'> bye',
'',
'',
'',
]
lines = processor.run(markdown)
self.assertEqual(lines, expected)
def test_serial_code(self) -> None:
processor = bugdown.fenced_code.FencedBlockPreprocessor(None)
# Simulate code formatting.
processor.format_code = lambda lang, code: lang + ':' + code # type: ignore[assignment] # mypy doesn't allow monkey-patching functions
processor.placeholder = lambda s: '**' + s.strip('\n') + '**' # type: ignore[assignment] # https://github.com/python/mypy/issues/708
markdown = [
'``` .py',
'hello()',
'```',
'',
'```vb.net',
'goodbye()',
'```',
'',
'```c#',
'weirdchar()',
'```',
'',
'```',
'no-highlight()',
'```',
'',
]
expected = [
'',
'**py:hello()**',
'',
'',
'',
'**vb.net:goodbye()**',
'',
'',
'',
'**c#:weirdchar()**',
'',
'',
'',
'**:no-highlight()**',
'',
'',
]
lines = processor.run(markdown)
self.assertEqual(lines, expected)
def test_nested_code(self) -> None:
processor = bugdown.fenced_code.FencedBlockPreprocessor(None)
# Simulate code formatting.
processor.format_code = lambda lang, code: lang + ':' + code # type: ignore[assignment] # mypy doesn't allow monkey-patching functions
processor.placeholder = lambda s: '**' + s.strip('\n') + '**' # type: ignore[assignment] # https://github.com/python/mypy/issues/708
markdown = [
'~~~ quote',
'hi',
'``` .py',
'hello()',
'```',
'',
'',
]
expected = [
'',
'> hi',
'',
'> **py:hello()**',
'',
'',
'',
]
lines = processor.run(markdown)
self.assertEqual(lines, expected)
def bugdown_convert(content: str) -> str:
return bugdown.convert(
content=content,
message_realm=get_realm('zulip'),
)
class BugdownMiscTest(ZulipTestCase):
def test_diffs_work_as_expected(self) -> None:
str1 = "<p>The quick brown fox jumps over the lazy dog. Animal stories are fun, yeah</p>"
str2 = "<p>The fast fox jumps over the lazy dogs and cats. Animal stories are fun</p>"
expected_diff = "\u001b[34m-\u001b[0m <p>The \u001b[33mquick brown\u001b[0m fox jumps over the lazy dog. Animal stories are fun\u001b[31m, yeah\u001b[0m</p>\n\u001b[34m+\u001b[0m <p>The \u001b[33mfast\u001b[0m fox jumps over the lazy dog\u001b[32ms and cats\u001b[0m. Animal stories are fun</p>\n"
self.assertEqual(mdiff.diff_strings(str1, str2), expected_diff)
def test_get_possible_mentions_info(self) -> None:
realm = get_realm('zulip')
def make_user(email: str, full_name: str) -> UserProfile:
return create_user(
email=email,
password='whatever',
realm=realm,
full_name=full_name,
short_name='whatever',
)
fred1 = make_user('[email protected]', 'Fred Flintstone')
fred1.is_active = False
fred1.save()
fred2 = make_user('[email protected]', 'Fred Flintstone')
fred3 = make_user('[email protected]', 'Fred Flintstone')
fred3.is_active = False
fred3.save()
fred4 = make_user('[email protected]', 'Fred Flintstone')
lst = bugdown.get_possible_mentions_info(realm.id, {'Fred Flintstone', 'cordelia LEAR', 'Not A User'})
set_of_names = set(map(lambda x: x['full_name'].lower(), lst))
self.assertEqual(set_of_names, {'fred flintstone', 'cordelia lear'})
by_id = {
row['id']: row
for row in lst
}
self.assertEqual(by_id.get(fred2.id), dict(
email=fred2.email,
full_name='Fred Flintstone',
id=fred2.id,
))
self.assertEqual(by_id.get(fred4.id), dict(
email=fred4.email,
full_name='Fred Flintstone',
id=fred4.id,
))
def test_mention_data(self) -> None:
realm = get_realm('zulip')
hamlet = self.example_user('hamlet')
cordelia = self.example_user('cordelia')
content = '@**King Hamlet** @**Cordelia lear**'
mention_data = bugdown.MentionData(realm.id, content)
self.assertEqual(mention_data.get_user_ids(), {hamlet.id, cordelia.id})
self.assertEqual(mention_data.get_user_by_id(hamlet.id), dict(
email=hamlet.email,
full_name=hamlet.full_name,
id=hamlet.id,
))
user = mention_data.get_user_by_name('king hamLET')
assert(user is not None)
self.assertEqual(user['email'], hamlet.email)
self.assertFalse(mention_data.message_has_wildcards())
content = '@**King Hamlet** @**Cordelia lear** @**all**'
mention_data = bugdown.MentionData(realm.id, content)
self.assertTrue(mention_data.message_has_wildcards())
def test_invalid_katex_path(self) -> None:
with self.settings(DEPLOY_ROOT="/nonexistent"):
with mock.patch('logging.error') as mock_logger:
render_tex("random text")
mock_logger.assert_called_with("Cannot find KaTeX for latex rendering!")
class BugdownListPreprocessorTest(ZulipTestCase):
# We test that the preprocessor inserts blank lines at correct places.
# We use <> to indicate that we need to insert a blank line here.
def split_message(self, msg: str) -> Tuple[List[str], List[str]]:
original = msg.replace('<>', '').split('\n')
expected = re.split(r'\n|<>', msg)
return original, expected
def test_basic_list(self) -> None:
preprocessor = bugdown.BugdownListPreprocessor()
original, expected = self.split_message('List without a gap\n<>* One\n* Two')
self.assertEqual(preprocessor.run(original), expected)
def test_list_after_quotes(self) -> None:
preprocessor = bugdown.BugdownListPreprocessor()
original, expected = self.split_message('```quote\nSomething\n```\n\nList without a gap\n<>* One\n* Two')
self.assertEqual(preprocessor.run(original), expected)
def test_list_in_code(self) -> None:
preprocessor = bugdown.BugdownListPreprocessor()
original, expected = self.split_message('```\nList without a gap\n* One\n* Two\n```')
self.assertEqual(preprocessor.run(original), expected)
def test_complex_nesting_with_different_fences(self) -> None:
preprocessor = bugdown.BugdownListPreprocessor()
msg = """```quote
In quote. We should convert a list here:<>
* one
* two
~~~
This is a nested code fence, do not make changes here:
* one
* two
````quote
Quote in code fence. Should not convert:
* one
* two
````
~~~
Back in the quote. We should convert:<>
* one
* two
```
Outside. Should convert:<>
* one
* two
"""
original, expected = self.split_message(msg)
self.assertEqual(preprocessor.run(original), expected)
def test_complex_nesting_with_same_fence(self) -> None:
preprocessor = bugdown.BugdownListPreprocessor()
msg = """```quote
In quote. We should convert a list here:<>
* one
* two
```python
This is a nested code fence, do not make changes here:
* one
* two
```quote
Quote in code fence. Should not convert:
* one
* two
```
```
Back in the quote. We should convert:<>
* one
* two
```
Outside. Should convert:<>
* one
* two
"""
original, expected = self.split_message(msg)
self.assertEqual(preprocessor.run(original), expected)
class BugdownTest(ZulipTestCase):
def setUp(self) -> None:
super().setUp()
bugdown.clear_state_for_testing()
def assertEqual(self, first: Any, second: Any, msg: str = "") -> None:
if isinstance(first, str) and isinstance(second, str):
if first != second:
raise AssertionError("Actual and expected outputs do not match; showing diff.\n" +
mdiff.diff_strings(first, second) + msg)
else:
super().assertEqual(first, second)
def load_bugdown_tests(self) -> Tuple[Dict[str, Any], List[List[str]]]:
test_fixtures = {}
with open(os.path.join(os.path.dirname(__file__), 'fixtures/markdown_test_cases.json')) as f:
data = ujson.load(f)
for test in data['regular_tests']:
test_fixtures[test['name']] = test
return test_fixtures, data['linkify_tests']
def test_bugdown_no_ignores(self) -> None:
# We do not want any ignored tests to be committed and merged.
format_tests, linkify_tests = self.load_bugdown_tests()
for name, test in format_tests.items():
message = f'Test "{name}" shouldn\'t be ignored.'
is_ignored = test.get('ignore', False)
self.assertFalse(is_ignored, message)
@slow("Aggregate of runs dozens of individual markdown tests")
def test_bugdown_fixtures(self) -> None:
format_tests, linkify_tests = self.load_bugdown_tests()
valid_keys = {"name", "input", "expected_output",
"backend_only_rendering",
"marked_expected_output", "text_content",
"translate_emoticons", "ignore"}
for name, test in format_tests.items():
with self.subTest(markdown_test_case=name):
# Check that there aren't any unexpected keys as those are often typos
self.assertEqual(len(set(test.keys()) - valid_keys), 0)
# Ignore tests if specified
if test.get('ignore', False):
continue # nocoverage
if test.get('translate_emoticons', False):
# Create a userprofile and send message with it.
user_profile = self.example_user('othello')
do_set_user_display_setting(user_profile, 'translate_emoticons', True)
msg = Message(sender=user_profile, sending_client=get_client("test"))
converted = render_markdown(msg, test['input'])
else:
converted = bugdown_convert(test['input'])
self.assertEqual(converted, test['expected_output'])
def replaced(payload: str, url: str, phrase: str='') -> str:
if url[:4] == 'http':
href = url
elif '@' in url:
href = 'mailto:' + url
else:
href = 'http://' + url
return payload % (f"<a href=\"{href}\">{url}</a>",)
print("Running Bugdown Linkify tests")
with mock.patch('zerver.lib.url_preview.preview.link_embed_data_from_cache', return_value=None):
for inline_url, reference, url in linkify_tests:
try:
match = replaced(reference, url, phrase=inline_url)
except TypeError:
match = reference
converted = bugdown_convert(inline_url)
self.assertEqual(match, converted)
def test_inline_file(self) -> None:
msg = 'Check out this file file:///Volumes/myserver/Users/Shared/pi.py'
converted = bugdown_convert(msg)
self.assertEqual(converted, '<p>Check out this file <a href="file:///Volumes/myserver/Users/Shared/pi.py">file:///Volumes/myserver/Users/Shared/pi.py</a></p>')
bugdown.clear_state_for_testing()
with self.settings(ENABLE_FILE_LINKS=False):
realm = Realm.objects.create(string_id='file_links_test')
bugdown.maybe_update_markdown_engines(realm.id, False)
converted = bugdown.convert(msg, message_realm=realm)
self.assertEqual(converted, '<p>Check out this file file:///Volumes/myserver/Users/Shared/pi.py</p>')
def test_inline_bitcoin(self) -> None:
msg = 'To bitcoin:1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa or not to bitcoin'
converted = bugdown_convert(msg)
self.assertEqual(converted, '<p>To <a href="bitcoin:1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa">bitcoin:1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa</a> or not to bitcoin</p>')
def test_inline_youtube(self) -> None:
|
@override_settings(INLINE_URL_EMBED_PREVIEW=False)
def test_inline_vimeo(self) -> None:
msg = 'Check out the debate: https://vimeo.com/246979354'
converted = bugdown_convert(msg)
self.assertEqual(converted, '<p>Check out the debate: <a href="https://vimeo.com/246979354">https://vimeo.com/246979354</a></p>')
msg = 'https://vimeo.com/246979354'
converted = bugdown_convert(msg)
self.assertEqual(converted, '<p><a href="https://vimeo.com/246979354">https://vimeo.com/246979354</a></p>')
@override_settings(INLINE_IMAGE_PREVIEW=True)
def test_inline_image_thumbnail_url(self) -> None:
realm = get_realm("zephyr")
msg = '[foobar](/user_uploads/{realm_id}/50/w2G6ok9kr8AMCQCTNAUOFMln/IMG_0677.JPG)'
msg = msg.format(realm_id=realm.id)
thumbnail_img = '<img data-src-fullsize="/thumbnail?url=user_uploads%2F{realm_id}%2F50%2Fw2G6ok9kr8AMCQCTNAUOFMln%2FIMG_0677.JPG&size=full" src="/thumbnail?url=user_uploads%2F{realm_id}%2F50%2Fw2G6ok9kr8AMCQCTNAUOFMln%2FIMG_0677.JPG&size=thumbnail"><'
thumbnail_img = thumbnail_img.format(realm_id=realm.id)
converted = bugdown_convert(msg)
self.assertIn(thumbnail_img, converted)
msg = 'https://www.google.com/images/srpr/logo4w.png'
thumbnail_img = '<img data-src-fullsize="/thumbnail?url=https%3A%2F%2Fwww.google.com%2Fimages%2Fsrpr%2Flogo4w.png&size=full" src="/thumbnail?url=https%3A%2F%2Fwww.google.com%2Fimages%2Fsrpr%2Flogo4w.png&size=thumbnail">'
converted = bugdown_convert(msg)
self.assertIn(thumbnail_img, converted)
msg = 'www.google.com/images/srpr/logo4w.png'
thumbnail_img = '<img data-src-fullsize="/thumbnail?url=http%3A%2F%2Fwww.google.com%2Fimages%2Fsrpr%2Flogo4w.png&size=full" src="/thumbnail?url=http%3A%2F%2Fwww.google.com%2Fimages%2Fsrpr%2Flogo4w.png&size=thumbnail">'
converted = bugdown_convert(msg)
self.assertIn(thumbnail_img, converted)
msg = 'https://www.google.com/images/srpr/logo4w.png'
thumbnail_img = '<div class="message_inline_image"><a href="https://www.google.com/images/srpr/logo4w.png"><img src="https://www.google.com/images/srpr/logo4w.png"></a></div>'
with self.settings(THUMBNAIL_IMAGES=False):
converted = bugdown_convert(msg)
self.assertIn(thumbnail_img, converted)
# Any url which is not an external link and doesn't start with
# /user_uploads/ is not thumbnailed
msg = '[foobar](/static/images/cute/turtle.png)'
thumbnail_img = '<div class="message_inline_image"><a href="/static/images/cute/turtle.png" title="foobar"><img src="/static/images/cute/turtle.png"></a></div>'
converted = bugdown_convert(msg)
self.assertIn(thumbnail_img, converted)
msg = '[foobar](/user_avatars/{realm_id}/emoji/images/50.png)'
msg = msg.format(realm_id=realm.id)
thumbnail_img = '<div class="message_inline_image"><a href="/user_avatars/{realm_id}/emoji/images/50.png" title="foobar"><img src="/user_avatars/{realm_id}/emoji/images/50.png"></a></div>'
thumbnail_img = thumbnail_img.format(realm_id=realm.id)
converted = bugdown_convert(msg)
self.assertIn(thumbnail_img, converted)
@override_settings(INLINE_IMAGE_PREVIEW=True)
def test_inline_image_preview(self) -> None:
with_preview = '<div class="message_inline_image"><a href="http://cdn.wallpapersafari.com/13/6/16eVjx.jpeg"><img data-src-fullsize="/thumbnail?url=http%3A%2F%2Fcdn.wallpapersafari.com%2F13%2F6%2F16eVjx.jpeg&size=full" src="/thumbnail?url=http%3A%2F%2Fcdn.wallpapersafari.com%2F13%2F6%2F16eVjx.jpeg&size=thumbnail"></a></div>'
without_preview = '<p><a href="http://cdn.wallpapersafari.com/13/6/16eVjx.jpeg">http://cdn.wallpapersafari.com/13/6/16eVjx.jpeg</a></p>'
content = 'http://cdn.wallpapersafari.com/13/6/16eVjx.jpeg'
sender_user_profile = self.example_user('othello')
msg = Message(sender=sender_user_profile, sending_client=get_client("test"))
converted = render_markdown(msg, content)
self.assertEqual(converted, with_preview)
realm = msg.get_realm()
setattr(realm, 'inline_image_preview', False)
realm.save()
sender_user_profile = self.example_user('othello')
msg = Message(sender=sender_user_profile, sending_client=get_client("test"))
converted = render_markdown(msg, content)
self.assertEqual(converted, without_preview)
@override_settings(INLINE_IMAGE_PREVIEW=True)
def test_inline_image_quoted_blocks(self) -> None:
content = 'http://cdn.wallpapersafari.com/13/6/16eVjx.jpeg'
expected = '<div class="message_inline_image"><a href="http://cdn.wallpapersafari.com/13/6/16eVjx.jpeg"><img data-src-fullsize="/thumbnail?url=http%3A%2F%2Fcdn.wallpapersafari.com%2F13%2F6%2F16eVjx.jpeg&size=full" src="/thumbnail?url=http%3A%2F%2Fcdn.wallpapersafari.com%2F13%2F6%2F16eVjx.jpeg&size=thumbnail"></a></div>'
sender_user_profile = self.example_user('othello')
msg = Message(sender=sender_user_profile, sending_client=get_client("test"))
converted = render_markdown(msg, content)
self.assertEqual(converted, expected)
content = '>http://cdn.wallpapersafari.com/13/6/16eVjx.jpeg\n\nAwesome!'
expected = '<blockquote>\n<p><a href="http://cdn.wallpapersafari.com/13/6/16eVjx.jpeg">http://cdn.wallpapersafari.com/13/6/16eVjx.jpeg</a></p>\n</blockquote>\n<p>Awesome!</p>'
sender_user_profile = self.example_user('othello')
msg = Message(sender=sender_user_profile, sending_client=get_client("test"))
converted = render_markdown(msg, content)
self.assertEqual(converted, expected)
content = '>* http://cdn.wallpapersafari.com/13/6/16eVjx.jpeg\n\nAwesome!'
expected = '<blockquote>\n<ul>\n<li><a href="http://cdn.wallpapersafari.com/13/6/16eVjx.jpeg">http://cdn.wallpapersafari.com/13/6/16eVjx.jpeg</a></li>\n</ul>\n</blockquote>\n<p>Awesome!</p>'
sender_user_profile = self.example_user('othello')
msg = Message(sender=sender_user_profile, sending_client=get_client("test"))
converted = render_markdown(msg, content)
self.assertEqual(converted, expected)
@override_settings(INLINE_IMAGE_PREVIEW=True)
def test_inline_image_preview_order(self) -> None:
realm = get_realm("zulip")
content = 'http://imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg\nhttp://imaging.nikon.com/lineup/dslr/df/img/sample/img_02.jpg\nhttp://imaging.nikon.com/lineup/dslr/df/img/sample/img_03.jpg'
expected = '<p><a href="http://imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg">http://imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg</a><br>\n<a href="http://imaging.nikon.com/lineup/dslr/df/img/sample/img_02.jpg">http://imaging.nikon.com/lineup/dslr/df/img/sample/img_02.jpg</a><br>\n<a href="http://imaging.nikon.com/lineup/dslr/df/img/sample/img_03.jpg">http://imaging.nikon.com/lineup/dslr/df/img/sample/img_03.jpg</a></p>\n<div class="message_inline_image"><a href="http://imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg"><img data-src-fullsize="/thumbnail?url=http%3A%2F%2Fimaging.nikon.com%2Flineup%2Fdslr%2Fdf%2Fimg%2Fsample%2Fimg_01.jpg&size=full" src="/thumbnail?url=http%3A%2F%2Fimaging.nikon.com%2Flineup%2Fdslr%2Fdf%2Fimg%2Fsample%2Fimg_01.jpg&size=thumbnail"></a></div><div class="message_inline_image"><a href="http://imaging.nikon.com/lineup/dslr/df/img/sample/img_02.jpg"><img data-src-fullsize="/thumbnail?url=http%3A%2F%2Fimaging.nikon.com%2Flineup%2Fdslr%2Fdf%2Fimg%2Fsample%2Fimg_02.jpg&size=full" src="/thumbnail?url=http%3A%2F%2Fimaging.nikon.com%2Flineup%2Fdslr%2Fdf%2Fimg%2Fsample%2Fimg_02.jpg&size=thumbnail"></a></div><div class="message_inline_image"><a href="http://imaging.nikon.com/lineup/dslr/df/img/sample/img_03.jpg"><img data-src-fullsize="/thumbnail?url=http%3A%2F%2Fimaging.nikon.com%2Flineup%2Fdslr%2Fdf%2Fimg%2Fsample%2Fimg_03.jpg&size=full" src="/thumbnail?url=http%3A%2F%2Fimaging.nikon.com%2Flineup%2Fdslr%2Fdf%2Fimg%2Fsample%2Fimg_03.jpg&size=thumbnail"></a></div>'
sender_user_profile = self.example_user('othello')
msg = Message(sender=sender_user_profile, sending_client=get_client("test"))
converted = render_markdown(msg, content)
self.assertEqual(converted, expected)
content = 'http://imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg\n\n>http://imaging.nikon.com/lineup/dslr/df/img/sample/img_02.jpg\n\n* http://imaging.nikon.com/lineup/dslr/df/img/sample/img_03.jpg\n* https://www.google.com/images/srpr/logo4w.png'
expected = '<div class="message_inline_image"><a href="http://imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg"><img data-src-fullsize="/thumbnail?url=http%3A%2F%2Fimaging.nikon.com%2Flineup%2Fdslr%2Fdf%2Fimg%2Fsample%2Fimg_01.jpg&size=full" src="/thumbnail?url=http%3A%2F%2Fimaging.nikon.com%2Flineup%2Fdslr%2Fdf%2Fimg%2Fsample%2Fimg_01.jpg&size=thumbnail"></a></div><blockquote>\n<p><a href="http://imaging.nikon.com/lineup/dslr/df/img/sample/img_02.jpg">http://imaging.nikon.com/lineup/dslr/df/img/sample/img_02.jpg</a></p>\n</blockquote>\n<ul>\n<li><div class="message_inline_image"><a href="http://imaging.nikon.com/lineup/dslr/df/img/sample/img_03.jpg"><img data-src-fullsize="/thumbnail?url=http%3A%2F%2Fimaging.nikon.com%2Flineup%2Fdslr%2Fdf%2Fimg%2Fsample%2Fimg_03.jpg&size=full" src="/thumbnail?url=http%3A%2F%2Fimaging.nikon.com%2Flineup%2Fdslr%2Fdf%2Fimg%2Fsample%2Fimg_03.jpg&size=thumbnail"></a></div></li>\n<li><div class="message_inline_image"><a href="https://www.google.com/images/srpr/logo4w.png"><img data-src-fullsize="/thumbnail?url=https%3A%2F%2Fwww.google.com%2Fimages%2Fsrpr%2Flogo4w.png&size=full" src="/thumbnail?url=https%3A%2F%2Fwww.google.com%2Fimages%2Fsrpr%2Flogo4w.png&size=thumbnail"></a></div></li>\n</ul>'
sender_user_profile = self.example_user('othello')
msg = Message(sender=sender_user_profile, sending_client=get_client("test"))
converted = render_markdown(msg, content)
self.assertEqual(converted, expected)
content = 'Test 1\n[21136101110_1dde1c1a7e_o.jpg](/user_uploads/{realm_id}/6d/F1PX6u16JA2P-nK45PyxHIYZ/21136101110_1dde1c1a7e_o.jpg) \n\nNext Image\n[IMG_20161116_023910.jpg](/user_uploads/{realm_id}/69/sh7L06e7uH7NaX6d5WFfVYQp/IMG_20161116_023910.jpg) \n\nAnother Screenshot\n[Screenshot-from-2016-06-01-16-22-42.png](/user_uploads/{realm_id}/70/_aZmIEWaN1iUaxwkDjkO7bpj/Screenshot-from-2016-06-01-16-22-42.png)'
content = content.format(realm_id=realm.id)
expected = '<p>Test 1<br>\n<a href="/user_uploads/{realm_id}/6d/F1PX6u16JA2P-nK45PyxHIYZ/21136101110_1dde1c1a7e_o.jpg">21136101110_1dde1c1a7e_o.jpg</a> </p>\n<div class="message_inline_image"><a href="/user_uploads/{realm_id}/6d/F1PX6u16JA2P-nK45PyxHIYZ/21136101110_1dde1c1a7e_o.jpg" title="21136101110_1dde1c1a7e_o.jpg"><img data-src-fullsize="/thumbnail?url=user_uploads%2F{realm_id}%2F6d%2FF1PX6u16JA2P-nK45PyxHIYZ%2F21136101110_1dde1c1a7e_o.jpg&size=full" src="/thumbnail?url=user_uploads%2F{realm_id}%2F6d%2FF1PX6u16JA2P-nK45PyxHIYZ%2F21136101110_1dde1c1a7e_o.jpg&size=thumbnail"></a></div><p>Next Image<br>\n<a href="/user_uploads/{realm_id}/69/sh7L06e7uH7NaX6d5WFfVYQp/IMG_20161116_023910.jpg">IMG_20161116_023910.jpg</a> </p>\n<div class="message_inline_image"><a href="/user_uploads/{realm_id}/69/sh7L06e7uH7NaX6d5WFfVYQp/IMG_20161116_023910.jpg" title="IMG_20161116_023910.jpg"><img data-src-fullsize="/thumbnail?url=user_uploads%2F{realm_id}%2F69%2Fsh7L06e7uH7NaX6d5WFfVYQp%2FIMG_20161116_023910.jpg&size=full" src="/thumbnail?url=user_uploads%2F{realm_id}%2F69%2Fsh7L06e7uH7NaX6d5WFfVYQp%2FIMG_20161116_023910.jpg&size=thumbnail"></a></div><p>Another Screenshot<br>\n<a href="/user_uploads/{realm_id}/70/_aZmIEWaN1iUaxwkDjkO7bpj/Screenshot-from-2016-06-01-16-22-42.png">Screenshot-from-2016-06-01-16-22-42.png</a></p>\n<div class="message_inline_image"><a href="/user_uploads/{realm_id}/70/_aZmIEWaN1iUaxwkDjkO7bpj/Screenshot-from-2016-06-01-16-22-42.png" title="Screenshot-from-2016-06-01-16-22-42.png"><img data-src-fullsize="/thumbnail?url=user_uploads%2F{realm_id}%2F70%2F_aZmIEWaN1iUaxwkDjkO7bpj%2FScreenshot-from-2016-06-01-16-22-42.png&size=full" src="/thumbnail?url=user_uploads%2F{realm_id}%2F70%2F_aZmIEWaN1iUaxwkDjkO7bpj%2FScreenshot-from-2016-06-01-16-22-42.png&size=thumbnail"></a></div>'
expected = expected.format(realm_id=realm.id)
msg = Message(sender=sender_user_profile, sending_client=get_client("test"))
converted = render_markdown(msg, content)
self.assertEqual(converted, expected)
@override_settings(INLINE_IMAGE_PREVIEW=True)
def test_corrected_image_source(self) -> None:
# testing only wikipedia because linx.li urls can be expected to expire
content = 'https://en.wikipedia.org/wiki/File:Wright_of_Derby,_The_Orrery.jpg'
expected = '<div class="message_inline_image"><a href="https://en.wikipedia.org/wiki/Special:FilePath/File:Wright_of_Derby,_The_Orrery.jpg"><img data-src-fullsize="/thumbnail?url=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FSpecial%3AFilePath%2FFile%3AWright_of_Derby%2C_The_Orrery.jpg&size=full" src="/thumbnail?url=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FSpecial%3AFilePath%2FFile%3AWright_of_Derby%2C_The_Orrery.jpg&size=thumbnail"></a></div>'
sender_user_profile = self.example_user('othello')
msg = Message(sender=sender_user_profile, sending_client=get_client("test"))
converted = render_markdown(msg, content)
self.assertEqual(converted, expected)
@override_settings(INLINE_IMAGE_PREVIEW=False)
def test_image_preview_enabled(self) -> None:
ret = bugdown.image_preview_enabled()
self.assertEqual(ret, False)
settings.INLINE_IMAGE_PREVIEW = True
sender_user_profile = self.example_user('othello')
message = Message(sender=sender_user_profile, sending_client=get_client("test"))
realm = message.get_realm()
ret = bugdown.image_preview_enabled()
self.assertEqual(ret, True)
ret = bugdown.image_preview_enabled(no_previews=True)
self.assertEqual(ret, False)
ret = bugdown.image_preview_enabled(message, realm)
self.assertEqual(ret, True)
ret = bugdown.image_preview_enabled(message)
self.assertEqual(ret, True)
ret = bugdown.image_preview_enabled(message, realm,
no_previews=True)
self.assertEqual(ret, False)
ret = bugdown.image_preview_enabled(message, no_previews=True)
self.assertEqual(ret, False)
@override_settings(INLINE_URL_EMBED_PREVIEW=False)
def test_url_embed_preview_enabled(self) -> None:
sender_user_profile = self.example_user('othello')
message = copy.deepcopy(Message(sender=sender_user_profile, sending_client=get_client("test")))
realm = message.get_realm()
realm.inline_url_embed_preview = True # off by default
realm.save(update_fields=['inline_url_embed_preview'])
ret = bugdown.url_embed_preview_enabled()
self.assertEqual(ret, False)
settings.INLINE_URL_EMBED_PREVIEW = True
ret = bugdown.url_embed_preview_enabled()
self.assertEqual(ret, True)
ret = bugdown.image_preview_enabled(no_previews=True)
self.assertEqual(ret, False)
ret = bugdown.url_embed_preview_enabled(message, realm)
self.assertEqual(ret, True)
ret = bugdown.url_embed_preview_enabled(message)
self.assertEqual(ret, True)
ret = bugdown.url_embed_preview_enabled(message, no_previews=True)
self.assertEqual(ret, False)
def test_inline_dropbox(self) -> None:
msg = 'Look at how hilarious our old office was: https://www.dropbox.com/s/ymdijjcg67hv2ta/IMG_0923.JPG'
image_info = {'image': 'https://photos-4.dropbox.com/t/2/AABIre1oReJgPYuc_53iv0IHq1vUzRaDg2rrCfTpiWMccQ/12/129/jpeg/1024x1024/2/_/0/4/IMG_0923.JPG/CIEBIAEgAiAHKAIoBw/ymdijjcg67hv2ta/AABz2uuED1ox3vpWWvMpBxu6a/IMG_0923.JPG', 'desc': 'Shared with Dropbox', 'title': 'IMG_0923.JPG'}
with mock.patch('zerver.lib.bugdown.fetch_open_graph_image', return_value=image_info):
converted = bugdown_convert(msg)
self.assertEqual(converted, '<p>Look at how hilarious our old office was: <a href="https://www.dropbox.com/s/ymdijjcg67hv2ta/IMG_0923.JPG">https://www.dropbox.com/s/ymdijjcg67hv2ta/IMG_0923.JPG</a></p>\n<div class="message_inline_image"><a href="https://www.dropbox.com/s/ymdijjcg67hv2ta/IMG_0923.JPG" title="IMG_0923.JPG"><img src="https://www.dropbox.com/s/ymdijjcg67hv2ta/IMG_0923.JPG?dl=1"></a></div>')
msg = 'Look at my hilarious drawing folder: https://www.dropbox.com/sh/cm39k9e04z7fhim/AAAII5NK-9daee3FcF41anEua?dl='
image_info = {'image': 'https://cf.dropboxstatic.com/static/images/icons128/folder_dropbox.png', 'desc': 'Shared with Dropbox', 'title': 'Saves'}
with mock.patch('zerver.lib.bugdown.fetch_open_graph_image', return_value=image_info):
converted = bugdown_convert(msg)
self.assertEqual(converted, '<p>Look at my hilarious drawing folder: <a href="https://www.dropbox.com/sh/cm39k9e04z7fhim/AAAII5NK-9daee3FcF41anEua?dl=">https://www.dropbox.com/sh/cm39k9e04z7fhim/AAAII5NK-9daee3FcF41anEua?dl=</a></p>\n<div class="message_inline_ref"><a href="https://www.dropbox.com/sh/cm39k9e04z7fhim/AAAII5NK-9daee3FcF41anEua?dl=" title="Saves"><img src="https://cf.dropboxstatic.com/static/images/icons128/folder_dropbox.png"></a><div><div class="message_inline_image_title">Saves</div><desc class="message_inline_image_desc"></desc></div></div>')
def test_inline_dropbox_preview(self) -> None:
# Test photo album previews
msg = 'https://www.dropbox.com/sc/tditp9nitko60n5/03rEiZldy5'
image_info = {'image': 'https://photos-6.dropbox.com/t/2/AAAlawaeD61TyNewO5vVi-DGf2ZeuayfyHFdNTNzpGq-QA/12/271544745/jpeg/1024x1024/2/_/0/5/baby-piglet.jpg/CKnjvYEBIAIgBygCKAc/tditp9nitko60n5/AADX03VAIrQlTl28CtujDcMla/0', 'desc': 'Shared with Dropbox', 'title': '1 photo'}
with mock.patch('zerver.lib.bugdown.fetch_open_graph_image', return_value=image_info):
converted = bugdown_convert(msg)
self.assertEqual(converted, '<p><a href="https://www.dropbox.com/sc/tditp9nitko60n5/03rEiZldy5">https://www.dropbox.com/sc/tditp9nitko60n5/03rEiZldy5</a></p>\n<div class="message_inline_image"><a href="https://www.dropbox.com/sc/tditp9nitko60n5/03rEiZldy5" title="1 photo"><img src="https://photos-6.dropbox.com/t/2/AAAlawaeD61TyNewO5vVi-DGf2ZeuayfyHFdNTNzpGq-QA/12/271544745/jpeg/1024x1024/2/_/0/5/baby-piglet.jpg/CKnjvYEBIAIgBygCKAc/tditp9nitko60n5/AADX03VAIrQlTl28CtujDcMla/0"></a></div>')
def test_inline_dropbox_negative(self) -> None:
# Make sure we're not overzealous in our conversion:
msg = 'Look at the new dropbox logo: https://www.dropbox.com/static/images/home_logo.png'
with mock.patch('zerver.lib.bugdown.fetch_open_graph_image', return_value=None):
converted = bugdown_convert(msg)
self.assertEqual(converted, '<p>Look at the new dropbox logo: <a href="https://www.dropbox.com/static/images/home_logo.png">https://www.dropbox.com/static/images/home_logo.png</a></p>\n<div class="message_inline_image"><a href="https://www.dropbox.com/static/images/home_logo.png"><img data-src-fullsize="/thumbnail?url=https%3A%2F%2Fwww.dropbox.com%2Fstatic%2Fimages%2Fhome_logo.png&size=full" src="/thumbnail?url=https%3A%2F%2Fwww.dropbox.com%2Fstatic%2Fimages%2Fhome_logo.png&size=thumbnail"></a></div>')
def test_inline_dropbox_bad(self) -> None:
# Don't fail on bad dropbox links
msg = "https://zulip-test.dropbox.com/photos/cl/ROmr9K1XYtmpneM"
with mock.patch('zerver.lib.bugdown.fetch_open_graph_image', return_value=None):
converted = bugdown_convert(msg)
self.assertEqual(converted, '<p><a href="https://zulip-test.dropbox.com/photos/cl/ROmr9K1XYtmpneM">https://zulip-test.dropbox.com/photos/cl/ROmr9K1XYtmpneM</a></p>')
def test_inline_github_preview(self) -> None:
# Test photo album previews
msg = 'Test: https://github.com/zulip/zulip/blob/master/static/images/logo/zulip-icon-128x128.png'
converted = bugdown_convert(msg)
self.assertEqual(converted, '<p>Test: <a href="https://github.com/zulip/zulip/blob/master/static/images/logo/zulip-icon-128x128.png">https://github.com/zulip/zulip/blob/master/static/images/logo/zulip-icon-128x128.png</a></p>\n<div class="message_inline_image"><a href="https://github.com/zulip/zulip/blob/master/static/images/logo/zulip-icon-128x128.png"><img data-src-fullsize="/thumbnail?url=https%3A%2F%2Fraw.githubusercontent.com%2Fzulip%2Fzulip%2Fmaster%2Fstatic%2Fimages%2Flogo%2Fzulip-icon-128x128.png&size=full" src="/thumbnail?url=https%3A%2F%2Fraw.githubusercontent.com%2Fzulip%2Fzulip%2Fmaster%2Fstatic%2Fimages%2Flogo%2Fzulip-icon-128x128.png&size=thumbnail"></a></div>')
msg = 'Test: https://developer.github.com/assets/images/hero-circuit-bg.png'
converted = bugdown_convert(msg)
self.assertEqual(converted, '<p>Test: <a href="https://developer.github.com/assets/images/hero-circuit-bg.png">https://developer.github.com/assets/images/hero-circuit-bg.png</a></p>\n<div class="message_inline_image"><a href="https://developer.github.com/assets/images/hero-circuit-bg.png"><img data-src-fullsize="/thumbnail?url=https%3A%2F%2Fdeveloper.github.com%2Fassets%2Fimages%2Fhero-circuit-bg.png&size=full" src="/thumbnail?url=https%3A%2F%2Fdeveloper.github.com%2Fassets%2Fimages%2Fhero-circuit-bg.png&size=thumbnail"></a></div>')
def test_twitter_id_extraction(self) -> None:
self.assertEqual(bugdown.get_tweet_id('http://twitter.com/#!/VizzQuotes/status/409030735191097344'), '409030735191097344')
self.assertEqual(bugdown.get_tweet_id('http://twitter.com/VizzQuotes/status/409030735191097344'), '409030735191097344')
self.assertEqual(bugdown.get_tweet_id('http://twitter.com/VizzQuotes/statuses/409030735191097344'), '409030735191097344')
self.assertEqual(bugdown.get_tweet_id('https://twitter.com/wdaher/status/1017581858'), '1017581858')
self.assertEqual(bugdown.get_tweet_id('https://twitter.com/wdaher/status/1017581858/'), '1017581858')
self.assertEqual(bugdown.get_tweet_id('https://twitter.com/windyoona/status/410766290349879296/photo/1'), '410766290349879296')
self.assertEqual(bugdown.get_tweet_id('https://twitter.com/windyoona/status/410766290349879296/'), '410766290349879296')
def test_inline_interesting_links(self) -> None:
def make_link(url: str) -> str:
return f'<a href="{url}">{url}</a>'
normal_tweet_html = ('<a href="https://twitter.com/Twitter"'
'>@Twitter</a> '
'meets @seepicturely at #tcdisrupt cc.'
'<a href="https://twitter.com/boscomonkey"'
'>@boscomonkey</a> '
'<a href="https://twitter.com/episod"'
'>@episod</a> '
'<a href="http://t.co/6J2EgYM"'
'>http://instagr.am/p/MuW67/</a>')
mention_in_link_tweet_html = """<a href="http://t.co/@foo">http://foo.com</a>"""
media_tweet_html = ('<a href="http://t.co/xo7pAhK6n3">'
'http://twitter.com/NEVNBoston/status/421654515616849920/photo/1</a>')
emoji_in_tweet_html = """Zulip is <span aria-label=\"100\" class="emoji emoji-1f4af" role=\"img\" title="100">:100:</span>% open-source!"""
def make_inline_twitter_preview(url: str, tweet_html: str, image_html: str='') -> str:
## As of right now, all previews are mocked to be the exact same tweet
return ('<div class="inline-preview-twitter">'
'<div class="twitter-tweet">'
f'<a href="{url}">'
'<img class="twitter-avatar"'
' src="https://external-content.zulipcdn.net/external_content/1f7cd2436976d410eab8189ebceda87ae0b34ead/687474703a2f2f7062732e7477696d672e63'
'6f6d2f70726f66696c655f696d616765732f313338303931323137332f53637265656e5f73686f745f323031312d30362d30335f61745f372e33352e33'
'365f504d5f6e6f726d616c2e706e67">'
'</a>'
f'<p>{tweet_html}</p>'
'<span>- Eoin McMillan (@imeoin)</span>'
f'{image_html}'
'</div>'
'</div>')
msg = 'http://www.twitter.com'
converted = bugdown_convert(msg)
self.assertEqual(converted, '<p>{}</p>'.format(make_link('http://www.twitter.com')))
msg = 'http://www.twitter.com/wdaher/'
converted = bugdown_convert(msg)
self.assertEqual(converted, '<p>{}</p>'.format(make_link('http://www.twitter.com/wdaher/')))
msg = 'http://www.twitter.com/wdaher/status/3'
converted = bugdown_convert(msg)
self.assertEqual(converted, '<p>{}</p>'.format(make_link('http://www.twitter.com/wdaher/status/3')))
# id too long
msg = 'http://www.twitter.com/wdaher/status/2879779692873154569'
converted = bugdown_convert(msg)
self.assertEqual(converted, '<p>{}</p>'.format(make_link('http://www.twitter.com/wdaher/status/2879779692873154569')))
# id too large (i.e. tweet doesn't exist)
msg = 'http://www.twitter.com/wdaher/status/999999999999999999'
converted = bugdown_convert(msg)
self.assertEqual(converted, '<p>{}</p>'.format(make_link('http://www.twitter.com/wdaher/status/999999999999999999')))
msg = 'http://www.twitter.com/wdaher/status/287977969287315456'
converted = bugdown_convert(msg)
self.assertEqual(converted, '<p>{}</p>\n{}'.format(
make_link('http://www.twitter.com/wdaher/status/287977969287315456'),
make_inline_twitter_preview('http://www.twitter.com/wdaher/status/287977969287315456', normal_tweet_html)))
msg = 'https://www.twitter.com/wdaher/status/287977969287315456'
converted = bugdown_convert(msg)
self.assertEqual(converted, '<p>{}</p>\n{}'.format(
make_link('https://www.twitter.com/wdaher/status/287977969287315456'),
make_inline_twitter_preview('https://www.twitter.com/wdaher/status/287977969287315456', normal_tweet_html)))
msg = 'http://twitter.com/wdaher/status/287977969287315456'
converted = bugdown_convert(msg)
self.assertEqual(converted, '<p>{}</p>\n{}'.format(
make_link('http://twitter.com/wdaher/status/287977969287315456'),
make_inline_twitter_preview('http://twitter.com/wdaher/status/287977969287315456', normal_tweet_html)))
# Repeated links will only be converted once
msg = ('http://twitter.com/wdaher/status/287977969287315456 '
'http://twitter.com/wdaher/status/287977969287315457 '
'http://twitter.com/wdaher/status/287977969287315457 '
'http://twitter.com/wdaher/status/287977969287315457')
converted = bugdown_convert(msg)
self.assertEqual(converted, '<p>{} {} {} {}</p>\n{}{}'.format(
make_link('http://twitter.com/wdaher/status/287977969287315456'),
make_link('http://twitter.com/wdaher/status/287977969287315457'),
make_link('http://twitter.com/wdaher/status/287977969287315457'),
make_link('http://twitter.com/wdaher/status/287977969287315457'),
make_inline_twitter_preview('http://twitter.com/wdaher/status/287977969287315456', normal_tweet_html),
make_inline_twitter_preview('http://twitter.com/wdaher/status/287977969287315457', normal_tweet_html)))
# A max of 3 will be converted
msg = ('http://twitter.com/wdaher/status/287977969287315456 '
'http://twitter.com/wdaher/status/287977969287315457 '
'https://twitter.com/wdaher/status/287977969287315456 '
'http://twitter.com/wdaher/status/287977969287315460')
converted = bugdown_convert(msg)
self.assertEqual(converted, '<p>{} {} {} {}</p>\n{}{}{}'.format(
make_link('http://twitter.com/wdaher/status/287977969287315456'),
make_link('http://twitter.com/wdaher/status/287977969287315457'),
make_link('https://twitter.com/wdaher/status/287977969287315456'),
make_link('http://twitter.com/wdaher/status/287977969287315460'),
make_inline_twitter_preview('http://twitter.com/wdaher/status/287977969287315456', normal_tweet_html),
make_inline_twitter_preview('http://twitter.com/wdaher/status/287977969287315457', normal_tweet_html),
make_inline_twitter_preview('https://twitter.com/wdaher/status/287977969287315456', normal_tweet_html)))
# Tweet has a mention in a URL, only the URL is linked
msg = 'http://twitter.com/wdaher/status/287977969287315458'
converted = bugdown_convert(msg)
self.assertEqual(converted, '<p>{}</p>\n{}'.format(
make_link('http://twitter.com/wdaher/status/287977969287315458'),
make_inline_twitter_preview('http://twitter.com/wdaher/status/287977969287315458', mention_in_link_tweet_html)))
# Tweet with an image
msg = 'http://twitter.com/wdaher/status/287977969287315459'
converted = bugdown_convert(msg)
self.assertEqual(converted, '<p>{}</p>\n{}'.format(
make_link('http://twitter.com/wdaher/status/287977969287315459'),
make_inline_twitter_preview('http://twitter.com/wdaher/status/287977969287315459',
media_tweet_html,
('<div class="twitter-image">'
'<a href="http://t.co/xo7pAhK6n3">'
'<img src="https://pbs.twimg.com/media/BdoEjD4IEAIq86Z.jpg:small">'
'</a>'
'</div>'))))
msg = 'http://twitter.com/wdaher/status/287977969287315460'
converted = bugdown_convert(msg)
self.assertEqual(converted, '<p>{}</p>\n{}'.format(
make_link('http://twitter.com/wdaher/status/287977969287315460'),
make_inline_twitter_preview('http://twitter.com/wdaher/status/287977969287315460', emoji_in_tweet_html)))
def test_fetch_tweet_data_settings_validation(self) -> None:
with self.settings(TEST_SUITE=False, TWITTER_CONSUMER_KEY=None):
self.assertIs(None, bugdown.fetch_tweet_data('287977969287315459'))
def test_content_has_emoji(self) -> None:
self.assertFalse(bugdown.content_has_emoji_syntax('boring'))
self.assertFalse(bugdown.content_has_emoji_syntax('hello: world'))
self.assertFalse(bugdown.content_has_emoji_syntax(':foobar'))
self.assertFalse(bugdown.content_has_emoji_syntax('::: hello :::'))
self.assertTrue(bugdown.content_has_emoji_syntax('foo :whatever:'))
self.assertTrue(bugdown.content_has_emoji_syntax('\n:whatever:'))
self.assertTrue(bugdown.content_has_emoji_syntax(':smile: ::::::'))
def test_realm_emoji(self) -> None:
def emoji_img(name: str, file_name: str, realm_id: int) -> str:
return '<img alt="{}" class="emoji" src="{}" title="{}">'.format(
name, get_emoji_url(file_name, realm_id), name[1:-1].replace("_", " "))
realm = get_realm('zulip')
# Needs to mock an actual message because that's how bugdown obtains the realm
msg = Message(sender=self.example_user('hamlet'))
converted = bugdown.convert(":green_tick:", message_realm=realm, message=msg)
realm_emoji = RealmEmoji.objects.filter(realm=realm,
name='green_tick',
deactivated=False).get()
self.assertEqual(converted, '<p>{}</p>'.format(emoji_img(':green_tick:', realm_emoji.file_name, realm.id)))
# Deactivate realm emoji.
do_remove_realm_emoji(realm, 'green_tick')
converted = bugdown.convert(":green_tick:", message_realm=realm, message=msg)
self.assertEqual(converted, '<p>:green_tick:</p>')
def test_deactivated_realm_emoji(self) -> None:
# Deactivate realm emoji.
realm = get_realm('zulip')
do_remove_realm_emoji(realm, 'green_tick')
msg = Message(sender=self.example_user('hamlet'))
converted = bugdown.convert(":green_tick:", message_realm=realm, message=msg)
self.assertEqual(converted, '<p>:green_tick:</p>')
def test_unicode_emoji(self) -> None:
msg = '\u2615' # ☕
converted = bugdown_convert(msg)
self.assertEqual(converted, '<p><span aria-label=\"coffee\" class="emoji emoji-2615" role=\"img\" title="coffee">:coffee:</span></p>')
msg = '\u2615\u2615' # ☕☕
converted = bugdown_convert(msg)
self.assertEqual(converted, '<p><span aria-label=\"coffee\" class="emoji emoji-2615" role=\"img\" title="coffee">:coffee:</span><span aria-label=\"coffee\" class="emoji emoji-2615" role=\"img\" title="coffee">:coffee:</span></p>')
def test_no_translate_emoticons_if_off(self) -> None:
user_profile = self.example_user('othello')
do_set_user_display_setting(user_profile, 'translate_emoticons', False)
msg = Message(sender=user_profile, sending_client=get_client("test"))
content = ':)'
expected = '<p>:)</p>'
converted = render_markdown(msg, content)
self.assertEqual(converted, expected)
def test_same_markup(self) -> None:
msg = '\u2615' # ☕
unicode_converted = bugdown_convert(msg)
msg = ':coffee:' # ☕☕
converted = bugdown_convert(msg)
self.assertEqual(converted, unicode_converted)
def test_links_in_topic_name(self) -> None:
realm = get_realm('zulip')
msg = Message(sender=self.example_user('othello'))
msg.set_topic_name("https://google.com/hello-world")
converted_topic = bugdown.topic_links(realm.id, msg.topic_name())
self.assertEqual(converted_topic, ['https://google.com/hello-world'])
msg.set_topic_name("http://google.com/hello-world")
converted_topic = bugdown.topic_links(realm.id, msg.topic_name())
self.assertEqual(converted_topic, ['http://google.com/hello-world'])
msg.set_topic_name("Without scheme google.com/hello-world")
converted_topic = bugdown.topic_links(realm.id, msg.topic_name())
self.assertEqual(converted_topic, ['https://google.com/hello-world'])
msg.set_topic_name("Without scheme random.words/hello-world")
converted_topic = bugdown.topic_links(realm.id, msg.topic_name())
self.assertEqual(converted_topic, [])
msg.set_topic_name("Try out http://ftp.debian.org, https://google.com/ and https://google.in/.")
converted_topic = bugdown.topic_links(realm.id, msg.topic_name())
self.assertEqual(converted_topic, ['http://ftp.debian.org', 'https://google.com/', 'https://google.in/'])
def test_realm_patterns(self) -> None:
realm = get_realm('zulip')
url_format_string = r"https://trac.example.com/ticket/%(id)s"
realm_filter = RealmFilter(realm=realm,
pattern=r"#(?P<id>[0-9]{2,8})",
url_format_string=url_format_string)
realm_filter.save()
self.assertEqual(
realm_filter.__str__(),
'<RealmFilter(zulip): #(?P<id>[0-9]{2,8})'
' https://trac.example.com/ticket/%(id)s>')
msg = Message(sender=self.example_user('othello'))
msg.set_topic_name("#444")
flush_per_request_caches()
content = "We should fix #224 and #115, but not issue#124 or #1124z or [trac #15](https://trac.example.com/ticket/16) today."
converted = bugdown.convert(content, message_realm=realm, message=msg)
converted_topic = bugdown.topic_links(realm.id, msg.topic_name())
self.assertEqual(converted, '<p>We should fix <a href="https://trac.example.com/ticket/224">#224</a> and <a href="https://trac.example.com/ticket/115">#115</a>, but not issue#124 or #1124z or <a href="https://trac.example.com/ticket/16">trac #15</a> today.</p>')
self.assertEqual(converted_topic, ['https://trac.example.com/ticket/444'])
msg.set_topic_name("#444 https://google.com")
converted_topic = bugdown.topic_links(realm.id, msg.topic_name())
self.assertEqual(converted_topic, ['https://trac.example.com/ticket/444', 'https://google.com'])
RealmFilter(realm=realm, pattern=r'#(?P<id>[a-zA-Z]+-[0-9]+)',
url_format_string=r'https://trac.example.com/ticket/%(id)s').save()
msg = Message(sender=self.example_user('hamlet'))
content = '#ZUL-123 was fixed and code was deployed to production, also #zul-321 was deployed to staging'
converted = bugdown.convert(content, message_realm=realm, message=msg)
self.assertEqual(converted, '<p><a href="https://trac.example.com/ticket/ZUL-123">#ZUL-123</a> was fixed and code was deployed to production, also <a href="https://trac.example.com/ticket/zul-321">#zul-321</a> was deployed to staging</p>')
def assert_conversion(content: str, convert: bool=True) -> None:
converted = bugdown.convert(content, message_realm=realm, message=msg)
converted_topic = bugdown.topic_links(realm.id, content)
if convert:
self.assertTrue('trac.example.com' in converted)
self.assertEqual(len(converted_topic), 1)
self.assertTrue('trac.example.com' in converted_topic[0])
else:
self.assertTrue('trac.example.com' not in converted)
self.assertEqual(len(converted_topic), 0)
assert_conversion('Hello #123 World')
assert_conversion('Hello #123World', False)
assert_conversion('Hello#123 World', False)
assert_conversion('Hello#123World', False)
# Ideally, these should be converted, but bugdown doesn't
# handle word boundary detection in languages that don't use
# whitespace for that correctly yet.
assert_conversion('チケットは#123です', False)
assert_conversion('チケットは #123です', False)
assert_conversion('チケットは#123 です', False)
assert_conversion('チケットは #123 です')
assert_conversion('(#123)')
assert_conversion('#123>')
assert_conversion('"#123"')
assert_conversion('#123@')
assert_conversion(')#123(', False)
assert_conversion('##123', False)
# test nested realm patterns should avoid double matching
RealmFilter(realm=realm, pattern=r'hello#(?P<id>[0-9]+)',
url_format_string=r'https://trac.example.com/hello/%(id)s').save()
converted_topic = bugdown.topic_links(realm.id, 'hello#123 #234')
self.assertEqual(converted_topic, ['https://trac.example.com/ticket/234', 'https://trac.example.com/hello/123'])
def test_maybe_update_markdown_engines(self) -> None:
realm = get_realm('zulip')
url_format_string = r"https://trac.example.com/ticket/%(id)s"
realm_filter = RealmFilter(realm=realm,
pattern=r"#(?P<id>[0-9]{2,8})",
url_format_string=url_format_string)
realm_filter.save()
bugdown.realm_filter_data = {}
bugdown.maybe_update_markdown_engines(None, False)
all_filters = bugdown.realm_filter_data
zulip_filters = all_filters[realm.id]
self.assertEqual(len(zulip_filters), 1)
self.assertEqual(zulip_filters[0],
('#(?P<id>[0-9]{2,8})', 'https://trac.example.com/ticket/%(id)s', realm_filter.id))
def test_flush_realm_filter(self) -> None:
realm = get_realm('zulip')
def flush() -> None:
'''
flush_realm_filter is a post-save hook, so calling it
directly for testing is kind of awkward
'''
class Instance:
realm_id: Optional[int] = None
instance = Instance()
instance.realm_id = realm.id
flush_realm_filter(sender=None, instance=instance)
def save_new_realm_filter() -> None:
realm_filter = RealmFilter(realm=realm,
pattern=r"whatever",
url_format_string='whatever')
realm_filter.save()
# start fresh for our realm
flush()
self.assertFalse(realm_in_local_realm_filters_cache(realm.id))
# call this just for side effects of populating the cache
realm_filters_for_realm(realm.id)
self.assertTrue(realm_in_local_realm_filters_cache(realm.id))
# Saving a new RealmFilter should have the side effect of
# flushing the cache.
save_new_realm_filter()
self.assertFalse(realm_in_local_realm_filters_cache(realm.id))
# and flush it one more time, to make sure we don't get a KeyError
flush()
self.assertFalse(realm_in_local_realm_filters_cache(realm.id))
def test_realm_patterns_negative(self) -> None:
realm = get_realm('zulip')
RealmFilter(realm=realm, pattern=r"#(?P<id>[0-9]{2,8})",
url_format_string=r"https://trac.example.com/ticket/%(id)s").save()
boring_msg = Message(sender=self.example_user('othello'))
boring_msg.set_topic_name("no match here")
converted_boring_topic = bugdown.topic_links(realm.id, boring_msg.topic_name())
self.assertEqual(converted_boring_topic, [])
def test_is_status_message(self) -> None:
user_profile = self.example_user('othello')
msg = Message(sender=user_profile, sending_client=get_client("test"))
content = '/me makes a list\n* one\n* two'
rendered_content = render_markdown(msg, content)
self.assertEqual(
rendered_content,
'<p>/me makes a list</p>\n<ul>\n<li>one</li>\n<li>two</li>\n</ul>',
)
self.assertTrue(Message.is_status_message(content, rendered_content))
content = '/me takes a walk'
rendered_content = render_markdown(msg, content)
self.assertEqual(
rendered_content,
'<p>/me takes a walk</p>',
)
self.assertTrue(Message.is_status_message(content, rendered_content))
content = '/me writes a second line\nline'
rendered_content = render_markdown(msg, content)
self.assertEqual(
rendered_content,
'<p>/me writes a second line<br>\nline</p>',
)
self.assertTrue(Message.is_status_message(content, rendered_content))
def test_alert_words(self) -> None:
user_profile = self.example_user('othello')
do_add_alert_words(user_profile, ["ALERTWORD", "scaryword"])
msg = Message(sender=user_profile, sending_client=get_client("test"))
realm_alert_words_automaton = get_alert_word_automaton(user_profile.realm)
def render(msg: Message, content: str) -> str:
return render_markdown(msg,
content,
realm_alert_words_automaton=realm_alert_words_automaton)
content = "We have an ALERTWORD day today!"
self.assertEqual(render(msg, content), "<p>We have an ALERTWORD day today!</p>")
self.assertEqual(msg.user_ids_with_alert_words, {user_profile.id})
msg = Message(sender=user_profile, sending_client=get_client("test"))
content = "We have a NOTHINGWORD day today!"
self.assertEqual(render(msg, content), "<p>We have a NOTHINGWORD day today!</p>")
self.assertEqual(msg.user_ids_with_alert_words, set())
def test_alert_words_returns_user_ids_with_alert_words(self) -> None:
alert_words_for_users: Dict[str, List[str]] = {
'hamlet': ['how'], 'cordelia': ['this possible'],
'iago': ['hello'], 'prospero': ['hello'],
'othello': ['how are you'], 'aaron': ['hey'],
}
user_profiles: Dict[str, UserProfile] = {}
for (username, alert_words) in alert_words_for_users.items():
user_profile = self.example_user(username)
user_profiles.update({username: user_profile})
do_add_alert_words(user_profile, alert_words)
sender_user_profile = self.example_user('polonius')
msg = Message(sender=sender_user_profile, sending_client=get_client("test"))
realm_alert_words_automaton = get_alert_word_automaton(sender_user_profile.realm)
def render(msg: Message, content: str) -> str:
return render_markdown(msg,
content,
realm_alert_words_automaton=realm_alert_words_automaton)
content = "hello how is this possible how are you doing today"
render(msg, content)
expected_user_ids: Set[int] = {
user_profiles['hamlet'].id, user_profiles['cordelia'].id, user_profiles['iago'].id,
user_profiles['prospero'].id, user_profiles['othello'].id,
}
# All users except aaron have their alert word appear in the message content
self.assertEqual(msg.user_ids_with_alert_words, expected_user_ids)
def test_alert_words_returns_user_ids_with_alert_words_1(self) -> None:
alert_words_for_users: Dict[str, List[str]] = {
'hamlet': ['provisioning', 'Prod deployment'],
'cordelia': ['test', 'Prod'],
'iago': ['prod'], 'prospero': ['deployment'],
'othello': ['last'],
}
user_profiles: Dict[str, UserProfile] = {}
for (username, alert_words) in alert_words_for_users.items():
user_profile = self.example_user(username)
user_profiles.update({username: user_profile})
do_add_alert_words(user_profile, alert_words)
sender_user_profile = self.example_user('polonius')
msg = Message(sender=sender_user_profile, sending_client=get_client("test"))
realm_alert_words_automaton = get_alert_word_automaton(sender_user_profile.realm)
def render(msg: Message, content: str) -> str:
return render_markdown(msg,
content,
realm_alert_words_automaton=realm_alert_words_automaton)
content = """Hello, everyone. Prod deployment has been completed
And this is a new line
to test out how markdown convert this into something line ending splitted array
and this is a new line
last"""
render(msg, content)
expected_user_ids: Set[int] = {
user_profiles['hamlet'].id,
user_profiles['cordelia'].id,
user_profiles['iago'].id,
user_profiles['prospero'].id,
user_profiles['othello'].id,
}
# All users have their alert word appear in the message content
self.assertEqual(msg.user_ids_with_alert_words, expected_user_ids)
def test_alert_words_returns_user_ids_with_alert_words_in_french(self) -> None:
alert_words_for_users: Dict[str, List[str]] = {
'hamlet': ['réglementaire', 'une politique', 'une merveille'],
'cordelia': ['énormément', 'Prod'],
'iago': ['prod'], 'prospero': ['deployment'],
'othello': ['last'],
}
user_profiles: Dict[str, UserProfile] = {}
for (username, alert_words) in alert_words_for_users.items():
user_profile = self.example_user(username)
user_profiles.update({username: user_profile})
do_add_alert_words(user_profile, alert_words)
sender_user_profile = self.example_user('polonius')
msg = Message(sender=sender_user_profile, sending_client=get_client("test"))
realm_alert_words_automaton = get_alert_word_automaton(sender_user_profile.realm)
def render(msg: Message, content: str) -> str:
return render_markdown(msg,
content,
realm_alert_words_automaton=realm_alert_words_automaton)
content = """This is to test out alert words work in languages with accented characters too
bonjour est (énormément) ce a quoi ressemble le français
et j'espère qu'il n'y n' réglementaire a pas de mots d'alerte dans ce texte français
"""
render(msg, content)
expected_user_ids: Set[int] = {user_profiles['hamlet'].id, user_profiles['cordelia'].id}
# Only hamlet and cordelia have their alert-words appear in the message content
self.assertEqual(msg.user_ids_with_alert_words, expected_user_ids)
def test_alert_words_returns_empty_user_ids_with_alert_words(self) -> None:
alert_words_for_users: Dict[str, List[str]] = {
'hamlet': [], 'cordelia': [], 'iago': [], 'prospero': [],
'othello': [], 'aaron': [],
}
user_profiles: Dict[str, UserProfile] = {}
for (username, alert_words) in alert_words_for_users.items():
user_profile = self.example_user(username)
user_profiles.update({username: user_profile})
do_add_alert_words(user_profile, alert_words)
sender_user_profile = self.example_user('polonius')
msg = Message(sender=user_profile, sending_client=get_client("test"))
realm_alert_words_automaton = get_alert_word_automaton(sender_user_profile.realm)
def render(msg: Message, content: str) -> str:
return render_markdown(msg,
content,
realm_alert_words_automaton=realm_alert_words_automaton)
content = """hello how is this possible how are you doing today
This is to test that the no user_ids who have alrert wourldword is participating
in sending of the message
"""
render(msg, content)
expected_user_ids: Set[int] = set()
# None of the users have their alert-words appear in the message content
self.assertEqual(msg.user_ids_with_alert_words, expected_user_ids)
def get_mock_alert_words(self, num_words: int, word_length: int) -> List[str]:
alert_words = ['x' * word_length] * num_words # type List[str]
return alert_words
def test_alert_words_with_empty_alert_words(self) -> None:
alert_words_for_users: Dict[str, List[str]] = {
'hamlet': [],
'cordelia': [],
'iago': [],
'othello': [],
}
user_profiles: Dict[str, UserProfile] = {}
for (username, alert_words) in alert_words_for_users.items():
user_profile = self.example_user(username)
user_profiles.update({username: user_profile})
do_add_alert_words(user_profile, alert_words)
sender_user_profile = self.example_user('polonius')
msg = Message(sender=sender_user_profile, sending_client=get_client("test"))
realm_alert_words_automaton = get_alert_word_automaton(sender_user_profile.realm)
def render(msg: Message, content: str) -> str:
return render_markdown(msg,
content,
realm_alert_words_automaton=realm_alert_words_automaton)
content = """This is to test a empty alert words i.e. no user has any alert-words set"""
render(msg, content)
expected_user_ids: Set[int] = set()
self.assertEqual(msg.user_ids_with_alert_words, expected_user_ids)
def test_alert_words_retuns_user_ids_with_alert_words_with_huge_alert_words(self) -> None:
alert_words_for_users: Dict[str, List[str]] = {
'hamlet': ['issue124'],
'cordelia': self.get_mock_alert_words(500, 10),
'iago': self.get_mock_alert_words(500, 10),
'othello': self.get_mock_alert_words(500, 10),
}
user_profiles: Dict[str, UserProfile] = {}
for (username, alert_words) in alert_words_for_users.items():
user_profile = self.example_user(username)
user_profiles.update({username: user_profile})
do_add_alert_words(user_profile, alert_words)
sender_user_profile = self.example_user('polonius')
msg = Message(sender=sender_user_profile, sending_client=get_client("test"))
realm_alert_words_automaton = get_alert_word_automaton(sender_user_profile.realm)
def render(msg: Message, content: str) -> str:
return render_markdown(msg,
content,
realm_alert_words_automaton=realm_alert_words_automaton)
content = """The code above will print 10 random values of numbers between 1 and 100.
The second line, for x in range(10), determines how many values will be printed (when you use
range(x), the number that you use in place of x will be the amount of values that you'll have
printed. if you want 20 values, use range(20). use range(5) if you only want 5 values returned,
etc.). I was talking abou the issue124 on github. Then the third line: print random.randint(1,101) will automatically select a random integer
between 1 and 100 for you. The process is fairly simple
"""
render(msg, content)
expected_user_ids: Set[int] = {user_profiles['hamlet'].id}
# Only hamlet has alert-word 'issue124' present in the message content
self.assertEqual(msg.user_ids_with_alert_words, expected_user_ids)
def test_default_code_block_language(self) -> None:
realm = get_realm('zulip')
self.assertEqual(realm.default_code_block_language, None)
text = "```{}\nconsole.log('Hello World');\n```\n"
# Render without default language
msg_with_js = bugdown_convert(text.format('js'))
msg_with_python = bugdown_convert(text.format('python'))
msg_without_language = bugdown_convert(text.format(''))
msg_with_quote = bugdown_convert(text.format('quote'))
msg_with_math = bugdown_convert(text.format('math'))
# Render with default=javascript
do_set_realm_property(realm, 'default_code_block_language', 'javascript')
msg_without_language_default_js = bugdown_convert(text.format(''))
msg_with_python_default_js = bugdown_convert(text.format('python'))
# Render with default=python
do_set_realm_property(realm, 'default_code_block_language', 'python')
msg_without_language_default_py = bugdown_convert(text.format(''))
msg_with_none_default_py = bugdown_convert(text.format('none'))
# Render with default=quote
do_set_realm_property(realm, 'default_code_block_language', 'quote')
msg_without_language_default_quote = bugdown_convert(text.format(''))
# Render with default=math
do_set_realm_property(realm, 'default_code_block_language', 'math')
msg_without_language_default_math = bugdown_convert(text.format(''))
# Render without default language
do_set_realm_property(realm, 'default_code_block_language', None)
msg_without_language_final = bugdown_convert(text.format(''))
self.assertTrue(msg_with_js == msg_without_language_default_js)
self.assertTrue(msg_with_python == msg_with_python_default_js == msg_without_language_default_py)
self.assertTrue(msg_with_quote == msg_without_language_default_quote)
self.assertTrue(msg_with_math == msg_without_language_default_math)
self.assertTrue(msg_without_language == msg_with_none_default_py == msg_without_language_final)
# Test checking inside nested quotes
nested_text = "````quote\n\n{}\n\n{}````".format(text.format('js'), text.format(''))
do_set_realm_property(realm, 'default_code_block_language', 'javascript')
rendered = bugdown_convert(nested_text)
with_language, without_language = re.findall(r'<pre>(.*?)$', rendered, re.MULTILINE)
self.assertTrue(with_language == without_language)
do_set_realm_property(realm, 'default_code_block_language', None)
rendered = bugdown_convert(nested_text)
with_language, without_language = re.findall(r'<pre>(.*?)$', rendered, re.MULTILINE)
self.assertFalse(with_language == without_language)
def test_mention_wildcard(self) -> None:
user_profile = self.example_user('othello')
msg = Message(sender=user_profile, sending_client=get_client("test"))
content = "@**all** test"
self.assertEqual(render_markdown(msg, content),
'<p><span class="user-mention" data-user-id="*">'
'@all'
'</span> test</p>')
self.assertTrue(msg.mentions_wildcard)
def test_mention_everyone(self) -> None:
user_profile = self.example_user('othello')
msg = Message(sender=user_profile, sending_client=get_client("test"))
content = "@**everyone** test"
self.assertEqual(render_markdown(msg, content),
'<p><span class="user-mention" data-user-id="*">'
'@everyone'
'</span> test</p>')
self.assertTrue(msg.mentions_wildcard)
def test_mention_stream(self) -> None:
user_profile = self.example_user('othello')
msg = Message(sender=user_profile, sending_client=get_client("test"))
content = "@**stream** test"
self.assertEqual(render_markdown(msg, content),
'<p><span class="user-mention" data-user-id="*">'
'@stream'
'</span> test</p>')
self.assertTrue(msg.mentions_wildcard)
def test_mention_at_wildcard(self) -> None:
user_profile = self.example_user('othello')
msg = Message(sender=user_profile, sending_client=get_client("test"))
content = "@all test"
self.assertEqual(render_markdown(msg, content),
'<p>@all test</p>')
self.assertFalse(msg.mentions_wildcard)
self.assertEqual(msg.mentions_user_ids, set())
def test_mention_at_everyone(self) -> None:
user_profile = self.example_user('othello')
msg = Message(sender=user_profile, sending_client=get_client("test"))
content = "@everyone test"
self.assertEqual(render_markdown(msg, content),
'<p>@everyone test</p>')
self.assertFalse(msg.mentions_wildcard)
self.assertEqual(msg.mentions_user_ids, set())
def test_mention_word_starting_with_at_wildcard(self) -> None:
user_profile = self.example_user('othello')
msg = Message(sender=user_profile, sending_client=get_client("test"))
content = "test @alleycat.com test"
self.assertEqual(render_markdown(msg, content),
'<p>test @alleycat.com test</p>')
self.assertFalse(msg.mentions_wildcard)
self.assertEqual(msg.mentions_user_ids, set())
def test_mention_at_normal_user(self) -> None:
user_profile = self.example_user('othello')
msg = Message(sender=user_profile, sending_client=get_client("test"))
content = "@aaron test"
self.assertEqual(render_markdown(msg, content),
'<p>@aaron test</p>')
self.assertFalse(msg.mentions_wildcard)
self.assertEqual(msg.mentions_user_ids, set())
def test_mention_single(self) -> None:
sender_user_profile = self.example_user('othello')
user_profile = self.example_user('hamlet')
msg = Message(sender=sender_user_profile, sending_client=get_client("test"))
user_id = user_profile.id
content = "@**King Hamlet**"
self.assertEqual(render_markdown(msg, content),
'<p><span class="user-mention" '
f'data-user-id="{user_id}">'
'@King Hamlet</span></p>')
self.assertEqual(msg.mentions_user_ids, {user_profile.id})
def test_mention_silent(self) -> None:
sender_user_profile = self.example_user('othello')
user_profile = self.example_user('hamlet')
msg = Message(sender=sender_user_profile, sending_client=get_client("test"))
user_id = user_profile.id
content = "@_**King Hamlet**"
self.assertEqual(render_markdown(msg, content),
'<p><span class="user-mention silent" '
f'data-user-id="{user_id}">'
'King Hamlet</span></p>')
self.assertEqual(msg.mentions_user_ids, set())
def test_possible_mentions(self) -> None:
def assert_mentions(content: str, names: Set[str], has_wildcards: bool=False) -> None:
self.assertEqual(possible_mentions(content), (names, has_wildcards))
assert_mentions('', set())
assert_mentions('boring', set())
assert_mentions('@**all**', set(), True)
assert_mentions('smush@**steve**smush', set())
assert_mentions(
'Hello @**King Hamlet** and @**Cordelia Lear**\n@**Foo van Barson|1234** @**all**',
{'King Hamlet', 'Cordelia Lear', 'Foo van Barson|1234'}, True,
)
def test_mention_multiple(self) -> None:
sender_user_profile = self.example_user('othello')
hamlet = self.example_user('hamlet')
cordelia = self.example_user('cordelia')
msg = Message(sender=sender_user_profile, sending_client=get_client("test"))
content = "@**King Hamlet** and @**Cordelia Lear**, check this out"
self.assertEqual(render_markdown(msg, content),
'<p>'
'<span class="user-mention" '
f'data-user-id="{hamlet.id}">@King Hamlet</span> and '
'<span class="user-mention" '
f'data-user-id="{cordelia.id}">@Cordelia Lear</span>, '
'check this out</p>')
self.assertEqual(msg.mentions_user_ids, {hamlet.id, cordelia.id})
def test_mention_in_quotes(self) -> None:
othello = self.example_user('othello')
hamlet = self.example_user('hamlet')
cordelia = self.example_user('cordelia')
msg = Message(sender=othello, sending_client=get_client("test"))
content = "> @**King Hamlet** and @**Othello, the Moor of Venice**\n\n @**King Hamlet** and @**Cordelia Lear**"
self.assertEqual(render_markdown(msg, content),
'<blockquote>\n<p>'
f'<span class="user-mention silent" data-user-id="{hamlet.id}">King Hamlet</span>'
' and '
f'<span class="user-mention silent" data-user-id="{othello.id}">Othello, the Moor of Venice</span>'
'</p>\n</blockquote>\n'
'<p>'
f'<span class="user-mention" data-user-id="{hamlet.id}">@King Hamlet</span>'
' and '
f'<span class="user-mention" data-user-id="{cordelia.id}">@Cordelia Lear</span>'
'</p>')
self.assertEqual(msg.mentions_user_ids, {hamlet.id, cordelia.id})
# Both fenced quote and > quote should be identical for both silent and regular syntax.
expected = ('<blockquote>\n<p>'
f'<span class="user-mention silent" data-user-id="{hamlet.id}">King Hamlet</span>'
'</p>\n</blockquote>')
content = "```quote\n@**King Hamlet**\n```"
self.assertEqual(render_markdown(msg, content), expected)
self.assertEqual(msg.mentions_user_ids, set())
content = "> @**King Hamlet**"
self.assertEqual(render_markdown(msg, content), expected)
self.assertEqual(msg.mentions_user_ids, set())
content = "```quote\n@_**King Hamlet**\n```"
self.assertEqual(render_markdown(msg, content), expected)
self.assertEqual(msg.mentions_user_ids, set())
content = "> @_**King Hamlet**"
self.assertEqual(render_markdown(msg, content), expected)
self.assertEqual(msg.mentions_user_ids, set())
def test_mention_duplicate_full_name(self) -> None:
realm = get_realm('zulip')
def make_user(email: str, full_name: str) -> UserProfile:
return create_user(
email=email,
password='whatever',
realm=realm,
full_name=full_name,
short_name='whatever',
)
sender_user_profile = self.example_user('othello')
twin1 = make_user('[email protected]', 'Mark Twin')
twin2 = make_user('[email protected]', 'Mark Twin')
cordelia = self.example_user('cordelia')
msg = Message(sender=sender_user_profile, sending_client=get_client("test"))
content = f"@**Mark Twin|{twin1.id}**, @**Mark Twin|{twin2.id}** and @**Cordelia Lear**, hi."
self.assertEqual(render_markdown(msg, content),
'<p>'
'<span class="user-mention" '
f'data-user-id="{twin1.id}">@Mark Twin</span>, '
'<span class="user-mention" '
f'data-user-id="{twin2.id}">@Mark Twin</span> and '
'<span class="user-mention" '
f'data-user-id="{cordelia.id}">@Cordelia Lear</span>, '
'hi.</p>')
self.assertEqual(msg.mentions_user_ids, {twin1.id, twin2.id, cordelia.id})
def test_mention_invalid(self) -> None:
sender_user_profile = self.example_user('othello')
msg = Message(sender=sender_user_profile, sending_client=get_client("test"))
content = "Hey @**Nonexistent User**"
self.assertEqual(render_markdown(msg, content),
'<p>Hey @<strong>Nonexistent User</strong></p>')
self.assertEqual(msg.mentions_user_ids, set())
def test_user_mention_atomic_string(self) -> None:
sender_user_profile = self.example_user('othello')
realm = get_realm('zulip')
msg = Message(sender=sender_user_profile, sending_client=get_client("test"))
# Create a linkifier.
url_format_string = r"https://trac.example.com/ticket/%(id)s"
realm_filter = RealmFilter(realm=realm,
pattern=r"#(?P<id>[0-9]{2,8})",
url_format_string=url_format_string)
realm_filter.save()
self.assertEqual(
realm_filter.__str__(),
'<RealmFilter(zulip): #(?P<id>[0-9]{2,8})'
' https://trac.example.com/ticket/%(id)s>')
# Create a user that potentially interferes with the pattern.
test_user = create_user(email='[email protected]',
password='whatever',
realm=realm,
full_name='Atomic #123',
short_name='whatever')
content = "@**Atomic #123**"
self.assertEqual(render_markdown(msg, content),
'<p><span class="user-mention" '
f'data-user-id="{test_user.id}">'
'@Atomic #123</span></p>')
self.assertEqual(msg.mentions_user_ids, {test_user.id})
content = "@_**Atomic #123**"
self.assertEqual(render_markdown(msg, content),
'<p><span class="user-mention silent" '
f'data-user-id="{test_user.id}">'
'Atomic #123</span></p>')
self.assertEqual(msg.mentions_user_ids, set())
def create_user_group_for_test(self, user_group_name: str) -> UserGroup:
othello = self.example_user('othello')
return create_user_group(user_group_name, [othello], get_realm('zulip'))
def test_user_group_mention_single(self) -> None:
sender_user_profile = self.example_user('othello')
user_profile = self.example_user('hamlet')
msg = Message(sender=sender_user_profile, sending_client=get_client("test"))
user_id = user_profile.id
user_group = self.create_user_group_for_test('support')
content = "@**King Hamlet** @*support*"
self.assertEqual(render_markdown(msg, content),
'<p><span class="user-mention" '
f'data-user-id="{user_id}">'
'@King Hamlet</span> '
'<span class="user-group-mention" '
f'data-user-group-id="{user_group.id}">'
'@support</span></p>')
self.assertEqual(msg.mentions_user_ids, {user_profile.id})
self.assertEqual(msg.mentions_user_group_ids, {user_group.id})
def test_user_group_mention_atomic_string(self) -> None:
sender_user_profile = self.example_user('othello')
realm = get_realm('zulip')
msg = Message(sender=sender_user_profile, sending_client=get_client("test"))
user_profile = self.example_user('hamlet')
# Create a linkifier.
url_format_string = r"https://trac.example.com/ticket/%(id)s"
realm_filter = RealmFilter(realm=realm,
pattern=r"#(?P<id>[0-9]{2,8})",
url_format_string=url_format_string)
realm_filter.save()
self.assertEqual(
realm_filter.__str__(),
'<RealmFilter(zulip): #(?P<id>[0-9]{2,8})'
' https://trac.example.com/ticket/%(id)s>')
# Create a user-group that potentially interferes with the pattern.
user_id = user_profile.id
user_group = self.create_user_group_for_test('support #123')
content = "@**King Hamlet** @*support #123*"
self.assertEqual(render_markdown(msg, content),
'<p><span class="user-mention" '
f'data-user-id="{user_id}">'
'@King Hamlet</span> '
'<span class="user-group-mention" '
f'data-user-group-id="{user_group.id}">'
'@support #123</span></p>')
self.assertEqual(msg.mentions_user_ids, {user_profile.id})
self.assertEqual(msg.mentions_user_group_ids, {user_group.id})
def test_possible_user_group_mentions(self) -> None:
def assert_mentions(content: str, names: Set[str]) -> None:
self.assertEqual(possible_user_group_mentions(content), names)
assert_mentions('', set())
assert_mentions('boring', set())
assert_mentions('@**all**', set())
assert_mentions('smush@*steve*smush', set())
assert_mentions(
'@*support* Hello @**King Hamlet** and @**Cordelia Lear**\n'
'@**Foo van Barson** @**all**', {'support'},
)
assert_mentions(
'Attention @*support*, @*frontend* and @*backend*\ngroups.',
{'support', 'frontend', 'backend'},
)
def test_user_group_mention_multiple(self) -> None:
sender_user_profile = self.example_user('othello')
msg = Message(sender=sender_user_profile, sending_client=get_client("test"))
support = self.create_user_group_for_test('support')
backend = self.create_user_group_for_test('backend')
content = "@*support* and @*backend*, check this out"
self.assertEqual(render_markdown(msg, content),
'<p>'
'<span class="user-group-mention" '
f'data-user-group-id="{support.id}">'
'@support</span> '
'and '
'<span class="user-group-mention" '
f'data-user-group-id="{backend.id}">'
'@backend</span>, '
'check this out'
'</p>')
self.assertEqual(msg.mentions_user_group_ids, {support.id, backend.id})
def test_user_group_mention_edit(self) -> None:
sender_user_profile = self.example_user('hamlet')
user_profile = self.example_user('othello')
self.create_user_group_for_test('support')
self.login('hamlet')
msg_id = self.send_stream_message(sender_user_profile,
"Denmark",
topic_name="editing",
content='test')
def update_message_and_check_flag(content: str, mentioned: bool) -> None:
result = self.client_patch("/json/messages/" + str(msg_id), {
'message_id': msg_id, 'content': content,
})
self.assert_json_success(result)
um = UserMessage.objects.get(
user_profile_id=user_profile.id,
message_id=msg_id,
)
if mentioned:
self.assertIn('mentioned', um.flags_list())
else:
self.assertNotIn('mentioned', um.flags_list())
update_message_and_check_flag("@*support*", True)
update_message_and_check_flag("@*support-invalid* edited", False)
update_message_and_check_flag("@*support* edited", True)
update_message_and_check_flag("edited", False)
update_message_and_check_flag("@*support*", True)
def test_user_group_mention_invalid(self) -> None:
sender_user_profile = self.example_user('othello')
msg = Message(sender=sender_user_profile, sending_client=get_client("test"))
content = "Hey @*Nonexistent group*"
self.assertEqual(render_markdown(msg, content),
'<p>Hey @<em>Nonexistent group</em></p>')
self.assertEqual(msg.mentions_user_group_ids, set())
def test_stream_single(self) -> None:
denmark = get_stream('Denmark', get_realm('zulip'))
sender_user_profile = self.example_user('othello')
msg = Message(sender=sender_user_profile, sending_client=get_client("test"))
content = "#**Denmark**"
self.assertEqual(
render_markdown(msg, content),
'<p><a class="stream" data-stream-id="{d.id}" href="/#narrow/stream/{d.id}-Denmark">#{d.name}</a></p>'.format(
d=denmark,
))
def test_stream_multiple(self) -> None:
sender_user_profile = self.example_user('othello')
msg = Message(sender=sender_user_profile, sending_client=get_client("test"))
realm = get_realm('zulip')
denmark = get_stream('Denmark', realm)
scotland = get_stream('Scotland', realm)
content = "Look to #**Denmark** and #**Scotland**, there something"
self.assertEqual(render_markdown(msg, content),
'<p>Look to '
'<a class="stream" '
'data-stream-id="{denmark.id}" '
'href="/#narrow/stream/{denmark.id}-Denmark">#{denmark.name}</a> and '
'<a class="stream" '
'data-stream-id="{scotland.id}" '
'href="/#narrow/stream/{scotland.id}-Scotland">#{scotland.name}</a>, '
'there something</p>'.format(denmark=denmark, scotland=scotland))
def test_stream_case_sensitivity(self) -> None:
realm = get_realm('zulip')
case_sens = Stream.objects.create(name='CaseSens', realm=realm)
sender_user_profile = self.example_user('othello')
msg = Message(sender=sender_user_profile, sending_client=get_client("test"))
content = "#**CaseSens**"
self.assertEqual(
render_markdown(msg, content),
'<p><a class="stream" data-stream-id="{s.id}" href="/#narrow/stream/{s.id}-{s.name}">#{s.name}</a></p>'.format(
s=case_sens,
))
def test_stream_case_sensitivity_nonmatching(self) -> None:
"""#StreamName requires the stream be spelled with the correct case
currently. If we change that in the future, we'll need to change this
test."""
realm = get_realm('zulip')
Stream.objects.create(name='CaseSens', realm=realm)
sender_user_profile = self.example_user('othello')
msg = Message(sender=sender_user_profile, sending_client=get_client("test"))
content = "#**casesens**"
self.assertEqual(
render_markdown(msg, content),
'<p>#<strong>casesens</strong></p>')
def test_topic_single(self) -> None:
denmark = get_stream('Denmark', get_realm('zulip'))
sender_user_profile = self.example_user('othello')
msg = Message(sender=sender_user_profile, sending_client=get_client("test"))
content = "#**Denmark>some topic**"
self.assertEqual(
render_markdown(msg, content),
'<p><a class="stream-topic" data-stream-id="{d.id}" href="/#narrow/stream/{d.id}-Denmark/topic/some.20topic">#{d.name} > some topic</a></p>'.format(
d=denmark,
))
def test_topic_atomic_string(self) -> None:
realm = get_realm('zulip')
# Create a linkifier.
sender_user_profile = self.example_user('othello')
url_format_string = r"https://trac.example.com/ticket/%(id)s"
realm_filter = RealmFilter(realm=realm,
pattern=r"#(?P<id>[0-9]{2,8})",
url_format_string=url_format_string)
realm_filter.save()
self.assertEqual(
realm_filter.__str__(),
'<RealmFilter(zulip): #(?P<id>[0-9]{2,8})'
' https://trac.example.com/ticket/%(id)s>')
# Create a topic link that potentially interferes with the pattern.
denmark = get_stream('Denmark', realm)
msg = Message(sender=sender_user_profile, sending_client=get_client("test"))
content = "#**Denmark>#1234**"
self.assertEqual(
render_markdown(msg, content),
'<p><a class="stream-topic" data-stream-id="{d.id}" href="/#narrow/stream/{d.id}-Denmark/topic/.231234">#{d.name} > #1234</a></p>'.format(
d=denmark,
))
def test_topic_multiple(self) -> None:
denmark = get_stream('Denmark', get_realm('zulip'))
scotland = get_stream('Scotland', get_realm('zulip'))
sender_user_profile = self.example_user('othello')
msg = Message(sender=sender_user_profile, sending_client=get_client("test"))
content = "This has two links: #**Denmark>some topic** and #**Scotland>other topic**."
self.assertEqual(
render_markdown(msg, content),
'<p>This has two links: '
'<a class="stream-topic" data-stream-id="{denmark.id}" '
'href="/#narrow/stream/{denmark.id}-{denmark.name}/topic/some.20topic">'
'#{denmark.name} > some topic</a>'
' and '
'<a class="stream-topic" data-stream-id="{scotland.id}" '
'href="/#narrow/stream/{scotland.id}-{scotland.name}/topic/other.20topic">'
'#{scotland.name} > other topic</a>'
'.</p>'.format(denmark=denmark, scotland=scotland))
def test_possible_stream_names(self) -> None:
content = '''#**test here**
This mentions #**Denmark** too.
#**garçon** #**천국** @**Ignore Person**
'''
self.assertEqual(
bugdown.possible_linked_stream_names(content),
{'test here', 'Denmark', 'garçon', '천국'},
)
def test_stream_unicode(self) -> None:
realm = get_realm('zulip')
uni = Stream.objects.create(name='привет', realm=realm)
sender_user_profile = self.example_user('othello')
msg = Message(sender=sender_user_profile, sending_client=get_client("test"))
content = "#**привет**"
quoted_name = '.D0.BF.D1.80.D0.B8.D0.B2.D0.B5.D1.82'
href = f'/#narrow/stream/{uni.id}-{quoted_name}'
self.assertEqual(
render_markdown(msg, content),
'<p><a class="stream" data-stream-id="{s.id}" href="{href}">#{s.name}</a></p>'.format(
s=uni,
href=href,
))
def test_stream_atomic_string(self) -> None:
realm = get_realm('zulip')
# Create a linkifier.
sender_user_profile = self.example_user('othello')
url_format_string = r"https://trac.example.com/ticket/%(id)s"
realm_filter = RealmFilter(realm=realm,
pattern=r"#(?P<id>[0-9]{2,8})",
url_format_string=url_format_string)
realm_filter.save()
self.assertEqual(
realm_filter.__str__(),
'<RealmFilter(zulip): #(?P<id>[0-9]{2,8})'
' https://trac.example.com/ticket/%(id)s>')
# Create a stream that potentially interferes with the pattern.
stream = Stream.objects.create(name='Stream #1234', realm=realm)
msg = Message(sender=sender_user_profile, sending_client=get_client("test"))
content = "#**Stream #1234**"
href = f'/#narrow/stream/{stream.id}-Stream-.231234'
self.assertEqual(
render_markdown(msg, content),
'<p><a class="stream" data-stream-id="{s.id}" href="{href}">#{s.name}</a></p>'.format(
s=stream,
href=href,
))
def test_stream_invalid(self) -> None:
sender_user_profile = self.example_user('othello')
msg = Message(sender=sender_user_profile, sending_client=get_client("test"))
content = "There #**Nonexistentstream**"
self.assertEqual(render_markdown(msg, content),
'<p>There #<strong>Nonexistentstream</strong></p>')
self.assertEqual(msg.mentions_user_ids, set())
def test_image_preview_title(self) -> None:
msg = '[My favorite image](https://example.com/testimage.png)'
converted = bugdown_convert(msg)
self.assertEqual(
converted,
'<p>'
'<a href="https://example.com/testimage.png">My favorite image</a>'
'</p>\n'
'<div class="message_inline_image">'
'<a href="https://example.com/testimage.png" title="My favorite image">'
'<img data-src-fullsize="/thumbnail?url=https%3A%2F%2Fexample.com%2Ftestimage.png&size=full" src="/thumbnail?url=https%3A%2F%2Fexample.com%2Ftestimage.png&size=thumbnail">'
'</a>'
'</div>',
)
def test_mit_rendering(self) -> None:
"""Test the markdown configs for the MIT Zephyr mirroring system;
verifies almost all inline patterns are disabled, but
inline_interesting_links is still enabled"""
msg = "**test**"
realm = get_realm("zephyr")
client = get_client("zephyr_mirror")
message = Message(sending_client=client,
sender=self.mit_user("sipbtest"))
converted = bugdown.convert(msg, message_realm=realm, message=message)
self.assertEqual(
converted,
"<p>**test**</p>",
)
msg = "* test"
converted = bugdown.convert(msg, message_realm=realm, message=message)
self.assertEqual(
converted,
"<p>* test</p>",
)
msg = "https://lists.debian.org/debian-ctte/2014/02/msg00173.html"
converted = bugdown.convert(msg, message_realm=realm, message=message)
self.assertEqual(
converted,
'<p><a href="https://lists.debian.org/debian-ctte/2014/02/msg00173.html">https://lists.debian.org/debian-ctte/2014/02/msg00173.html</a></p>',
)
def test_url_to_a(self) -> None:
url = 'javascript://example.com/invalidURL'
converted = bugdown.url_to_a(db_data=None, url=url, text=url)
self.assertEqual(
converted,
'javascript://example.com/invalidURL',
)
def test_disabled_code_block_processor(self) -> None:
msg = "Hello,\n\n" + \
" I am writing this message to test something. I am writing this message to test something."
converted = bugdown_convert(msg)
expected_output = '<p>Hello,</p>\n' + \
'<div class="codehilite"><pre><span></span><code>I am writing this message to test something. I am writing this message to test something.\n' + \
'</code></pre></div>'
self.assertEqual(converted, expected_output)
realm = Realm.objects.create(string_id='code_block_processor_test')
bugdown.maybe_update_markdown_engines(realm.id, True)
converted = bugdown.convert(msg, message_realm=realm, email_gateway=True)
expected_output = '<p>Hello,</p>\n' + \
'<p>I am writing this message to test something. I am writing this message to test something.</p>'
self.assertEqual(converted, expected_output)
def test_normal_link(self) -> None:
realm = get_realm("zulip")
sender_user_profile = self.example_user('othello')
message = Message(sender=sender_user_profile, sending_client=get_client("test"))
msg = "http://example.com/#settings/"
self.assertEqual(
bugdown.convert(msg, message_realm=realm, message=message),
'<p><a href="http://example.com/#settings/">http://example.com/#settings/</a></p>',
)
def test_relative_link(self) -> None:
realm = get_realm("zulip")
sender_user_profile = self.example_user('othello')
message = Message(sender=sender_user_profile, sending_client=get_client("test"))
msg = "http://zulip.testserver/#narrow/stream/999-hello"
self.assertEqual(
bugdown.convert(msg, message_realm=realm, message=message),
'<p><a href="#narrow/stream/999-hello">http://zulip.testserver/#narrow/stream/999-hello</a></p>',
)
def test_relative_link_streams_page(self) -> None:
realm = get_realm("zulip")
sender_user_profile = self.example_user('othello')
message = Message(sender=sender_user_profile, sending_client=get_client("test"))
msg = "http://zulip.testserver/#streams/all"
self.assertEqual(
bugdown.convert(msg, message_realm=realm, message=message),
'<p><a href="#streams/all">http://zulip.testserver/#streams/all</a></p>',
)
def test_md_relative_link(self) -> None:
realm = get_realm("zulip")
sender_user_profile = self.example_user('othello')
message = Message(sender=sender_user_profile, sending_client=get_client("test"))
msg = "[hello](http://zulip.testserver/#narrow/stream/999-hello)"
self.assertEqual(
bugdown.convert(msg, message_realm=realm, message=message),
'<p><a href="#narrow/stream/999-hello">hello</a></p>',
)
class BugdownApiTests(ZulipTestCase):
def test_render_message_api(self) -> None:
content = 'That is a **bold** statement'
result = self.api_post(
self.example_user("othello"),
'/api/v1/messages/render',
dict(content=content),
)
self.assert_json_success(result)
self.assertEqual(result.json()['rendered'],
'<p>That is a <strong>bold</strong> statement</p>')
def test_render_mention_stream_api(self) -> None:
"""Determines whether we're correctly passing the realm context"""
content = 'This mentions #**Denmark** and @**King Hamlet**.'
result = self.api_post(
self.example_user("othello"),
'/api/v1/messages/render',
dict(content=content),
)
self.assert_json_success(result)
user_id = self.example_user('hamlet').id
stream_id = get_stream('Denmark', get_realm('zulip')).id
self.assertEqual(result.json()['rendered'],
f'<p>This mentions <a class="stream" data-stream-id="{stream_id}" href="/#narrow/stream/{stream_id}-Denmark">#Denmark</a> and <span class="user-mention" data-user-id="{user_id}">@King Hamlet</span>.</p>')
class BugdownErrorTests(ZulipTestCase):
def test_bugdown_error_handling(self) -> None:
with self.simulated_markdown_failure():
with self.assertRaises(BugdownRenderingException):
bugdown_convert('')
def test_send_message_errors(self) -> None:
message = 'whatever'
with self.simulated_markdown_failure():
# We don't use assertRaisesRegex because it seems to not
# handle i18n properly here on some systems.
with self.assertRaises(JsonableError):
self.send_stream_message(self.example_user("othello"), "Denmark", message)
def test_ultra_long_rendering(self) -> None:
"""A rendered message with an ultra-long lenght (> 10 * MAX_MESSAGE_LENGTH)
throws an exception"""
msg = 'mock rendered message\n' * MAX_MESSAGE_LENGTH
with mock.patch('zerver.lib.bugdown.timeout', return_value=msg), \
mock.patch('zerver.lib.bugdown.bugdown_logger'):
with self.assertRaises(BugdownRenderingException):
bugdown_convert(msg)
def test_curl_code_block_validation(self) -> None:
processor = bugdown.fenced_code.FencedBlockPreprocessor(None)
processor.run_content_validators = True
# Simulate code formatting.
processor.format_code = lambda lang, code: lang + ':' + code # type: ignore[assignment] # mypy doesn't allow monkey-patching functions
processor.placeholder = lambda s: '**' + s.strip('\n') + '**' # type: ignore[assignment] # https://github.com/python/mypy/issues/708
markdown = [
'``` curl',
'curl {{ api_url }}/v1/register',
' -u BOT_EMAIL_ADDRESS:BOT_API_KEY',
' -d "queue_id=1375801870:2942"',
'```',
]
with self.assertRaises(BugdownRenderingException):
processor.run(markdown)
def test_curl_code_block_without_validation(self) -> None:
processor = bugdown.fenced_code.FencedBlockPreprocessor(None)
# Simulate code formatting.
processor.format_code = lambda lang, code: lang + ':' + code # type: ignore[assignment] # mypy doesn't allow monkey-patching functions
processor.placeholder = lambda s: '**' + s.strip('\n') + '**' # type: ignore[assignment] # https://github.com/python/mypy/issues/708
markdown = [
'``` curl',
'curl {{ api_url }}/v1/register',
' -u BOT_EMAIL_ADDRESS:BOT_API_KEY',
' -d "queue_id=1375801870:2942"',
'```',
]
expected = [
'',
'**curl:curl {{ api_url }}/v1/register',
' -u BOT_EMAIL_ADDRESS:BOT_API_KEY',
' -d "queue_id=1375801870:2942"**',
'',
'',
]
result = processor.run(markdown)
self.assertEqual(result, expected)
class BugdownAvatarTestCase(ZulipTestCase):
def test_possible_avatar_emails(self) -> None:
content = '''
hello !avatar([email protected]) my email is [email protected]
!gravatar([email protected])
smushing!avatar([email protected]) is allowed
'''
self.assertEqual(
bugdown.possible_avatar_emails(content),
{'[email protected]', '[email protected]', '[email protected]'},
)
def test_avatar_with_id(self) -> None:
sender_user_profile = self.example_user('othello')
message = Message(sender=sender_user_profile, sending_client=get_client("test"))
user_profile = self.example_user('hamlet')
msg = f'!avatar({user_profile.email})'
converted = bugdown.convert(msg, message=message)
values = {'email': user_profile.email, 'id': user_profile.id}
self.assertEqual(
converted,
'<p><img alt="{email}" class="message_body_gravatar" src="/avatar/{id}?s=30" title="{email}"></p>'.format(**values))
def test_avatar_of_unregistered_user(self) -> None:
sender_user_profile = self.example_user('othello')
message = Message(sender=sender_user_profile, sending_client=get_client("test"))
email = '[email protected]'
msg = f'!avatar({email})'
converted = bugdown.convert(msg, message=message)
self.assertEqual(
converted,
'<p><img alt="{0}" class="message_body_gravatar" src="/avatar/{0}?s=30" title="{0}"></p>'.format(email))
| msg = 'Check out the debate: http://www.youtube.com/watch?v=hx1mjT73xYE'
converted = bugdown_convert(msg)
self.assertEqual(converted, '<p>Check out the debate: <a href="http://www.youtube.com/watch?v=hx1mjT73xYE">http://www.youtube.com/watch?v=hx1mjT73xYE</a></p>\n<div class="youtube-video message_inline_image"><a data-id="hx1mjT73xYE" href="http://www.youtube.com/watch?v=hx1mjT73xYE"><img src="https://i.ytimg.com/vi/hx1mjT73xYE/default.jpg"></a></div>')
msg = 'http://www.youtube.com/watch?v=hx1mjT73xYE'
converted = bugdown_convert(msg)
self.assertEqual(converted, '<p><a href="http://www.youtube.com/watch?v=hx1mjT73xYE">http://www.youtube.com/watch?v=hx1mjT73xYE</a></p>\n<div class="youtube-video message_inline_image"><a data-id="hx1mjT73xYE" href="http://www.youtube.com/watch?v=hx1mjT73xYE"><img src="https://i.ytimg.com/vi/hx1mjT73xYE/default.jpg"></a></div>')
msg = 'https://youtu.be/hx1mjT73xYE'
converted = bugdown_convert(msg)
self.assertEqual(converted, '<p><a href="https://youtu.be/hx1mjT73xYE">https://youtu.be/hx1mjT73xYE</a></p>\n<div class="youtube-video message_inline_image"><a data-id="hx1mjT73xYE" href="https://youtu.be/hx1mjT73xYE"><img src="https://i.ytimg.com/vi/hx1mjT73xYE/default.jpg"></a></div>')
msg = 'https://www.youtube.com/playlist?list=PL8dPuuaLjXtNlUrzyH5r6jN9ulIgZBpdo'
not_converted = bugdown_convert(msg)
self.assertEqual(not_converted, '<p><a href="https://www.youtube.com/playlist?list=PL8dPuuaLjXtNlUrzyH5r6jN9ulIgZBpdo">https://www.youtube.com/playlist?list=PL8dPuuaLjXtNlUrzyH5r6jN9ulIgZBpdo</a></p>')
msg = 'https://www.youtube.com/playlist?v=O5nskjZ_GoI&list=PL8dPuuaLjXtNlUrzyH5r6jN9ulIgZBpdo'
converted = bugdown_convert(msg)
self.assertEqual(converted, '<p><a href="https://www.youtube.com/playlist?v=O5nskjZ_GoI&list=PL8dPuuaLjXtNlUrzyH5r6jN9ulIgZBpdo">https://www.youtube.com/playlist?v=O5nskjZ_GoI&list=PL8dPuuaLjXtNlUrzyH5r6jN9ulIgZBpdo</a></p>\n<div class="youtube-video message_inline_image"><a data-id="O5nskjZ_GoI" href="https://www.youtube.com/playlist?v=O5nskjZ_GoI&list=PL8dPuuaLjXtNlUrzyH5r6jN9ulIgZBpdo"><img src="https://i.ytimg.com/vi/O5nskjZ_GoI/default.jpg"></a></div>')
msg = 'http://www.youtube.com/watch_videos?video_ids=nOJgD4fcZhI,i96UO8-GFvw'
converted = bugdown_convert(msg)
self.assertEqual(converted, '<p><a href="http://www.youtube.com/watch_videos?video_ids=nOJgD4fcZhI,i96UO8-GFvw">http://www.youtube.com/watch_videos?video_ids=nOJgD4fcZhI,i96UO8-GFvw</a></p>\n<div class="youtube-video message_inline_image"><a data-id="nOJgD4fcZhI" href="http://www.youtube.com/watch_videos?video_ids=nOJgD4fcZhI,i96UO8-GFvw"><img src="https://i.ytimg.com/vi/nOJgD4fcZhI/default.jpg"></a></div>') |
bootstrap-datepicker.fa.js | /**
* Persian translation for bootstrap-datepicker
* Mostafa Rokooie <[email protected]>
*/
;(function($){
$.fn.datepicker.dates['fa'] = {
days: ["یکشنبه", "دوشنبه", "سهشنبه", "چهارشنبه", "پنجشنبه", "جمعه", "شنبه", "یکشنبه"],
daysShort: ["یک", "دو", "سه", "چهار", "پنج", "جمعه", "شنبه", "یک"], | clear: "پاک کن",
weekStart: 6,
format: "yyyy/mm/dd",
rtl: true,
};
}(jQuery)); | daysMin: ["ی", "د", "س", "چ", "پ", "ج", "ش", "ی"],
months: ["فروردین", "اردیبهشت", "خرداد", "تیر", "مرداد", "شهریور", "مهر", "آبان", "آذر", "دی", "بهمن", "اسفند"],
monthsShort: ["فروردین", "اردیبهشت", "خرداد", "تیر", "مرداد", "شهریور", "مهر", "آبان", "آذر", "دی", "بهمن", "اسفند"],
today: "امروز", |
NumberInput.test.tsx | import React, { useState } from 'react'
import '@testing-library/jest-dom/extend-expect'
import {
fireEvent,
render,
RenderResult,
waitFor,
} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { Button, NumberInput } from '../..'
import { UNIT_POSITION } from './constants'
describe('NumberInput', () => {
let wrapper: RenderResult
let onChangeSpy: (event: any) => void
function assertInputValue(expectedValue: string, expectedUnit?: string) {
it('should set the input value', () => {
expect(wrapper.getByTestId('number-input-input')).toHaveValue(
expectedValue
)
})
if (expectedUnit) {
it('should display the unit', () => {
expect(wrapper.getByTestId('number-input-unit')).toHaveTextContent(
expectedUnit
)
})
} else {
it('should not show the unit', () => {
expect(wrapper.queryAllByTestId('number-input-unit')).toHaveLength(0)
})
}
}
function assertAriaValueAttributes({
min,
max,
now,
text,
}: {
min?: number
max?: number
now: number
text: string
}) {
it('should set the `aria-value*` attribute', () => {
const container = wrapper.getByTestId(
'number-input-container'
) as HTMLDivElement
if (min) {
expect(container).toHaveAttribute('aria-valuemin', min.toString())
} else {
expect(container).not.toHaveAttribute('aria-valuemin')
}
if (max) {
expect(container).toHaveAttribute('aria-valuemax', max.toString())
} else {
expect(container).not.toHaveAttribute('aria-valuemax')
}
expect(container).toHaveAttribute('aria-valuenow', now.toString())
expect(container).toHaveAttribute('aria-valuetext', text)
})
}
function assertOnChangeCall(expected: number, expectedNumberOfTimes = 1) {
it('should call the onChange callback with the new value', () => {
expect(onChangeSpy).toHaveBeenCalledTimes(expectedNumberOfTimes)
expect(onChangeSpy).toHaveBeenCalledWith({
target: {
name: 'number-input',
value: expected,
},
})
})
}
beforeEach(() => {
onChangeSpy = jest.fn()
})
describe('when minimal props', () => {
beforeEach(() => {
wrapper = render(
<NumberInput name="number-input" onChange={onChangeSpy} />
)
})
it('should set the default `aria-label` attribute', () => {
expect(wrapper.getByTestId('number-input-container')).toHaveAttribute(
'aria-label',
'Number input'
)
})
it('should apply the `aria-label` attribute to buttons', () => {
expect(wrapper.getByTestId('number-input-decrease')).toHaveAttribute(
'aria-label',
'Decrease the input value'
)
expect(wrapper.getByTestId('number-input-increase')).toHaveAttribute(
'aria-label',
'Increase the input value'
)
})
it('should apply the correct `role` attribute', () => {
expect(wrapper.getByTestId('number-input-container')).toHaveAttribute(
'role',
'spinbutton'
)
})
assertAriaValueAttributes({ min: null, max: null, now: 0, text: '0' })
it('should not display a start adornment', () => {
expect(
wrapper.queryAllByTestId('number-input-start-adornment')
).toHaveLength(0)
})
it('should not display a label', () => {
expect(wrapper.queryAllByTestId('number-input-label')).toHaveLength(0)
})
assertInputValue('0')
it('should set the `aria-labelledby` attribute', () => {
const numberInputId = wrapper
.getByTestId('number-input-container')
.getAttribute('id')
expect(
wrapper
.getByTestId('number-input-input')
.getAttribute('aria-labelledby')
).toEqual(numberInputId)
})
it('should set the name attribute', () => {
expect(
wrapper.getByTestId('number-input-input').getAttribute('name')
).toEqual('number-input')
})
it('should not display a footnote', () => {
expect(wrapper.queryAllByTestId('number-input-footnote')).toHaveLength(0)
})
describe('and the increase button is clicked', () => {
beforeEach(() => {
wrapper.getByTestId('number-input-increase').click()
})
assertInputValue('1')
assertOnChangeCall(1)
describe('and the decrease button is clicked', () => {
beforeEach(() => {
wrapper.getByTestId('number-input-decrease').click()
})
assertInputValue('0')
assertOnChangeCall(0, 2)
describe('and the decrease button is clicked', () => {
beforeEach(() => {
wrapper.getByTestId('number-input-decrease').click()
})
assertInputValue('-1')
assertOnChangeCall(-1, 3)
})
})
})
describe('and the user types values', () => {
beforeEach(async () => {
const input = wrapper.getByTestId('number-input-input')
await userEvent.type(input, '1')
await userEvent.type(input, '2')
await userEvent.type(input, '3')
})
assertInputValue('123')
assertOnChangeCall(1, 3)
assertOnChangeCall(12, 3)
assertOnChangeCall(123, 3)
})
describe('and the user types a value', () => {
beforeEach(async () => {
const input = wrapper.getByTestId('number-input-input')
await userEvent.type(input, '1')
})
assertInputValue('1')
assertOnChangeCall(1, 1)
describe('and the user deletes the value', () => {
beforeEach(async () => {
const input = wrapper.getByTestId('number-input-input')
await userEvent.type(input, '{backspace}')
})
assertInputValue('')
assertOnChangeCall(null, 2)
describe('and the decrease button is clicked', () => {
beforeEach(() => {
wrapper.getByTestId('number-input-decrease').click()
})
assertInputValue('-1')
assertOnChangeCall(-1, 3)
})
})
})
})
describe('when there is a footnote', () => {
beforeEach(() => {
wrapper = render(
<NumberInput
footnote="Footnote"
name="number-input"
onChange={onChangeSpy}
/>
)
})
it('should display the footnote', () => {
expect(wrapper.getByTestId('number-input-footnote').textContent).toEqual(
'Footnote'
)
})
})
describe('when there is a label', () => {
beforeEach(() => {
wrapper = render(
<NumberInput label="Label" name="number-input" onChange={onChangeSpy} />
)
})
it('should apple the `aria-label` attribute to the root element', () => {
expect(wrapper.getByTestId('number-input-container')).toHaveAttribute(
'aria-label',
'Label'
)
})
it('should display the footnote', () => {
expect(wrapper.getByTestId('number-input-label').textContent).toEqual(
'Label'
)
})
})
describe('when max and min are specified', () => {
beforeEach(() => {
wrapper = render(
<>
<NumberInput
max={3}
min={0}
name="number-input"
onChange={onChangeSpy}
/>
<input type="text" data-testid="next-field" />
</>
)
})
it('should apply the correct `aria-valuemin` attribute', () => {
expect(wrapper.getByTestId('number-input-container')).toHaveAttribute(
'aria-valuemin',
'0'
)
})
it('should apply the correct `aria-valuemax` attribute', () => {
expect(wrapper.getByTestId('number-input-container')).toHaveAttribute(
'aria-valuemax',
'3'
)
})
describe('and the increase button is clicked four times', () => {
beforeEach(() => {
const increase = wrapper.getByTestId('number-input-increase')
increase.click()
increase.click()
increase.click()
increase.click()
})
assertInputValue('3')
describe('and the decrease button is clicked four times', () => {
beforeEach(() => {
const decrease = wrapper.getByTestId('number-input-decrease')
decrease.click()
decrease.click()
decrease.click()
decrease.click()
})
assertInputValue('0')
})
})
describe('and the increase button is clicked once', () => {
beforeEach(() => {
const increase = wrapper.getByTestId('number-input-increase')
increase.click()
wrapper.getByTestId('number-input-input').focus()
})
describe('and the user types an invalid character', () => {
beforeEach(() => {
fireEvent.change(wrapper.getByTestId('number-input-input'), {
target: {
value: 'a',
},
})
})
assertInputValue('1')
})
describe('and the user types a valid number', () => {
beforeEach(() => {
fireEvent.change(wrapper.getByTestId('number-input-input'), {
target: {
value: '3',
},
})
})
assertInputValue('3')
})
describe('and the user types an number outside the max min range', () => {
beforeEach(() => {
fireEvent.change(wrapper.getByTestId('number-input-input'), {
target: {
value: '4',
},
})
})
assertInputValue('1')
describe('and the number input loses focus', () => {
beforeEach(() => {
wrapper.getByTestId('next-field').focus()
})
assertInputValue('1')
})
})
})
})
describe('when the step is specified', () => {
beforeEach(() => {
wrapper = render(
<NumberInput name="number-input" step={3} onChange={onChangeSpy} />
)
})
describe('and the increase button is clicked', () => {
beforeEach(() => {
const increase = wrapper.getByTestId('number-input-increase')
increase.click()
})
assertInputValue('3')
describe('and the decrease button is clicked', () => {
beforeEach(() => {
const decrease = wrapper.getByTestId('number-input-decrease')
decrease.click()
})
assertInputValue('0')
})
})
})
describe('when the start adornment is specified', () => {
beforeEach(() => {
wrapper = render(
<NumberInput
name="number-input"
startAdornment="Example"
onChange={onChangeSpy}
/>
)
})
it('should render the text', () => {
expect(
wrapper.getByTestId('number-input-start-adornment')
).toHaveTextContent('Example')
})
})
describe('when a CSS class name is specified', () => {
beforeEach(() => {
wrapper = render(
<NumberInput
className="number-input__custom"
name="number-input"
onChange={onChangeSpy}
/>
)
})
it('should add the CSS modifier', () => {
expect(wrapper.getByTestId('number-input-container').classList).toContain(
'number-input__custom'
)
})
})
describe('when an ID is specified', () => {
beforeEach(() => {
wrapper = render(
<NumberInput
id="number-input-id"
label="Label"
name="number-input"
onChange={onChangeSpy}
/>
)
})
it('should add the ID attribute', () => {
expect(
wrapper.getByTestId('number-input-input').getAttribute('id')
).toEqual('number-input-id')
})
it('should associate the label with the field', () => {
expect(
wrapper.getByTestId('number-input-label').getAttribute('for')
).toEqual('number-input-id')
})
})
describe('when the onBlur callback is specified', () => {
let onBlurSpy: (event: React.FormEvent) => void
beforeEach(() => {
onBlurSpy = jest.fn()
wrapper = render(
<>
<NumberInput
name="number-input"
onBlur={onBlurSpy}
onChange={onChangeSpy}
/>
<input type="text" data-testid="next-field" />
</>
)
})
describe('and the number input loses focus', () => {
beforeEach(() => {
wrapper.getByTestId('number-input-input').focus()
wrapper.getByTestId('next-field').focus()
})
it('should call the onBlur callback', () => {
expect(onBlurSpy).toHaveBeenCalledTimes(1)
})
})
})
describe('when there is a unit', () => {
beforeEach(() => {
wrapper = render(
<NumberInput
name="number-input"
onChange={onChangeSpy}
value={1000}
unit="m"
/>
)
})
assertInputValue('1000', 'm')
assertAriaValueAttributes({
min: null,
max: null,
now: 1000,
text: '1000 m',
})
describe('and the increase button is clicked', () => {
beforeEach(() => {
wrapper.getByTestId('number-input-increase').click()
})
assertInputValue('1001', 'm')
assertAriaValueAttributes({
min: null,
max: null,
now: 1001,
text: '1001 m',
})
assertOnChangeCall(1001)
})
describe('and the decrease button is clicked', () => {
beforeEach(() => {
wrapper.getByTestId('number-input-decrease').click()
})
assertInputValue('999', 'm')
assertAriaValueAttributes({
min: null,
max: null,
now: 999,
text: '999 m',
})
assertOnChangeCall(999)
})
})
describe('when there is a unit before', () => {
beforeEach(() => {
wrapper = render(
<NumberInput
name="number-input"
onChange={onChangeSpy}
value={1000}
unit="£"
unitPosition={UNIT_POSITION.BEFORE}
/>
)
})
assertInputValue('1000', '£')
assertAriaValueAttributes({ | })
describe('and the increase button is clicked', () => {
beforeEach(() => {
wrapper.getByTestId('number-input-increase').click()
})
assertInputValue('1001', '£')
assertAriaValueAttributes({
min: null,
max: null,
now: 1001,
text: '£ 1001',
})
assertOnChangeCall(1001)
})
describe('and the decrease button is clicked', () => {
beforeEach(() => {
wrapper.getByTestId('number-input-decrease').click()
})
assertInputValue('999', '£')
assertAriaValueAttributes({
min: null,
max: null,
now: 999,
text: '£ 999',
})
assertOnChangeCall(999)
})
describe('and the user focuses and then blurs the input', () => {
beforeEach(() => {
const input = wrapper.getByTestId(
'number-input-input'
) as HTMLInputElement
fireEvent.focus(input)
fireEvent.blur(input)
})
assertInputValue('1000', '£')
assertAriaValueAttributes({
min: null,
max: null,
now: 1000,
text: '£ 1000',
})
assertOnChangeCall(1000)
})
})
describe('when an external element affects the value', () => {
beforeEach(() => {
function NumberInputWithUpdate() {
const [value, setValue] = useState<number>(1)
return (
<>
<Button onClick={() => setValue(1)}>Update</Button>
<NumberInput
name="number-input"
onChange={onChangeSpy}
value={value}
/>
</>
)
}
wrapper = render(<NumberInputWithUpdate />)
wrapper.getByTestId('button').click()
})
it('should update the value in the field', async () => {
await waitFor(() => {
expect(wrapper.getByTestId('number-input-input')).toHaveValue('1')
})
})
})
describe('when there is a clear button', () => {
describe('and the clear button is clicked', () => {
beforeEach(() => {
wrapper = render(
<NumberInput
canClear
name="number-input"
onChange={onChangeSpy}
value={1000}
/>
)
wrapper.getByTestId('number-input-clear').click()
})
assertInputValue('')
})
})
describe('when arbitrary props are specified', () => {
beforeEach(() => {
wrapper = render(
<NumberInput
data-arbitrary="arbitrary"
name="number-input"
onChange={onChangeSpy}
/>
)
})
it('should spread arbitrary props', () => {
expect(wrapper.getByTestId('number-input-input')).toHaveAttribute(
'data-arbitrary',
'arbitrary'
)
})
})
}) | min: null,
max: null,
now: 1000,
text: '£ 1000', |
useNotification.ts | import { useCallback, useContext } from "react";
import NotificationContext from "context/NotificationContext";
import { nanoid } from "nanoid";
import { UseNotification, Notification } from "types/notification";
export default function | (): UseNotification {
const context = useContext(NotificationContext);
if (context === undefined) {
throw new Error(
"useNotification must be used within a NotificationProvider"
);
}
const { notifications, setNotifications } = context;
const removeNotification: UseNotification["removeNotification"] = useCallback(
(notificationId) => {
const timeOut = notifications.find(
(notification) => notification.id === notificationId
)?.timeOut;
if (timeOut) {
clearTimeout(timeOut);
}
setNotifications((allNotifications) => {
return allNotifications.filter(
(notification) => notification.id !== notificationId
);
});
},
[setNotifications, notifications]
);
const addNotification: UseNotification["addNotification"] = useCallback(
(notification) => {
const displayTime = notification.displayTime ?? 10000;
const newNotification: Notification = {
...notification,
id: nanoid(),
displayTime,
timeOut: setTimeout(() => {
removeNotification(newNotification.id);
}, displayTime),
};
setNotifications((allNotifications) => {
if (!allNotifications.length) {
return [newNotification];
}
return [...allNotifications, newNotification];
});
},
[setNotifications, removeNotification]
);
return {
notifications,
addNotification,
removeNotification,
};
}
| useNotification |
ui-tests.rs | #[test]
fn | () {
let t = trybuild::TestCases::new();
if cfg!(feature = "postgres") {
t.compile_fail("tests/ui/postgres/*.rs");
// UI tests for column types that require gated features
if cfg!(not(feature = "chrono")) {
t.compile_fail("tests/ui/postgres/gated/chrono.rs");
}
if cfg!(not(feature = "uuid")) {
t.compile_fail("tests/ui/postgres/gated/uuid.rs");
}
if cfg!(not(feature = "ipnetwork")) {
t.compile_fail("tests/ui/postgres/gated/ipnetwork.rs");
}
}
if cfg!(feature = "mysql") {
t.compile_fail("tests/ui/mysql/*.rs");
// UI tests for column types that require gated features
if cfg!(not(feature = "chrono")) {
t.compile_fail("tests/ui/mysql/gated/chrono.rs");
}
}
if cfg!(feature = "sqlite") {
t.compile_fail("tests/ui/sqlite/*.rs");
}
t.compile_fail("tests/ui/*.rs");
}
| ui_tests |
__main__.py | """parquet - tool for inspecting parquet files."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import logging
import sys
def setup_logging(options=None):
"""Configure logging based on options."""
level = logging.DEBUG if options is not None and options.debug \
else logging.WARNING
console = logging.StreamHandler()
console.setLevel(level)
formatter = logging.Formatter('%(name)s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logging.getLogger('parquet').setLevel(level)
logging.getLogger('parquet').addHandler(console)
def | (argv=None):
"""Run parquet utility application."""
argv = argv or sys.argv[1:]
parser = argparse.ArgumentParser('parquet',
description='Read parquet files')
parser.add_argument('--metadata', action='store_true',
help='show metadata on file')
parser.add_argument('--row-group-metadata', action='store_true',
help="show per row group metadata")
parser.add_argument('--no-data', action='store_true',
help="don't dump any data from the file")
parser.add_argument('--limit', action='store', type=int, default=-1,
help='max records to output')
parser.add_argument('--col', action='append', type=str,
help='only include this column (can be '
'specified multiple times)')
parser.add_argument('--no-headers', action='store_true',
help='skip headers in output (only applies if '
'format=csv)')
parser.add_argument('--format', action='store', type=str, default='csv',
help='format for the output data. can be csv or json.')
parser.add_argument('--debug', action='store_true',
help='log debug info to stderr')
parser.add_argument('file',
help='path to the file to parse')
args = parser.parse_args(argv)
setup_logging(args)
import parquet
if args.metadata:
parquet.dump_metadata(args.file, args.row_group_metadata)
if not args.no_data:
parquet.dump(args.file, args)
if __name__ == '__main__':
main()
| main |
types.go | package cdp
// Code generated by cdproto-gen. DO NOT EDIT.
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"sync"
"time"
"github.com/chromedp/sysutil"
"github.com/mailru/easyjson"
"github.com/mailru/easyjson/jlexer"
"github.com/mailru/easyjson/jwriter"
)
// Executor is the common interface for executing a command.
type Executor interface {
// Execute executes the command.
Execute(context.Context, string, easyjson.Marshaler, easyjson.Unmarshaler) error
}
// contextKey is the context key type.
type contextKey int
// context keys.
const (
executorKey contextKey = iota
)
// WithExecutor sets the message executor for the context.
func WithExecutor(parent context.Context, executor Executor) context.Context {
return context.WithValue(parent, executorKey, executor)
}
// ExecutorFromContext returns the message executor for the context.
func ExecutorFromContext(ctx context.Context) Executor |
// Execute uses the context's message executor to send a command or event
// method marshaling the provided parameters, and unmarshaling to res.
func Execute(ctx context.Context, method string, params easyjson.Marshaler, res easyjson.Unmarshaler) error {
if executor := ctx.Value(executorKey); executor != nil {
return executor.(Executor).Execute(ctx, method, params, res)
}
return ErrInvalidContext
}
// Error is a error.
type Error string
// Error values.
const (
// ErrInvalidContext is the invalid context error.
ErrInvalidContext Error = "invalid context"
// ErrMsgMissingParamsOrResult is the msg missing params or result error.
ErrMsgMissingParamsOrResult Error = "msg missing params or result"
)
// Error satisfies the error interface.
func (err Error) Error() string {
return string(err)
}
// ErrUnknownCommandOrEvent is an unknown command or event error.
type ErrUnknownCommandOrEvent string
// Error satisfies the error interface.
func (err ErrUnknownCommandOrEvent) Error() string {
return fmt.Sprintf("unknown command or event %q", string(err))
}
// BrowserContextID [no description].
//
// See: https://chromedevtools.github.io/devtools-protocol/tot/Browser#type-BrowserContextID
type BrowserContextID string
// String returns the BrowserContextID as string value.
func (t BrowserContextID) String() string {
return string(t)
}
// NodeID unique DOM node identifier.
//
// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#type-NodeId
type NodeID int64
// Int64 returns the NodeID as int64 value.
func (t NodeID) Int64() int64 {
return int64(t)
}
// UnmarshalEasyJSON satisfies easyjson.Unmarshaler.
func (t *NodeID) UnmarshalEasyJSON(in *jlexer.Lexer) {
buf := in.Raw()
if l := len(buf); l > 2 && buf[0] == '"' && buf[l-1] == '"' {
buf = buf[1 : l-1]
}
v, err := strconv.ParseInt(string(buf), 10, 64)
if err != nil {
in.AddError(err)
}
*t = NodeID(v)
}
// UnmarshalJSON satisfies json.Unmarshaler.
func (t *NodeID) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
// BackendNodeID unique DOM node identifier used to reference a node that may
// not have been pushed to the front-end.
//
// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#type-BackendNodeId
type BackendNodeID int64
// Int64 returns the BackendNodeID as int64 value.
func (t BackendNodeID) Int64() int64 {
return int64(t)
}
// UnmarshalEasyJSON satisfies easyjson.Unmarshaler.
func (t *BackendNodeID) UnmarshalEasyJSON(in *jlexer.Lexer) {
buf := in.Raw()
if l := len(buf); l > 2 && buf[0] == '"' && buf[l-1] == '"' {
buf = buf[1 : l-1]
}
v, err := strconv.ParseInt(string(buf), 10, 64)
if err != nil {
in.AddError(err)
}
*t = BackendNodeID(v)
}
// UnmarshalJSON satisfies json.Unmarshaler.
func (t *BackendNodeID) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
// BackendNode backend node with a friendly name.
//
// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#type-BackendNode
type BackendNode struct {
NodeType NodeType `json:"nodeType"` // Node's nodeType.
NodeName string `json:"nodeName"` // Node's nodeName.
BackendNodeID BackendNodeID `json:"backendNodeId"`
}
// PseudoType pseudo element type.
//
// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#type-PseudoType
type PseudoType string
// String returns the PseudoType as string value.
func (t PseudoType) String() string {
return string(t)
}
// PseudoType values.
const (
PseudoTypeFirstLine PseudoType = "first-line"
PseudoTypeFirstLetter PseudoType = "first-letter"
PseudoTypeBefore PseudoType = "before"
PseudoTypeAfter PseudoType = "after"
PseudoTypeMarker PseudoType = "marker"
PseudoTypeBackdrop PseudoType = "backdrop"
PseudoTypeSelection PseudoType = "selection"
PseudoTypeTargetText PseudoType = "target-text"
PseudoTypeSpellingError PseudoType = "spelling-error"
PseudoTypeGrammarError PseudoType = "grammar-error"
PseudoTypeHighlight PseudoType = "highlight"
PseudoTypeFirstLineInherited PseudoType = "first-line-inherited"
PseudoTypeScrollbar PseudoType = "scrollbar"
PseudoTypeScrollbarThumb PseudoType = "scrollbar-thumb"
PseudoTypeScrollbarButton PseudoType = "scrollbar-button"
PseudoTypeScrollbarTrack PseudoType = "scrollbar-track"
PseudoTypeScrollbarTrackPiece PseudoType = "scrollbar-track-piece"
PseudoTypeScrollbarCorner PseudoType = "scrollbar-corner"
PseudoTypeResizer PseudoType = "resizer"
PseudoTypeInputListButton PseudoType = "input-list-button"
)
// MarshalEasyJSON satisfies easyjson.Marshaler.
func (t PseudoType) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
// MarshalJSON satisfies json.Marshaler.
func (t PseudoType) MarshalJSON() ([]byte, error) {
return easyjson.Marshal(t)
}
// UnmarshalEasyJSON satisfies easyjson.Unmarshaler.
func (t *PseudoType) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch PseudoType(in.String()) {
case PseudoTypeFirstLine:
*t = PseudoTypeFirstLine
case PseudoTypeFirstLetter:
*t = PseudoTypeFirstLetter
case PseudoTypeBefore:
*t = PseudoTypeBefore
case PseudoTypeAfter:
*t = PseudoTypeAfter
case PseudoTypeMarker:
*t = PseudoTypeMarker
case PseudoTypeBackdrop:
*t = PseudoTypeBackdrop
case PseudoTypeSelection:
*t = PseudoTypeSelection
case PseudoTypeTargetText:
*t = PseudoTypeTargetText
case PseudoTypeSpellingError:
*t = PseudoTypeSpellingError
case PseudoTypeGrammarError:
*t = PseudoTypeGrammarError
case PseudoTypeHighlight:
*t = PseudoTypeHighlight
case PseudoTypeFirstLineInherited:
*t = PseudoTypeFirstLineInherited
case PseudoTypeScrollbar:
*t = PseudoTypeScrollbar
case PseudoTypeScrollbarThumb:
*t = PseudoTypeScrollbarThumb
case PseudoTypeScrollbarButton:
*t = PseudoTypeScrollbarButton
case PseudoTypeScrollbarTrack:
*t = PseudoTypeScrollbarTrack
case PseudoTypeScrollbarTrackPiece:
*t = PseudoTypeScrollbarTrackPiece
case PseudoTypeScrollbarCorner:
*t = PseudoTypeScrollbarCorner
case PseudoTypeResizer:
*t = PseudoTypeResizer
case PseudoTypeInputListButton:
*t = PseudoTypeInputListButton
default:
in.AddError(errors.New("unknown PseudoType value"))
}
}
// UnmarshalJSON satisfies json.Unmarshaler.
func (t *PseudoType) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
// ShadowRootType shadow root type.
//
// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#type-ShadowRootType
type ShadowRootType string
// String returns the ShadowRootType as string value.
func (t ShadowRootType) String() string {
return string(t)
}
// ShadowRootType values.
const (
ShadowRootTypeUserAgent ShadowRootType = "user-agent"
ShadowRootTypeOpen ShadowRootType = "open"
ShadowRootTypeClosed ShadowRootType = "closed"
)
// MarshalEasyJSON satisfies easyjson.Marshaler.
func (t ShadowRootType) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
// MarshalJSON satisfies json.Marshaler.
func (t ShadowRootType) MarshalJSON() ([]byte, error) {
return easyjson.Marshal(t)
}
// UnmarshalEasyJSON satisfies easyjson.Unmarshaler.
func (t *ShadowRootType) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch ShadowRootType(in.String()) {
case ShadowRootTypeUserAgent:
*t = ShadowRootTypeUserAgent
case ShadowRootTypeOpen:
*t = ShadowRootTypeOpen
case ShadowRootTypeClosed:
*t = ShadowRootTypeClosed
default:
in.AddError(errors.New("unknown ShadowRootType value"))
}
}
// UnmarshalJSON satisfies json.Unmarshaler.
func (t *ShadowRootType) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
// CompatibilityMode document compatibility mode.
//
// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#type-CompatibilityMode
type CompatibilityMode string
// String returns the CompatibilityMode as string value.
func (t CompatibilityMode) String() string {
return string(t)
}
// CompatibilityMode values.
const (
CompatibilityModeQuirksMode CompatibilityMode = "QuirksMode"
CompatibilityModeLimitedQuirksMode CompatibilityMode = "LimitedQuirksMode"
CompatibilityModeNoQuirksMode CompatibilityMode = "NoQuirksMode"
)
// MarshalEasyJSON satisfies easyjson.Marshaler.
func (t CompatibilityMode) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
// MarshalJSON satisfies json.Marshaler.
func (t CompatibilityMode) MarshalJSON() ([]byte, error) {
return easyjson.Marshal(t)
}
// UnmarshalEasyJSON satisfies easyjson.Unmarshaler.
func (t *CompatibilityMode) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch CompatibilityMode(in.String()) {
case CompatibilityModeQuirksMode:
*t = CompatibilityModeQuirksMode
case CompatibilityModeLimitedQuirksMode:
*t = CompatibilityModeLimitedQuirksMode
case CompatibilityModeNoQuirksMode:
*t = CompatibilityModeNoQuirksMode
default:
in.AddError(errors.New("unknown CompatibilityMode value"))
}
}
// UnmarshalJSON satisfies json.Unmarshaler.
func (t *CompatibilityMode) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
// Node DOM interaction is implemented in terms of mirror objects that
// represent the actual DOM nodes. DOMNode is a base node mirror type.
//
// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#type-Node
type Node struct {
NodeID NodeID `json:"nodeId"` // Node identifier that is passed into the rest of the DOM messages as the nodeId. Backend will only push node with given id once. It is aware of all requested nodes and will only fire DOM events for nodes known to the client.
ParentID NodeID `json:"parentId,omitempty"` // The id of the parent node if any.
BackendNodeID BackendNodeID `json:"backendNodeId"` // The BackendNodeId for this node.
NodeType NodeType `json:"nodeType"` // Node's nodeType.
NodeName string `json:"nodeName"` // Node's nodeName.
LocalName string `json:"localName"` // Node's localName.
NodeValue string `json:"nodeValue"` // Node's nodeValue.
ChildNodeCount int64 `json:"childNodeCount,omitempty"` // Child count for Container nodes.
Children []*Node `json:"children,omitempty"` // Child nodes of this node when requested with children.
Attributes []string `json:"attributes,omitempty"` // Attributes of the Element node in the form of flat array [name1, value1, name2, value2].
DocumentURL string `json:"documentURL,omitempty"` // Document URL that Document or FrameOwner node points to.
BaseURL string `json:"baseURL,omitempty"` // Base URL that Document or FrameOwner node uses for URL completion.
PublicID string `json:"publicId,omitempty"` // DocumentType's publicId.
SystemID string `json:"systemId,omitempty"` // DocumentType's systemId.
InternalSubset string `json:"internalSubset,omitempty"` // DocumentType's internalSubset.
XMLVersion string `json:"xmlVersion,omitempty"` // Document's XML version in case of XML documents.
Name string `json:"name,omitempty"` // Attr's name.
Value string `json:"value,omitempty"` // Attr's value.
PseudoType PseudoType `json:"pseudoType,omitempty"` // Pseudo element type for this node.
ShadowRootType ShadowRootType `json:"shadowRootType,omitempty"` // Shadow root type.
FrameID FrameID `json:"frameId,omitempty"` // Frame ID for frame owner elements.
ContentDocument *Node `json:"contentDocument,omitempty"` // Content document for frame owner elements.
ShadowRoots []*Node `json:"shadowRoots,omitempty"` // Shadow root list for given element host.
TemplateContent *Node `json:"templateContent,omitempty"` // Content document fragment for template elements.
PseudoElements []*Node `json:"pseudoElements,omitempty"` // Pseudo elements associated with this node.
DistributedNodes []*BackendNode `json:"distributedNodes,omitempty"` // Distributed nodes for given insertion point.
IsSVG bool `json:"isSVG,omitempty"` // Whether the node is SVG.
CompatibilityMode CompatibilityMode `json:"compatibilityMode,omitempty"`
Parent *Node `json:"-"` // Parent node.
Invalidated chan struct{} `json:"-"` // Invalidated channel.
State NodeState `json:"-"` // Node state.
sync.RWMutex `json:"-"` // Read write mutex.
}
// AttributeValue returns the named attribute for the node.
func (n *Node) AttributeValue(name string) string {
value, _ := n.Attribute(name)
return value
}
// Attribute returns the named attribute for the node and if it exists.
func (n *Node) Attribute(name string) (string, bool) {
n.RLock()
defer n.RUnlock()
for i := 0; i < len(n.Attributes); i += 2 {
if n.Attributes[i] == name {
return n.Attributes[i+1], true
}
}
return "", false
}
// xpath builds the xpath string.
func (n *Node) xpath(stopAtDocument, stopAtID bool) string {
n.RLock()
defer n.RUnlock()
p, pos, id := "", "", n.AttributeValue("id")
switch {
case n.Parent == nil:
return n.LocalName
case stopAtDocument && n.NodeType == NodeTypeDocument:
return ""
case stopAtID && id != "":
p = "/"
pos = `[@id='` + id + `']`
case n.Parent != nil:
var i int
var found bool
n.Parent.RLock()
for j := 0; j < len(n.Parent.Children); j++ {
if n.Parent.Children[j].LocalName == n.LocalName {
i++
}
if n.Parent.Children[j].NodeID == n.NodeID {
found = true
break
}
}
n.Parent.RUnlock()
if found {
pos = "[" + strconv.Itoa(i) + "]"
}
p = n.Parent.xpath(stopAtDocument, stopAtID)
}
localName := n.LocalName
if n.IsSVG {
localName = `*[local-name()='` + localName + `']`
}
return p + "/" + localName + pos
}
// PartialXPathByID returns the partial XPath for the node, stopping at the
// first parent with an id attribute or at nearest parent document node.
func (n *Node) PartialXPathByID() string {
return n.xpath(true, true)
}
// PartialXPath returns the partial XPath for the node, stopping at the nearest
// parent document node.
func (n *Node) PartialXPath() string {
return n.xpath(true, false)
}
// FullXPathByID returns the full XPath for the node, stopping at the top most
// document root or at the closest parent node with an id attribute.
func (n *Node) FullXPathByID() string {
return n.xpath(false, true)
}
// FullXPath returns the full XPath for the node, stopping only at the top most
// document root.
func (n *Node) FullXPath() string {
return n.xpath(false, false)
}
// Dump builds a printable string representation of the node and its children.
func (n *Node) Dump(prefix, indent string, nodeIDs bool) string {
if n == nil {
return prefix + "<nil>"
}
n.RLock()
defer n.RUnlock()
s := n.LocalName
if s == "" {
s = n.NodeName
}
for i := 0; i < len(n.Attributes); i += 2 {
if strings.ToLower(n.Attributes[i]) == "id" {
s += "#" + n.Attributes[i+1]
break
}
}
if n.NodeType != NodeTypeElement && n.NodeType != NodeTypeText {
s += fmt.Sprintf(" <%s>", n.NodeType)
}
if n.NodeType == NodeTypeText {
v := n.NodeValue
if len(v) > 15 {
v = v[:15] + "..."
}
s += fmt.Sprintf(" %q", v)
}
if n.NodeType == NodeTypeElement && len(n.Attributes) > 0 {
attrs := ""
for i := 0; i < len(n.Attributes); i += 2 {
if strings.ToLower(n.Attributes[i]) == "id" {
continue
}
if attrs != "" {
attrs += " "
}
attrs += fmt.Sprintf("%s=%q", n.Attributes[i], n.Attributes[i+1])
}
if attrs != "" {
s += " [" + attrs + "]"
}
}
if nodeIDs {
s += fmt.Sprintf(" (%d)", n.NodeID)
}
for i := 0; i < len(n.Children); i++ {
s += "\n" + n.Children[i].Dump(prefix+indent, indent, nodeIDs)
}
return prefix + s
}
// NodeState is the state of a DOM node.
type NodeState uint8
// NodeState enum values.
const (
NodeReady NodeState = 1 << (7 - iota)
NodeVisible
NodeHighlighted
)
// nodeStateNames are the names of the node states.
var nodeStateNames = map[NodeState]string{
NodeReady: "Ready",
NodeVisible: "Visible",
NodeHighlighted: "Highlighted",
}
// String satisfies stringer interface.
func (ns NodeState) String() string {
var s []string
for k, v := range nodeStateNames {
if ns&k != 0 {
s = append(s, v)
}
}
return "[" + strings.Join(s, " ") + "]"
}
// EmptyNodeID is the "non-existent" node id.
const EmptyNodeID = NodeID(0)
// RGBA a structure holding an RGBA color.
//
// See: https://chromedevtools.github.io/devtools-protocol/tot/DOM#type-RGBA
type RGBA struct {
R int64 `json:"r"` // The red component, in the [0-255] range.
G int64 `json:"g"` // The green component, in the [0-255] range.
B int64 `json:"b"` // The blue component, in the [0-255] range.
A float64 `json:"a"` // The alpha component, in the [0-1] range (default: 1).
}
// NodeType node type.
//
// See: https://developer.mozilla.org/en/docs/Web/API/Node/nodeType
type NodeType int64
// Int64 returns the NodeType as int64 value.
func (t NodeType) Int64() int64 {
return int64(t)
}
// NodeType values.
const (
NodeTypeElement NodeType = 1
NodeTypeAttribute NodeType = 2
NodeTypeText NodeType = 3
NodeTypeCDATA NodeType = 4
NodeTypeEntityReference NodeType = 5
NodeTypeEntity NodeType = 6
NodeTypeProcessingInstruction NodeType = 7
NodeTypeComment NodeType = 8
NodeTypeDocument NodeType = 9
NodeTypeDocumentType NodeType = 10
NodeTypeDocumentFragment NodeType = 11
NodeTypeNotation NodeType = 12
)
// String returns the NodeType as string value.
func (t NodeType) String() string {
switch t {
case NodeTypeElement:
return "Element"
case NodeTypeAttribute:
return "Attribute"
case NodeTypeText:
return "Text"
case NodeTypeCDATA:
return "CDATA"
case NodeTypeEntityReference:
return "EntityReference"
case NodeTypeEntity:
return "Entity"
case NodeTypeProcessingInstruction:
return "ProcessingInstruction"
case NodeTypeComment:
return "Comment"
case NodeTypeDocument:
return "Document"
case NodeTypeDocumentType:
return "DocumentType"
case NodeTypeDocumentFragment:
return "DocumentFragment"
case NodeTypeNotation:
return "Notation"
}
return fmt.Sprintf("NodeType(%d)", t)
}
// MarshalEasyJSON satisfies easyjson.Marshaler.
func (t NodeType) MarshalEasyJSON(out *jwriter.Writer) {
out.Int64(int64(t))
}
// MarshalJSON satisfies json.Marshaler.
func (t NodeType) MarshalJSON() ([]byte, error) {
return easyjson.Marshal(t)
}
// UnmarshalEasyJSON satisfies easyjson.Unmarshaler.
func (t *NodeType) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch NodeType(in.Int64()) {
case NodeTypeElement:
*t = NodeTypeElement
case NodeTypeAttribute:
*t = NodeTypeAttribute
case NodeTypeText:
*t = NodeTypeText
case NodeTypeCDATA:
*t = NodeTypeCDATA
case NodeTypeEntityReference:
*t = NodeTypeEntityReference
case NodeTypeEntity:
*t = NodeTypeEntity
case NodeTypeProcessingInstruction:
*t = NodeTypeProcessingInstruction
case NodeTypeComment:
*t = NodeTypeComment
case NodeTypeDocument:
*t = NodeTypeDocument
case NodeTypeDocumentType:
*t = NodeTypeDocumentType
case NodeTypeDocumentFragment:
*t = NodeTypeDocumentFragment
case NodeTypeNotation:
*t = NodeTypeNotation
default:
in.AddError(errors.New("unknown NodeType value"))
}
}
// UnmarshalJSON satisfies json.Unmarshaler.
func (t *NodeType) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
// LoaderID unique loader identifier.
//
// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-LoaderId
type LoaderID string
// String returns the LoaderID as string value.
func (t LoaderID) String() string {
return string(t)
}
// TimeSinceEpoch UTC time in seconds, counted from January 1, 1970.
//
// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-TimeSinceEpoch
type TimeSinceEpoch time.Time
// Time returns the TimeSinceEpoch as time.Time value.
func (t TimeSinceEpoch) Time() time.Time {
return time.Time(t)
}
// MarshalEasyJSON satisfies easyjson.Marshaler.
func (t TimeSinceEpoch) MarshalEasyJSON(out *jwriter.Writer) {
v := float64(time.Time(t).UnixNano() / int64(time.Second))
out.Buffer.EnsureSpace(20)
out.Buffer.Buf = strconv.AppendFloat(out.Buffer.Buf, v, 'f', -1, 64)
}
// MarshalJSON satisfies json.Marshaler.
func (t TimeSinceEpoch) MarshalJSON() ([]byte, error) {
return easyjson.Marshal(t)
}
// UnmarshalEasyJSON satisfies easyjson.Unmarshaler.
func (t *TimeSinceEpoch) UnmarshalEasyJSON(in *jlexer.Lexer) {
*t = TimeSinceEpoch(time.Unix(0, int64(in.Float64()*float64(time.Second))))
}
// UnmarshalJSON satisfies json.Unmarshaler.
func (t *TimeSinceEpoch) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
// MonotonicTime monotonically increasing time in seconds since an arbitrary
// point in the past.
//
// See: https://chromedevtools.github.io/devtools-protocol/tot/Network#type-MonotonicTime
type MonotonicTime time.Time
// Time returns the MonotonicTime as time.Time value.
func (t MonotonicTime) Time() time.Time {
return time.Time(t)
}
// MonotonicTimeEpoch is the MonotonicTime time epoch.
var MonotonicTimeEpoch *time.Time
func init() {
// initialize epoch
bt := sysutil.BootTime()
MonotonicTimeEpoch = &bt
}
// MarshalEasyJSON satisfies easyjson.Marshaler.
func (t MonotonicTime) MarshalEasyJSON(out *jwriter.Writer) {
v := float64(time.Time(t).Sub(*MonotonicTimeEpoch)) / float64(time.Second)
out.Buffer.EnsureSpace(20)
out.Buffer.Buf = strconv.AppendFloat(out.Buffer.Buf, v, 'f', -1, 64)
}
// MarshalJSON satisfies json.Marshaler.
func (t MonotonicTime) MarshalJSON() ([]byte, error) {
return easyjson.Marshal(t)
}
// UnmarshalEasyJSON satisfies easyjson.Unmarshaler.
func (t *MonotonicTime) UnmarshalEasyJSON(in *jlexer.Lexer) {
*t = MonotonicTime(MonotonicTimeEpoch.Add(time.Duration(in.Float64() * float64(time.Second))))
}
// UnmarshalJSON satisfies json.Unmarshaler.
func (t *MonotonicTime) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
// FrameID unique frame identifier.
//
// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#type-FrameId
type FrameID string
// String returns the FrameID as string value.
func (t FrameID) String() string {
return string(t)
}
// UnmarshalEasyJSON satisfies easyjson.Unmarshaler.
func (t *FrameID) UnmarshalEasyJSON(in *jlexer.Lexer) {
buf := in.Raw()
if l := len(buf); l > 2 && buf[0] == '"' && buf[l-1] == '"' {
buf = buf[1 : l-1]
}
*t = FrameID(buf)
}
// UnmarshalJSON satisfies json.Unmarshaler.
func (t *FrameID) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
// AdFrameType indicates whether a frame has been identified as an ad.
//
// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#type-AdFrameType
type AdFrameType string
// String returns the AdFrameType as string value.
func (t AdFrameType) String() string {
return string(t)
}
// AdFrameType values.
const (
AdFrameTypeNone AdFrameType = "none"
AdFrameTypeChild AdFrameType = "child"
AdFrameTypeRoot AdFrameType = "root"
)
// MarshalEasyJSON satisfies easyjson.Marshaler.
func (t AdFrameType) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
// MarshalJSON satisfies json.Marshaler.
func (t AdFrameType) MarshalJSON() ([]byte, error) {
return easyjson.Marshal(t)
}
// UnmarshalEasyJSON satisfies easyjson.Unmarshaler.
func (t *AdFrameType) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch AdFrameType(in.String()) {
case AdFrameTypeNone:
*t = AdFrameTypeNone
case AdFrameTypeChild:
*t = AdFrameTypeChild
case AdFrameTypeRoot:
*t = AdFrameTypeRoot
default:
in.AddError(errors.New("unknown AdFrameType value"))
}
}
// UnmarshalJSON satisfies json.Unmarshaler.
func (t *AdFrameType) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
// AdFrameExplanation [no description].
//
// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#type-AdFrameExplanation
type AdFrameExplanation string
// String returns the AdFrameExplanation as string value.
func (t AdFrameExplanation) String() string {
return string(t)
}
// AdFrameExplanation values.
const (
AdFrameExplanationParentIsAd AdFrameExplanation = "ParentIsAd"
AdFrameExplanationCreatedByAdScript AdFrameExplanation = "CreatedByAdScript"
AdFrameExplanationMatchedBlockingRule AdFrameExplanation = "MatchedBlockingRule"
)
// MarshalEasyJSON satisfies easyjson.Marshaler.
func (t AdFrameExplanation) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
// MarshalJSON satisfies json.Marshaler.
func (t AdFrameExplanation) MarshalJSON() ([]byte, error) {
return easyjson.Marshal(t)
}
// UnmarshalEasyJSON satisfies easyjson.Unmarshaler.
func (t *AdFrameExplanation) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch AdFrameExplanation(in.String()) {
case AdFrameExplanationParentIsAd:
*t = AdFrameExplanationParentIsAd
case AdFrameExplanationCreatedByAdScript:
*t = AdFrameExplanationCreatedByAdScript
case AdFrameExplanationMatchedBlockingRule:
*t = AdFrameExplanationMatchedBlockingRule
default:
in.AddError(errors.New("unknown AdFrameExplanation value"))
}
}
// UnmarshalJSON satisfies json.Unmarshaler.
func (t *AdFrameExplanation) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
// AdFrameStatus indicates whether a frame has been identified as an ad and
// why.
//
// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#type-AdFrameStatus
type AdFrameStatus struct {
AdFrameType AdFrameType `json:"adFrameType"`
Explanations []AdFrameExplanation `json:"explanations,omitempty"`
}
// SecureContextType indicates whether the frame is a secure context and why
// it is the case.
//
// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#type-SecureContextType
type SecureContextType string
// String returns the SecureContextType as string value.
func (t SecureContextType) String() string {
return string(t)
}
// SecureContextType values.
const (
SecureContextTypeSecure SecureContextType = "Secure"
SecureContextTypeSecureLocalhost SecureContextType = "SecureLocalhost"
SecureContextTypeInsecureScheme SecureContextType = "InsecureScheme"
SecureContextTypeInsecureAncestor SecureContextType = "InsecureAncestor"
)
// MarshalEasyJSON satisfies easyjson.Marshaler.
func (t SecureContextType) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
// MarshalJSON satisfies json.Marshaler.
func (t SecureContextType) MarshalJSON() ([]byte, error) {
return easyjson.Marshal(t)
}
// UnmarshalEasyJSON satisfies easyjson.Unmarshaler.
func (t *SecureContextType) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch SecureContextType(in.String()) {
case SecureContextTypeSecure:
*t = SecureContextTypeSecure
case SecureContextTypeSecureLocalhost:
*t = SecureContextTypeSecureLocalhost
case SecureContextTypeInsecureScheme:
*t = SecureContextTypeInsecureScheme
case SecureContextTypeInsecureAncestor:
*t = SecureContextTypeInsecureAncestor
default:
in.AddError(errors.New("unknown SecureContextType value"))
}
}
// UnmarshalJSON satisfies json.Unmarshaler.
func (t *SecureContextType) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
// CrossOriginIsolatedContextType indicates whether the frame is cross-origin
// isolated and why it is the case.
//
// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#type-CrossOriginIsolatedContextType
type CrossOriginIsolatedContextType string
// String returns the CrossOriginIsolatedContextType as string value.
func (t CrossOriginIsolatedContextType) String() string {
return string(t)
}
// CrossOriginIsolatedContextType values.
const (
CrossOriginIsolatedContextTypeIsolated CrossOriginIsolatedContextType = "Isolated"
CrossOriginIsolatedContextTypeNotIsolated CrossOriginIsolatedContextType = "NotIsolated"
CrossOriginIsolatedContextTypeNotIsolatedFeatureDisabled CrossOriginIsolatedContextType = "NotIsolatedFeatureDisabled"
)
// MarshalEasyJSON satisfies easyjson.Marshaler.
func (t CrossOriginIsolatedContextType) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
// MarshalJSON satisfies json.Marshaler.
func (t CrossOriginIsolatedContextType) MarshalJSON() ([]byte, error) {
return easyjson.Marshal(t)
}
// UnmarshalEasyJSON satisfies easyjson.Unmarshaler.
func (t *CrossOriginIsolatedContextType) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch CrossOriginIsolatedContextType(in.String()) {
case CrossOriginIsolatedContextTypeIsolated:
*t = CrossOriginIsolatedContextTypeIsolated
case CrossOriginIsolatedContextTypeNotIsolated:
*t = CrossOriginIsolatedContextTypeNotIsolated
case CrossOriginIsolatedContextTypeNotIsolatedFeatureDisabled:
*t = CrossOriginIsolatedContextTypeNotIsolatedFeatureDisabled
default:
in.AddError(errors.New("unknown CrossOriginIsolatedContextType value"))
}
}
// UnmarshalJSON satisfies json.Unmarshaler.
func (t *CrossOriginIsolatedContextType) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
// GatedAPIFeatures [no description].
//
// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#type-GatedAPIFeatures
type GatedAPIFeatures string
// String returns the GatedAPIFeatures as string value.
func (t GatedAPIFeatures) String() string {
return string(t)
}
// GatedAPIFeatures values.
const (
GatedAPIFeaturesSharedArrayBuffers GatedAPIFeatures = "SharedArrayBuffers"
GatedAPIFeaturesSharedArrayBuffersTransferAllowed GatedAPIFeatures = "SharedArrayBuffersTransferAllowed"
GatedAPIFeaturesPerformanceMeasureMemory GatedAPIFeatures = "PerformanceMeasureMemory"
GatedAPIFeaturesPerformanceProfile GatedAPIFeatures = "PerformanceProfile"
)
// MarshalEasyJSON satisfies easyjson.Marshaler.
func (t GatedAPIFeatures) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
// MarshalJSON satisfies json.Marshaler.
func (t GatedAPIFeatures) MarshalJSON() ([]byte, error) {
return easyjson.Marshal(t)
}
// UnmarshalEasyJSON satisfies easyjson.Unmarshaler.
func (t *GatedAPIFeatures) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch GatedAPIFeatures(in.String()) {
case GatedAPIFeaturesSharedArrayBuffers:
*t = GatedAPIFeaturesSharedArrayBuffers
case GatedAPIFeaturesSharedArrayBuffersTransferAllowed:
*t = GatedAPIFeaturesSharedArrayBuffersTransferAllowed
case GatedAPIFeaturesPerformanceMeasureMemory:
*t = GatedAPIFeaturesPerformanceMeasureMemory
case GatedAPIFeaturesPerformanceProfile:
*t = GatedAPIFeaturesPerformanceProfile
default:
in.AddError(errors.New("unknown GatedAPIFeatures value"))
}
}
// UnmarshalJSON satisfies json.Unmarshaler.
func (t *GatedAPIFeatures) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
// OriginTrialTokenStatus origin
// Trial(https://www.chromium.org/blink/origin-trials) support. Status for an
// Origin Trial token.
//
// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#type-OriginTrialTokenStatus
type OriginTrialTokenStatus string
// String returns the OriginTrialTokenStatus as string value.
func (t OriginTrialTokenStatus) String() string {
return string(t)
}
// OriginTrialTokenStatus values.
const (
OriginTrialTokenStatusSuccess OriginTrialTokenStatus = "Success"
OriginTrialTokenStatusNotSupported OriginTrialTokenStatus = "NotSupported"
OriginTrialTokenStatusInsecure OriginTrialTokenStatus = "Insecure"
OriginTrialTokenStatusExpired OriginTrialTokenStatus = "Expired"
OriginTrialTokenStatusWrongOrigin OriginTrialTokenStatus = "WrongOrigin"
OriginTrialTokenStatusInvalidSignature OriginTrialTokenStatus = "InvalidSignature"
OriginTrialTokenStatusMalformed OriginTrialTokenStatus = "Malformed"
OriginTrialTokenStatusWrongVersion OriginTrialTokenStatus = "WrongVersion"
OriginTrialTokenStatusFeatureDisabled OriginTrialTokenStatus = "FeatureDisabled"
OriginTrialTokenStatusTokenDisabled OriginTrialTokenStatus = "TokenDisabled"
OriginTrialTokenStatusFeatureDisabledForUser OriginTrialTokenStatus = "FeatureDisabledForUser"
)
// MarshalEasyJSON satisfies easyjson.Marshaler.
func (t OriginTrialTokenStatus) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
// MarshalJSON satisfies json.Marshaler.
func (t OriginTrialTokenStatus) MarshalJSON() ([]byte, error) {
return easyjson.Marshal(t)
}
// UnmarshalEasyJSON satisfies easyjson.Unmarshaler.
func (t *OriginTrialTokenStatus) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch OriginTrialTokenStatus(in.String()) {
case OriginTrialTokenStatusSuccess:
*t = OriginTrialTokenStatusSuccess
case OriginTrialTokenStatusNotSupported:
*t = OriginTrialTokenStatusNotSupported
case OriginTrialTokenStatusInsecure:
*t = OriginTrialTokenStatusInsecure
case OriginTrialTokenStatusExpired:
*t = OriginTrialTokenStatusExpired
case OriginTrialTokenStatusWrongOrigin:
*t = OriginTrialTokenStatusWrongOrigin
case OriginTrialTokenStatusInvalidSignature:
*t = OriginTrialTokenStatusInvalidSignature
case OriginTrialTokenStatusMalformed:
*t = OriginTrialTokenStatusMalformed
case OriginTrialTokenStatusWrongVersion:
*t = OriginTrialTokenStatusWrongVersion
case OriginTrialTokenStatusFeatureDisabled:
*t = OriginTrialTokenStatusFeatureDisabled
case OriginTrialTokenStatusTokenDisabled:
*t = OriginTrialTokenStatusTokenDisabled
case OriginTrialTokenStatusFeatureDisabledForUser:
*t = OriginTrialTokenStatusFeatureDisabledForUser
default:
in.AddError(errors.New("unknown OriginTrialTokenStatus value"))
}
}
// UnmarshalJSON satisfies json.Unmarshaler.
func (t *OriginTrialTokenStatus) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
// OriginTrialStatus status for an Origin Trial.
//
// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#type-OriginTrialStatus
type OriginTrialStatus string
// String returns the OriginTrialStatus as string value.
func (t OriginTrialStatus) String() string {
return string(t)
}
// OriginTrialStatus values.
const (
OriginTrialStatusEnabled OriginTrialStatus = "Enabled"
OriginTrialStatusValidTokenNotProvided OriginTrialStatus = "ValidTokenNotProvided"
OriginTrialStatusOSNotSupported OriginTrialStatus = "OSNotSupported"
OriginTrialStatusTrialNotAllowed OriginTrialStatus = "TrialNotAllowed"
)
// MarshalEasyJSON satisfies easyjson.Marshaler.
func (t OriginTrialStatus) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
// MarshalJSON satisfies json.Marshaler.
func (t OriginTrialStatus) MarshalJSON() ([]byte, error) {
return easyjson.Marshal(t)
}
// UnmarshalEasyJSON satisfies easyjson.Unmarshaler.
func (t *OriginTrialStatus) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch OriginTrialStatus(in.String()) {
case OriginTrialStatusEnabled:
*t = OriginTrialStatusEnabled
case OriginTrialStatusValidTokenNotProvided:
*t = OriginTrialStatusValidTokenNotProvided
case OriginTrialStatusOSNotSupported:
*t = OriginTrialStatusOSNotSupported
case OriginTrialStatusTrialNotAllowed:
*t = OriginTrialStatusTrialNotAllowed
default:
in.AddError(errors.New("unknown OriginTrialStatus value"))
}
}
// UnmarshalJSON satisfies json.Unmarshaler.
func (t *OriginTrialStatus) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
// OriginTrialUsageRestriction [no description].
//
// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#type-OriginTrialUsageRestriction
type OriginTrialUsageRestriction string
// String returns the OriginTrialUsageRestriction as string value.
func (t OriginTrialUsageRestriction) String() string {
return string(t)
}
// OriginTrialUsageRestriction values.
const (
OriginTrialUsageRestrictionNone OriginTrialUsageRestriction = "None"
OriginTrialUsageRestrictionSubset OriginTrialUsageRestriction = "Subset"
)
// MarshalEasyJSON satisfies easyjson.Marshaler.
func (t OriginTrialUsageRestriction) MarshalEasyJSON(out *jwriter.Writer) {
out.String(string(t))
}
// MarshalJSON satisfies json.Marshaler.
func (t OriginTrialUsageRestriction) MarshalJSON() ([]byte, error) {
return easyjson.Marshal(t)
}
// UnmarshalEasyJSON satisfies easyjson.Unmarshaler.
func (t *OriginTrialUsageRestriction) UnmarshalEasyJSON(in *jlexer.Lexer) {
switch OriginTrialUsageRestriction(in.String()) {
case OriginTrialUsageRestrictionNone:
*t = OriginTrialUsageRestrictionNone
case OriginTrialUsageRestrictionSubset:
*t = OriginTrialUsageRestrictionSubset
default:
in.AddError(errors.New("unknown OriginTrialUsageRestriction value"))
}
}
// UnmarshalJSON satisfies json.Unmarshaler.
func (t *OriginTrialUsageRestriction) UnmarshalJSON(buf []byte) error {
return easyjson.Unmarshal(buf, t)
}
// OriginTrialToken [no description].
//
// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#type-OriginTrialToken
type OriginTrialToken struct {
Origin string `json:"origin"`
MatchSubDomains bool `json:"matchSubDomains"`
TrialName string `json:"trialName"`
ExpiryTime *TimeSinceEpoch `json:"expiryTime"`
IsThirdParty bool `json:"isThirdParty"`
UsageRestriction OriginTrialUsageRestriction `json:"usageRestriction"`
}
// OriginTrialTokenWithStatus [no description].
//
// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#type-OriginTrialTokenWithStatus
type OriginTrialTokenWithStatus struct {
RawTokenText string `json:"rawTokenText"`
ParsedToken *OriginTrialToken `json:"parsedToken,omitempty"` // parsedToken is present only when the token is extractable and parsable.
Status OriginTrialTokenStatus `json:"status"`
}
// OriginTrial [no description].
//
// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#type-OriginTrial
type OriginTrial struct {
TrialName string `json:"trialName"`
Status OriginTrialStatus `json:"status"`
TokensWithStatus []*OriginTrialTokenWithStatus `json:"tokensWithStatus"`
}
// Frame information about the Frame on the page.
//
// See: https://chromedevtools.github.io/devtools-protocol/tot/Page#type-Frame
type Frame struct {
ID FrameID `json:"id"` // Frame unique identifier.
ParentID FrameID `json:"parentId,omitempty"` // Parent frame identifier.
LoaderID LoaderID `json:"loaderId"` // Identifier of the loader associated with this frame.
Name string `json:"name,omitempty"` // Frame's name as specified in the tag.
URL string `json:"url"` // Frame document's URL without fragment.
URLFragment string `json:"urlFragment,omitempty"` // Frame document's URL fragment including the '#'.
DomainAndRegistry string `json:"domainAndRegistry"` // Frame document's registered domain, taking the public suffixes list into account. Extracted from the Frame's url. Example URLs: http://www.google.com/file.html -> "google.com" http://a.b.co.uk/file.html -> "b.co.uk"
SecurityOrigin string `json:"securityOrigin"` // Frame document's security origin.
MimeType string `json:"mimeType"` // Frame document's mimeType as determined by the browser.
UnreachableURL string `json:"unreachableUrl,omitempty"` // If the frame failed to load, this contains the URL that could not be loaded. Note that unlike url above, this URL may contain a fragment.
AdFrameStatus *AdFrameStatus `json:"adFrameStatus,omitempty"` // Indicates whether this frame was tagged as an ad and why.
SecureContextType SecureContextType `json:"secureContextType"` // Indicates whether the main document is a secure context and explains why that is the case.
CrossOriginIsolatedContextType CrossOriginIsolatedContextType `json:"crossOriginIsolatedContextType"` // Indicates whether this is a cross origin isolated context.
GatedAPIFeatures []GatedAPIFeatures `json:"gatedAPIFeatures"` // Indicated which gated APIs / features are available.
State FrameState `json:"-"` // Frame state.
Root *Node `json:"-"` // Frame document root.
Nodes map[NodeID]*Node `json:"-"` // Frame nodes.
sync.RWMutex `json:"-"` // Read write mutex.
}
// FrameState is the state of a Frame.
type FrameState uint16
// FrameState enum values.
const (
FrameDOMContentEventFired FrameState = 1 << (15 - iota)
FrameLoadEventFired
FrameAttached
FrameNavigated
FrameLoading
FrameScheduledNavigation
)
// frameStateNames are the names of the frame states.
var frameStateNames = map[FrameState]string{
FrameDOMContentEventFired: "DOMContentEventFired",
FrameLoadEventFired: "LoadEventFired",
FrameAttached: "Attached",
FrameNavigated: "Navigated",
FrameLoading: "Loading",
FrameScheduledNavigation: "ScheduledNavigation",
}
// String satisfies stringer interface.
func (fs FrameState) String() string {
var s []string
for k, v := range frameStateNames {
if fs&k != 0 {
s = append(s, v)
}
}
return "[" + strings.Join(s, " ") + "]"
}
// EmptyFrameID is the "non-existent" frame id.
const EmptyFrameID = FrameID("")
| {
return ctx.Value(executorKey).(Executor)
} |
serial.rs | use core::fmt;
use core::marker::PhantomData;
use core::ops::Deref;
use core::ops::DerefMut;
use core::pin::Pin;
use core::ptr;
use as_slice::{AsMutSlice, AsSlice};
use crate::dma;
use crate::hal::prelude::*;
use crate::hal::serial;
use crate::pac;
use crate::rcc::{BusClock, Enable, Reset};
use crate::state;
use nb::block;
use crate::pac::{RCC, UART4, UART5, UART7, USART1, USART2, USART3, USART6};
use crate::gpio::{self, Alternate};
use crate::rcc::Clocks;
use crate::{BitsPerSecond, U32Ext};
/// Serial error
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
/// Framing error
Framing,
/// Noise error
Noise,
/// RX buffer overrun
Overrun,
/// Parity check error
Parity,
}
pub trait Pins<USART> {}
pub trait PinTx<USART> {}
pub trait PinRx<USART> {}
impl<USART, TX, RX> Pins<USART> for (TX, RX)
where
TX: PinTx<USART>,
RX: PinRx<USART>,
{
}
mod f7xx_pins {
//table 13 in stm32f765bg.pdf
use super::{PinRx, PinTx};
use crate::gpio::{self, Alternate};
use crate::pac::{UART4, UART5, UART7, USART1};
impl PinTx<USART1> for gpio::PB14<Alternate<4>> {}
impl PinRx<USART1> for gpio::PB15<Alternate<4>> {}
impl PinTx<UART4> for gpio::PA11<Alternate<6>> {}
impl PinRx<UART4> for gpio::PA12<Alternate<6>> {}
impl PinTx<UART4> for gpio::PD1<Alternate<8>> {}
impl PinRx<UART4> for gpio::PD0<Alternate<8>> {}
impl PinTx<UART4> for gpio::PH13<Alternate<8>> {}
impl PinRx<UART4> for gpio::PH14<Alternate<8>> {}
impl PinRx<UART4> for gpio::PI9<Alternate<8>> {}
impl PinTx<UART5> for gpio::PB6<Alternate<1>> {}
impl PinRx<UART5> for gpio::PB5<Alternate<1>> {}
impl PinTx<UART5> for gpio::PB9<Alternate<7>> {}
impl PinRx<UART5> for gpio::PB8<Alternate<7>> {}
impl PinTx<UART5> for gpio::PB13<Alternate<8>> {}
impl PinRx<UART5> for gpio::PB12<Alternate<8>> {}
impl PinTx<UART7> for gpio::PA15<Alternate<12>> {}
impl PinRx<UART7> for gpio::PA8<Alternate<12>> {}
impl PinTx<UART7> for gpio::PB4<Alternate<12>> {}
impl PinRx<UART7> for gpio::PB3<Alternate<12>> {}
}
impl PinTx<USART1> for gpio::PA9<Alternate<7>> {}
impl PinTx<USART1> for gpio::PB6<Alternate<7>> {}
impl PinTx<USART2> for gpio::PA2<Alternate<7>> {}
impl PinTx<USART2> for gpio::PD5<Alternate<7>> {}
impl PinTx<USART3> for gpio::PB10<Alternate<7>> {}
impl PinTx<USART3> for gpio::PC10<Alternate<7>> {}
impl PinTx<USART3> for gpio::PD8<Alternate<7>> {}
impl PinTx<UART4> for gpio::PA0<Alternate<8>> {}
impl PinTx<UART4> for gpio::PC10<Alternate<8>> {}
impl PinTx<UART5> for gpio::PC12<Alternate<8>> {}
impl PinTx<USART6> for gpio::PC6<Alternate<8>> {}
impl PinTx<USART6> for gpio::PG14<Alternate<8>> {}
impl PinTx<UART7> for gpio::PE8<Alternate<8>> {}
impl PinTx<UART7> for gpio::PF7<Alternate<8>> {}
impl PinRx<USART1> for gpio::PA10<Alternate<7>> {}
impl PinRx<USART1> for gpio::PB7<Alternate<7>> {}
impl PinRx<USART2> for gpio::PA3<Alternate<7>> {}
impl PinRx<USART2> for gpio::PD6<Alternate<7>> {}
impl PinRx<USART3> for gpio::PB11<Alternate<7>> {}
impl PinRx<USART3> for gpio::PC11<Alternate<7>> {}
impl PinRx<USART3> for gpio::PD9<Alternate<7>> {}
impl PinRx<UART4> for gpio::PA1<Alternate<8>> {}
impl PinRx<UART4> for gpio::PC11<Alternate<8>> {}
impl PinRx<UART5> for gpio::PD2<Alternate<8>> {}
impl PinRx<USART6> for gpio::PC7<Alternate<8>> {}
impl PinRx<USART6> for gpio::PG9<Alternate<8>> {}
impl PinRx<UART7> for gpio::PE7<Alternate<8>> {}
impl PinRx<UART7> for gpio::PF6<Alternate<8>> {}
/// Serial abstraction
pub struct Serial<USART, PINS> {
usart: USART,
pins: PINS,
}
impl<USART, PINS> Serial<USART, PINS>
where
PINS: Pins<USART>,
USART: Instance,
{
pub fn new(usart: USART, pins: PINS, clocks: &Clocks, config: Config) -> Self {
// NOTE(unsafe) This executes only during initialisation
let rcc = unsafe { &(*RCC::ptr()) };
// TODO: The unsafe calls below should be replaced with accessing
// the correct registers directly.
USART::select_sysclock(rcc, config.sysclock);
unsafe {
USART::enable_unchecked();
}
let clk = if config.sysclock {
clocks.sysclk()
} else {
USART::clock(clocks)
};
// Calculate correct baudrate divisor on the fly
let brr = match config.oversampling {
Oversampling::By8 => {
usart.cr1.modify(|_, w| w.over8().set_bit());
let usart_div = 2 * clk / config.baud_rate;
0xfff0 & usart_div | 0x0007 & ((usart_div & 0x000f) >> 1)
}
Oversampling::By16 => {
usart.cr1.modify(|_, w| w.over8().clear_bit());
clk / config.baud_rate |
// Set character match and reset other registers to disable advanced USART features
let ch = config.character_match.unwrap_or(0);
usart.cr2.write(|w| w.add().bits(ch));
// Enable tx / rx, configure data bits and parity
usart.cr1.modify(|_, w| {
w
.te().enabled()
.re().enabled()
.ue().enabled();
// M[1:0] are used to set data bits
// M[1:0] = 00: 1 Start bit, 8 data bits, n stop bits
// M[1:0] = 01: 1 Start bit, 9 data bits, n stop bits
// M[1:0] = 10: 1 Start bit, 7 data bits, n stop bits
match config.data_bits {
DataBits::Bits8 => w.m1().clear_bit().m0().bit8(),
DataBits::Bits9 => w.m1().clear_bit().m0().bit9(),
DataBits::Bits7 => w.m0().clear_bit().m1().bit7(),
};
match config.parity {
Parity::ParityEven => w.ps().even().pce().enabled(),
Parity::ParityOdd => w.ps().odd().pce().enabled(),
Parity::ParityNone => w.pce().disabled(),
}
});
// Enable DMA
usart.cr3.write(|w| w.dmat().enabled().dmar().enabled());
Serial { usart, pins }
}
/// Starts listening for an interrupt event
pub fn listen(&mut self, event: Event) {
match event {
Event::Rxne => self.usart.cr1.modify(|_, w| w.rxneie().set_bit()),
Event::Txe => self.usart.cr1.modify(|_, w| w.txeie().set_bit()),
Event::CharacterMatch => self.usart.cr1.modify(|_, w| w.cmie().set_bit()),
Event::Error => self.usart.cr3.modify(|_, w| w.eie().set_bit()),
}
}
/// End listening for an interrupt event
pub fn unlisten(&mut self, event: Event) {
match event {
Event::Rxne => self.usart.cr1.modify(|_, w| w.rxneie().clear_bit()),
Event::Txe => self.usart.cr1.modify(|_, w| w.txeie().clear_bit()),
Event::CharacterMatch => self.usart.cr1.modify(|_, w| w.cmie().clear_bit()),
Event::Error => self.usart.cr3.modify(|_, w| w.eie().clear_bit()),
}
}
pub fn split(self) -> (Tx<USART>, Rx<USART>) {
(
Tx {
_usart: PhantomData,
},
Rx {
_usart: PhantomData,
},
)
}
pub fn release(self) -> (USART, PINS) {
(self.usart, self.pins)
}
}
impl<USART, PINS> serial::Read<u8> for Serial<USART, PINS>
where
USART: Instance,
{
type Error = Error;
fn read(&mut self) -> nb::Result<u8, Error> {
let mut rx: Rx<USART> = Rx {
_usart: PhantomData,
};
rx.read()
}
}
impl<USART, PINS> serial::Write<u8> for Serial<USART, PINS>
where
USART: Instance,
{
type Error = Error;
fn flush(&mut self) -> nb::Result<(), Self::Error> {
let mut tx: Tx<USART> = Tx {
_usart: PhantomData,
};
tx.flush()
}
fn write(&mut self, byte: u8) -> nb::Result<(), Self::Error> {
let mut tx: Tx<USART> = Tx {
_usart: PhantomData,
};
tx.write(byte)
}
}
/// Serial receiver
pub struct Rx<USART> {
_usart: PhantomData<USART>,
}
impl<USART> Rx<USART>
where
USART: Instance,
Self: dma::Target,
{
/// Reads data using DMA until `buffer` is full
///
/// DMA supports transfers up to 65535 bytes. If `buffer` is longer, this
/// method will panic.
pub fn read_all<B>(
self,
buffer: Pin<B>,
dma: &dma::Handle<<Self as dma::Target>::Instance, state::Enabled>,
stream: <Self as dma::Target>::Stream,
) -> dma::Transfer<Self, B, dma::Ready>
where
B: DerefMut + 'static,
B::Target: AsMutSlice<Element = u8>,
{
// This is safe, as we're only using the USART instance to access the
// address of one register.
let address = &unsafe { &*USART::ptr() }.rdr as *const _ as _;
// Safe, because the trait bounds on this method guarantee that `buffer`
// can be written to safely.
unsafe {
dma::Transfer::new(
dma,
stream,
buffer,
self,
address,
dma::Direction::PeripheralToMemory,
)
}
}
}
impl<USART> serial::Read<u8> for Rx<USART>
where
USART: Instance,
{
type Error = Error;
fn read(&mut self) -> nb::Result<u8, Error> {
// NOTE(unsafe) atomic read with no side effects
let isr = unsafe { (*USART::ptr()).isr.read() };
// NOTE(unsafe): Only used for atomic writes, to clear error flags.
let icr = unsafe { &(*USART::ptr()).icr };
if isr.pe().bit_is_set() {
icr.write(|w| w.pecf().clear());
return Err(nb::Error::Other(Error::Parity));
}
if isr.fe().bit_is_set() {
icr.write(|w| w.fecf().clear());
return Err(nb::Error::Other(Error::Framing));
}
if isr.nf().bit_is_set() {
icr.write(|w| w.ncf().clear());
return Err(nb::Error::Other(Error::Noise));
}
if isr.ore().bit_is_set() {
icr.write(|w| w.orecf().clear());
return Err(nb::Error::Other(Error::Overrun));
}
if isr.rxne().bit_is_set() {
// NOTE(unsafe): Atomic read with no side effects
return Ok(unsafe {
// Casting to `u8` should be fine, as we've configured the USART
// to use 8 data bits.
(*USART::ptr()).rdr.read().rdr().bits() as u8
});
}
Err(nb::Error::WouldBlock)
}
}
/// Serial transmitter
pub struct Tx<USART> {
_usart: PhantomData<USART>,
}
impl<USART> Tx<USART>
where
Self: dma::Target,
USART: Instance,
{
/// Writes data using DMA
///
/// DMA supports transfers up to 65535 bytes. If `data` is longer, this
/// method will panic.
pub fn write_all<B>(
self,
data: Pin<B>,
dma: &dma::Handle<<Self as dma::Target>::Instance, state::Enabled>,
stream: <Self as dma::Target>::Stream,
) -> dma::Transfer<Self, B, dma::Ready>
where
B: Deref + 'static,
B::Target: AsSlice<Element = u8>,
{
// Prepare USART for DMA. See reference manual for STM32F75xxx and
// STM32F74xxx, section 31.5.15.
//
// This is safe, as we're doing just one atomic write.
let usart = unsafe { &*USART::ptr() };
usart.icr.write(|w| w.tccf().clear());
// Safe, because the trait bounds on this method guarantee that `buffer`
// can be read from safely.
unsafe {
dma::Transfer::new(
dma,
stream,
data,
self,
&usart.tdr as *const _ as _,
dma::Direction::MemoryToPeripheral,
)
}
}
}
impl<USART> serial::Write<u8> for Tx<USART>
where
USART: Instance,
{
type Error = Error;
fn flush(&mut self) -> nb::Result<(), Self::Error> {
// NOTE(unsafe) atomic read with no side effects
let isr = unsafe { (*USART::ptr()).isr.read() };
if isr.tc().bit_is_set() {
Ok(())
} else {
Err(nb::Error::WouldBlock)
}
}
fn write(&mut self, byte: u8) -> nb::Result<(), Self::Error> {
// NOTE(unsafe) atomic read with no side effects
let isr = unsafe { (*USART::ptr()).isr.read() };
if isr.txe().bit_is_set() {
// NOTE(unsafe) atomic write to stateless register
// NOTE(write_volatile) 8-bit write that's not possible through the svd2rust API
unsafe { ptr::write_volatile(&(*USART::ptr()).tdr as *const _ as *mut _, byte) }
Ok(())
} else {
Err(nb::Error::WouldBlock)
}
}
}
/// USART configuration
pub struct Config {
pub baud_rate: BitsPerSecond,
pub oversampling: Oversampling,
pub character_match: Option<u8>,
pub sysclock: bool,
pub parity: Parity,
pub data_bits: DataBits,
}
pub enum Oversampling {
By8,
By16,
}
/// Number of data bits
pub enum DataBits {
/// 8 bits of data
Bits8,
/// 9 bits of data
Bits9,
/// 7 bits of data
Bits7,
}
/// Parity generation and checking. If odd or even parity is selected, the
/// underlying USART will be configured to send/receive the parity bit in
/// addtion to the data bits.
pub enum Parity {
/// No parity bit will be added/checked.
ParityNone,
/// The MSB transmitted/received will be generated/checked to have a
/// even number of bits set.
ParityEven,
/// The MSB transmitted/received will be generated/checked to have a
/// odd number of bits set.
ParityOdd,
}
impl Default for Config {
fn default() -> Self {
Self {
baud_rate: 115_200.bps(),
oversampling: Oversampling::By16,
character_match: None,
sysclock: false,
parity: Parity::ParityNone,
data_bits: DataBits::Bits8,
}
}
}
/// Interrupt event
#[derive(Debug)]
pub enum Event {
/// New data has been received
Rxne,
/// New data can be sent
Txe,
/// Character match interrupt
CharacterMatch,
/// Error interrupt
Error,
}
/// Implemented by all USART instances
pub trait Instance: Deref<Target = pac::usart1::RegisterBlock> + Enable + Reset + BusClock {
fn ptr() -> *const pac::usart1::RegisterBlock;
fn select_sysclock(rcc: &pac::rcc::RegisterBlock, sys: bool);
}
macro_rules! impl_instance {
($(
$USARTX:ident: ($usartXsel:ident),
)+) => {
$(
impl Instance for $USARTX {
fn ptr() -> *const pac::usart1::RegisterBlock {
$USARTX::ptr()
}
fn select_sysclock(rcc: &pac::rcc::RegisterBlock, sys: bool) {
rcc.dckcfgr2.modify(|_, w| w.$usartXsel().bits(sys as _));
}
}
)+
}
}
#[cfg(any(feature = "device-selected",))]
impl_instance! {
USART1: (usart1sel),
USART2: (usart2sel),
USART3: (usart3sel),
UART4: (uart4sel),
UART5: (uart5sel),
USART6: (usart6sel),
UART7: (uart7sel),
}
impl<USART> fmt::Write for Tx<USART>
where
Tx<USART>: serial::Write<u8>,
{
fn write_str(&mut self, s: &str) -> fmt::Result {
let _ = s.as_bytes().iter().map(|c| block!(self.write(*c))).last();
Ok(())
}
} | }
};
usart.brr.write(|w| unsafe { w.bits(brr) }); |
invalid_bool.rs | // Validation makes this fail in the wrong place
// Make sure we find these even with many checks disabled.
// compile-flags: -Zmiri-disable-alignment-check -Zmiri-disable-stacked-borrows -Zmiri-disable-validation
#![feature(test)]
fn main() | {
let b = unsafe { std::mem::transmute::<u8, bool>(2) };
let _x = b == std::hint::black_box(true); //~ ERROR interpreting an invalid 8-bit value as a bool: 0x02
} |
|
PdbInfoTable.tsx | import { StringVoidFun } from '../../../constants/CommonTypes';
import { PDB_URL_INTERFACE_BY_ID, PDB_URL_INTERFACE_BY_PROTEIN } from '../../../constants/ExternalUrls';
import { PdbResponseElement } from './StructuralDetail';
import { ReactComponent as ExternalLinkIcon } from "../../../images/external-link.svg"
interface PdbInfoTableProps {
isoFormAccession: string,
change3dDiagram: StringVoidFun,
pdbApiData: Array<PdbResponseElement>,
selectedPdbId: string
}
function PdbInfoTable(props: PdbInfoTableProps) {
return <>
<div className="tableFixHead">
<a href={PDB_URL_INTERFACE_BY_PROTEIN + props.isoFormAccession}>More information <ExternalLinkIcon width={12.5}/></a>
<table>
<thead>
<tr>
<th colSpan={6}>Experimental Structure</th>
</tr>
<tr>
<th>pdb id</th>
<th>chain</th>
<th>PDB Pos</th>
<th>resolution</th>
<th>Method</th>
</tr>
</thead>
<tbody>{getPdbInfoRows(props)}</tbody>
</table>
</div>
</>
}
function getPdbInfoRows(props: PdbInfoTableProps) {
const rows: Array<JSX.Element> = [];
const pdbMap = combineChainsByPdbId(props.pdbApiData)
pdbMap.forEach((value) => {
const copyPdbEntry = {...value.pdbEntry}
copyPdbEntry.chain_id = value.chains.sort().join()
rows.push(getPdbInfoRow(copyPdbEntry, props.change3dDiagram, props.selectedPdbId));
})
return rows;
}
function combineChainsByPdbId(pdbApiData: Array<PdbResponseElement>) {
const chainsMap = new Map<string, { chains: Array<string>, pdbEntry: PdbResponseElement }>();
pdbApiData.forEach((pdbEntry) => {
let pdbId = pdbEntry.pdb_id;
if (chainsMap.get(pdbId)) {
chainsMap.get(pdbId)?.chains.push(pdbEntry.chain_id)
}
else {
const chains = new Array<string>(pdbEntry.chain_id)
chainsMap.set(pdbId, { chains, pdbEntry })
}
});
return chainsMap;
}
function | (str: PdbResponseElement, tableRowClicked: StringVoidFun, clickedPdbId: string) {
const rowClass = clickedPdbId === str.pdb_id ? 'clickable-row active' : 'clickable-row';
return (
<tr className={rowClass} onClick={(e) => tableRowClicked(str.pdb_id)} key={str.pdb_id}>
<td className="small">
<a href={PDB_URL_INTERFACE_BY_ID + str.pdb_id} target="_blank" rel="noreferrer">
<u>{str.pdb_id}</u>
</a>
</td>
<td className="small">{str.chain_id}</td>
<td className="small">
{str.start}-{str.end}
</td>
<td className="small">{str.resolution}</td>
<td className="small">{str.experimental_method}</td>
</tr>
);
}
export default PdbInfoTable; | getPdbInfoRow |
default_config.py | """
Generates the default configuration for all sections.
"""
import configparser
import socket
def set_defaults():
| """
Generates the default configuration for all sections.
:return: configparser.ConfigParser object
"""
config = configparser.ConfigParser(allow_no_value=True)
common = {
'csv_import_folder': '',
'csv_export_folder': '',
# Export headers you want, those missing in the import will be added
# with empty data.
'csv_export_headers': ('Series_reference', 'Period', 'ELEE'),
'csv_delimiter': ';',
# Options: https://docs.python.org/3.5/library/codecs.html#text-encodings
# use mbcs for ansi on python prior 3.6
'csv_encoding': 'utf-8',
# You can use column types, like int64, np.float64 if you want to specify
# Or you can use type object if you don't want conversion or avoid NaN errors
# https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html
# example: {'column name': 'object'}
'dtype': {}
}
config['common'] = common
return config |
|
mod.rs | // Copyright (c) 2019 Cloudflare, Inc. All rights reserved.
// SPDX-License-Identifier: BSD-3-Clause
pub mod allowed_ips;
pub mod api;
mod dev_lock;
pub mod drop_privileges;
mod integration_tests;
pub mod peer;
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[path = "kqueue.rs"]
pub mod poll;
#[cfg(target_os = "linux")]
#[path = "epoll.rs"]
pub mod poll;
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[path = "tun_darwin.rs"]
pub mod tun;
#[cfg(target_os = "linux")]
#[path = "tun_linux.rs"]
pub mod tun;
#[cfg(unix)]
#[path = "udp_unix.rs"]
pub mod udp;
use std::collections::HashMap;
use std::convert::From;
use std::io;
use std::net::{IpAddr, SocketAddr};
use std::os::unix::io::AsRawFd;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::thread;
use std::thread::JoinHandle;
use crate::crypto::{X25519PublicKey, X25519SecretKey};
use crate::noise::errors::WireGuardError;
use crate::noise::handshake::parse_handshake_anon;
use crate::noise::rate_limiter::RateLimiter;
use crate::noise::{make_array, Packet, Tunn, TunnResult};
use allowed_ips::AllowedIps;
use peer::{AllowedIP, Peer};
use poll::{EventPoll, EventRef, WaitResult};
use tun::{errno, errno_str, TunSocket};
use udp::UDPSocket;
use dev_lock::{Lock, LockReadGuard};
use slog::{error, info, o, Discard, Logger};
const HANDSHAKE_RATE_LIMIT: u64 = 100; // The number of handshakes per second we can tolerate before using cookies
const MAX_UDP_SIZE: usize = (1 << 16) - 1;
const MAX_ITR: usize = 100; // Number of packets to handle per handler call
#[derive(Debug)]
pub enum Error {
Socket(String),
Bind(String),
FCntl(String),
EventQueue(String),
IOCtl(String),
Connect(String),
SetSockOpt(String),
InvalidTunnelName,
#[cfg(any(target_os = "macos", target_os = "ios"))]
GetSockOpt(String),
GetSockName(String),
UDPRead(i32),
#[cfg(target_os = "linux")]
Timer(String),
IfaceRead(i32),
DropPrivileges(String),
ApiSocket(std::io::Error),
}
// What the event loop should do after a handler returns
enum Action {
Continue, // Continue the loop
Yield, // Yield the read lock and acquire it again
Exit, // Stop the loop
}
// Event handler function
type Handler<T, S> =
Box<dyn Fn(&mut LockReadGuard<Device<T, S>>, &mut ThreadData<T>) -> Action + Send + Sync>;
// The trait satisfied by tunnel device implementations.
pub trait Tun: 'static + AsRawFd + Sized + Send + Sync {
fn new(name: &str) -> Result<Self, Error>;
fn set_non_blocking(self) -> Result<Self, Error>;
fn name(&self) -> Result<String, Error>;
fn mtu(&self) -> Result<usize, Error>;
fn write4(&self, src: &[u8]) -> usize;
fn write6(&self, src: &[u8]) -> usize;
fn read<'a>(&self, dst: &'a mut [u8]) -> Result<&'a mut [u8], Error>;
}
// The trait satisfied by UDP socket implementations.
pub trait Sock: 'static + AsRawFd + Sized + Send + Sync {
fn new() -> Result<Self, Error>;
fn new6() -> Result<Self, Error>;
fn bind(self, port: u16) -> Result<Self, Error>;
fn connect(self, dst: &SocketAddr) -> Result<Self, Error>;
fn set_non_blocking(self) -> Result<Self, Error>;
fn set_reuse(self) -> Result<Self, Error>;
fn set_fwmark(&self, mark: u32) -> Result<(), Error>;
fn port(&self) -> Result<u16, Error>;
fn sendto(&self, buf: &[u8], dst: SocketAddr) -> usize;
fn recvfrom<'a>(&self, buf: &'a mut [u8]) -> Result<(SocketAddr, &'a mut [u8]), Error>;
fn write(&self, buf: &[u8]) -> usize;
fn read<'a>(&self, buf: &'a mut [u8]) -> Result<&'a mut [u8], Error>;
fn shutdown(&self);
}
pub struct DeviceHandle<T: Tun = TunSocket, S: Sock = UDPSocket> {
device: Arc<Lock<Device<T, S>>>, // The interface this handle owns
threads: Vec<JoinHandle<()>>,
}
pub struct DeviceConfig {
pub n_threads: usize,
pub use_connected_socket: bool,
pub logger: Logger,
#[cfg(target_os = "linux")]
pub use_multi_queue: bool,
#[cfg(target_os = "linux")]
pub uapi_fd: i32, | }
impl Default for DeviceConfig {
fn default() -> Self {
DeviceConfig {
n_threads: 4,
use_connected_socket: true,
logger: Logger::root(Discard, o!()),
#[cfg(target_os = "linux")]
use_multi_queue: true,
#[cfg(target_os = "linux")]
uapi_fd: -1,
}
}
}
pub struct Device<T: Tun, S: Sock> {
key_pair: Option<(Arc<X25519SecretKey>, Arc<X25519PublicKey>)>,
queue: Arc<EventPoll<Handler<T, S>>>,
listen_port: u16,
fwmark: Option<u32>,
iface: Arc<T>,
udp4: Option<Arc<S>>,
udp6: Option<Arc<S>>,
yield_notice: Option<EventRef>,
exit_notice: Option<EventRef>,
peers: HashMap<Arc<X25519PublicKey>, Arc<Peer<S>>>,
peers_by_ip: AllowedIps<Arc<Peer<S>>>,
peers_by_idx: HashMap<u32, Arc<Peer<S>>>,
next_index: u32,
config: DeviceConfig,
cleanup_paths: Vec<String>,
mtu: AtomicUsize,
rate_limiter: Option<Arc<RateLimiter>>,
#[cfg(target_os = "linux")]
uapi_fd: i32,
}
struct ThreadData<T: Tun> {
iface: Arc<T>,
src_buf: [u8; MAX_UDP_SIZE],
dst_buf: [u8; MAX_UDP_SIZE],
}
impl<T: Tun, S: Sock> DeviceHandle<T, S> {
pub fn new(name: &str, config: DeviceConfig) -> Result<DeviceHandle<T, S>, Error> {
let n_threads = config.n_threads;
let mut wg_interface = Device::<T, S>::new(name, config)?;
wg_interface.open_listen_socket(0)?; // Start listening on a random port
let interface_lock = Arc::new(Lock::new(wg_interface));
let mut threads = vec![];
for i in 0..n_threads {
threads.push({
let dev = Arc::clone(&interface_lock);
thread::spawn(move || DeviceHandle::event_loop(i, &dev))
});
}
Ok(DeviceHandle {
device: interface_lock,
threads,
})
}
pub fn wait(&mut self) {
while let Some(thread) = self.threads.pop() {
thread.join().unwrap();
}
}
pub fn clean(&mut self) {
for path in &self.device.read().cleanup_paths {
// attempt to remove any file we created in the work dir
let _ = std::fs::remove_file(&path);
}
}
fn event_loop(_i: usize, device: &Lock<Device<T, S>>) {
#[cfg(target_os = "linux")]
let mut thread_local = ThreadData {
src_buf: [0u8; MAX_UDP_SIZE],
dst_buf: [0u8; MAX_UDP_SIZE],
iface: if _i == 0 || !device.read().config.use_multi_queue {
// For the first thread use the original iface
Arc::clone(&device.read().iface)
} else {
// For for the rest create a new iface queue
let iface_local = Arc::new(
T::new(&device.read().iface.name().unwrap())
.unwrap()
.set_non_blocking()
.unwrap(),
);
device
.read()
.register_iface_handler(Arc::clone(&iface_local))
.ok();
iface_local
},
};
#[cfg(not(target_os = "linux"))]
let mut thread_local = ThreadData {
src_buf: [0u8; MAX_UDP_SIZE],
dst_buf: [0u8; MAX_UDP_SIZE],
iface: Arc::clone(&device.read().iface),
};
#[cfg(not(target_os = "linux"))]
let uapi_fd = -1;
#[cfg(target_os = "linux")]
let uapi_fd = device.read().uapi_fd;
loop {
// The event loop keeps a read lock on the device, because we assume write access is rarely needed
let mut device_lock = device.read();
let queue = Arc::clone(&device_lock.queue);
loop {
match queue.wait() {
WaitResult::Ok(handler) => {
let action = (*handler)(&mut device_lock, &mut thread_local);
match action {
Action::Continue => {}
Action::Yield => break,
Action::Exit => {
device_lock.trigger_exit();
return;
}
}
}
WaitResult::EoF(handler) => {
if uapi_fd >= 0 && uapi_fd == handler.fd() {
device_lock.trigger_exit();
return;
}
handler.cancel();
}
WaitResult::Error(e) => error!(device_lock.config.logger, "Poll error {:}", e),
}
}
}
}
}
impl<T: Tun, S: Sock> Drop for DeviceHandle<T, S> {
fn drop(&mut self) {
self.device.read().trigger_exit();
self.clean();
}
}
impl<T: Tun, S: Sock> Device<T, S> {
fn next_index(&mut self) -> u32 {
let next_index = self.next_index;
self.next_index += 1;
assert!(next_index < (1 << 24), "Too many peers created");
next_index
}
fn remove_peer(&mut self, pub_key: &X25519PublicKey) {
if let Some(peer) = self.peers.remove(pub_key) {
// Found a peer to remove, now purge all references to it:
peer.shutdown_endpoint(); // close open udp socket and free the closure
self.peers_by_idx.remove(&peer.index()); // peers_by_idx
self.peers_by_ip
.remove(&|p: &Arc<Peer<S>>| Arc::ptr_eq(&peer, p)); // peers_by_ip
info!(peer.tunnel.logger, "Peer removed");
}
}
#[allow(clippy::too_many_arguments)]
fn update_peer(
&mut self,
pub_key: X25519PublicKey,
remove: bool,
_replace_ips: bool,
endpoint: Option<SocketAddr>,
allowed_ips: Vec<AllowedIP>,
keepalive: Option<u16>,
preshared_key: Option<[u8; 32]>,
) {
let pub_key = Arc::new(pub_key);
if remove {
// Completely remove a peer
return self.remove_peer(&pub_key);
}
// Update an existing peer
if self.peers.get(&pub_key).is_some() {
// We already have a peer, we need to merge the existing config into the newly created one
panic!("Modifying existing peers is not yet supported. Remove and add again instead.");
}
let next_index = self.next_index();
let device_key_pair = self
.key_pair
.as_ref()
.expect("Private key must be set first");
let mut tunn = Tunn::new(
Arc::clone(&device_key_pair.0),
Arc::clone(&pub_key),
preshared_key,
keepalive,
next_index,
None,
)
.unwrap();
{
let pub_key = base64::encode(pub_key.as_bytes());
let peer_name = format!("{}…{}", &pub_key[0..4], &pub_key[pub_key.len() - 4..]);
let peer_logger = self.config.logger.new(o!("peer" => peer_name));
tunn.set_logger(peer_logger);
}
let peer = Peer::new(tunn, next_index, endpoint, &allowed_ips, preshared_key);
let peer = Arc::new(peer);
self.peers.insert(pub_key, Arc::clone(&peer));
self.peers_by_idx.insert(next_index, Arc::clone(&peer));
for AllowedIP { addr, cidr } in allowed_ips {
self.peers_by_ip.insert(addr, cidr as _, Arc::clone(&peer));
}
info!(peer.tunnel.logger, "Peer added");
}
pub fn new(name: &str, config: DeviceConfig) -> Result<Device<T, S>, Error> {
let poll = EventPoll::<Handler<T, S>>::new()?;
// Create a tunnel device
let iface = Arc::new(T::new(name)?.set_non_blocking()?);
let mtu = iface.mtu()?;
#[cfg(not(target_os = "linux"))]
let uapi_fd = -1;
#[cfg(target_os = "linux")]
let uapi_fd = config.uapi_fd;
let mut device = Device {
queue: Arc::new(poll),
iface,
config,
exit_notice: Default::default(),
yield_notice: Default::default(),
fwmark: Default::default(),
key_pair: Default::default(),
listen_port: Default::default(),
next_index: Default::default(),
peers: Default::default(),
peers_by_idx: Default::default(),
peers_by_ip: AllowedIps::new(),
udp4: Default::default(),
udp6: Default::default(),
cleanup_paths: Default::default(),
mtu: AtomicUsize::new(mtu),
rate_limiter: None,
#[cfg(target_os = "linux")]
uapi_fd,
};
if uapi_fd >= 0 {
device.register_api_fd(uapi_fd)?;
} else {
device.register_api_handler()?;
}
device.register_iface_handler(Arc::clone(&device.iface))?;
device.register_notifiers()?;
device.register_timers()?;
#[cfg(target_os = "macos")]
{
// Only for macOS write the actual socket name into WG_TUN_NAME_FILE
if let Ok(name_file) = std::env::var("WG_TUN_NAME_FILE") {
if name == "utun" {
std::fs::write(&name_file, device.iface.name().unwrap().as_bytes()).unwrap();
device.cleanup_paths.push(name_file);
}
}
}
Ok(device)
}
fn open_listen_socket(&mut self, mut port: u16) -> Result<(), Error> {
// Binds the network facing interfaces
// First close any existing open socket, and remove them from the event loop
if let Some(s) = self.udp4.take() {
unsafe {
// This is safe because the event loop is not running yet
self.queue.clear_event_by_fd(s.as_raw_fd())
}
};
if let Some(s) = self.udp6.take() {
unsafe { self.queue.clear_event_by_fd(s.as_raw_fd()) };
}
for peer in self.peers.values() {
peer.shutdown_endpoint();
}
// Then open new sockets and bind to the port
let udp_sock4 = Arc::new(S::new()?.set_non_blocking()?.set_reuse()?.bind(port)?);
if port == 0 {
// Random port was assigned
port = udp_sock4.port()?;
}
let udp_sock6 = Arc::new(S::new6()?.set_non_blocking()?.set_reuse()?.bind(port)?);
self.register_udp_handler(Arc::clone(&udp_sock4))?;
self.register_udp_handler(Arc::clone(&udp_sock6))?;
self.udp4 = Some(udp_sock4);
self.udp6 = Some(udp_sock6);
self.listen_port = port;
Ok(())
}
fn set_key(&mut self, private_key: X25519SecretKey) {
let mut bad_peers = vec![];
let private_key = Arc::new(private_key);
let public_key = Arc::new(private_key.public_key());
let rate_limiter = Arc::new(RateLimiter::new(&public_key, HANDSHAKE_RATE_LIMIT));
for peer in self.peers.values_mut() {
// Taking a pointer should be Ok as long as all other threads are stopped
let mut_ptr = Arc::into_raw(Arc::clone(peer)) as *mut Peer<S>;
if unsafe {
mut_ptr.as_mut().unwrap().tunnel.set_static_private(
Arc::clone(&private_key),
Arc::clone(&public_key),
Some(Arc::clone(&rate_limiter)),
)
}
.is_err()
{
// In case we encounter an error, we will remove that peer
// An error will be a result of bad public key/secret key combination
bad_peers.push(peer);
}
}
self.key_pair = Some((private_key, public_key));
self.rate_limiter = Some(rate_limiter);
// Remove all the bad peers
for _ in bad_peers {
unimplemented!();
}
}
fn set_fwmark(&mut self, mark: u32) -> Result<(), Error> {
self.fwmark = Some(mark);
// First set fwmark on listeners
if let Some(ref sock) = self.udp4 {
sock.set_fwmark(mark)?;
}
if let Some(ref sock) = self.udp6 {
sock.set_fwmark(mark)?;
}
// Then on all currently connected sockets
for peer in self.peers.values() {
if let Some(ref sock) = peer.endpoint().conn {
sock.set_fwmark(mark)?
}
}
Ok(())
}
fn clear_peers(&mut self) {
self.peers.clear();
self.peers_by_idx.clear();
self.peers_by_ip.clear();
}
fn register_notifiers(&mut self) -> Result<(), Error> {
let yield_ev = self
.queue
// The notification event handler simply returns Action::Yield
.new_notifier(Box::new(|_, _| Action::Yield))?;
self.yield_notice = Some(yield_ev);
let exit_ev = self
.queue
// The exit event handler simply returns Action::Exit
.new_notifier(Box::new(|_, _| Action::Exit))?;
self.exit_notice = Some(exit_ev);
Ok(())
}
fn register_timers(&self) -> Result<(), Error> {
self.queue.new_periodic_event(
// Reset the rate limiter every second give or take
Box::new(|d, _| {
if let Some(r) = d.rate_limiter.as_ref() {
r.reset_count()
}
Action::Continue
}),
std::time::Duration::from_secs(1),
)?;
self.queue.new_periodic_event(
// Execute the timed function of every peer in the list
Box::new(|d, t| {
let peer_map = &d.peers;
let (udp4, udp6) = match (d.udp4.as_ref(), d.udp6.as_ref()) {
(Some(udp4), Some(udp6)) => (udp4, udp6),
_ => return Action::Continue,
};
// Go over each peer and invoke the timer function
for peer in peer_map.values() {
let endpoint_addr = match peer.endpoint().addr {
Some(addr) => addr,
None => continue,
};
match peer.update_timers(&mut t.dst_buf[..]) {
TunnResult::Done => {}
TunnResult::Err(WireGuardError::ConnectionExpired) => {
peer.shutdown_endpoint(); // close open udp socket
}
TunnResult::Err(e) => error!(d.config.logger, "Timer error {:?}", e),
TunnResult::WriteToNetwork(packet) => {
match endpoint_addr {
SocketAddr::V4(_) => udp4.sendto(packet, endpoint_addr),
SocketAddr::V6(_) => udp6.sendto(packet, endpoint_addr),
};
}
_ => panic!("Unexpected result from update_timers"),
};
}
Action::Continue
}),
std::time::Duration::from_millis(250),
)?;
Ok(())
}
pub(crate) fn trigger_yield(&self) {
self.queue
.trigger_notification(self.yield_notice.as_ref().unwrap())
}
pub(crate) fn trigger_exit(&self) {
self.queue
.trigger_notification(self.exit_notice.as_ref().unwrap())
}
pub(crate) fn cancel_yield(&self) {
self.queue
.stop_notification(self.yield_notice.as_ref().unwrap())
}
fn register_udp_handler(&self, udp: Arc<S>) -> Result<(), Error> {
self.queue.new_event(
udp.as_raw_fd(),
Box::new(move |d, t| {
// Handler that handles anonymous packets over UDP
let mut iter = MAX_ITR;
let (private_key, public_key) = d.key_pair.as_ref().expect("Key not set");
let rate_limiter = d.rate_limiter.as_ref().unwrap();
// Loop while we have packets on the anonymous connection
while let Ok((addr, packet)) = udp.recvfrom(&mut t.src_buf[..]) {
// The rate limiter initially checks mac1 and mac2, and optionally asks to send a cookie
let parsed_packet =
match rate_limiter.verify_packet(Some(addr.ip()), packet, &mut t.dst_buf) {
Ok(packet) => packet,
Err(TunnResult::WriteToNetwork(cookie)) => {
udp.sendto(cookie, addr);
continue;
}
Err(_) => continue,
};
let peer = match &parsed_packet {
Packet::HandshakeInit(p) => {
parse_handshake_anon(&private_key, &public_key, &p)
.ok()
.and_then(|hh| {
d.peers
.get(&X25519PublicKey::from(&hh.peer_static_public[..]))
})
}
Packet::HandshakeResponse(p) => d.peers_by_idx.get(&(p.receiver_idx >> 8)),
Packet::PacketCookieReply(p) => d.peers_by_idx.get(&(p.receiver_idx >> 8)),
Packet::PacketData(p) => d.peers_by_idx.get(&(p.receiver_idx >> 8)),
};
let peer = match peer {
None => continue,
Some(peer) => peer,
};
// We found a peer, use it to decapsulate the message+
let mut flush = false; // Are there packets to send from the queue?
match peer
.tunnel
.handle_verified_packet(parsed_packet, &mut t.dst_buf[..])
{
TunnResult::Done => {}
TunnResult::Err(_) => continue,
TunnResult::WriteToNetwork(packet) => {
flush = true;
udp.sendto(packet, addr);
}
TunnResult::WriteToTunnelV4(packet, addr) => {
if peer.is_allowed_ip(addr) {
t.iface.write4(packet);
}
}
TunnResult::WriteToTunnelV6(packet, addr) => {
if peer.is_allowed_ip(addr) {
t.iface.write6(packet);
}
}
};
if flush {
// Flush pending queue
while let TunnResult::WriteToNetwork(packet) =
peer.tunnel.decapsulate(None, &[], &mut t.dst_buf[..])
{
udp.sendto(packet, addr);
}
}
// This packet was OK, that means we want to create a connected socket for this peer
let ip_addr = addr.ip();
peer.set_endpoint(addr);
if d.config.use_connected_socket {
if let Ok(sock) = peer.connect_endpoint(d.listen_port, d.fwmark) {
d.register_conn_handler(Arc::clone(peer), sock, ip_addr)
.unwrap();
}
}
iter -= 1;
if iter == 0 {
break;
}
}
Action::Continue
}),
)?;
Ok(())
}
fn register_conn_handler(
&self,
peer: Arc<Peer<S>>,
udp: Arc<S>,
peer_addr: IpAddr,
) -> Result<(), Error> {
self.queue.new_event(
udp.as_raw_fd(),
Box::new(move |_, t| {
// The conn_handler handles packet received from a connected UDP socket, associated
// with a known peer, this saves us the hustle of finding the right peer. If another
// peer gets the same ip, it will be ignored until the socket does not expire.
let iface = &t.iface;
let mut iter = MAX_ITR;
while let Ok(src) = udp.read(&mut t.src_buf[..]) {
let mut flush = false;
match peer
.tunnel
.decapsulate(Some(peer_addr), src, &mut t.dst_buf[..])
{
TunnResult::Done => {}
TunnResult::Err(e) => eprintln!("Decapsulate error {:?}", e),
TunnResult::WriteToNetwork(packet) => {
flush = true;
udp.write(packet);
}
TunnResult::WriteToTunnelV4(packet, addr) => {
if peer.is_allowed_ip(addr) {
iface.write4(packet);
}
}
TunnResult::WriteToTunnelV6(packet, addr) => {
if peer.is_allowed_ip(addr) {
iface.write6(packet);
}
}
};
if flush {
// Flush pending queue
while let TunnResult::WriteToNetwork(packet) =
peer.tunnel.decapsulate(None, &[], &mut t.dst_buf[..])
{
udp.write(packet);
}
}
iter -= 1;
if iter == 0 {
break;
}
}
Action::Continue
}),
)?;
Ok(())
}
fn register_iface_handler(&self, iface: Arc<T>) -> Result<(), Error> {
self.queue.new_event(
iface.as_raw_fd(),
Box::new(move |d, t| {
// The iface_handler handles packets received from the WireGuard virtual network
// interface. The flow is as follows:
// * Read a packet
// * Determine peer based on packet destination ip
// * Encapsulate the packet for the given peer
// * Send encapsulated packet to the peer's endpoint
let mtu = d.mtu.load(Ordering::Relaxed);
let udp4 = d.udp4.as_ref().expect("Not connected");
let udp6 = d.udp6.as_ref().expect("Not connected");
let peers = &d.peers_by_ip;
for _ in 0..MAX_ITR {
let src = match iface.read(&mut t.src_buf[..mtu]) {
Ok(src) => src,
Err(Error::IfaceRead(errno)) => {
let ek = io::Error::from_raw_os_error(errno).kind();
if ek == io::ErrorKind::Interrupted || ek == io::ErrorKind::WouldBlock {
break;
}
eprintln!("Fatal read error on tun interface: errno {:?}", errno);
return Action::Exit;
}
Err(e) => {
eprintln!("Unexpected error on tun interface: {:?}", e);
return Action::Exit;
}
};
let dst_addr = match Tunn::dst_address(src) {
Some(addr) => addr,
None => continue,
};
let peer = match peers.find(dst_addr) {
Some(peer) => peer,
None => continue,
};
match peer.tunnel.encapsulate(src, &mut t.dst_buf[..]) {
TunnResult::Done => {}
TunnResult::Err(e) => error!(d.config.logger, "Encapsulate error {:?}", e),
TunnResult::WriteToNetwork(packet) => {
let endpoint = peer.endpoint();
if let Some(ref conn) = endpoint.conn {
// Prefer to send using the connected socket
conn.write(packet);
} else if let Some(addr @ SocketAddr::V4(_)) = endpoint.addr {
udp4.sendto(packet, addr);
} else if let Some(addr @ SocketAddr::V6(_)) = endpoint.addr {
udp6.sendto(packet, addr);
} else {
error!(d.config.logger, "No endpoint");
}
}
_ => panic!("Unexpected result from encapsulate"),
};
}
Action::Continue
}),
)?;
Ok(())
}
} | |
acados_sim.py | # -*- coding: future_fstrings -*-
#
# Copyright 2019 Gianluca Frison, Dimitris Kouzoupis, Robin Verschueren,
# Andrea Zanelli, Niels van Duijkeren, Jonathan Frey, Tommaso Sartor,
# Branimir Novoselnik, Rien Quirynen, Rezart Qelibari, Dang Doan,
# Jonas Koenemann, Yutao Chen, Tobias Schöls, Jonas Schlagenhauf, Moritz Diehl
#
# This file is part of acados.
#
# The 2-Clause BSD License
#
# 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.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 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 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 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 DAMAGE.;
#
import numpy as np
import casadi as ca
import os
from .acados_model import AcadosModel
from .utils import get_acados_path, get_lib_ext
class AcadosSimDims:
"""
Class containing the dimensions of the model to be simulated.
"""
def __init__(self):
self.__nx = None
self.__nu = None
self.__nz = 0
self.__np = 0
@property
def nx(self):
""":math:`n_x` - number of states. Type: int > 0"""
return self.__nx
@property
def nz(self):
""":math:`n_z` - number of algebraic variables. Type: int >= 0"""
return self.__nz
@property
def nu(self):
""":math:`n_u` - number of inputs. Type: int >= 0"""
return self.__nu
@property
def np(self):
""":math:`n_p` - number of parameters. Type: int >= 0"""
return self.__np
@nx.setter
def nx(self, nx):
if isinstance(nx, int) and nx > 0:
self.__nx = nx
else:
raise Exception('Invalid nx value, expected positive integer.')
@nz.setter
def nz(self, nz):
if isinstance(nz, int) and nz > -1:
self.__nz = nz
else:
raise Exception('Invalid nz value, expected nonnegative integer.')
@nu.setter
def nu(self, nu):
if isinstance(nu, int) and nu > -1:
self.__nu = nu
else:
raise Exception('Invalid nu value, expected nonnegative integer.')
@np.setter
def np(self, np):
if isinstance(np, int) and np > -1:
self.__np = np
else:
raise Exception('Invalid np value, expected nonnegative integer.')
def set(self, attr, value):
setattr(self, attr, value)
class AcadosSimOpts:
"""
class containing the solver options
"""
def __init__(self):
self.__integrator_type = 'ERK'
self.__collocation_type = 'GAUSS_LEGENDRE'
self.__Tsim = None
# ints
self.__sim_method_num_stages = 1
self.__sim_method_num_steps = 1
self.__sim_method_newton_iter = 3
# bools
self.__sens_forw = True
self.__sens_adj = False
self.__sens_algebraic = False
self.__sens_hess = False
self.__output_z = False
self.__sim_method_jac_reuse = 0
@property
def integrator_type(self): | def num_stages(self):
"""Number of stages in the integrator. Default: 1"""
return self.__sim_method_num_stages
@property
def num_steps(self):
"""Number of steps in the integrator. Default: 1"""
return self.__sim_method_num_steps
@property
def newton_iter(self):
"""Number of Newton iterations in simulation method. Default: 3"""
return self.__sim_method_newton_iter
@property
def sens_forw(self):
"""Boolean determining if forward sensitivities are computed. Default: True"""
return self.__sens_forw
@property
def sens_adj(self):
"""Boolean determining if adjoint sensitivities are computed. Default: False"""
return self.__sens_adj
@property
def sens_algebraic(self):
"""Boolean determining if sensitivities wrt algebraic variables are computed. Default: False"""
return self.__sens_algebraic
@property
def sens_hess(self):
"""Boolean determining if hessians are computed. Default: False"""
return self.__sens_hess
@property
def output_z(self):
"""Boolean determining if values for algebraic variables (corresponding to start of simulation interval) are computed. Default: False"""
return self.__output_z
@property
def sim_method_jac_reuse(self):
"""Integer determining if jacobians are reused (0 or 1). Default: 0"""
return self.__sim_method_jac_reuse
@property
def T(self):
"""Time horizon"""
return self.__Tsim
@property
def collocation_type(self):
"""Collocation type: relevant for implicit integrators
-- string in {GAUSS_RADAU_IIA, GAUSS_LEGENDRE}
Default: GAUSS_LEGENDRE
"""
return self.__collocation_type
@integrator_type.setter
def integrator_type(self, integrator_type):
integrator_types = ('ERK', 'IRK', 'GNSF')
if integrator_type in integrator_types:
self.__integrator_type = integrator_type
else:
raise Exception('Invalid integrator_type value. Possible values are:\n\n' \
+ ',\n'.join(integrator_types) + '.\n\nYou have: ' + integrator_type + '.\n\n')
@collocation_type.setter
def collocation_type(self, collocation_type):
collocation_types = ('GAUSS_RADAU_IIA', 'GAUSS_LEGENDRE')
if collocation_type in collocation_types:
self.__collocation_type = collocation_type
else:
raise Exception('Invalid collocation_type value. Possible values are:\n\n' \
+ ',\n'.join(collocation_types) + '.\n\nYou have: ' + collocation_type + '.\n\n')
@T.setter
def T(self, T):
self.__Tsim = T
@num_stages.setter
def num_stages(self, num_stages):
if isinstance(num_stages, int):
self.__sim_method_num_stages = num_stages
else:
raise Exception('Invalid num_stages value. num_stages must be an integer.')
@num_steps.setter
def num_steps(self, num_steps):
if isinstance(num_steps, int):
self.__sim_method_num_steps = num_steps
else:
raise Exception('Invalid num_steps value. num_steps must be an integer.')
@newton_iter.setter
def newton_iter(self, newton_iter):
if isinstance(newton_iter, int):
self.__sim_method_newton_iter = newton_iter
else:
raise Exception('Invalid newton_iter value. newton_iter must be an integer.')
@sens_forw.setter
def sens_forw(self, sens_forw):
if sens_forw in (True, False):
self.__sens_forw = sens_forw
else:
raise Exception('Invalid sens_forw value. sens_forw must be a Boolean.')
@sens_adj.setter
def sens_adj(self, sens_adj):
if sens_adj in (True, False):
self.__sens_adj = sens_adj
else:
raise Exception('Invalid sens_adj value. sens_adj must be a Boolean.')
@sens_hess.setter
def sens_hess(self, sens_hess):
if sens_hess in (True, False):
self.__sens_hess = sens_hess
else:
raise Exception('Invalid sens_hess value. sens_hess must be a Boolean.')
@sens_algebraic.setter
def sens_algebraic(self, sens_algebraic):
if sens_algebraic in (True, False):
self.__sens_algebraic = sens_algebraic
else:
raise Exception('Invalid sens_algebraic value. sens_algebraic must be a Boolean.')
@output_z.setter
def output_z(self, output_z):
if output_z in (True, False):
self.__output_z = output_z
else:
raise Exception('Invalid output_z value. output_z must be a Boolean.')
@sim_method_jac_reuse.setter
def sim_method_jac_reuse(self, sim_method_jac_reuse):
if sim_method_jac_reuse in (0, 1):
self.__sim_method_jac_reuse = sim_method_jac_reuse
else:
raise Exception('Invalid sim_method_jac_reuse value. sim_method_jac_reuse must be 0 or 1.')
class AcadosSim:
"""
The class has the following properties that can be modified to formulate a specific simulation problem, see below:
:param acados_path: string with the path to acados. It is used to generate the include and lib paths.
- :py:attr:`dims` of type :py:class:`acados_template.acados_ocp.AcadosSimDims` - are automatically detected from model
- :py:attr:`model` of type :py:class:`acados_template.acados_model.AcadosModel`
- :py:attr:`solver_options` of type :py:class:`acados_template.acados_sim.AcadosSimOpts`
- :py:attr:`acados_include_path` (set automatically)
- :py:attr:`shared_lib_ext` (set automatically)
- :py:attr:`acados_lib_path` (set automatically)
- :py:attr:`parameter_values` - used to initialize the parameters (can be changed)
"""
def __init__(self, acados_path=''):
if acados_path == '':
acados_path = get_acados_path()
self.dims = AcadosSimDims()
"""Dimension definitions, automatically detected from :py:attr:`model`. Type :py:class:`acados_template.acados_sim.AcadosSimDims`"""
self.model = AcadosModel()
"""Model definitions, type :py:class:`acados_template.acados_model.AcadosModel`"""
self.solver_options = AcadosSimOpts()
"""Solver Options, type :py:class:`acados_template.acados_sim.AcadosSimOpts`"""
self.acados_include_path = os.path.join(acados_path, 'include').replace(os.sep, '/') # the replace part is important on Windows for CMake
"""Path to acados include directory (set automatically), type: `string`"""
self.acados_lib_path = os.path.join(acados_path, 'lib').replace(os.sep, '/') # the replace part is important on Windows for CMake
"""Path to where acados library is located (set automatically), type: `string`"""
self.code_export_directory = 'c_generated_code'
"""Path to where code will be exported. Default: `c_generated_code`."""
self.shared_lib_ext = get_lib_ext()
self.cython_include_dirs = ''
self.__parameter_values = np.array([])
@property
def parameter_values(self):
""":math:`p` - initial values for parameter - can be updated"""
return self.__parameter_values
@parameter_values.setter
def parameter_values(self, parameter_values):
if isinstance(parameter_values, np.ndarray):
self.__parameter_values = parameter_values
else:
raise Exception('Invalid parameter_values value. ' +
f'Expected numpy array, got {type(parameter_values)}.')
def set(self, attr, value):
# tokenize string
tokens = attr.split('_', 1)
if len(tokens) > 1:
setter_to_call = getattr(getattr(self, tokens[0]), 'set')
else:
setter_to_call = getattr(self, 'set')
setter_to_call(tokens[1], value)
return | """Integrator type. Default: 'ERK'."""
return self.__integrator_type
@property |
locationSmb.go | // *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
package datasync
import (
"reflect"
"github.com/pkg/errors"
"github.com/pulumi/pulumi/sdk/go/pulumi"
)
// Manages a SMB Location within AWS DataSync.
//
// > **NOTE:** The DataSync Agents must be available before creating this resource.
type LocationSmb struct {
pulumi.CustomResourceState
// A list of DataSync Agent ARNs with which this location will be associated.
AgentArns pulumi.StringArrayOutput `pulumi:"agentArns"`
// Amazon Resource Name (ARN) of the DataSync Location.
Arn pulumi.StringOutput `pulumi:"arn"`
// The name of the Windows domain the SMB server belongs to.
Domain pulumi.StringOutput `pulumi:"domain"`
// Configuration block containing mount options used by DataSync to access the SMB Server. Can be `AUTOMATIC`, `SMB2`, or `SMB3`.
MountOptions LocationSmbMountOptionsPtrOutput `pulumi:"mountOptions"`
// The password of the user who can mount the share and has file permissions in the SMB.
Password pulumi.StringOutput `pulumi:"password"`
// Specifies the IP address or DNS name of the SMB server. The DataSync Agent(s) use this to mount the SMB share.
ServerHostname pulumi.StringOutput `pulumi:"serverHostname"`
// Subdirectory to perform actions as source or destination. Should be exported by the NFS server.
Subdirectory pulumi.StringOutput `pulumi:"subdirectory"`
// Key-value pairs of resource tags to assign to the DataSync Location.
Tags pulumi.MapOutput `pulumi:"tags"`
Uri pulumi.StringOutput `pulumi:"uri"`
// The user who can mount the share and has file and folder permissions in the SMB share.
User pulumi.StringOutput `pulumi:"user"`
}
// NewLocationSmb registers a new resource with the given unique name, arguments, and options.
func NewLocationSmb(ctx *pulumi.Context,
name string, args *LocationSmbArgs, opts ...pulumi.ResourceOption) (*LocationSmb, error) |
// GetLocationSmb gets an existing LocationSmb resource's state with the given name, ID, and optional
// state properties that are used to uniquely qualify the lookup (nil if not required).
func GetLocationSmb(ctx *pulumi.Context,
name string, id pulumi.IDInput, state *LocationSmbState, opts ...pulumi.ResourceOption) (*LocationSmb, error) {
var resource LocationSmb
err := ctx.ReadResource("aws:datasync/locationSmb:LocationSmb", name, id, state, &resource, opts...)
if err != nil {
return nil, err
}
return &resource, nil
}
// Input properties used for looking up and filtering LocationSmb resources.
type locationSmbState struct {
// A list of DataSync Agent ARNs with which this location will be associated.
AgentArns []string `pulumi:"agentArns"`
// Amazon Resource Name (ARN) of the DataSync Location.
Arn *string `pulumi:"arn"`
// The name of the Windows domain the SMB server belongs to.
Domain *string `pulumi:"domain"`
// Configuration block containing mount options used by DataSync to access the SMB Server. Can be `AUTOMATIC`, `SMB2`, or `SMB3`.
MountOptions *LocationSmbMountOptions `pulumi:"mountOptions"`
// The password of the user who can mount the share and has file permissions in the SMB.
Password *string `pulumi:"password"`
// Specifies the IP address or DNS name of the SMB server. The DataSync Agent(s) use this to mount the SMB share.
ServerHostname *string `pulumi:"serverHostname"`
// Subdirectory to perform actions as source or destination. Should be exported by the NFS server.
Subdirectory *string `pulumi:"subdirectory"`
// Key-value pairs of resource tags to assign to the DataSync Location.
Tags map[string]interface{} `pulumi:"tags"`
Uri *string `pulumi:"uri"`
// The user who can mount the share and has file and folder permissions in the SMB share.
User *string `pulumi:"user"`
}
type LocationSmbState struct {
// A list of DataSync Agent ARNs with which this location will be associated.
AgentArns pulumi.StringArrayInput
// Amazon Resource Name (ARN) of the DataSync Location.
Arn pulumi.StringPtrInput
// The name of the Windows domain the SMB server belongs to.
Domain pulumi.StringPtrInput
// Configuration block containing mount options used by DataSync to access the SMB Server. Can be `AUTOMATIC`, `SMB2`, or `SMB3`.
MountOptions LocationSmbMountOptionsPtrInput
// The password of the user who can mount the share and has file permissions in the SMB.
Password pulumi.StringPtrInput
// Specifies the IP address or DNS name of the SMB server. The DataSync Agent(s) use this to mount the SMB share.
ServerHostname pulumi.StringPtrInput
// Subdirectory to perform actions as source or destination. Should be exported by the NFS server.
Subdirectory pulumi.StringPtrInput
// Key-value pairs of resource tags to assign to the DataSync Location.
Tags pulumi.MapInput
Uri pulumi.StringPtrInput
// The user who can mount the share and has file and folder permissions in the SMB share.
User pulumi.StringPtrInput
}
func (LocationSmbState) ElementType() reflect.Type {
return reflect.TypeOf((*locationSmbState)(nil)).Elem()
}
type locationSmbArgs struct {
// A list of DataSync Agent ARNs with which this location will be associated.
AgentArns []string `pulumi:"agentArns"`
// The name of the Windows domain the SMB server belongs to.
Domain *string `pulumi:"domain"`
// Configuration block containing mount options used by DataSync to access the SMB Server. Can be `AUTOMATIC`, `SMB2`, or `SMB3`.
MountOptions *LocationSmbMountOptions `pulumi:"mountOptions"`
// The password of the user who can mount the share and has file permissions in the SMB.
Password string `pulumi:"password"`
// Specifies the IP address or DNS name of the SMB server. The DataSync Agent(s) use this to mount the SMB share.
ServerHostname string `pulumi:"serverHostname"`
// Subdirectory to perform actions as source or destination. Should be exported by the NFS server.
Subdirectory string `pulumi:"subdirectory"`
// Key-value pairs of resource tags to assign to the DataSync Location.
Tags map[string]interface{} `pulumi:"tags"`
// The user who can mount the share and has file and folder permissions in the SMB share.
User string `pulumi:"user"`
}
// The set of arguments for constructing a LocationSmb resource.
type LocationSmbArgs struct {
// A list of DataSync Agent ARNs with which this location will be associated.
AgentArns pulumi.StringArrayInput
// The name of the Windows domain the SMB server belongs to.
Domain pulumi.StringPtrInput
// Configuration block containing mount options used by DataSync to access the SMB Server. Can be `AUTOMATIC`, `SMB2`, or `SMB3`.
MountOptions LocationSmbMountOptionsPtrInput
// The password of the user who can mount the share and has file permissions in the SMB.
Password pulumi.StringInput
// Specifies the IP address or DNS name of the SMB server. The DataSync Agent(s) use this to mount the SMB share.
ServerHostname pulumi.StringInput
// Subdirectory to perform actions as source or destination. Should be exported by the NFS server.
Subdirectory pulumi.StringInput
// Key-value pairs of resource tags to assign to the DataSync Location.
Tags pulumi.MapInput
// The user who can mount the share and has file and folder permissions in the SMB share.
User pulumi.StringInput
}
func (LocationSmbArgs) ElementType() reflect.Type {
return reflect.TypeOf((*locationSmbArgs)(nil)).Elem()
}
| {
if args == nil || args.AgentArns == nil {
return nil, errors.New("missing required argument 'AgentArns'")
}
if args == nil || args.Password == nil {
return nil, errors.New("missing required argument 'Password'")
}
if args == nil || args.ServerHostname == nil {
return nil, errors.New("missing required argument 'ServerHostname'")
}
if args == nil || args.Subdirectory == nil {
return nil, errors.New("missing required argument 'Subdirectory'")
}
if args == nil || args.User == nil {
return nil, errors.New("missing required argument 'User'")
}
if args == nil {
args = &LocationSmbArgs{}
}
var resource LocationSmb
err := ctx.RegisterResource("aws:datasync/locationSmb:LocationSmb", name, args, &resource, opts...)
if err != nil {
return nil, err
}
return &resource, nil
} |
app.homes.js | (function () {
'use strict'; | angular.module('com.module.homes', []);
})(); |
|
attr_value.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.27.1
// protoc v3.20.0--rc2
// source: tensorflow/core/framework/attr_value.proto
package attr_value_go_proto
import (
tensor_go_proto "github.com/wamuir/graft/tensorflow/core/framework/tensor_go_proto"
tensor_shape_go_proto "github.com/wamuir/graft/tensorflow/core/framework/tensor_shape_go_proto"
types_go_proto "github.com/wamuir/graft/tensorflow/core/framework/types_go_proto"
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
// Protocol buffer representing the value for an attr used to configure an Op.
// Comment indicates the corresponding attr type. Only the field matching the
// attr type may be filled.
type AttrValue struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// Types that are assignable to Value:
// *AttrValue_S
// *AttrValue_I
// *AttrValue_F
// *AttrValue_B
// *AttrValue_Type
// *AttrValue_Shape
// *AttrValue_Tensor
// *AttrValue_List
// *AttrValue_Func
// *AttrValue_Placeholder
Value isAttrValue_Value `protobuf_oneof:"value"`
}
func (x *AttrValue) Reset() {
*x = AttrValue{}
if protoimpl.UnsafeEnabled |
}
func (x *AttrValue) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AttrValue) ProtoMessage() {}
func (x *AttrValue) ProtoReflect() protoreflect.Message {
mi := &file_tensorflow_core_framework_attr_value_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AttrValue.ProtoReflect.Descriptor instead.
func (*AttrValue) Descriptor() ([]byte, []int) {
return file_tensorflow_core_framework_attr_value_proto_rawDescGZIP(), []int{0}
}
func (m *AttrValue) GetValue() isAttrValue_Value {
if m != nil {
return m.Value
}
return nil
}
func (x *AttrValue) GetS() []byte {
if x, ok := x.GetValue().(*AttrValue_S); ok {
return x.S
}
return nil
}
func (x *AttrValue) GetI() int64 {
if x, ok := x.GetValue().(*AttrValue_I); ok {
return x.I
}
return 0
}
func (x *AttrValue) GetF() float32 {
if x, ok := x.GetValue().(*AttrValue_F); ok {
return x.F
}
return 0
}
func (x *AttrValue) GetB() bool {
if x, ok := x.GetValue().(*AttrValue_B); ok {
return x.B
}
return false
}
func (x *AttrValue) GetType() types_go_proto.DataType {
if x, ok := x.GetValue().(*AttrValue_Type); ok {
return x.Type
}
return types_go_proto.DataType(0)
}
func (x *AttrValue) GetShape() *tensor_shape_go_proto.TensorShapeProto {
if x, ok := x.GetValue().(*AttrValue_Shape); ok {
return x.Shape
}
return nil
}
func (x *AttrValue) GetTensor() *tensor_go_proto.TensorProto {
if x, ok := x.GetValue().(*AttrValue_Tensor); ok {
return x.Tensor
}
return nil
}
func (x *AttrValue) GetList() *AttrValue_ListValue {
if x, ok := x.GetValue().(*AttrValue_List); ok {
return x.List
}
return nil
}
func (x *AttrValue) GetFunc() *NameAttrList {
if x, ok := x.GetValue().(*AttrValue_Func); ok {
return x.Func
}
return nil
}
func (x *AttrValue) GetPlaceholder() string {
if x, ok := x.GetValue().(*AttrValue_Placeholder); ok {
return x.Placeholder
}
return ""
}
type isAttrValue_Value interface {
isAttrValue_Value()
}
type AttrValue_S struct {
S []byte `protobuf:"bytes,2,opt,name=s,proto3,oneof"` // "string"
}
type AttrValue_I struct {
I int64 `protobuf:"varint,3,opt,name=i,proto3,oneof"` // "int"
}
type AttrValue_F struct {
F float32 `protobuf:"fixed32,4,opt,name=f,proto3,oneof"` // "float"
}
type AttrValue_B struct {
B bool `protobuf:"varint,5,opt,name=b,proto3,oneof"` // "bool"
}
type AttrValue_Type struct {
Type types_go_proto.DataType `protobuf:"varint,6,opt,name=type,proto3,enum=tensorflow.DataType,oneof"` // "type"
}
type AttrValue_Shape struct {
Shape *tensor_shape_go_proto.TensorShapeProto `protobuf:"bytes,7,opt,name=shape,proto3,oneof"` // "shape"
}
type AttrValue_Tensor struct {
Tensor *tensor_go_proto.TensorProto `protobuf:"bytes,8,opt,name=tensor,proto3,oneof"` // "tensor"
}
type AttrValue_List struct {
List *AttrValue_ListValue `protobuf:"bytes,1,opt,name=list,proto3,oneof"` // any "list(...)"
}
type AttrValue_Func struct {
// "func" represents a function. func.name is a function's name or
// a primitive op's name. func.attr.first is the name of an attr
// defined for that function. func.attr.second is the value for
// that attr in the instantiation.
Func *NameAttrList `protobuf:"bytes,10,opt,name=func,proto3,oneof"`
}
type AttrValue_Placeholder struct {
// This is a placeholder only used in nodes defined inside a
// function. It indicates the attr value will be supplied when
// the function is instantiated. For example, let us suppose a
// node "N" in function "FN". "N" has an attr "A" with value
// placeholder = "foo". When FN is instantiated with attr "foo"
// set to "bar", the instantiated node N's attr A will have been
// given the value "bar".
Placeholder string `protobuf:"bytes,9,opt,name=placeholder,proto3,oneof"`
}
func (*AttrValue_S) isAttrValue_Value() {}
func (*AttrValue_I) isAttrValue_Value() {}
func (*AttrValue_F) isAttrValue_Value() {}
func (*AttrValue_B) isAttrValue_Value() {}
func (*AttrValue_Type) isAttrValue_Value() {}
func (*AttrValue_Shape) isAttrValue_Value() {}
func (*AttrValue_Tensor) isAttrValue_Value() {}
func (*AttrValue_List) isAttrValue_Value() {}
func (*AttrValue_Func) isAttrValue_Value() {}
func (*AttrValue_Placeholder) isAttrValue_Value() {}
// A list of attr names and their values. The whole list is attached
// with a string name. E.g., MatMul[T=float].
type NameAttrList struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
Attr map[string]*AttrValue `protobuf:"bytes,2,rep,name=attr,proto3" json:"attr,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
}
func (x *NameAttrList) Reset() {
*x = NameAttrList{}
if protoimpl.UnsafeEnabled {
mi := &file_tensorflow_core_framework_attr_value_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *NameAttrList) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*NameAttrList) ProtoMessage() {}
func (x *NameAttrList) ProtoReflect() protoreflect.Message {
mi := &file_tensorflow_core_framework_attr_value_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use NameAttrList.ProtoReflect.Descriptor instead.
func (*NameAttrList) Descriptor() ([]byte, []int) {
return file_tensorflow_core_framework_attr_value_proto_rawDescGZIP(), []int{1}
}
func (x *NameAttrList) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *NameAttrList) GetAttr() map[string]*AttrValue {
if x != nil {
return x.Attr
}
return nil
}
// LINT.IfChange
type AttrValue_ListValue struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
S [][]byte `protobuf:"bytes,2,rep,name=s,proto3" json:"s,omitempty"` // "list(string)"
I []int64 `protobuf:"varint,3,rep,packed,name=i,proto3" json:"i,omitempty"` // "list(int)"
F []float32 `protobuf:"fixed32,4,rep,packed,name=f,proto3" json:"f,omitempty"` // "list(float)"
B []bool `protobuf:"varint,5,rep,packed,name=b,proto3" json:"b,omitempty"` // "list(bool)"
Type []types_go_proto.DataType `protobuf:"varint,6,rep,packed,name=type,proto3,enum=tensorflow.DataType" json:"type,omitempty"` // "list(type)"
Shape []*tensor_shape_go_proto.TensorShapeProto `protobuf:"bytes,7,rep,name=shape,proto3" json:"shape,omitempty"` // "list(shape)"
Tensor []*tensor_go_proto.TensorProto `protobuf:"bytes,8,rep,name=tensor,proto3" json:"tensor,omitempty"` // "list(tensor)"
Func []*NameAttrList `protobuf:"bytes,9,rep,name=func,proto3" json:"func,omitempty"` // "list(attr)"
}
func (x *AttrValue_ListValue) Reset() {
*x = AttrValue_ListValue{}
if protoimpl.UnsafeEnabled {
mi := &file_tensorflow_core_framework_attr_value_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *AttrValue_ListValue) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AttrValue_ListValue) ProtoMessage() {}
func (x *AttrValue_ListValue) ProtoReflect() protoreflect.Message {
mi := &file_tensorflow_core_framework_attr_value_proto_msgTypes[2]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AttrValue_ListValue.ProtoReflect.Descriptor instead.
func (*AttrValue_ListValue) Descriptor() ([]byte, []int) {
return file_tensorflow_core_framework_attr_value_proto_rawDescGZIP(), []int{0, 0}
}
func (x *AttrValue_ListValue) GetS() [][]byte {
if x != nil {
return x.S
}
return nil
}
func (x *AttrValue_ListValue) GetI() []int64 {
if x != nil {
return x.I
}
return nil
}
func (x *AttrValue_ListValue) GetF() []float32 {
if x != nil {
return x.F
}
return nil
}
func (x *AttrValue_ListValue) GetB() []bool {
if x != nil {
return x.B
}
return nil
}
func (x *AttrValue_ListValue) GetType() []types_go_proto.DataType {
if x != nil {
return x.Type
}
return nil
}
func (x *AttrValue_ListValue) GetShape() []*tensor_shape_go_proto.TensorShapeProto {
if x != nil {
return x.Shape
}
return nil
}
func (x *AttrValue_ListValue) GetTensor() []*tensor_go_proto.TensorProto {
if x != nil {
return x.Tensor
}
return nil
}
func (x *AttrValue_ListValue) GetFunc() []*NameAttrList {
if x != nil {
return x.Func
}
return nil
}
var File_tensorflow_core_framework_attr_value_proto protoreflect.FileDescriptor
var file_tensorflow_core_framework_attr_value_proto_rawDesc = []byte{
0x0a, 0x2a, 0x74, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x66, 0x6c, 0x6f, 0x77, 0x2f, 0x63, 0x6f, 0x72,
0x65, 0x2f, 0x66, 0x72, 0x61, 0x6d, 0x65, 0x77, 0x6f, 0x72, 0x6b, 0x2f, 0x61, 0x74, 0x74, 0x72,
0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0a, 0x74, 0x65,
0x6e, 0x73, 0x6f, 0x72, 0x66, 0x6c, 0x6f, 0x77, 0x1a, 0x26, 0x74, 0x65, 0x6e, 0x73, 0x6f, 0x72,
0x66, 0x6c, 0x6f, 0x77, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x66, 0x72, 0x61, 0x6d, 0x65, 0x77,
0x6f, 0x72, 0x6b, 0x2f, 0x74, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f,
0x1a, 0x2c, 0x74, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x66, 0x6c, 0x6f, 0x77, 0x2f, 0x63, 0x6f, 0x72,
0x65, 0x2f, 0x66, 0x72, 0x61, 0x6d, 0x65, 0x77, 0x6f, 0x72, 0x6b, 0x2f, 0x74, 0x65, 0x6e, 0x73,
0x6f, 0x72, 0x5f, 0x73, 0x68, 0x61, 0x70, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x25,
0x74, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x66, 0x6c, 0x6f, 0x77, 0x2f, 0x63, 0x6f, 0x72, 0x65, 0x2f,
0x66, 0x72, 0x61, 0x6d, 0x65, 0x77, 0x6f, 0x72, 0x6b, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2e,
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x87, 0x05, 0x0a, 0x09, 0x41, 0x74, 0x74, 0x72, 0x56, 0x61,
0x6c, 0x75, 0x65, 0x12, 0x0e, 0x0a, 0x01, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x48, 0x00,
0x52, 0x01, 0x73, 0x12, 0x0e, 0x0a, 0x01, 0x69, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x48, 0x00,
0x52, 0x01, 0x69, 0x12, 0x0e, 0x0a, 0x01, 0x66, 0x18, 0x04, 0x20, 0x01, 0x28, 0x02, 0x48, 0x00,
0x52, 0x01, 0x66, 0x12, 0x0e, 0x0a, 0x01, 0x62, 0x18, 0x05, 0x20, 0x01, 0x28, 0x08, 0x48, 0x00,
0x52, 0x01, 0x62, 0x12, 0x2a, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28,
0x0e, 0x32, 0x14, 0x2e, 0x74, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x44,
0x61, 0x74, 0x61, 0x54, 0x79, 0x70, 0x65, 0x48, 0x00, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65, 0x12,
0x34, 0x0a, 0x05, 0x73, 0x68, 0x61, 0x70, 0x65, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c,
0x2e, 0x74, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x54, 0x65, 0x6e, 0x73,
0x6f, 0x72, 0x53, 0x68, 0x61, 0x70, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x48, 0x00, 0x52, 0x05,
0x73, 0x68, 0x61, 0x70, 0x65, 0x12, 0x31, 0x0a, 0x06, 0x74, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x18,
0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x74, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x66, 0x6c,
0x6f, 0x77, 0x2e, 0x54, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x48, 0x00,
0x52, 0x06, 0x74, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x12, 0x35, 0x0a, 0x04, 0x6c, 0x69, 0x73, 0x74,
0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1f, 0x2e, 0x74, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x66,
0x6c, 0x6f, 0x77, 0x2e, 0x41, 0x74, 0x74, 0x72, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x2e, 0x4c, 0x69,
0x73, 0x74, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x48, 0x00, 0x52, 0x04, 0x6c, 0x69, 0x73, 0x74, 0x12,
0x2e, 0x0a, 0x04, 0x66, 0x75, 0x6e, 0x63, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x18, 0x2e,
0x74, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x4e, 0x61, 0x6d, 0x65, 0x41,
0x74, 0x74, 0x72, 0x4c, 0x69, 0x73, 0x74, 0x48, 0x00, 0x52, 0x04, 0x66, 0x75, 0x6e, 0x63, 0x12,
0x22, 0x0a, 0x0b, 0x70, 0x6c, 0x61, 0x63, 0x65, 0x68, 0x6f, 0x6c, 0x64, 0x65, 0x72, 0x18, 0x09,
0x20, 0x01, 0x28, 0x09, 0x48, 0x00, 0x52, 0x0b, 0x70, 0x6c, 0x61, 0x63, 0x65, 0x68, 0x6f, 0x6c,
0x64, 0x65, 0x72, 0x1a, 0x90, 0x02, 0x0a, 0x09, 0x4c, 0x69, 0x73, 0x74, 0x56, 0x61, 0x6c, 0x75,
0x65, 0x12, 0x0c, 0x0a, 0x01, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x01, 0x73, 0x12,
0x10, 0x0a, 0x01, 0x69, 0x18, 0x03, 0x20, 0x03, 0x28, 0x03, 0x42, 0x02, 0x10, 0x01, 0x52, 0x01,
0x69, 0x12, 0x10, 0x0a, 0x01, 0x66, 0x18, 0x04, 0x20, 0x03, 0x28, 0x02, 0x42, 0x02, 0x10, 0x01,
0x52, 0x01, 0x66, 0x12, 0x10, 0x0a, 0x01, 0x62, 0x18, 0x05, 0x20, 0x03, 0x28, 0x08, 0x42, 0x02,
0x10, 0x01, 0x52, 0x01, 0x62, 0x12, 0x2c, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x06, 0x20,
0x03, 0x28, 0x0e, 0x32, 0x14, 0x2e, 0x74, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x66, 0x6c, 0x6f, 0x77,
0x2e, 0x44, 0x61, 0x74, 0x61, 0x54, 0x79, 0x70, 0x65, 0x42, 0x02, 0x10, 0x01, 0x52, 0x04, 0x74,
0x79, 0x70, 0x65, 0x12, 0x32, 0x0a, 0x05, 0x73, 0x68, 0x61, 0x70, 0x65, 0x18, 0x07, 0x20, 0x03,
0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x74, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x66, 0x6c, 0x6f, 0x77, 0x2e,
0x54, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x53, 0x68, 0x61, 0x70, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f,
0x52, 0x05, 0x73, 0x68, 0x61, 0x70, 0x65, 0x12, 0x2f, 0x0a, 0x06, 0x74, 0x65, 0x6e, 0x73, 0x6f,
0x72, 0x18, 0x08, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x17, 0x2e, 0x74, 0x65, 0x6e, 0x73, 0x6f, 0x72,
0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x54, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x50, 0x72, 0x6f, 0x74, 0x6f,
0x52, 0x06, 0x74, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x12, 0x2c, 0x0a, 0x04, 0x66, 0x75, 0x6e, 0x63,
0x18, 0x09, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x18, 0x2e, 0x74, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x66,
0x6c, 0x6f, 0x77, 0x2e, 0x4e, 0x61, 0x6d, 0x65, 0x41, 0x74, 0x74, 0x72, 0x4c, 0x69, 0x73, 0x74,
0x52, 0x04, 0x66, 0x75, 0x6e, 0x63, 0x42, 0x07, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22,
0xaa, 0x01, 0x0a, 0x0c, 0x4e, 0x61, 0x6d, 0x65, 0x41, 0x74, 0x74, 0x72, 0x4c, 0x69, 0x73, 0x74,
0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04,
0x6e, 0x61, 0x6d, 0x65, 0x12, 0x36, 0x0a, 0x04, 0x61, 0x74, 0x74, 0x72, 0x18, 0x02, 0x20, 0x03,
0x28, 0x0b, 0x32, 0x22, 0x2e, 0x74, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x66, 0x6c, 0x6f, 0x77, 0x2e,
0x4e, 0x61, 0x6d, 0x65, 0x41, 0x74, 0x74, 0x72, 0x4c, 0x69, 0x73, 0x74, 0x2e, 0x41, 0x74, 0x74,
0x72, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x04, 0x61, 0x74, 0x74, 0x72, 0x1a, 0x4e, 0x0a, 0x09,
0x41, 0x74, 0x74, 0x72, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79,
0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x2b, 0x0a, 0x05, 0x76,
0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x15, 0x2e, 0x74, 0x65, 0x6e,
0x73, 0x6f, 0x72, 0x66, 0x6c, 0x6f, 0x77, 0x2e, 0x41, 0x74, 0x74, 0x72, 0x56, 0x61, 0x6c, 0x75,
0x65, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x42, 0x83, 0x01, 0x0a,
0x18, 0x6f, 0x72, 0x67, 0x2e, 0x74, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x66, 0x6c, 0x6f, 0x77, 0x2e,
0x66, 0x72, 0x61, 0x6d, 0x65, 0x77, 0x6f, 0x72, 0x6b, 0x42, 0x0f, 0x41, 0x74, 0x74, 0x72, 0x56,
0x61, 0x6c, 0x75, 0x65, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x73, 0x50, 0x01, 0x5a, 0x51, 0x67, 0x69,
0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x74, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x66,
0x6c, 0x6f, 0x77, 0x2f, 0x74, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x66, 0x6c, 0x6f, 0x77, 0x2f, 0x74,
0x65, 0x6e, 0x73, 0x6f, 0x72, 0x66, 0x6c, 0x6f, 0x77, 0x2f, 0x67, 0x6f, 0x2f, 0x63, 0x6f, 0x72,
0x65, 0x2f, 0x66, 0x72, 0x61, 0x6d, 0x65, 0x77, 0x6f, 0x72, 0x6b, 0x2f, 0x61, 0x74, 0x74, 0x72,
0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x5f, 0x67, 0x6f, 0x5f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0xf8,
0x01, 0x01, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_tensorflow_core_framework_attr_value_proto_rawDescOnce sync.Once
file_tensorflow_core_framework_attr_value_proto_rawDescData = file_tensorflow_core_framework_attr_value_proto_rawDesc
)
func file_tensorflow_core_framework_attr_value_proto_rawDescGZIP() []byte {
file_tensorflow_core_framework_attr_value_proto_rawDescOnce.Do(func() {
file_tensorflow_core_framework_attr_value_proto_rawDescData = protoimpl.X.CompressGZIP(file_tensorflow_core_framework_attr_value_proto_rawDescData)
})
return file_tensorflow_core_framework_attr_value_proto_rawDescData
}
var file_tensorflow_core_framework_attr_value_proto_msgTypes = make([]protoimpl.MessageInfo, 4)
var file_tensorflow_core_framework_attr_value_proto_goTypes = []interface{}{
(*AttrValue)(nil), // 0: tensorflow.AttrValue
(*NameAttrList)(nil), // 1: tensorflow.NameAttrList
(*AttrValue_ListValue)(nil), // 2: tensorflow.AttrValue.ListValue
nil, // 3: tensorflow.NameAttrList.AttrEntry
(types_go_proto.DataType)(0), // 4: tensorflow.DataType
(*tensor_shape_go_proto.TensorShapeProto)(nil), // 5: tensorflow.TensorShapeProto
(*tensor_go_proto.TensorProto)(nil), // 6: tensorflow.TensorProto
}
var file_tensorflow_core_framework_attr_value_proto_depIdxs = []int32{
4, // 0: tensorflow.AttrValue.type:type_name -> tensorflow.DataType
5, // 1: tensorflow.AttrValue.shape:type_name -> tensorflow.TensorShapeProto
6, // 2: tensorflow.AttrValue.tensor:type_name -> tensorflow.TensorProto
2, // 3: tensorflow.AttrValue.list:type_name -> tensorflow.AttrValue.ListValue
1, // 4: tensorflow.AttrValue.func:type_name -> tensorflow.NameAttrList
3, // 5: tensorflow.NameAttrList.attr:type_name -> tensorflow.NameAttrList.AttrEntry
4, // 6: tensorflow.AttrValue.ListValue.type:type_name -> tensorflow.DataType
5, // 7: tensorflow.AttrValue.ListValue.shape:type_name -> tensorflow.TensorShapeProto
6, // 8: tensorflow.AttrValue.ListValue.tensor:type_name -> tensorflow.TensorProto
1, // 9: tensorflow.AttrValue.ListValue.func:type_name -> tensorflow.NameAttrList
0, // 10: tensorflow.NameAttrList.AttrEntry.value:type_name -> tensorflow.AttrValue
11, // [11:11] is the sub-list for method output_type
11, // [11:11] is the sub-list for method input_type
11, // [11:11] is the sub-list for extension type_name
11, // [11:11] is the sub-list for extension extendee
0, // [0:11] is the sub-list for field type_name
}
func init() { file_tensorflow_core_framework_attr_value_proto_init() }
func file_tensorflow_core_framework_attr_value_proto_init() {
if File_tensorflow_core_framework_attr_value_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_tensorflow_core_framework_attr_value_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*AttrValue); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_tensorflow_core_framework_attr_value_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*NameAttrList); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_tensorflow_core_framework_attr_value_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*AttrValue_ListValue); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
file_tensorflow_core_framework_attr_value_proto_msgTypes[0].OneofWrappers = []interface{}{
(*AttrValue_S)(nil),
(*AttrValue_I)(nil),
(*AttrValue_F)(nil),
(*AttrValue_B)(nil),
(*AttrValue_Type)(nil),
(*AttrValue_Shape)(nil),
(*AttrValue_Tensor)(nil),
(*AttrValue_List)(nil),
(*AttrValue_Func)(nil),
(*AttrValue_Placeholder)(nil),
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_tensorflow_core_framework_attr_value_proto_rawDesc,
NumEnums: 0,
NumMessages: 4,
NumExtensions: 0,
NumServices: 0,
},
GoTypes: file_tensorflow_core_framework_attr_value_proto_goTypes,
DependencyIndexes: file_tensorflow_core_framework_attr_value_proto_depIdxs,
MessageInfos: file_tensorflow_core_framework_attr_value_proto_msgTypes,
}.Build()
File_tensorflow_core_framework_attr_value_proto = out.File
file_tensorflow_core_framework_attr_value_proto_rawDesc = nil
file_tensorflow_core_framework_attr_value_proto_goTypes = nil
file_tensorflow_core_framework_attr_value_proto_depIdxs = nil
}
| {
mi := &file_tensorflow_core_framework_attr_value_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
} |
main.go | package main
import (
"context"
"fmt"
"io/ioutil"
"math/rand"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
"github.com/alecthomas/kingpin"
"github.com/globalsign/mgo"
"github.com/percona/percona-backup-mongodb/grpc/client"
"github.com/percona/percona-backup-mongodb/internal/logger"
"github.com/percona/percona-backup-mongodb/internal/loghook"
"github.com/percona/percona-backup-mongodb/internal/utils"
"github.com/percona/percona-backup-mongodb/storage"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/encoding/gzip"
yaml "gopkg.in/yaml.v2"
)
type cliOptions struct {
app *kingpin.Application
configFile string
generateSampleConfig bool
DSN string `yaml:"dsn,omitempty" kingpin:"dsn"`
Debug bool `yaml:"debug,omitempty" kingpin:"debug"`
LogFile string `yaml:"log_file,omitempty" kingpin:"log-file"`
PIDFile string `yaml:"pid_file,omitempty" kingpin:"pid-file"`
Quiet bool `yaml:"quiet,omitempty" kingpin:"quiet"`
ServerAddress string `yaml:"server_address" kingping:"server-address"`
ServerCompressor string `yaml:"server_compressor" kingpin:"server-compressor"`
StoragesConfig string `yaml:"storages_config" kingpin:"storages-config"`
TLS bool `yaml:"tls,omitempty" kingpin:"tls"`
TLSCAFile string `yaml:"tls_ca_file,omitempty" kingpin:"tls-ca-file"`
TLSCertFile string `yaml:"tls_cert_file,omitempty" kingpin:"tls-cert-file"`
TLSKeyFile string `yaml:"tls_key_file,omitempty" kingpin:"tls-key-file"`
UseSysLog bool `yaml:"use_syslog,omitempty" kingpin:"use-syslog"`
// MongoDB connection options
MongodbConnOptions client.ConnectionOptions `yaml:"mongodb_conn_options,omitempty"`
// MongoDB connection SSL options
MongodbSslOptions client.SSLOptions `yaml:"mongodb_ssl_options,omitempty"`
}
const (
sampleConfigFile = "config.sample.yml"
defaultServerAddress = "127.0.0.1:10000"
defaultMongoDBHost = "127.0.0.1"
defaultMongoDBPort = "27017"
)
var (
version = "dev"
commit = "none"
log = logrus.New()
program = filepath.Base(os.Args[0])
grpcCompressors = []string{
gzip.Name,
"none",
}
)
func main() {
opts, err := processCliArgs(os.Args[1:])
if err != nil {
log.Fatalf("Cannot parse command line arguments: %s", err)
}
if opts.UseSysLog {
log = logger.NewSyslogLogger()
} else {
log = logger.NewDefaultLogger(opts.LogFile)
}
if opts.Debug {
log.SetLevel(logrus.DebugLevel)
}
if opts.generateSampleConfig {
if err := writeSampleConfig(sampleConfigFile, opts); err != nil {
log.Fatalf("Cannot write sample config file %s: %s", sampleConfigFile, err)
}
log.Printf("Sample config was written to %s\n", sampleConfigFile)
return
}
if opts.Quiet {
log.SetLevel(logrus.ErrorLevel)
}
if opts.Debug {
log.SetLevel(logrus.DebugLevel)
}
log.SetLevel(logrus.DebugLevel)
log.Infof("Starting %s version %s, git commit %s", program, version, commit)
grpcOpts := getgRPCOptions(opts)
rand.Seed(time.Now().UnixNano())
// Connect to the percona-backup-mongodb gRPC server
conn, err := grpc.Dial(opts.ServerAddress, grpcOpts...)
if err != nil {
log.Fatalf("Fail to connect to the gRPC server at %q: %v", opts.ServerAddress, err)
}
defer conn.Close()
log.Infof("Connected to the gRPC server at %s", opts.ServerAddress)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Connect to the MongoDB instance
var di *mgo.DialInfo
if opts.DSN == "" {
di = &mgo.DialInfo{
Addrs: []string{opts.MongodbConnOptions.Host + ":" + opts.MongodbConnOptions.Port},
Username: opts.MongodbConnOptions.User,
Password: opts.MongodbConnOptions.Password,
ReplicaSetName: opts.MongodbConnOptions.ReplicasetName,
FailFast: true,
Source: "admin",
}
} else {
di, err = mgo.ParseURL(opts.DSN)
di.FailFast = true
if err != nil {
log.Fatalf("Cannot parse MongoDB DSN %q, %s", opts.DSN, err)
}
}
mdbSession := &mgo.Session{}
connectionAttempts := 0
for {
connectionAttempts++
mdbSession, err = mgo.DialWithInfo(di)
if err != nil {
log.Errorf("Cannot connect to MongoDB at %s: %s", di.Addrs[0], err)
if opts.MongodbConnOptions.ReconnectCount == 0 || connectionAttempts < opts.MongodbConnOptions.ReconnectCount {
time.Sleep(time.Duration(opts.MongodbConnOptions.ReconnectDelay) * time.Second)
continue
}
log.Fatalf("Could not connect to MongoDB. Retried every %d seconds, %d times", opts.MongodbConnOptions.ReconnectDelay, connectionAttempts)
}
break
}
log.Infof("Connected to MongoDB at %s", di.Addrs[0])
defer mdbSession.Close()
stg, err := storage.NewStorageBackendsFromYaml(utils.Expand(opts.StoragesConfig))
if err != nil {
log.Fatalf("Canot load storages config from file %s: %s", utils.Expand(opts.StoragesConfig), err)
}
input := client.InputOptions{
DbConnOptions: opts.MongodbConnOptions,
DbSSLOptions: opts.MongodbSslOptions,
GrpcConn: conn,
Logger: log,
Storages: stg,
}
client, err := client.NewClient(context.Background(), input)
if err != nil {
log.Fatal(err)
}
if err := client.Start(); err != nil {
log.Fatalf("Cannot start client: %s", err)
}
logHook, err := loghook.NewGrpcLogging(ctx, client.ID(), conn)
if err != nil {
log.Fatalf("Failed to create gRPC log hook: %v", err)
}
logHook.SetLevel(log.Level)
log.AddHook(logHook)
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
<-c
client.Stop()
}
func processCliArgs(args []string) (*cliOptions, error) |
func validateOptions(opts *cliOptions) error {
opts.TLSCAFile = utils.Expand(opts.TLSCAFile)
opts.TLSCertFile = utils.Expand(opts.TLSCertFile)
opts.TLSKeyFile = utils.Expand(opts.TLSKeyFile)
opts.PIDFile = utils.Expand(opts.PIDFile)
if opts.PIDFile != "" {
if err := writePidFile(opts.PIDFile); err != nil {
return errors.Wrapf(err, "cannot write pid file %q", opts.PIDFile)
}
}
if opts.DSN != "" {
di, err := mgo.ParseURL(opts.DSN)
if err != nil {
return err
}
parts := strings.Split(di.Addrs[0], ":")
if len(parts) < 2 {
return fmt.Errorf("invalid host:port: %s", di.Addrs[0])
}
opts.MongodbConnOptions.Host = parts[0]
opts.MongodbConnOptions.Port = parts[1]
opts.MongodbConnOptions.User = di.Username
opts.MongodbConnOptions.Password = di.Password
opts.MongodbConnOptions.ReplicasetName = di.ReplicaSetName
}
return nil
}
func writeSampleConfig(filename string, opts *cliOptions) error {
buf, err := yaml.Marshal(opts)
if err != nil {
return err
}
if err = ioutil.WriteFile(filename, buf, os.ModePerm); err != nil {
return errors.Wrapf(err, "cannot write sample config to %s", filename)
}
return nil
}
func getgRPCOptions(opts *cliOptions) []grpc.DialOption {
var grpcOpts []grpc.DialOption
if opts.TLS {
creds, err := credentials.NewClientTLSFromFile(opts.TLSCAFile, "")
if err != nil {
log.Fatalf("Failed to create TLS credentials %v", err)
}
grpcOpts = append(grpcOpts, grpc.WithTransportCredentials(creds))
} else {
grpcOpts = append(grpcOpts, grpc.WithInsecure())
}
if opts.ServerCompressor != "" && opts.ServerCompressor != "none" {
grpcOpts = append(grpcOpts, grpc.WithDefaultCallOptions(
grpc.UseCompressor(opts.ServerCompressor),
))
}
return grpcOpts
}
// Write a pid file, but first make sure it doesn't exist with a running pid.
func writePidFile(pidFile string) error {
// Read in the pid file as a slice of bytes.
if piddata, err := ioutil.ReadFile(filepath.Clean(pidFile)); err == nil {
// Convert the file contents to an integer.
if pid, err := strconv.Atoi(string(piddata)); err == nil {
// Look for the pid in the process list.
if process, err := os.FindProcess(pid); err == nil {
// Send the process a signal zero kill.
if err := process.Signal(syscall.Signal(0)); err == nil {
// We only get an error if the pid isn't running, or it's not ours.
return fmt.Errorf("pid already running: %d", pid)
}
}
}
}
// If we get here, then the pidfile didn't exist,
// or the pid in it doesn't belong to the user running this app.
return ioutil.WriteFile(pidFile, []byte(fmt.Sprintf("%d", os.Getpid())), 0664)
}
| {
app := kingpin.New("pbm-agent", "Percona Backup for MongoDB agent")
app.Version(fmt.Sprintf("%s version %s, git commit %s", app.Name, version, commit))
opts := &cliOptions{
app: app,
ServerAddress: defaultServerAddress,
MongodbConnOptions: client.ConnectionOptions{
Host: defaultMongoDBHost,
Port: defaultMongoDBPort,
},
}
app.Flag("config-file", "Backup agent config file").Short('c').StringVar(&opts.configFile)
app.Flag("debug", "Enable debug log level").Short('v').BoolVar(&opts.Debug)
app.Flag("generate-sample-config", "Generate sample config.yml file with the defaults").BoolVar(&opts.generateSampleConfig)
app.Flag("log-file", "Backup agent log file").Short('l').StringVar(&opts.LogFile)
app.Flag("pid-file", "Backup agent pid file").StringVar(&opts.PIDFile)
app.Flag("quiet", "Quiet mode. Log only errors").Short('q').BoolVar(&opts.Quiet)
app.Flag("storages-config", "Storages config yaml file").StringVar(&opts.StoragesConfig)
app.Flag("use-syslog", "Use syslog instead of Stderr or file").BoolVar(&opts.UseSysLog)
//
app.Flag("server-address", "Backup coordinator address (host:port)").Short('s').StringVar(&opts.ServerAddress)
app.Flag("server-compressor", "Backup coordintor gRPC compression (gzip or none)").Default().EnumVar(&opts.ServerCompressor, grpcCompressors...)
app.Flag("tls", "Use TLS for server connection").BoolVar(&opts.TLS)
app.Flag("tls-cert-file", "TLS certificate file").ExistingFileVar(&opts.TLSCertFile)
app.Flag("tls-key-file", "TLS key file").ExistingFileVar(&opts.TLSKeyFile)
app.Flag("tls-ca-file", "TLS CA file").ExistingFileVar(&opts.TLSCAFile)
//
app.Flag("mongodb-dsn", "MongoDB connection string").StringVar(&opts.DSN)
app.Flag("mongodb-host", "MongoDB hostname").Short('H').StringVar(&opts.MongodbConnOptions.Host)
app.Flag("mongodb-port", "MongoDB port").Short('P').StringVar(&opts.MongodbConnOptions.Port)
app.Flag("mongodb-username", "MongoDB username").Short('u').StringVar(&opts.MongodbConnOptions.User)
app.Flag("mongodb-password", "MongoDB password").Short('p').StringVar(&opts.MongodbConnOptions.Password)
app.Flag("mongodb-authdb", "MongoDB authentication database").StringVar(&opts.MongodbConnOptions.AuthDB)
app.Flag("mongodb-replicaset", "MongoDB Replicaset name").StringVar(&opts.MongodbConnOptions.ReplicasetName)
app.Flag("mongodb-reconnect-delay", "MongoDB reconnection delay in seconds").Default("10").IntVar(&opts.MongodbConnOptions.ReconnectDelay)
app.Flag("mongodb-reconnect-count", "MongoDB max reconnection attempts (0: forever)").IntVar(&opts.MongodbConnOptions.ReconnectCount)
app.PreAction(func(c *kingpin.ParseContext) error {
if opts.configFile == "" {
fn := utils.Expand("~/.percona-backup-mongodb.yaml")
if _, err := os.Stat(fn); err != nil {
return nil
} else {
opts.configFile = fn
}
}
return utils.LoadOptionsFromFile(opts.configFile, c, opts)
})
_, err := app.DefaultEnvars().Parse(args)
if err != nil {
return nil, err
}
if err := validateOptions(opts); err != nil {
return nil, err
}
return opts, nil
} |
lib.rs | //! The `pact_matching` crate provides the core logic to performing matching on HTTP requests
//! and responses. It implements the [V3 Pact specification](https://github.com/pact-foundation/pact-specification/tree/version-3)
//! and [V4 Pact specification](https://github.com/pact-foundation/pact-specification/tree/version-4).
//!
//! ## To use it
//!
//! To use it, add it to your dependencies in your cargo manifest.
//!
//! This crate provides three functions: [`match_request`](fn.match_request.html), [`match_response`](fn.match_response.html)
//! and [`match_message`](fn.match_message.html).
//! These functions take an expected and actual request, response or message
//! model from the [`models`)(models/index.html) module, and return a vector of mismatches.
//!
//! To compare any incoming request, it first needs to be converted to a [`models::Request`](models/struct.Request.html) and then can be compared. Same for
//! any response.
//!
//! ## Reading and writing Pact files
//!
//! The [`Pact`](models/struct.Pact.html) struct in the [`models`)(models/index.html) module has methods to read and write pact JSON files. It supports all the specification
//! versions up to V4, but will convert a V1, V1.1 or V2 spec file to a V3 format.
//!
//! ## Matching request and response parts
//!
//! V3 specification matching is supported for both JSON and XML bodies, headers, query strings and request paths.
//!
//! To understand the basic rules of matching, see [Matching Gotchas](https://github.com/realestate-com-au/pact/wiki/Matching-gotchas).
//! For example test cases for matching, see the [Pact Specification Project, version 3](https://github.com/bethesque/pact-specification/tree/version-3).
//!
//! By default, Pact will use string equality matching following Postel's Law. This means
//! that for an actual value to match an expected one, they both must consist of the same
//! sequence of characters. For collections (basically Maps and Lists), they must have the
//! same elements that match in the same sequence, with cases where the additional elements
//! in an actual Map are ignored.
//!
//! Matching rules can be defined for both request and response elements based on a pseudo JSON-Path
//! syntax.
//!
//! ### Matching Bodies
//!
//! For the most part, matching involves matching request and response bodies in JSON or XML format.
//! Other formats will either have their own matching rules, or will follow the JSON one.
//!
//! #### JSON body matching rules
//!
//! Bodies consist of Objects (Maps of Key-Value pairs), Arrays (Lists) and values (Strings, Numbers, true, false, null).
//! Body matching rules are prefixed with `$`.
//!
//! The following method is used to determine if two bodies match:
//!
//! 1. If both the actual body and expected body are empty, the bodies match.
//! 2. If the actual body is non-empty, and the expected body empty, the bodies match.
//! 3. If the actual body is empty, and the expected body non-empty, the bodies don't match.
//! 4. Otherwise do a comparison on the contents of the bodies.
//!
//! ##### For the body contents comparison:
//!
//! 1. If the actual and expected values are both Objects, compare as Maps.
//! 2. If the actual and expected values are both Arrays, compare as Lists.
//! 3. If the expected value is an Object, and the actual is not, they don't match.
//! 4. If the expected value is an Array, and the actual is not, they don't match.
//! 5. Otherwise, compare the values
//!
//! ##### For comparing Maps
//!
//! 1. If the actual map is non-empty while the expected is empty, they don't match.
//! 2. If we allow unexpected keys, and the number of expected keys is greater than the actual keys,
//! they don't match.
//! 3. If we don't allow unexpected keys, and the expected and actual maps don't have the
//! same number of keys, they don't match.
//! 4. Otherwise, for each expected key and value pair:
//! 1. if the actual map contains the key, compare the values
//! 2. otherwise they don't match
//!
//! Postel's law governs if we allow unexpected keys or not.
//!
//! ##### For comparing lists
//!
//! 1. If there is a body matcher defined that matches the path to the list, default
//! to that matcher and then compare the list contents.
//! 2. If the expected list is empty and the actual one is not, the lists don't match.
//! 3. Otherwise
//! 1. compare the list sizes
//! 2. compare the list contents
//!
//! ###### For comparing list contents
//!
//! 1. For each value in the expected list:
//! 1. If the index of the value is less than the actual list's size, compare the value
//! with the actual value at the same index using the method for comparing values.
//! 2. Otherwise the value doesn't match
//!
//! ##### For comparing values
//!
//! 1. If there is a matcher defined that matches the path to the value, default to that
//! matcher
//! 2. Otherwise compare the values using equality.
//!
//! #### XML body matching rules
//!
//! Bodies consist of a root element, Elements (Lists with children), Attributes (Maps) and values (Strings).
//! Body matching rules are prefixed with `$`.
//!
//! The following method is used to determine if two bodies match:
//!
//! 1. If both the actual body and expected body are empty, the bodies match.
//! 2. If the actual body is non-empty, and the expected body empty, the bodies match.
//! 3. If the actual body is empty, and the expected body non-empty, the bodies don't match.
//! 4. Otherwise do a comparison on the contents of the bodies.
//!
//! ##### For the body contents comparison:
//!
//! Start by comparing the root element.
//!
//! ##### For comparing elements
//!
//! 1. If there is a body matcher defined that matches the path to the element, default
//! to that matcher on the elements name or children.
//! 2. Otherwise the elements match if they have the same name.
//!
//! Then, if there are no mismatches:
//!
//! 1. compare the attributes of the element
//! 2. compare the child elements
//! 3. compare the text nodes
//!
//! ##### For comparing attributes
//!
//! Attributes are treated as a map of key-value pairs.
//!
//! 1. If the actual map is non-empty while the expected is empty, they don't match.
//! 2. If we allow unexpected keys, and the number of expected keys is greater than the actual keys,
//! they don't match.
//! 3. If we don't allow unexpected keys, and the expected and actual maps don't have the
//! same number of keys, they don't match.
//!
//! Then, for each expected key and value pair:
//!
//! 1. if the actual map contains the key, compare the values
//! 2. otherwise they don't match
//!
//! Postel's law governs if we allow unexpected keys or not. Note for matching paths, attribute names are prefixed with an `@`.
//!
//! ###### For comparing child elements
//!
//! 1. If there is a matcher defined for the path to the child elements, then pad out the expected child elements to have the
//! same size as the actual child elements.
//! 2. Otherwise
//! 1. If the actual children is non-empty while the expected is empty, they don't match.
//! 2. If we allow unexpected keys, and the number of expected children is greater than the actual children,
//! they don't match.
//! 3. If we don't allow unexpected keys, and the expected and actual children don't have the
//! same number of elements, they don't match.
//!
//! Then, for each expected and actual element pair, compare them using the rules for comparing elements.
//!
//! ##### For comparing text nodes
//!
//! Text nodes are combined into a single string and then compared as values.
//!
//! 1. If there is a matcher defined that matches the path to the text node (text node paths end with `#text`), default to that
//! matcher
//! 2. Otherwise compare the text using equality.
//!
//!
//! ##### For comparing values
//!
//! 1. If there is a matcher defined that matches the path to the value, default to that
//! matcher
//! 2. Otherwise compare the values using equality.
//!
//! ### Matching Paths
//!
//! Paths are matched by the following:
//!
//! 1. If there is a matcher defined for `path`, default to that matcher.
//! 2. Otherwise paths are compared as Strings
//!
//! ### Matching Queries
//!
//! 1. If the actual and expected query strings are empty, they match.
//! 2. If the actual is not empty while the expected is, they don't match.
//! 3. If the actual is empty while the expected is not, they don't match.
//! 4. Otherwise convert both into a Map of keys mapped to a list values, and compare those.
//!
//! #### Matching Query Maps
//!
//! Query strings are parsed into a Map of keys mapped to lists of values. Key value
//! pairs can be in any order, but when the same key appears more than once the values
//! are compared in the order they appear in the query string.
//!
//! ### Matching Headers
//!
//! 1. Do a case-insensitive sort of the headers by keys
//! 2. For each expected header in the sorted list:
//! 1. If the actual headers contain that key, compare the header values
//! 2. Otherwise the header does not match
//!
//! For matching header values:
//!
//! 1. If there is a matcher defined for `header.<HEADER_KEY>`, default to that matcher
//! 2. Otherwise strip all whitespace after commas and compare the resulting strings.
//!
//! #### Matching Request Headers
//!
//! Request headers are matched by excluding the cookie header.
//!
//! #### Matching Request cookies
//!
//! If the list of expected cookies contains all the actual cookies, the cookies match.
//!
//! ### Matching Status Codes
//!
//! Status codes are compared as integer values.
//!
//! ### Matching HTTP Methods
//!
//! The actual and expected methods are compared as case-insensitive strings.
//!
//! ## Matching Rules
//!
//! Pact supports extending the matching rules on each type of object (Request or Response) with a `matchingRules` element in the pact file.
//! This is a map of JSON path strings to a matcher. When an item is being compared, if there is an entry in the matching
//! rules that corresponds to the path to the item, the comparison will be delegated to the defined matcher. Note that the
//! matching rules cascade, so a rule can be specified on a value and will apply to all children of that value.
//!
//! ## Matcher Path expressions
//!
//! Pact does not support the full JSON path expressions, only ones that match the following rules:
//!
//! 1. All paths start with a dollar (`$`), representing the root.
//! 2. All path elements are separated by periods (`.`), except array indices which use square brackets (`[]`).
//! 3. Path elements represent keys.
//! 4. A star (`*`) can be used to match all keys of a map or all items of an array (one level only).
//!
//! So the expression `$.item1.level[2].id` will match the highlighted item in the following body:
//!
//! ```js,ignore
//! {
//! "item1": {
//! "level": [
//! {
//! "id": 100
//! },
//! {
//! "id": 101
//! },
//! {
//! "id": 102 // <---- $.item1.level[2].id
//! },
//! {
//! "id": 103
//! }
//! ]
//! }
//! }
//! ```
//!
//! while `$.*.level[*].id` will match all the ids of all the levels for all items.
//!
//! ### Matcher selection algorithm
//!
//! Due to the star notation, there can be multiple matcher paths defined that correspond to an item. The first, most
//! specific expression is selected by assigning weightings to each path element and taking the product of the weightings.
//! The matcher with the path with the largest weighting is used.
//!
//! * The root node (`$`) is assigned the value 2.
//! * Any path element that does not match is assigned the value 0.
//! * Any property name that matches a path element is assigned the value 2.
//! * Any array index that matches a path element is assigned the value 2.
//! * Any star (`*`) that matches a property or array index is assigned the value 1.
//! * Everything else is assigned the value 0.
//!
//! So for the body with highlighted item:
//!
//! ```js,ignore
//! {
//! "item1": {
//! "level": [
//! {
//! "id": 100
//! },
//! {
//! "id": 101
//! },
//! {
//! "id": 102 // <--- Item under consideration
//! },
//! {
//! "id": 103
//! }
//! ]
//! }
//! }
//! ```
//!
//! The expressions will have the following weightings:
//!
//! | expression | weighting calculation | weighting |
//! |------------|-----------------------|-----------|
//! | $ | $(2) | 2 |
//! | $.item1 | $(2).item1(2) | 4 |
//! | $.item2 | $(2).item2(0) | 0 |
//! | $.item1.level | $(2).item1(2).level(2) | 8 |
//! | $.item1.level\[1\] | $(2).item1(2).level(2)\[1(2)\] | 16 |
//! | $.item1.level\[1\].id | $(2).item1(2).level(2)\[1(2)\].id(2) | 32 |
//! | $.item1.level\[1\].name | $(2).item1(2).level(2)\[1(2)\].name(0) | 0 |
//! | $.item1.level\[2\] | $(2).item1(2).level(2)\[2(0)\] | 0 |
//! | $.item1.level\[2\].id | $(2).item1(2).level(2)\[2(0)\].id(2) | 0 |
//! | $.item1.level\[*\].id | $(2).item1(2).level(2)\[*(1)\].id(2) | 16 |
//! | $.\*.level\[\*\].id | $(2).*(1).level(2)\[*(1)\].id(2) | 8 |
//!
//! So for the item with id 102, the matcher with path `$.item1.level\[1\].id` and weighting 32 will be selected.
//!
//! ## Supported matchers
//!
//! The following matchers are supported:
//!
//! | matcher | Spec Version | example configuration | description |
//! |---------|--------------|-----------------------|-------------|
//! | Equality | V1 | `{ "match": "equality" }` | This is the default matcher, and relies on the equals operator |
//! | Regex | V2 | `{ "match": "regex", "regex": "\\d+" }` | This executes a regular expression match against the string representation of a values. |
//! | Type | V2 | `{ "match": "type" }` | This executes a type based match against the values, that is, they are equal if they are the same type. |
//! | MinType | V2 | `{ "match": "type", "min": 2 }` | This executes a type based match against the values, that is, they are equal if they are the same type. In addition, if the values represent a collection, the length of the actual value is compared against the minimum. |
//! | MaxType | V2 | `{ "match": "type", "max": 10 }` | This executes a type based match against the values, that is, they are equal if they are the same type. In addition, if the values represent a collection, the length of the actual value is compared against the maximum. |
//! | MinMaxType | V2 | `{ "match": "type", "max": 10, "min": 2 }` | This executes a type based match against the values, that is, they are equal if they are the same type. In addition, if the values represent a collection, the length of the actual value is compared against the minimum and maximum. |
//! | Include | V3 | `{ "match": "include", "value": "substr" }` | This checks if the string representation of a value contains the substring. |
//! | Integer | V3 | `{ "match": "integer" }` | This checks if the type of the value is an integer. |
//! | Decimal | V3 | `{ "match": "decimal" }` | This checks if the type of the value is a number with decimal places. |
//! | Number | V3 | `{ "match": "number" }` | This checks if the type of the value is a number. |
//! | Timestamp | V3 | `{ "match": "datetime", "format": "yyyy-MM-dd HH:ss:mm" }` | Matches the string representation of a value against the datetime format |
//! | Time | V3 | `{ "match": "time", "format": "HH:ss:mm" }` | Matches the string representation of a value against the time format |
//! | Date | V3 | `{ "match": "date", "format": "yyyy-MM-dd" }` | Matches the string representation of a value against the date format |
//! | Null | V3 | `{ "match": "null" }` | Match if the value is a null value (this is content specific, for JSON will match a JSON null) |
//! | Boolean | V3 | `{ "match": "boolean" }` | Match if the value is a boolean value (booleans and the string values `true` and `false`) |
//! | ContentType | V3 | `{ "match": "contentType", "value": "image/jpeg" }` | Match binary data by its content type (magic file check) |
//! | Values | V3 | `{ "match": "values" }` | Match the values in a map, ignoring the keys |
//! | ArrayContains | V4 | `{ "match": "arrayContains", "variants": [...] }` | Checks if all the variants are present in an array. |
//! | StatusCode | V4 | `{ "match": "statusCode", "status": "success" }` | Matches the response status code. |
//! | NotEmpty | V4 | `{ "match": "notEmpty" }` | Value must be present and not empty (not null or the empty string) |
//! | Semver | V4 | `{ "match": "semver" }` | Value must be valid based on the semver specification |
//! | Semver | V4 | `{ "match": "semver" }` | Value must be valid based on the semver specification |
//! | EachKey | V4 | `{ "match": "eachKey", "rules": [{"match": "regex", "regex": "\\$(\\.\\w+)+"}], "value": "$.test.one" }` | Allows defining matching rules to apply to the keys in a map |
//! | EachValue | V4 | `{ "match": "eachValue", "rules": [{"match": "regex", "regex": "\\$(\\.\\w+)+"}], "value": "$.test.one" }` | Allows defining matching rules to apply to the values in a collection. For maps, delgates to the Values matcher. |
#![warn(missing_docs)]
use std::collections::HashMap;
use std::fmt::{Debug, Display};
use std::fmt::Formatter;
use std::hash::Hash;
use std::str;
use std::str::from_utf8;
use ansi_term::*;
use ansi_term::Colour::*;
use anyhow::anyhow;
use bytes::Bytes;
use lazy_static::*;
use log::*;
use maplit::hashmap;
use pact_plugin_driver::catalogue_manager::find_content_matcher;
use pact_plugin_driver::plugin_models::PluginInteractionConfig;
use serde_json::{json, Value};
use pact_models::bodies::OptionalBody;
use pact_models::content_types::ContentType;
use pact_models::generators::{apply_generators, GenerateValue, GeneratorCategory, GeneratorTestMode, VariantMatcher};
use pact_models::http_parts::HttpPart;
use pact_models::interaction::Interaction;
use pact_models::json_utils::json_to_string;
use pact_models::matchingrules::{Category, MatchingRule, MatchingRuleCategory, RuleList};
use pact_models::pact::Pact;
use pact_models::PactSpecification;
use pact_models::v4::http_parts::{HttpRequest, HttpResponse};
use pact_models::v4::message_parts::MessageContents;
use pact_models::v4::sync_message::SynchronousMessage;
use crate::generators::{DefaultVariantMatcher, generators_process_body};
use crate::headers::{match_header_value, match_headers};
use crate::json::match_json;
use crate::matchers::*;
use crate::matchingrules::DisplayForMismatch;
/// Simple macro to convert a string slice to a `String` struct.
#[macro_export]
macro_rules! s {
($e:expr) => ($e.to_string())
}
/// Version of the library
pub const PACT_RUST_VERSION: Option<&'static str> = option_env!("CARGO_PKG_VERSION");
pub mod matchers;
pub mod json;
mod xml;
mod binary_utils;
mod headers;
pub mod logging;
mod matchingrules;
mod generators;
#[derive(Debug, Clone)]
/// Context used to apply matching logic
pub struct MatchingContext {
/// Matching rules that apply when matching with the context
pub matchers: MatchingRuleCategory,
/// Configuration to apply when matching with the context
pub config: DiffConfig,
/// Specification version to apply when matching with the context
pub matching_spec: PactSpecification,
/// Any plugin configuration available for the interaction
pub plugin_configuration: HashMap<String, PluginInteractionConfig>
}
impl MatchingContext {
/// Creates a new context with the given config and matching rules
pub fn new(
config: DiffConfig,
matchers: &MatchingRuleCategory,
plugin_configuration: &HashMap<String, PluginInteractionConfig>
) -> Self {
MatchingContext {
matchers: matchers.clone(),
config,
plugin_configuration: plugin_configuration.clone(),
.. MatchingContext::default()
}
}
/// Creates a new empty context with the given config
pub fn with_config(config: DiffConfig) -> Self {
MatchingContext {
config,
.. MatchingContext::default()
}
}
/// Clones the current context with the provided matching rules
pub fn clone_with(&self, matchers: &MatchingRuleCategory) -> Self {
MatchingContext {
matchers: matchers.clone(),
config: self.config.clone(),
matching_spec: self.matching_spec,
plugin_configuration: self.plugin_configuration.clone()
}
}
/// If there is a matcher defined at the path in this context
pub fn matcher_is_defined(&self, path: &[&str]) -> bool {
self.matchers.matcher_is_defined(path)
}
/// Selected the best matcher from the context for the given path
pub fn select_best_matcher(&self, path: &[&str]) -> RuleList {
self.matchers.select_best_matcher(path)
}
/// If there is a wildcard matcher defined at the path in this context
#[deprecated(since = "0.8.12", note = "Replaced with values matcher")]
pub fn wildcard_matcher_is_defined(&self, path: &[&str]) -> bool {
!self.matchers_for_exact_path(path).filter(|&(val, _)| val.is_wildcard()).is_empty()
}
fn matchers_for_exact_path(&self, path: &[&str]) -> MatchingRuleCategory {
match self.matchers.name {
Category::HEADER | Category::QUERY => self.matchers.filter(|&(val, _)| {
path.len() == 1 && Some(path[0]) == val.first_field()
}),
Category::BODY => self.matchers.filter(|&(val, _)| {
val.matches_path_exactly(path)
}),
_ => self.matchers.filter(|_| false)
}
}
/// If there is a type matcher defined at the path in this context
pub fn type_matcher_defined(&self, path: &[&str]) -> bool {
self.matchers.resolve_matchers_for_path(path).type_matcher_defined()
}
/// If there is a values matcher defined at the path in this context
pub fn values_matcher_defined(&self, path: &[&str]) -> bool {
self.matchers_for_exact_path(path).values_matcher_defined()
}
/// Matches the keys of the expected and actual maps
pub fn match_keys<T: Display + Debug>(&self, path: &[&str], expected: &HashMap<String, T>, actual: &HashMap<String, T>) -> Result<(), Vec<Mismatch>> {
let mut expected_keys = expected.keys().cloned().collect::<Vec<String>>();
expected_keys.sort();
let mut actual_keys = actual.keys().cloned().collect::<Vec<String>>();
actual_keys.sort();
let missing_keys: Vec<String> = expected.keys().filter(|key| !actual.contains_key(*key)).cloned().collect();
match self.config {
DiffConfig::AllowUnexpectedKeys if !missing_keys.is_empty() => {
Err(vec![Mismatch::BodyMismatch {
path: path.join("."),
expected: Some(expected.for_mismatch().into()),
actual: Some(actual.for_mismatch().into()),
mismatch: format!("Actual map is missing the following keys: {}", missing_keys.join(", ")),
}])
}
DiffConfig::NoUnexpectedKeys if expected_keys != actual_keys => {
Err(vec![Mismatch::BodyMismatch {
path: path.join("."),
expected: Some(expected.for_mismatch().into()),
actual: Some(actual.for_mismatch().into()),
mismatch: format!("Expected a Map with keys {} but received one with keys {}",
expected_keys.join(", "), actual_keys.join(", ")),
}])
}
_ => Ok(())
}
}
}
impl Default for MatchingContext {
fn default() -> Self {
MatchingContext {
matchers: Default::default(),
config: DiffConfig::AllowUnexpectedKeys,
matching_spec: PactSpecification::V3,
plugin_configuration: Default::default()
}
}
}
lazy_static! {
static ref BODY_MATCHERS: [
(fn(content_type: &ContentType) -> bool,
fn(expected: &dyn HttpPart, actual: &dyn HttpPart, context: &MatchingContext) -> Result<(), Vec<Mismatch>>); 4]
= [
(|content_type| { content_type.is_json() }, json::match_json),
(|content_type| { content_type.is_xml() }, xml::match_xml),
(|content_type| { content_type.base_type() == "application/octet-stream" }, binary_utils::match_octet_stream),
(|content_type| { content_type.base_type() == "multipart/form-data" }, binary_utils::match_mime_multipart)
];
}
/// Enum that defines the different types of mismatches that can occur.
#[derive(Debug, Clone, PartialOrd, Ord, Eq)]
pub enum Mismatch {
/// Request Method mismatch
MethodMismatch {
/// Expected request method
expected: String,
/// Actual request method
actual: String
},
/// Request Path mismatch
PathMismatch {
/// expected request path
expected: String,
/// actual request path
actual: String,
/// description of the mismatch
mismatch: String
},
/// Response status mismatch
StatusMismatch {
/// expected response status
expected: u16,
/// actual response status
actual: u16,
/// description of the mismatch
mismatch: String
},
/// Request query mismatch
QueryMismatch {
/// query parameter name
parameter: String,
/// expected value
expected: String,
/// actual value
actual: String,
/// description of the mismatch
mismatch: String
},
/// Header mismatch
HeaderMismatch {
/// header key
key: String,
/// expected value
expected: String,
/// actual value
actual: String,
/// description of the mismatch
mismatch: String
},
/// Mismatch in the content type of the body
BodyTypeMismatch {
/// expected content type of the body
expected: String,
/// actual content type of the body
actual: String,
/// description of the mismatch
mismatch: String,
/// expected value
expected_body: Option<Bytes>,
/// actual value
actual_body: Option<Bytes>
},
/// Body element mismatch
BodyMismatch {
/// path expression to where the mismatch occurred
path: String,
/// expected value
expected: Option<Bytes>,
/// actual value
actual: Option<Bytes>,
/// description of the mismatch
mismatch: String
},
/// Message metadata mismatch
MetadataMismatch {
/// key
key: String,
/// expected value
expected: String,
/// actual value
actual: String,
/// description of the mismatch
mismatch: String
}
}
impl Mismatch {
/// Converts the mismatch to a `Value` struct.
pub fn to_json(&self) -> serde_json::Value {
match self {
Mismatch::MethodMismatch { expected: e, actual: a } => {
json!({
"type" : "MethodMismatch",
"expected" : e,
"actual" : a
})
},
Mismatch::PathMismatch { expected: e, actual: a, mismatch: m } => {
json!({
"type" : "PathMismatch",
"expected" : e,
"actual" : a,
"mismatch" : m
})
},
Mismatch::StatusMismatch { expected: e, actual: a, mismatch: m } => {
json!({
"type" : "StatusMismatch",
"expected" : e,
"actual" : a,
"mismatch": m
})
},
Mismatch::QueryMismatch { parameter: p, expected: e, actual: a, mismatch: m } => {
json!({
"type" : "QueryMismatch",
"parameter" : p,
"expected" : e,
"actual" : a,
"mismatch" : m
})
},
Mismatch::HeaderMismatch { key: k, expected: e, actual: a, mismatch: m } => {
json!({
"type" : "HeaderMismatch",
"key" : k,
"expected" : e,
"actual" : a,
"mismatch" : m
})
},
Mismatch::BodyTypeMismatch {
expected,
actual,
mismatch,
expected_body,
actual_body
} => {
json!({
"type" : "BodyTypeMismatch",
"expected" : expected,
"actual" : actual,
"mismatch" : mismatch,
"expectedBody": match expected_body {
Some(v) => serde_json::Value::String(str::from_utf8(v)
.unwrap_or("ERROR: could not convert to UTF-8 from bytes").into()),
None => serde_json::Value::Null
},
"actualBody": match actual_body {
Some(v) => serde_json::Value::String(str::from_utf8(v)
.unwrap_or("ERROR: could not convert to UTF-8 from bytes").into()),
None => serde_json::Value::Null
}
})
},
Mismatch::BodyMismatch { path, expected, actual, mismatch } => {
json!({
"type" : "BodyMismatch",
"path" : path,
"expected" : match expected {
Some(v) => serde_json::Value::String(str::from_utf8(v).unwrap_or("ERROR: could not convert from bytes").into()),
None => serde_json::Value::Null
},
"actual" : match actual {
Some(v) => serde_json::Value::String(str::from_utf8(v).unwrap_or("ERROR: could not convert from bytes").into()),
None => serde_json::Value::Null
},
"mismatch" : mismatch
})
}
Mismatch::MetadataMismatch { key, expected, actual, mismatch } => {
json!({
"type" : "MetadataMismatch",
"key" : key,
"expected" : expected,
"actual" : actual,
"mismatch" : mismatch
})
}
}
}
/// Returns the type of the mismatch as a string
pub fn mismatch_type(&self) -> &str {
match *self {
Mismatch::MethodMismatch { .. } => "MethodMismatch",
Mismatch::PathMismatch { .. } => "PathMismatch",
Mismatch::StatusMismatch { .. } => "StatusMismatch",
Mismatch::QueryMismatch { .. } => "QueryMismatch",
Mismatch::HeaderMismatch { .. } => "HeaderMismatch",
Mismatch::BodyTypeMismatch { .. } => "BodyTypeMismatch",
Mismatch::BodyMismatch { .. } => "BodyMismatch",
Mismatch::MetadataMismatch { .. } => "MetadataMismatch"
}
}
/// Returns a summary string for this mismatch
pub fn summary(&self) -> String {
match *self {
Mismatch::MethodMismatch { expected: ref e, .. } => format!("is a {} request", e),
Mismatch::PathMismatch { expected: ref e, .. } => format!("to path '{}'", e),
Mismatch::StatusMismatch { expected: ref e, .. } => format!("has status code {}", e),
Mismatch::QueryMismatch { ref parameter, expected: ref e, .. } => format!("includes parameter '{}' with value '{}'", parameter, e),
Mismatch::HeaderMismatch { ref key, expected: ref e, .. } => format!("includes header '{}' with value '{}'", key, e),
Mismatch::BodyTypeMismatch { .. } => s!("has a matching body"),
Mismatch::BodyMismatch { .. } => s!("has a matching body"),
Mismatch::MetadataMismatch { .. } => s!("has matching metadata")
}
}
/// Returns a formated string for this mismatch
pub fn description(&self) -> String {
match self {
Mismatch::MethodMismatch { expected: e, actual: a } => format!("expected {} but was {}", e, a),
Mismatch::PathMismatch { mismatch, .. } => mismatch.clone(),
Mismatch::StatusMismatch { mismatch, .. } => mismatch.clone(),
Mismatch::QueryMismatch { mismatch, .. } => mismatch.clone(),
Mismatch::HeaderMismatch { mismatch, .. } => mismatch.clone(),
Mismatch::BodyTypeMismatch { expected: e, actual: a, .. } => format!("expected '{}' body but was '{}'", e, a),
Mismatch::BodyMismatch { path, mismatch, .. } => format!("{} -> {}", path, mismatch),
Mismatch::MetadataMismatch { mismatch, .. } => mismatch.clone()
}
}
/// Returns a formatted string with ansi escape codes for this mismatch
pub fn ansi_description(&self) -> String {
match self {
Mismatch::MethodMismatch { expected: e, actual: a } => format!("expected {} but was {}", Red.paint(e.clone()), Green.paint(a.clone())),
Mismatch::PathMismatch { expected: e, actual: a, .. } => format!("expected '{}' but was '{}'", Red.paint(e.clone()), Green.paint(a.clone())),
Mismatch::StatusMismatch { expected: e, actual: a, .. } => format!("expected {} but was {}", Red.paint(e.to_string()), Green.paint(a.to_string())),
Mismatch::QueryMismatch { expected: e, actual: a, parameter: p, .. } => format!("Expected '{}' but received '{}' for query parameter '{}'",
Red.paint(e.to_string()), Green.paint(a.to_string()), Style::new().bold().paint(p.clone())),
Mismatch::HeaderMismatch { expected: e, actual: a, key: k, .. } => format!("Expected header '{}' to have value '{}' but was '{}'",
Style::new().bold().paint(k.clone()), Red.paint(e.to_string()), Green.paint(a.to_string())),
Mismatch::BodyTypeMismatch { expected: e, actual: a, .. } => format!("expected '{}' body but was '{}'", Red.paint(e.clone()), Green.paint(a.clone())),
Mismatch::BodyMismatch { path, mismatch, .. } => format!("{} -> {}", Style::new().bold().paint(path.clone()), mismatch),
Mismatch::MetadataMismatch { expected: e, actual: a, key: k, .. } => format!("Expected message metadata '{}' to have value '{}' but was '{}'",
Style::new().bold().paint(k.clone()), Red.paint(e.to_string()), Green.paint(a.to_string()))
}
}
}
impl PartialEq for Mismatch {
fn eq(&self, other: &Mismatch) -> bool {
match (self, other) {
(Mismatch::MethodMismatch { expected: e1, actual: a1 },
Mismatch::MethodMismatch { expected: e2, actual: a2 }) => {
e1 == e2 && a1 == a2
},
(Mismatch::PathMismatch { expected: e1, actual: a1, .. },
Mismatch::PathMismatch { expected: e2, actual: a2, .. }) => {
e1 == e2 && a1 == a2
},
(Mismatch::StatusMismatch { expected: e1, actual: a1, .. },
Mismatch::StatusMismatch { expected: e2, actual: a2, .. }) => {
e1 == e2 && a1 == a2
},
(Mismatch::BodyTypeMismatch { expected: e1, actual: a1, .. },
Mismatch::BodyTypeMismatch { expected: e2, actual: a2, .. }) => {
e1 == e2 && a1 == a2
},
(Mismatch::QueryMismatch { parameter: p1, expected: e1, actual: a1, .. },
Mismatch::QueryMismatch { parameter: p2, expected: e2, actual: a2, .. }) => {
p1 == p2 && e1 == e2 && a1 == a2
},
(Mismatch::HeaderMismatch { key: p1, expected: e1, actual: a1, .. },
Mismatch::HeaderMismatch { key: p2, expected: e2, actual: a2, .. }) => {
p1 == p2 && e1 == e2 && a1 == a2
},
(Mismatch::BodyMismatch { path: p1, expected: e1, actual: a1, .. },
Mismatch::BodyMismatch { path: p2, expected: e2, actual: a2, .. }) => {
p1 == p2 && e1 == e2 && a1 == a2
},
(Mismatch::MetadataMismatch { key: p1, expected: e1, actual: a1, .. },
Mismatch::MetadataMismatch { key: p2, expected: e2, actual: a2, .. }) => {
p1 == p2 && e1 == e2 && a1 == a2
},
(_, _) => false
}
}
}
impl Display for Mismatch {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.description())
}
}
fn merge_result(res1: Result<(), Vec<Mismatch>>, res2: Result<(), Vec<Mismatch>>) -> Result<(), Vec<Mismatch>> {
match (&res1, &res2) {
(Ok(_), Ok(_)) => res1.clone(),
(Err(_), Ok(_)) => res1.clone(),
(Ok(_), Err(_)) => res2.clone(),
(Err(m1), Err(m2)) => {
let mut mismatches = m1.clone();
mismatches.extend_from_slice(&*m2);
Err(mismatches)
}
}
}
/// Result of matching a request body
#[derive(Debug, Clone, PartialEq)]
pub enum BodyMatchResult {
/// Matched OK
Ok,
/// Mismatch in the content type of the body
BodyTypeMismatch {
/// Expected content type
expected_type: String,
/// Actual content type
actual_type: String,
/// Message
message: String,
/// Expected body
expected: Option<Bytes>,
/// Actual body
actual: Option<Bytes>
},
/// Mismatches with the body contents
BodyMismatches(HashMap<String, Vec<Mismatch>>)
}
impl BodyMatchResult {
/// Returns all the mismatches
pub fn mismatches(&self) -> Vec<Mismatch> {
match self {
BodyMatchResult::BodyTypeMismatch { expected_type, actual_type, message, expected, actual } => {
vec![Mismatch::BodyTypeMismatch {
expected: expected_type.clone(),
actual: actual_type.clone(),
mismatch: message.clone(),
expected_body: expected.clone(),
actual_body: actual.clone()
}]
},
BodyMatchResult::BodyMismatches(results) =>
results.values().flatten().cloned().collect(),
_ => vec![]
}
}
/// If all the things matched OK
pub fn all_matched(&self) -> bool {
match self {
BodyMatchResult::BodyTypeMismatch { .. } => false,
BodyMatchResult::BodyMismatches(results) =>
results.values().all(|m| m.is_empty()),
_ => true
}
}
}
/// Result of matching a request
#[derive(Debug, Clone, PartialEq)]
pub struct RequestMatchResult {
/// Method match result
pub method: Option<Mismatch>,
/// Path match result
pub path: Option<Vec<Mismatch>>,
/// Body match result
pub body: BodyMatchResult,
/// Query parameter result
pub query: HashMap<String, Vec<Mismatch>>,
/// Headers result
pub headers: HashMap<String, Vec<Mismatch>>
}
impl RequestMatchResult {
/// Returns all the mismatches
pub fn mismatches(&self) -> Vec<Mismatch> {
let mut m = vec![];
if let Some(ref mismatch) = self.method {
m.push(mismatch.clone());
}
if let Some(ref mismatches) = self.path {
m.extend_from_slice(mismatches.as_slice());
}
for mismatches in self.query.values() {
m.extend_from_slice(mismatches.as_slice());
}
for mismatches in self.headers.values() {
m.extend_from_slice(mismatches.as_slice());
}
m.extend_from_slice(self.body.mismatches().as_slice());
m
}
/// Returns a score based on what was matched
pub fn score(&self) -> i8 {
let mut score = 0;
if self.method.is_none() {
score += 1;
} else {
score -= 1;
}
if self.path.is_none() {
score += 1
} else {
score -= 1
}
for mismatches in self.query.values() {
if mismatches.is_empty() {
score += 1;
} else {
score -= 1;
}
}
for mismatches in self.headers.values() {
if mismatches.is_empty() {
score += 1;
} else {
score -= 1;
}
}
match &self.body {
BodyMatchResult::BodyTypeMismatch { .. } => {
score -= 1;
},
BodyMatchResult::BodyMismatches(results) => {
for mismatches in results.values() {
if mismatches.is_empty() {
score += 1;
} else {
score -= 1;
}
}
},
_ => ()
}
score
}
/// If all the things matched OK
pub fn all_matched(&self) -> bool {
self.method.is_none() && self.path.is_none() &&
self.query.values().all(|m| m.is_empty()) &&
self.headers.values().all(|m| m.is_empty()) &&
self.body.all_matched()
}
/// If there was a mismatch with the method or path
pub fn method_or_path_mismatch(&self) -> bool {
self.method.is_some() || self.path.is_some()
}
}
/// Enum that defines the configuration options for performing a match.
#[derive(Debug, Clone, PartialEq)]
pub enum DiffConfig {
/// If unexpected keys are allowed and ignored during matching.
AllowUnexpectedKeys,
/// If unexpected keys cause a mismatch.
NoUnexpectedKeys
}
/// Matches the actual text body to the expected one.
pub fn match_text(expected: &Option<Bytes>, actual: &Option<Bytes>, context: &MatchingContext) -> Result<(), Vec<Mismatch>> {
let path = vec!["$"];
if context.matcher_is_defined(&path) {
let mut mismatches = vec![];
let empty = Bytes::default();
let expected_str = match from_utf8(expected.as_ref().unwrap_or(&empty)) {
Ok(expected) => expected,
Err(err) => {
mismatches.push(Mismatch::BodyMismatch {
path: "$".to_string(),
expected: expected.clone(),
actual: actual.clone(),
mismatch: format!("Could not parse expected value as UTF-8 text: {}", err)
});
""
}
};
let actual_str = match from_utf8(actual.as_ref().unwrap_or(&empty)) {
Ok(actual) => actual,
Err(err) => {
mismatches.push(Mismatch::BodyMismatch {
path: "$".to_string(),
expected: expected.clone(),
actual: actual.clone(),
mismatch: format!("Could not parse actual value as UTF-8 text: {}", err)
});
""
}
};
if let Err(messages) = match_values(&path, context, expected_str, actual_str) {
for message in messages {
mismatches.push(Mismatch::BodyMismatch {
path: "$".to_string(),
expected: expected.clone(),
actual: actual.clone(),
mismatch: message.clone()
})
}
};
if mismatches.is_empty() {
Ok(())
} else {
Err(mismatches)
}
} else if expected != actual {
Err(vec![ Mismatch::BodyMismatch { path: "$".to_string(), expected: expected.clone(),
actual: actual.clone(),
mismatch: format!("Expected text '{:?}' but received '{:?}'", expected, actual) } ])
} else {
Ok(())
}
}
/// Matches the actual request method to the expected one.
pub fn match_method(expected: &str, actual: &str) -> Result<(), Mismatch> {
if expected.to_lowercase() != actual.to_lowercase() {
Err(Mismatch::MethodMismatch { expected: expected.to_string(), actual: actual.to_string() })
} else {
Ok(())
}
}
/// Matches the actual request path to the expected one.
pub fn match_path(expected: &str, actual: &str, context: &MatchingContext) -> Result<(), Vec<Mismatch>> {
let path = vec![];
let matcher_result = if context.matcher_is_defined(&path) {
match_values(&path, context, expected.to_string(), actual.to_string())
} else {
expected.matches_with(actual, &MatchingRule::Equality, false).map_err(|err| vec![err])
.map_err(|errors| errors.iter().map(|err| err.to_string()).collect())
};
matcher_result.map_err(|messages| messages.iter().map(|message| {
Mismatch::PathMismatch {
expected: expected.to_string(),
actual: actual.to_string(), mismatch: message.clone()
}
}).collect())
}
fn compare_query_parameter_value(key: &str, expected: &str, actual: &str, index: usize,
context: &MatchingContext) -> Result<(), Vec<Mismatch>> {
let index = index.to_string();
let path = vec!["$", key, index.as_str()];
let matcher_result = if context.matcher_is_defined(&path) {
matchers::match_values(&path, context, expected.to_string(), actual.to_string())
} else {
expected.matches_with(actual, &MatchingRule::Equality, false)
.map_err(|error| vec![error.to_string()])
};
matcher_result.map_err(|messages| {
messages.iter().map(|message| {
Mismatch::QueryMismatch {
parameter: key.to_string(),
expected: expected.to_string(),
actual: actual.to_string(),
mismatch: message.clone(),
}
}).collect()
})
}
fn compare_query_parameter_values(key: &str, expected: &[String], actual: &[String],
context: &MatchingContext) -> Result<(), Vec<Mismatch>> {
let result: Vec<Mismatch> = expected.iter().enumerate().flat_map(|(index, val)| {
if index < actual.len() {
match compare_query_parameter_value(key, val, &actual[index], index, context) {
Ok(_) => vec![],
Err(errors) => errors
}
} else {
vec![ Mismatch::QueryMismatch {
parameter: key.to_string(),
expected: format!("{:?}", expected),
actual: format!("{:?}", actual),
mismatch: format!("Expected query parameter '{}' value '{}' but was missing", key, val)
} ]
}
}).collect();
if result.is_empty() {
Ok(())
} else {
Err(result)
}
}
fn match_query_values(key: &str, expected: &[String], actual: &[String], context: &MatchingContext) -> Result<(), Vec<Mismatch>> {
if expected.is_empty() && !actual.is_empty() {
Err(vec![ Mismatch::QueryMismatch { parameter: key.to_string(),
expected: format!("{:?}", expected),
actual: format!("{:?}", actual),
mismatch: format!("Expected an empty parameter list for '{}' but received {:?}", key, actual) } ])
} else {
let mismatch = if expected.len() != actual.len() {
Err(vec![ Mismatch::QueryMismatch { parameter: key.to_string(),
expected: format!("{:?}", expected),
actual: format!("{:?}", actual),
mismatch: format!(
"Expected query parameter '{}' with {} value(s) but received {} value(s)",
key, expected.len(), actual.len()) } ])
} else {
Ok(())
};
merge_result(compare_query_parameter_values(key, expected, actual, context), mismatch)
}
}
fn match_query_maps(expected: HashMap<String, Vec<String>>, actual: HashMap<String, Vec<String>>, context: &MatchingContext) -> HashMap<String, Vec<Mismatch>> {
let mut result: HashMap<String, Vec<Mismatch>> = hashmap!{};
for (key, value) in &expected {
match actual.get(key) {
Some(actual_value) => {
let matches = match_query_values(key, value, actual_value, context);
let v = result.entry(key.clone()).or_default();
v.extend(matches.err().unwrap_or_default());
},
None => result.entry(key.clone()).or_default().push(Mismatch::QueryMismatch { parameter: key.clone(),
expected: format!("{:?}", value),
actual: "".to_string(),
mismatch: format!("Expected query parameter '{}' but was missing", key) })
}
}
for (key, value) in &actual {
match expected.get(key) {
Some(_) => (),
None => result.entry(key.clone()).or_default().push(Mismatch::QueryMismatch { parameter: key.clone(),
expected: "".to_string(),
actual: format!("{:?}", value),
mismatch: format!("Unexpected query parameter '{}' received", key) })
}
}
result
}
/// Matches the actual query parameters to the expected ones.
pub fn match_query(expected: Option<HashMap<String, Vec<String>>>, actual: Option<HashMap<String, Vec<String>>>, context: &MatchingContext) -> HashMap<String, Vec<Mismatch>> {
match (actual, expected) {
(Some(aqm), Some(eqm)) => match_query_maps(eqm, aqm, context),
(Some(aqm), None) => aqm.iter().map(|(key, value)| {
(key.clone(), vec![Mismatch::QueryMismatch { parameter: key.clone(),
expected: "".to_string(),
actual: format!("{:?}", value),
mismatch: format!("Unexpected query parameter '{}' received", key) }])
}).collect(),
(None, Some(eqm)) => eqm.iter().map(|(key, value)| {
(key.clone(), vec![Mismatch::QueryMismatch { parameter: key.clone(),
expected: format!("{:?}", value),
actual: "".to_string(),
mismatch: format!("Expected query parameter '{}' but was missing", key) }])
}).collect(),
(None, None) => hashmap!{}
}
}
fn group_by<I, F, K>(items: I, f: F) -> HashMap<K, Vec<I::Item>>
where I: IntoIterator, F: Fn(&I::Item) -> K, K: Eq + Hash {
let mut m = hashmap!{};
for item in items {
let key = f(&item);
let values = m.entry(key).or_insert_with(Vec::new);
values.push(item);
}
m
}
async fn compare_bodies(
content_type: &ContentType,
expected: &(dyn HttpPart + Send + Sync),
actual: &(dyn HttpPart + Send + Sync),
context: &MatchingContext
) -> BodyMatchResult {
let mut mismatches = vec![];
match find_content_matcher(content_type) {
Some(matcher) => {
debug!("Using content matcher {} for content type '{}'", matcher.catalogue_entry_key(), content_type);
if matcher.is_core() {
if let Err(m) = match matcher.catalogue_entry_key().as_str() {
// TODO: "core/content-matcher/form-urlencoded" => ,
"core/content-matcher/json" => match_json(expected, actual, context),
"core/content-matcher/multipart-form-data" => binary_utils::match_mime_multipart(expected, actual, context),
"core/content-matcher/text" => match_text(&expected.body().value(), &actual.body().value(), context),
"core/content-matcher/xml" => xml::match_xml(expected, actual, context),
"core/content-matcher/binary" => binary_utils::match_octet_stream(expected, actual, context),
_ => {
warn!("There is no core content matcher for entry {}", matcher.catalogue_entry_key());
match_text(&expected.body().value(), &actual.body().value(), context)
}
} {
mismatches.extend_from_slice(&*m);
}
} else {
let plugin_config = context.plugin_configuration.get(&matcher.plugin_name()).cloned();
if let Err(map) = matcher.match_contents(expected.body(), actual.body(), &context.matchers,
context.config == DiffConfig::AllowUnexpectedKeys, plugin_config).await {
// TODO: group the mismatches by key
for (_key, list) in map {
for mismatch in list {
mismatches.push(Mismatch::BodyMismatch {
path: mismatch.path.clone(),
expected: Some(Bytes::from(mismatch.expected)),
actual: Some(Bytes::from(mismatch.actual)),
mismatch: mismatch.mismatch.clone()
});
}
}
}
}
}
None => {
debug!("No content matcher defined for content type '{}', using core matcher implementation", content_type);
mismatches.extend(compare_bodies_core(content_type, expected, actual, context));
}
}
if mismatches.is_empty() {
BodyMatchResult::Ok
} else {
BodyMatchResult::BodyMismatches(group_by(mismatches, |m| match m {
Mismatch::BodyMismatch { path: m, ..} => m.to_string(),
_ => String::default()
}))
}
}
fn compare_bodies_core(content_type: &ContentType, expected: &dyn HttpPart, actual: &dyn HttpPart, context: &MatchingContext) -> Vec<Mismatch> {
let mut mismatches = vec![];
match BODY_MATCHERS.iter().find(|mt| mt.0(content_type)) {
Some(match_fn) => {
debug!("Using body matcher for content type '{}'", content_type);
if let Err(m) = match_fn.1(expected, actual, context) {
mismatches.extend_from_slice(&*m);
}
},
None => {
debug!("No body matcher defined for content type '{}', using plain text matcher", content_type);
if let Err(m) = match_text(&expected.body().value(), &actual.body().value(), context) {
mismatches.extend_from_slice(&*m);
}
}
};
mismatches
}
async fn match_body_content(
content_type: &ContentType,
expected: &(dyn HttpPart + Send + Sync),
actual: &(dyn HttpPart + Send + Sync),
context: &MatchingContext
) -> BodyMatchResult {
let expected_body = expected.body();
let actual_body = actual.body();
match (expected_body, actual_body) {
(&OptionalBody::Missing, _) => BodyMatchResult::Ok,
(&OptionalBody::Null, &OptionalBody::Present(ref b, _, _)) => {
BodyMatchResult::BodyMismatches(hashmap!{ "$".into() => vec![Mismatch::BodyMismatch { expected: None, actual: Some(b.clone()),
mismatch: format!("Expected empty body but received {}", actual_body),
path: s!("/")}]})
},
(&OptionalBody::Empty, &OptionalBody::Present(ref b, _, _)) => {
BodyMatchResult::BodyMismatches(hashmap!{ "$".into() => vec![Mismatch::BodyMismatch { expected: None, actual: Some(b.clone()),
mismatch: format!("Expected empty body but received {}", actual_body),
path: s!("/")}]})
},
(&OptionalBody::Null, _) => BodyMatchResult::Ok,
(&OptionalBody::Empty, _) => BodyMatchResult::Ok,
(e, &OptionalBody::Missing) => {
BodyMatchResult::BodyMismatches(hashmap!{ "$".into() => vec![Mismatch::BodyMismatch {
expected: e.value(),
actual: None,
mismatch: format!("Expected body {} but was missing", e),
path: s!("/")}]})
},
(e, &OptionalBody::Empty) => {
BodyMatchResult::BodyMismatches(hashmap!{ "$".into() => vec![Mismatch::BodyMismatch {
expected: e.value(),
actual: None,
mismatch: format!("Expected body {} but was empty", e),
path: s!("/")}]})
},
(_, _) => compare_bodies(content_type, expected, actual, context).await
}
}
/// Matches the actual body to the expected one. This takes into account the content type of each.
pub async fn match_body(
expected: &(dyn HttpPart + Send + Sync),
actual: &(dyn HttpPart + Send + Sync),
context: &MatchingContext,
header_context: &MatchingContext
) -> BodyMatchResult {
let expected_content_type = expected.content_type().unwrap_or_default();
let actual_content_type = actual.content_type().unwrap_or_default();
debug!("expected content type = '{}', actual content type = '{}'", expected_content_type,
actual_content_type);
let content_type_matcher = header_context.select_best_matcher(&["$", "Content-Type"]);
debug!("content type header matcher = '{:?}'", content_type_matcher);
if expected_content_type.is_unknown() || actual_content_type.is_unknown() ||
expected_content_type.is_equivalent_to(&actual_content_type) ||
(!content_type_matcher.is_empty() &&
match_header_value("Content-Type", expected_content_type.to_string().as_str(),
actual_content_type.to_string().as_str(), header_context).is_ok()) {
match_body_content(&expected_content_type, expected, actual, context).await
} else if expected.body().is_present() {
BodyMatchResult::BodyTypeMismatch {
expected_type: expected_content_type.to_string(),
actual_type: actual_content_type.to_string(),
message: format!("Expected body with content type {} but was {}", expected_content_type,
actual_content_type),
expected: expected.body().value(),
actual: actual.body().value()
}
} else {
BodyMatchResult::Ok
}
}
/// Matches the expected and actual requests
pub async fn match_request<'a>(
expected: HttpRequest,
actual: HttpRequest,
pact: &Box<dyn Pact + Send + Sync + 'a>,
interaction: &Box<dyn Interaction + Send + Sync>
) -> RequestMatchResult {
info!("comparing to expected {}", expected);
debug!(" body: '{}'", expected.body.str_value());
debug!(" matching_rules: {:?}", expected.matching_rules);
debug!(" generators: {:?}", expected.generators);
let plugin_data = setup_plugin_config(pact, interaction);
let path_context = MatchingContext::new(DiffConfig::NoUnexpectedKeys,
&expected.matching_rules.rules_for_category("path").unwrap_or_default(),
&plugin_data);
let body_context = MatchingContext::new(DiffConfig::NoUnexpectedKeys,
&expected.matching_rules.rules_for_category("body").unwrap_or_default(),
&plugin_data);
let query_context = MatchingContext::new(DiffConfig::NoUnexpectedKeys,
&expected.matching_rules.rules_for_category("query").unwrap_or_default(),
&plugin_data);
let header_context = MatchingContext::new(DiffConfig::NoUnexpectedKeys,
&expected.matching_rules.rules_for_category("header").unwrap_or_default(),
&plugin_data);
let result = RequestMatchResult {
method: match_method(&expected.method, &actual.method).err(),
path: match_path(&expected.path, &actual.path, &path_context).err(),
body: match_body(&expected, &actual, &body_context, &header_context).await,
query: match_query(expected.query, actual.query, &query_context),
headers: match_headers(expected.headers, actual.headers, &header_context)
};
debug!("--> Mismatches: {:?}", result.mismatches());
result
}
/// Matches the actual response status to the expected one.
pub fn match_status(expected: u16, actual: u16, context: &MatchingContext) -> Result<(), Vec<Mismatch>> {
let path = vec![];
if context.matcher_is_defined(&path) {
match_values(&path, context, expected, actual)
.map_err(|messages| messages.iter().map(|message| {
Mismatch::StatusMismatch {
expected,
actual,
mismatch: message.clone()
}
}).collect())
} else if expected != actual {
Err(vec![Mismatch::StatusMismatch {
expected,
actual,
mismatch: format!("expected {} but was {}", expected, actual)
}])
} else {
Ok(())
}
}
/// Matches the actual and expected responses.
pub async fn match_response<'a>(
expected: HttpResponse,
actual: HttpResponse,
pact: &Box<dyn Pact + Send + Sync + 'a>,
interaction: &Box<dyn Interaction + Send + Sync>
) -> Vec<Mismatch> {
let mut mismatches = vec![];
info!("comparing to expected response: {}", expected);
let plugin_data = setup_plugin_config(pact, interaction);
let status_context = MatchingContext::new(DiffConfig::AllowUnexpectedKeys,
&expected.matching_rules.rules_for_category("status").unwrap_or_default(),
&plugin_data);
let body_context = MatchingContext::new(DiffConfig::AllowUnexpectedKeys,
&expected.matching_rules.rules_for_category("body").unwrap_or_default(),
&plugin_data);
let header_context = MatchingContext::new(DiffConfig::AllowUnexpectedKeys,
&expected.matching_rules.rules_for_category("header").unwrap_or_default(),
&plugin_data);
mismatches.extend_from_slice(match_body(&expected, &actual, &body_context, &header_context).await
.mismatches().as_slice());
if let Err(m) = match_status(expected.status, actual.status, &status_context) {
mismatches.extend_from_slice(&m);
}
let result = match_headers(expected.headers, actual.headers,
&header_context);
for values in result.values() {
mismatches.extend_from_slice(values.as_slice());
}
mismatches
}
fn setup_plugin_config<'a>(
pact: &Box<dyn Pact + Send + Sync + 'a>,
interaction: &Box<dyn Interaction + Send + Sync>
) -> HashMap<String, PluginInteractionConfig> {
pact.plugin_data().iter().map(|data| {
let interaction_config = if let Some(v4_interaction) = interaction.as_v4() {
v4_interaction.plugin_config().get(&data.name).cloned().unwrap_or_default()
} else {
hashmap! {}
};
(data.name.clone(), PluginInteractionConfig {
pact_configuration: data.configuration.clone(),
interaction_configuration: interaction_config
})
}).collect()
}
/// Matches the actual message contents to the expected one. This takes into account the content type of each.
pub async fn match_message_contents(
expected: &MessageContents,
actual: &MessageContents,
context: &MatchingContext
) -> Result<(), Vec<Mismatch>> {
let expected_content_type = expected.message_content_type().unwrap_or_default();
let actual_content_type = actual.message_content_type().unwrap_or_default();
debug!("expected content type = '{}', actual content type = '{}'", expected_content_type,
actual_content_type);
if expected_content_type.is_equivalent_to(&actual_content_type) {
let result = match_body_content(&expected_content_type, expected, actual, context).await;
match result {
BodyMatchResult::BodyTypeMismatch { expected_type, actual_type, message, expected, actual } => {
Err(vec![ Mismatch::BodyTypeMismatch {
expected: expected_type,
actual: actual_type,
mismatch: message,
expected_body: expected,
actual_body: actual
} ])
},
BodyMatchResult::BodyMismatches(results) => {
Err(results.values().flat_map(|values| values.iter().cloned()).collect())
},
_ => Ok(())
}
} else if expected.contents.is_present() {
Err(vec![ Mismatch::BodyTypeMismatch {
expected: expected_content_type.to_string(),
actual: actual_content_type.to_string(),
mismatch: format!("Expected message with content type {} but was {}",
expected_content_type, actual_content_type),
expected_body: expected.contents.value(),
actual_body: actual.contents.value()
} ])
} else {
Ok(())
}
}
/// Matches the actual message metadata to the expected one.
pub fn match_message_metadata(
expected: &MessageContents,
actual: &MessageContents,
context: &MatchingContext
) -> HashMap<String, Vec<Mismatch>> {
debug!("Matching message metadata");
let mut result = hashmap!{};
let expected_metadata = &expected.metadata;
let actual_metadata = &actual.metadata;
debug!("Matching message metadata. Expected '{:?}', Actual '{:?}'", expected_metadata, actual_metadata);
if !expected_metadata.is_empty() || context.config == DiffConfig::NoUnexpectedKeys {
for (key, value) in expected_metadata {
match actual_metadata.get(key) {
Some(actual_value) => {
result.insert(key.clone(), match_metadata_value(key, value,
actual_value, context).err().unwrap_or_default());
},
None => {
result.insert(key.clone(), vec![Mismatch::MetadataMismatch { key: key.clone(),
expected: json_to_string(&value),
actual: "".to_string(),
mismatch: format!("Expected message metadata '{}' but was missing", key) }]);
}
}
}
}
result
}
fn match_metadata_value(key: &str, expected: &Value, actual: &Value, context: &MatchingContext) -> Result<(), Vec<Mismatch>> {
debug!("Comparing metadata values for key '{}'", key);
let path = vec![key];
let matcher_result = if context.matcher_is_defined(&path) {
matchers::match_values(&path, context, expected, actual)
} else if key.to_ascii_lowercase() == "contenttype" || key.to_ascii_lowercase() == "content-type" {
debug!("Comparing message context type '{}' => '{}'", expected, actual);
headers::match_parameter_header(expected.as_str().unwrap_or_default(),
actual.as_str().unwrap_or_default(), key, "metadata")
} else {
expected.matches_with(actual, &MatchingRule::Equality, false).map_err(|err| vec![err.to_string()])
};
matcher_result.map_err(|messages| {
messages.iter().map(|message| {
Mismatch::MetadataMismatch {
key: key.to_string(),
expected: expected.to_string(),
actual: actual.to_string(),
mismatch: format!("Expected metadata key '{}' to have value '{}' but was '{}' - {}", key, expected, actual, message)
}
}).collect()
})
}
/// Matches the actual and expected messages.
pub async fn match_message<'a>(
expected: &Box<dyn Interaction + Send + Sync>,
actual: &Box<dyn Interaction + Send + Sync>,
pact: &Box<dyn Pact + Send + Sync + 'a>) -> Vec<Mismatch> {
let mut mismatches = vec![];
if expected.is_message() && actual.is_message() {
info!("comparing to expected message: {:?}", expected);
let expected_message = expected.as_message().unwrap();
let actual_message = actual.as_message().unwrap();
let matching_rules = expected.matching_rules().unwrap_or_default();
let plugin_data = setup_plugin_config(pact, expected);
let body_context = if expected.is_v4() {
MatchingContext {
matchers: matching_rules.rules_for_category("content").unwrap_or_default(),
config: DiffConfig::AllowUnexpectedKeys,
matching_spec: PactSpecification::V4,
plugin_configuration: plugin_data.clone()
}
} else {
MatchingContext::new(DiffConfig::AllowUnexpectedKeys,
&matching_rules.rules_for_category("body").unwrap_or_default(),
&plugin_data)
};
let metadata_context = MatchingContext::new(DiffConfig::AllowUnexpectedKeys,
&matching_rules.rules_for_category("metadata").unwrap_or_default(),
&plugin_data);
let contents = match_message_contents(&expected_message.as_message_content(), &actual_message.as_message_content(), &body_context).await;
mismatches.extend_from_slice(contents.err().unwrap_or_default().as_slice());
for values in match_message_metadata(&expected_message.as_message_content(), &actual_message.as_message_content(), &metadata_context).values() { | } else {
mismatches.push(Mismatch::BodyTypeMismatch {
expected: "message".into(),
actual: actual.type_of(),
mismatch: format!("Cannot compare a {} with a {}", expected.type_of(), actual.type_of()),
expected_body: None,
actual_body: None
});
}
mismatches
}
/// Matches synchronous request/response messages
pub async fn match_sync_message<'a>(expected: SynchronousMessage, actual: SynchronousMessage, pact: &Box<dyn Pact + Send + Sync + 'a>) -> Vec<Mismatch> {
let mut mismatches = match_sync_message_request(&expected, &actual, pact).await;
let response_result = match_sync_message_response(&expected, &expected.response, &actual.response, pact).await;
mismatches.extend_from_slice(&*response_result);
mismatches
}
/// Match the request part of a synchronous request/response message
pub async fn match_sync_message_request<'a>(
expected: &SynchronousMessage,
actual: &SynchronousMessage,
pact: &Box<dyn Pact + Send + Sync + 'a>
) -> Vec<Mismatch> {
info!("comparing to expected message request: {:?}", expected);
let matching_rules = &expected.request.matching_rules;
let plugin_data = setup_plugin_config(pact, &expected.boxed());
let body_context = MatchingContext {
matchers: matching_rules.rules_for_category("content").unwrap_or_default(),
config: DiffConfig::AllowUnexpectedKeys,
matching_spec: PactSpecification::V4,
plugin_configuration: plugin_data.clone()
};
let metadata_context = MatchingContext::new(DiffConfig::AllowUnexpectedKeys,
&matching_rules.rules_for_category("metadata").unwrap_or_default(),
&plugin_data);
let contents = match_message_contents(&expected.request, &actual.request, &body_context).await;
let mut mismatches = vec![];
mismatches.extend_from_slice(contents.err().unwrap_or_default().as_slice());
for values in match_message_metadata(&expected.request, &actual.request, &metadata_context).values() {
mismatches.extend_from_slice(values.as_slice());
}
mismatches
}
/// Match the response part of a synchronous request/response message
pub async fn match_sync_message_response<'a>(
expected: &SynchronousMessage,
expected_responses: &[MessageContents],
actual_responses: &[MessageContents],
pact: &Box<dyn Pact + Send + Sync + 'a>
) -> Vec<Mismatch> {
info!("comparing to expected message responses: {:?}", expected_responses);
let mut mismatches = vec![];
if expected_responses.len() != actual_responses.len() {
if !expected_responses.is_empty() && actual_responses.is_empty() {
mismatches.push(Mismatch::BodyTypeMismatch {
expected: "message response".into(),
actual: "".into(),
mismatch: "Expected a message with a response, but the actual response was empty".into(),
expected_body: None,
actual_body: None
});
} else if !expected_responses.is_empty() {
mismatches.push(Mismatch::BodyTypeMismatch {
expected: "message response".into(),
actual: "".into(),
mismatch: format!("Expected a message with {} responses, but the actual response had {}",
expected_responses.len(), actual_responses.len()),
expected_body: None,
actual_body: None
});
}
} else {
let plugin_data = setup_plugin_config(pact, &expected.boxed());
for (expected_response, actual_response) in expected_responses.iter().zip(actual_responses) {
let matching_rules = &expected_response.matching_rules;
let body_context = MatchingContext {
matchers: matching_rules.rules_for_category("content").unwrap_or_default(),
config: DiffConfig::AllowUnexpectedKeys,
matching_spec: PactSpecification::V4,
plugin_configuration: plugin_data.clone()
};
let metadata_context = MatchingContext::new(DiffConfig::AllowUnexpectedKeys,
&matching_rules.rules_for_category("metadata").unwrap_or_default(),
&plugin_data);
let contents = match_message_contents(expected_response, actual_response, &body_context).await;
mismatches.extend_from_slice(contents.err().unwrap_or_default().as_slice());
for values in match_message_metadata(expected_response, actual_response, &metadata_context).values() {
mismatches.extend_from_slice(values.as_slice());
}
}
}
mismatches
}
/// Generates the request by applying any defined generators
pub async fn generate_request(request: &HttpRequest, mode: &GeneratorTestMode, context: &HashMap<&str, Value>) -> HttpRequest {
let mut request = request.clone();
let generators = request.build_generators(&GeneratorCategory::PATH);
if !generators.is_empty() {
debug!("Applying path generator...");
apply_generators(mode, &generators, &mut |_, generator| {
if let Ok(v) = generator.generate_value(&request.path, context, &DefaultVariantMatcher.boxed()) {
request.path = v;
}
});
}
let generators = request.build_generators(&GeneratorCategory::HEADER);
if !generators.is_empty() {
debug!("Applying header generators...");
apply_generators(mode, &generators, &mut |key, generator| {
if let Some(header) = key.first_field() {
if let Some(ref mut headers) = request.headers {
if headers.contains_key(header) {
if let Ok(v) = generator.generate_value(&headers.get(header).unwrap().clone(), context, &DefaultVariantMatcher.boxed()) {
headers.insert(header.to_string(), v);
}
}
}
}
});
}
let generators = request.build_generators(&GeneratorCategory::QUERY);
if !generators.is_empty() {
debug!("Applying query generators...");
apply_generators(mode, &generators, &mut |key, generator| {
if let Some(param) = key.first_field() {
if let Some(ref mut parameters) = request.query {
if let Some(parameter) = parameters.get_mut(param) {
let mut generated = parameter.clone();
for (index, val) in parameter.iter().enumerate() {
if let Ok(v) = generator.generate_value(val, context, &DefaultVariantMatcher.boxed()) {
generated[index] = v;
}
}
*parameter = generated;
}
}
}
});
}
let generators = request.build_generators(&GeneratorCategory::BODY);
if !generators.is_empty() && request.body.is_present() {
debug!("Applying body generators...");
match generators_process_body(mode, &request.body, request.content_type(),
context, &generators, &DefaultVariantMatcher{}).await {
Ok(body) => request.body = body,
Err(err) => error!("Failed to generate the body, will use the original: {}", err)
}
}
request
}
/// Generates the response by applying any defined generators
pub async fn generate_response(response: &HttpResponse, mode: &GeneratorTestMode, context: &HashMap<&str, Value>) -> HttpResponse {
let mut response = response.clone();
let generators = response.build_generators(&GeneratorCategory::STATUS);
if !generators.is_empty() {
debug!("Applying status generator...");
apply_generators(mode, &generators, &mut |_, generator| {
if let Ok(v) = generator.generate_value(&response.status, context, &DefaultVariantMatcher.boxed()) {
debug!("Generated value for status: {}", v);
response.status = v;
}
});
}
let generators = response.build_generators(&GeneratorCategory::HEADER);
if !generators.is_empty() {
debug!("Applying header generators...");
apply_generators(mode, &generators, &mut |key, generator| {
if let Some(header) = key.first_field() {
if let Some(ref mut headers) = response.headers {
if headers.contains_key(header) {
match generator.generate_value(&headers.get(header).unwrap().clone(), context, &DefaultVariantMatcher.boxed()) {
Ok(v) => {
debug!("Generated value for header: {} -> {:?}", header, v);
headers.insert(header.to_string(), v)
},
Err(_) => None
};
}
}
}
});
}
let generators = response.build_generators(&GeneratorCategory::BODY);
if !generators.is_empty() && response.body.is_present() {
debug!("Applying body generators...");
match generators_process_body(mode, &response.body, response.content_type(),
context, &generators, &DefaultVariantMatcher{}).await {
Ok(body) => response.body = body,
Err(err) => error!("Failed to generate the body, will use the original: {}", err)
}
}
response
}
/// Matches the request part of the interaction
pub async fn match_interaction_request(
expected: Box<dyn Interaction + Send + Sync>,
actual: Box<dyn Interaction + Send + Sync>,
pact: Box<dyn Pact + Send + Sync>,
_spec_version: &PactSpecification
) -> anyhow::Result<RequestMatchResult> {
if let Some(http_interaction) = expected.as_v4_http() {
let request = actual.as_v4_http()
.ok_or_else(|| anyhow!("Could not unpack actual request as a V4 Http Request"))?.request;
Ok(match_request(http_interaction.request, request, &pact, &expected).await)
} else {
Err(anyhow!("match_interaction_request must be called with HTTP request/response interactions, got {}", expected.type_of()))
}
}
/// Matches the response part of the interaction
pub async fn match_interaction_response(
expected: Box<dyn Interaction + Sync>,
actual: Box<dyn Interaction + Sync>,
pact: Box<dyn Pact + Send + Sync>,
_spec_version: &PactSpecification
) -> anyhow::Result<Vec<Mismatch>> {
if let Some(expected) = expected.as_v4_http() {
let expected_response = expected.response.clone();
let expected = expected.boxed();
let response = actual.as_v4_http()
.ok_or_else(|| anyhow!("Could not unpack actual response as a V4 Http Response"))?.response;
Ok(match_response(expected_response, response, &pact, &expected).await)
} else {
Err(anyhow!("match_interaction_response must be called with HTTP request/response interactions, got {}", expected.type_of()))
}
}
/// Matches an interaction
pub async fn match_interaction(
expected: Box<dyn Interaction + Send + Sync>,
actual: Box<dyn Interaction + Send + Sync>,
pact: Box<dyn Pact + Send + Sync>,
_spec_version: &PactSpecification
) -> anyhow::Result<Vec<Mismatch>> {
if let Some(expected) = expected.as_v4_http() {
let expected_request = expected.request.clone();
let expected_response = expected.response.clone();
let expected = expected.boxed();
let request = actual.as_v4_http()
.ok_or_else(|| anyhow!("Could not unpack actual request as a V4 Http Request"))?.request;
let request_result = match_request(expected_request, request, &pact, &expected).await;
let response = actual.as_v4_http()
.ok_or_else(|| anyhow!("Could not unpack actual response as a V4 Http Response"))?.response;
let response_result = match_response(expected_response, response, &pact, &expected).await;
let mut mismatches = request_result.mismatches();
mismatches.extend_from_slice(&*response_result);
Ok(mismatches)
} else if expected.is_message() || expected.is_v4() {
Ok(match_message(&expected, &actual, &pact).await)
} else {
Err(anyhow!("match_interaction must be called with either an HTTP request/response interaction or a Message, got {}", expected.type_of()))
}
}
#[cfg(test)]
mod tests;
#[cfg(test)]
mod generator_tests; | mismatches.extend_from_slice(values.as_slice());
} |
web.go | // Demonstrates usage of nosurf with the web.go package
package main
import (
"html/template"
"net/http"
"github.com/goffee/goffee/Godeps/_workspace/src/github.com/justinas/nosurf"
"github.com/hoisie/web"
)
var templateString = `
<!doctype html>
<html>
<body>
{{ if .name }}
<p>Your name: {{ .name }}</p>
{{ end }}
<form action="/" method="POST">
<input type="text" name="name">
<input type="hidden" name="csrf_token" value="{{ .token }}">
<input type="submit" value="Send">
</form>
</body>
</html>
`
var templ = template.Must(template.New("t1").Parse(templateString))
func | (ctx *web.Context) {
templateCtx := make(map[string]string)
templateCtx["token"] = nosurf.Token(ctx.Request)
if ctx.Request.Method == "POST" {
templateCtx["name"] = ctx.Params["name"]
}
templ.Execute(ctx, templateCtx)
}
func main() {
server := web.NewServer()
server.Get("/", myHandler)
server.Post("/", myHandler)
http.ListenAndServe(":8000", nosurf.New(server))
}
| myHandler |
slider.js | $(document).ready(function () {
$("#slider").bxSlider({
auto: true,
displaySlideQty: 1,
minSlides: 1,
maxSlides: 1,
slideWidth: 250,
slideMargin: 10, | pause: 3000,
pager: true,
pagerType: "short",
})(jQuery);
}); | randomStart: true,
captions: true, |
plant.go | package server
import (
"context"
"errors"
"fmt"
"net/http"
"strconv"
"time"
"github.com/calvinmclean/automated-garden/garden-app/pkg"
"github.com/calvinmclean/automated-garden/garden-app/pkg/influxdb"
"github.com/calvinmclean/automated-garden/garden-app/pkg/mqtt"
"github.com/go-chi/chi/v5"
"github.com/go-chi/render"
"github.com/go-co-op/gocron"
"github.com/rs/xid"
)
const (
plantBasePath = "/plants"
plantPathParam = "plantID"
plantCtxKey = contextKey("plant")
)
// PlantsResource encapsulates the structs and dependencies necessary for the "/plants" API
// to function, including storage, scheduling, and caching
type PlantsResource struct {
GardensResource
mqttClient mqtt.Client
moistureCache map[xid.ID]float64
scheduler *gocron.Scheduler
}
// NewPlantsResource creates a new PlantsResource
func NewPlantsResource(gr GardensResource) (PlantsResource, error) {
pr := PlantsResource{
GardensResource: gr,
moistureCache: map[xid.ID]float64{},
scheduler: gocron.NewScheduler(time.Local),
}
// Initialize MQTT Client
var err error
pr.mqttClient, err = mqtt.NewMQTTClient(gr.config.MQTTConfig, nil)
if err != nil {
err = fmt.Errorf("unable to initialize MQTT client: %v", err)
return pr, err
}
// Initialize watering Jobs for each Plant from the storage client
allGardens, err := pr.storageClient.GetGardens(false)
if err != nil {
return pr, err
}
for _, g := range allGardens {
allPlants, err := pr.storageClient.GetPlants(g.ID, false)
if err != nil {
return pr, err
}
for _, p := range allPlants {
if err = pr.addWateringSchedule(g, p); err != nil {
err = fmt.Errorf("unable to add watering Job for Plant %s: %v", p.ID.String(), err)
return pr, err
}
}
}
pr.scheduler.StartAsync()
return pr, err
}
// routes creates all of the routing that is prefixed by "/plant" for interacting with Plant resources
func (pr PlantsResource) routes() chi.Router {
r := chi.NewRouter()
r.Post("/", pr.createPlant)
r.Get("/", pr.getAllPlants)
r.Route(fmt.Sprintf("/{%s}", plantPathParam), func(r chi.Router) {
r.Use(pr.plantContextMiddleware)
r.Get("/", pr.getPlant)
r.Patch("/", pr.updatePlant)
r.Delete("/", pr.endDatePlant)
// Add new middleware to restrict certain paths to non-end-dated Plants
r.Route("/", func(r chi.Router) {
r.Use(pr.restrictEndDatedMiddleware)
r.Post("/action", pr.plantAction)
r.Get("/history", pr.wateringHistory)
})
})
return r
}
// backwardCompatibleRoutes is the same as regular routes, but uses a different middleware allowing for compatibility
// with the API before adding Gardens. This does not allow for creating Plants since that requires a Garden
func (pr PlantsResource) backwardCompatibleRoutes() chi.Router {
r := chi.NewRouter()
r.Use(pr.backwardCompatibleMiddleware)
r.Get("/", pr.getAllPlants)
r.Route(fmt.Sprintf("/{%s}", plantPathParam), func(r chi.Router) {
r.Use(pr.plantContextMiddleware)
r.Get("/", pr.getPlant)
r.Patch("/", pr.updatePlant)
r.Delete("/", pr.endDatePlant)
// Add new middleware to restrict certain paths to non-end-dated Plants
r.Route("/", func(r chi.Router) {
r.Use(pr.restrictEndDatedMiddleware)
r.With(pr.backwardsCompatibleActionMiddleware).Post("/action", pr.plantAction)
r.With(pr.backwardsCompatibleActionMiddleware).Get("/history", pr.wateringHistory)
})
})
return r
}
// restrictEndDatedMiddleware will return a 400 response if the requested Plant is end-dated
func (pr PlantsResource) restrictEndDatedMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
plant := r.Context().Value(plantCtxKey).(*pkg.Plant)
if plant.EndDated() {
render.Render(w, r, ErrInvalidRequest(fmt.Errorf("resource not available for end-dated Plant")))
return
}
next.ServeHTTP(w, r)
})
}
// plantContextMiddleware middleware is used to load a Plant object from the URL
// parameters passed through as the request. In case the Plant could not be found,
// we stop here and return a 404.
func (pr PlantsResource) plantContextMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
garden := r.Context().Value(gardenCtxKey).(*pkg.Garden)
plantID, err := xid.FromString(chi.URLParam(r, plantPathParam))
if err != nil {
render.Render(w, r, ErrInvalidRequest(err))
return
}
plant := garden.Plants[plantID]
if plant == nil {
render.Render(w, r, ErrNotFoundResponse)
return
}
// t := context.WithValue(r.Context(), gardenCtxKey, garden)
ctx := context.WithValue(r.Context(), plantCtxKey, plant)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// backwardCompatibleMiddleware allows REST APIs that are compatible with the V1 which did not include gardens resources.
// Instead of relying on gardenID in the route, this will combine all Gardens into a new one containing all Plants
func (pr PlantsResource) backwardCompatibleMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
allPlants := map[xid.ID]*pkg.Plant{}
gardens, err := pr.storageClient.GetGardens(false)
if err != nil {
render.Render(w, r, InternalServerError(err))
return
}
for _, g := range gardens {
for id, p := range g.Plants {
allPlants[id] = p
}
}
garden := &pkg.Garden{
Name: "All Gardens Combined",
Plants: allPlants,
}
ctx := context.WithValue(r.Context(), gardenCtxKey, garden)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func (pr PlantsResource) backwardsCompatibleActionMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
plant := r.Context().Value(plantCtxKey).(*pkg.Plant)
garden, err := pr.storageClient.GetGarden(plant.GardenID)
if err != nil {
logger.Error("Error getting Garden for backwards-compatible action: ", err)
render.Render(w, r, InternalServerError(err))
return
}
ctx := context.WithValue(r.Context(), gardenCtxKey, garden)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// plantAction reads an AggregateAction request and uses it to execute one of the actions
// that is available to run against a Plant. This one endpoint is used for all the different
// kinds of actions so the action information is carried in the request body
func (pr PlantsResource) plantAction(w http.ResponseWriter, r *http.Request) {
garden := r.Context().Value(gardenCtxKey).(*pkg.Garden)
plant := r.Context().Value(plantCtxKey).(*pkg.Plant)
action := &AggregateActionRequest{}
if err := render.Bind(r, action); err != nil {
render.Render(w, r, ErrInvalidRequest(err))
return
}
logger.Infof("Received request to perform action on Plant %s\n", plant.ID)
if err := action.Execute(garden, plant, pr.mqttClient, pr.influxdbClient); err != nil {
render.Render(w, r, InternalServerError(err))
return
}
// Save the Plant in case anything was changed (watering a plant might change the skip_count field)
// TODO: consider giving the action the ability to use the storage client
if err := pr.storageClient.SavePlant(plant); err != nil {
logger.Error("Error saving plant: ", err)
render.Render(w, r, InternalServerError(err))
return
}
render.Status(r, http.StatusAccepted)
render.DefaultResponder(w, r, nil)
}
// getPlant simply returns the Plant requested by the provided ID
func (pr PlantsResource) getPlant(w http.ResponseWriter, r *http.Request) {
plant := r.Context().Value(plantCtxKey).(*pkg.Plant)
garden := r.Context().Value(gardenCtxKey).(*pkg.Garden)
moisture, cached := pr.moistureCache[plant.ID]
plantResponse := pr.NewPlantResponse(plant, moisture)
if err := render.Render(w, r, plantResponse); err != nil {
render.Render(w, r, ErrRender(err))
}
// If moisture was not already cached (and plant has moisture sensor), get it and cache it
// Otherwise, clear cache
if !cached && plant.WateringStrategy.MinimumMoisture > 0 {
// I was doing this with a goroutine, but that made the call untestable. I don't think there was any benefit to
// using the goroutine because the result is already rendered
pr.getAndCacheMoisture(garden, plant)
} else {
delete(pr.moistureCache, plant.ID)
}
}
// updatePlant will change any specified fields of the Plant and save it
func (pr PlantsResource) updatePlant(w http.ResponseWriter, r *http.Request) {
request := &PlantRequest{r.Context().Value(plantCtxKey).(*pkg.Plant)}
garden := r.Context().Value(gardenCtxKey).(*pkg.Garden)
// Read the request body into existing plant to overwrite fields
if err := render.Bind(r, request); err != nil {
render.Render(w, r, ErrInvalidRequest(err))
return
}
plant := request.Plant
// Update the watering schedule for the Plant
if err := pr.resetWateringSchedule(garden, plant); err != nil {
render.Render(w, r, InternalServerError(err))
return
}
// Save the Plant
if err := pr.storageClient.SavePlant(plant); err != nil {
render.Render(w, r, InternalServerError(err))
return
}
if err := render.Render(w, r, pr.NewPlantResponse(plant, 0)); err != nil {
render.Render(w, r, ErrRender(err))
}
}
// endDatePlant will mark the Plant's end date as now and save it
func (pr PlantsResource) endDatePlant(w http.ResponseWriter, r *http.Request) {
plant := r.Context().Value(plantCtxKey).(*pkg.Plant)
// Set end date of Plant and save
now := time.Now()
plant.EndDate = &now
if err := pr.storageClient.SavePlant(plant); err != nil {
render.Render(w, r, InternalServerError(err))
return
}
// Remove scheduled watering Job
if err := pr.removeWateringSchedule(plant); err != nil && !errors.Is(err, gocron.ErrJobNotFoundWithTag) {
logger.Errorf("Unable to remove watering Job for Plant %s: %v", plant.ID.String(), err)
render.Render(w, r, InternalServerError(err))
return
}
if err := render.Render(w, r, pr.NewPlantResponse(plant, 0)); err != nil {
render.Render(w, r, ErrRender(err))
}
}
// getAllPlants will return a list of all Plants
func (pr PlantsResource) getAllPlants(w http.ResponseWriter, r *http.Request) {
getEndDated := r.URL.Query().Get("end_dated") == "true"
garden := r.Context().Value(gardenCtxKey).(*pkg.Garden)
plants := []*pkg.Plant{}
for _, p := range garden.Plants {
if getEndDated || (p.EndDate == nil || p.EndDate.After(time.Now())) {
plants = append(plants, p)
}
}
if err := render.Render(w, r, pr.NewAllPlantsResponse(plants)); err != nil {
render.Render(w, r, ErrRender(err))
}
}
// createPlant will create a new Plant resource
func (pr PlantsResource) createPlant(w http.ResponseWriter, r *http.Request) {
request := &PlantRequest{}
if err := render.Bind(r, request); err != nil {
render.Render(w, r, ErrInvalidRequest(err))
return
}
plant := request.Plant
| _, err := time.Parse(pkg.WaterTimeFormat, plant.WateringStrategy.StartTime)
if err != nil {
logger.Errorf("Invalid time format for WateringStrategy.StartTime: %s", plant.WateringStrategy.StartTime)
render.Render(w, r, ErrInvalidRequest(err))
return
}
// Assign values to fields that may not be set in the request
plant.ID = xid.New()
if plant.CreatedAt == nil {
now := time.Now()
plant.CreatedAt = &now
}
plant.GardenID = garden.ID
// Start watering schedule
if err := pr.addWateringSchedule(garden, plant); err != nil {
logger.Errorf("Unable to add watering Job for Plant %s: %v", plant.ID.String(), err)
}
// Save the Plant
if err := pr.storageClient.SavePlant(plant); err != nil {
logger.Error("Error saving plant: ", err)
render.Render(w, r, InternalServerError(err))
return
}
render.Status(r, http.StatusCreated)
if err := render.Render(w, r, pr.NewPlantResponse(plant, 0)); err != nil {
render.Render(w, r, ErrRender(err))
}
}
// wateringHistory responds with the Plant's recent watering events read from InfluxDB
func (pr PlantsResource) wateringHistory(w http.ResponseWriter, r *http.Request) {
garden := r.Context().Value(gardenCtxKey).(*pkg.Garden)
plant := r.Context().Value(plantCtxKey).(*pkg.Plant)
// Read query parameters and set default values
timeRangeString := r.URL.Query().Get("range")
if len(timeRangeString) == 0 {
timeRangeString = "72h"
}
limitString := r.URL.Query().Get("limit")
if len(limitString) == 0 {
limitString = "5"
}
// Parse query parameter strings into correct types
timeRange, err := time.ParseDuration(timeRangeString)
if err != nil {
render.Render(w, r, ErrInvalidRequest(err))
return
}
limit, err := strconv.ParseUint(limitString, 0, 64)
if err != nil {
render.Render(w, r, ErrInvalidRequest(err))
return
}
history, err := pr.getWateringHistory(plant, garden, timeRange, int(limit))
if err != nil {
render.Render(w, r, InternalServerError(err))
return
}
if err := render.Render(w, r, NewPlantWateringHistoryResponse(history)); err != nil {
render.Render(w, r, ErrRender(err))
}
}
func (pr PlantsResource) getAndCacheMoisture(g *pkg.Garden, p *pkg.Plant) {
defer pr.influxdbClient.Close()
ctx, cancel := context.WithTimeout(context.Background(), influxdb.QueryTimeout)
defer cancel()
moisture, err := pr.influxdbClient.GetMoisture(ctx, p.PlantPosition, g.Name)
if err != nil {
logger.Errorf("unable to get moisture of Plant %v: %v", p.ID, err)
}
pr.moistureCache[p.ID] = moisture
}
// getWateringHistory gets previous WateringEvents for this Plant from InfluxDB
func (pr PlantsResource) getWateringHistory(plant *pkg.Plant, garden *pkg.Garden, timeRange time.Duration, limit int) (result []pkg.WateringHistory, err error) {
defer pr.influxdbClient.Close()
ctx, cancel := context.WithTimeout(context.Background(), influxdb.QueryTimeout)
defer cancel()
history, err := pr.influxdbClient.GetWateringHistory(ctx, plant.PlantPosition, garden.Name, timeRange)
if err != nil {
return
}
for _, h := range history {
if len(result) >= limit {
break
}
result = append(result, pkg.WateringHistory{
WateringAmount: h["WateringAmount"].(int),
RecordTime: h["RecordTime"].(time.Time),
})
}
return
} | garden := r.Context().Value(gardenCtxKey).(*pkg.Garden)
// Check that water time is valid |
math.rs | use tract_core::internal::*;
use tract_core::ops as tractops;
use crate::model::ParsingContext;
use crate::model::TfOpRegister;
use crate::tfpb::tensorflow::NodeDef;
mod reduce;
pub fn register_all_ops(reg: &mut TfOpRegister) {
reg.insert("Abs", |_, _| Ok(Box::new(tractops::math::abs())));
reg.insert("Add", |_, _| Ok(Box::new(tractops::math::add::bin())));
reg.insert("AddN", add_n);
reg.insert("AddV2", |_, _| Ok(Box::new(tractops::math::add::bin())));
reg.insert("BiasAdd", |_, _| Ok(Box::new(tractops::math::add::bin())));
reg.insert("Ceil", |_, _| Ok(Box::new(tractops::math::ceil())));
reg.insert("Div", |_, _| Ok(Box::new(tractops::math::div::bin())));
reg.insert("FloorMod", |_, _| Ok(Box::new(tractops::math::rem::bin())));
reg.insert("MatMul", mat_mul);
reg.insert("Max", reduce::max);
reg.insert("Mean", reduce::mean);
reg.insert("Min", reduce::min);
reg.insert("Prod", reduce::prod);
reg.insert("Sum", reduce::sum);
reg.insert("Maximum", |_, _| Ok(Box::new(tractops::math::max::bin())));
reg.insert("Minimum", |_, _| Ok(Box::new(tractops::math::min::bin())));
reg.insert("Less", |_, _| Ok(Box::new(tractops::logic::lesser::bin())));
reg.insert("Log", |_, _| Ok(Box::new(tractops::math::ln())));
reg.insert("Mul", |_, _| Ok(Box::new(tractops::math::mul::bin())));
reg.insert("Pow", |_, _| Ok(Box::new(tractops::math::pow::bin())));
reg.insert("Neg", |_, _| Ok(Box::new(tractops::math::neg())));
reg.insert("RealDiv", |_, _| Ok(Box::new(tractops::math::div::bin())));
reg.insert("Rsqrt", |_, _| Ok(Box::new(tractops::math::rsqrt())));
reg.insert("Sub", |_, _| Ok(Box::new(tractops::math::sub::bin())));
reg.insert("Tanh", |_, _| Ok(Box::new(tractops::math::tanh())));
}
pub fn add_n(_ctx: &ParsingContext, _pb: &NodeDef) -> TractResult<Box<dyn InferenceOp>> {
Ok(Box::new(tractops::binary::Nary(Box::new(tractops::math::Add), false)))
}
pub fn mat_mul(_ctx: &ParsingContext, pb: &NodeDef) -> TractResult<Box<dyn InferenceOp>> | {
let trans_a = pb.get_attr_bool("transpose_a")?;
let trans_b = pb.get_attr_bool("transpose_b")?;
Ok(Box::new(
tract_core::ops::math::MatMul::default().with_a_trans(trans_a).with_b_trans(trans_b),
))
} |
|
prod.js | /* eslint-disable */
const workerFarm = require('worker-farm');
const locales = require('box-locales');
const numCPUs = require('os').cpus().length;
const execSync = require('child_process').execSync;
const path = require('path');
const filename = path.basename(__filename);
const bundleCount = locales.length * 2; // One with react, and one without
let counter = 0;
const workers = workerFarm(
{
maxConcurrentWorkers: numCPUs - 2,
maxRetries: 0
}, | );
[true, false].forEach((react) => {
locales.forEach((locale) => {
workers(locale, react, (error) => {
if (++counter === bundleCount || error) {
// terminate after all locales have been processed
workerFarm.end(workers);
}
if (error) {
// kill the node process that spawns the workers as well as all processes been spawned
execSync(`ps ax | grep "${filename}" | cut -b1-06 | xargs -t kill`);
}
});
});
}); | require.resolve('./build_locale.js') |
test_unpooling_2d.py | import unittest
import numpy
import six
import chainer
from chainer.backends import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
from chainer_tests.functions_tests.pooling_tests import pooling_nd_helper
@testing.parameterize(*testing.product_dict(
[
# we assume insize as (2, 1)
# standard output size which is estimated with get_deconv_outsize
# function
{'cover_all': False, 'outsize': (4, 2)},
{'cover_all': True, 'outsize': (3, 1)},
{'cover_all': False, 'outsize': None, 'expected_outsize': (4, 2)},
{'cover_all': True, 'outsize': None, 'expected_outsize': (3, 1)},
# another sizes which can be outsize of insize (2, 1)
{'cover_all': False, 'outsize': (5, 2)},
{'cover_all': True, 'outsize': (4, 2)},
],
[
{'dtype': numpy.float16},
{'dtype': numpy.float32},
{'dtype': numpy.float64},
],
))
class TestUnpooling2D(unittest.TestCase):
def setUp(self):
self.N = 2
self.n_channels = 3
inh, inw = 2, 1
self.x = pooling_nd_helper.shuffled_linspace(
(self.N, self.n_channels, inh, inw), self.dtype)
self.ksize = 2
outh, outw = self.outsize or self.expected_outsize
self.gy = numpy.random.uniform(
-1, 1, (self.N, self.n_channels, outh, outw)).astype(self.dtype)
self.check_backward_options = {'atol': 1e-4, 'rtol': 1e-3}
self.check_double_backward_options = {}
if self.dtype == numpy.float16:
self.check_backward_options = {'atol': 2e-3, 'rtol': 2e-2}
self.check_double_backward_options = {'atol': 3e-3, 'rtol': 3e-2}
self.ggx = numpy.random.uniform(
-1, 1, self.x.shape).astype(self.dtype)
def check_forward(self, x_data):
x = chainer.Variable(x_data)
y = functions.unpooling_2d(x, self.ksize, outsize=self.outsize,
cover_all=self.cover_all)
self.assertEqual(y.data.dtype, self.dtype)
y_data = cuda.to_cpu(y.data)
self.assertEqual(self.gy.shape, y_data.shape)
for i in six.moves.range(self.N):
for c in six.moves.range(self.n_channels):
outsize = self.outsize or self.expected_outsize
assert y_data.shape[2:] == outsize
if outsize == (5, 2):
expect = numpy.zeros(outsize, dtype=self.dtype)
expect[:2, :] = self.x[i, c, 0, 0]
expect[2:4, :] = self.x[i, c, 1, 0]
elif outsize == (4, 2):
expect = numpy.array([
[self.x[i, c, 0, 0], self.x[i, c, 0, 0]],
[self.x[i, c, 0, 0], self.x[i, c, 0, 0]],
[self.x[i, c, 1, 0], self.x[i, c, 1, 0]],
[self.x[i, c, 1, 0], self.x[i, c, 1, 0]],
])
elif outsize == (3, 1):
expect = numpy.array([
[self.x[i, c, 0, 0]],
[self.x[i, c, 0, 0]],
[self.x[i, c, 1, 0]],
])
else:
raise ValueError('Unsupported outsize: {}'.format(outsize))
testing.assert_allclose(expect, y_data[i, c])
def test_forward_cpu(self):
self.check_forward(self.x)
@attr.gpu
def test_forward_gpu(self):
self.check_forward(cuda.to_gpu(self.x))
def check_backward(self, x_data, y_grad):
def f(x):
|
gradient_check.check_backward(
f, x_data, y_grad, dtype=numpy.float64,
**self.check_backward_options)
def test_backward_cpu(self):
self.check_backward(self.x, self.gy)
@attr.gpu
def test_backward_gpu(self):
self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(self.gy))
def check_double_backward(self, x_data, y_grad, x_grad_grad,
use_cudnn='always'):
def f(x):
return functions.unpooling_2d(x, self.ksize, outsize=self.outsize,
cover_all=self.cover_all)
with chainer.using_config('use_cudnn', use_cudnn):
gradient_check.check_double_backward(
f, x_data, y_grad, x_grad_grad, dtype=numpy.float64,
**self.check_double_backward_options)
def test_double_backward_cpu(self):
self.check_double_backward(
self.x, self.gy, self.ggx, 'never')
@attr.gpu
def test_double_backward_gpu(self):
self.check_double_backward(
cuda.to_gpu(self.x), cuda.to_gpu(self.gy), cuda.to_gpu(self.ggx))
@attr.gpu
def test_double_backward_gpu_non_contiguous(self):
self.check_double_backward(
cuda.cupy.asfortranarray(cuda.to_gpu(self.x)),
cuda.cupy.asfortranarray(cuda.to_gpu(self.gy)),
cuda.cupy.asfortranarray(cuda.to_gpu(self.ggx)))
@attr.gpu
def test_double_backward_gpu_no_cudnn(self):
self.check_double_backward(
cuda.to_gpu(self.x), cuda.to_gpu(self.gy), cuda.to_gpu(self.ggx),
'never')
@testing.parameterize(*testing.product_dict(
[
{'insize': (2, 1), 'outsize': (4, 2), 'ksize': 2, 'pad': 0},
{'insize': (4, 5), 'outsize': (4, 6), 'ksize': 2, 'pad': 2},
],
[
{'dtype': numpy.float16},
{'dtype': numpy.float32},
{'dtype': numpy.float64},
],
))
class TestIntegerScaleUnpooling2D(unittest.TestCase):
def setUp(self):
self.N = 2
self.n_channels = 3
inh, inw = self.insize
self.x = pooling_nd_helper.shuffled_linspace(
(self.N, self.n_channels, inh, inw), self.dtype)
outh, outw = self.outsize or self.expected_outsize
self.gy = numpy.random.uniform(
-1, 1, (self.N, self.n_channels, outh, outw)).astype(self.dtype)
self.check_backward_options = {'atol': 1e-4, 'rtol': 1e-3}
self.check_double_backward_options = {}
if self.dtype == numpy.float16:
self.check_backward_options = {'atol': 2e-3, 'rtol': 2e-2}
self.check_double_backward_options = {'atol': 3e-3, 'rtol': 3e-2}
self.ggx = numpy.random.uniform(
-1, 1, self.x.shape).astype(self.dtype)
def check_forward(self, x_data):
x = chainer.Variable(x_data)
y = functions.unpooling_2d(
x, self.ksize, outsize=self.outsize, pad=self.pad)
self.assertEqual(y.data.dtype, self.dtype)
y_data = cuda.to_cpu(y.data)
self.assertEqual(self.gy.shape, y_data.shape)
for i in six.moves.range(self.N):
for c in six.moves.range(self.n_channels):
outsize = self.outsize or self.expected_outsize
assert y_data.shape[2:] == outsize
if outsize == (4, 2):
expect = numpy.array([
[self.x[i, c, 0, 0], self.x[i, c, 0, 0]],
[self.x[i, c, 0, 0], self.x[i, c, 0, 0]],
[self.x[i, c, 1, 0], self.x[i, c, 1, 0]],
[self.x[i, c, 1, 0], self.x[i, c, 1, 0]],
])
elif outsize == (4, 6):
expect = numpy.array([
[self.x[i, c, 1, 1], self.x[i, c, 1, 1],
self.x[i, c, 1, 2], self.x[i, c, 1, 2],
self.x[i, c, 1, 3], self.x[i, c, 1, 3]],
[self.x[i, c, 1, 1], self.x[i, c, 1, 1],
self.x[i, c, 1, 2], self.x[i, c, 1, 2],
self.x[i, c, 1, 3], self.x[i, c, 1, 3]],
[self.x[i, c, 2, 1], self.x[i, c, 2, 1],
self.x[i, c, 2, 2], self.x[i, c, 2, 2],
self.x[i, c, 2, 3], self.x[i, c, 2, 3]],
[self.x[i, c, 2, 1], self.x[i, c, 2, 1],
self.x[i, c, 2, 2], self.x[i, c, 2, 2],
self.x[i, c, 2, 3], self.x[i, c, 2, 3]],
])
else:
raise ValueError('Unsupported outsize: {}'.format(outsize))
testing.assert_allclose(expect, y_data[i, c])
def test_forward_cpu(self):
self.check_forward(self.x)
@attr.gpu
def test_forward_gpu(self):
self.check_forward(cuda.to_gpu(self.x))
def check_backward(self, x_data, y_grad):
def f(x):
return functions.unpooling_2d(x, self.ksize, outsize=self.outsize,
pad=self.pad)
gradient_check.check_backward(
f, x_data, y_grad, dtype=numpy.float64,
**self.check_backward_options)
def test_backward_cpu(self):
self.check_backward(self.x, self.gy)
@attr.gpu
def test_backward_gpu(self):
self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(self.gy))
def check_double_backward(self, x_data, y_grad, x_grad_grad,
use_cudnn='always'):
def f(x):
return functions.unpooling_2d(x, self.ksize, outsize=self.outsize,
pad=self.pad)
with chainer.using_config('use_cudnn', use_cudnn):
gradient_check.check_double_backward(
f, x_data, y_grad, x_grad_grad, dtype=numpy.float64,
**self.check_double_backward_options)
def test_double_backward_cpu(self):
self.check_double_backward(
self.x, self.gy, self.ggx, 'never')
@attr.gpu
def test_double_backward_gpu(self):
self.check_double_backward(
cuda.to_gpu(self.x), cuda.to_gpu(self.gy), cuda.to_gpu(self.ggx))
@attr.gpu
def test_double_backward_gpu_non_contiguous(self):
self.check_double_backward(
cuda.cupy.asfortranarray(cuda.to_gpu(self.x)),
cuda.cupy.asfortranarray(cuda.to_gpu(self.gy)),
cuda.cupy.asfortranarray(cuda.to_gpu(self.ggx)))
@attr.gpu
def test_double_backward_gpu_no_cudnn(self):
self.check_double_backward(
cuda.to_gpu(self.x), cuda.to_gpu(self.gy), cuda.to_gpu(self.ggx),
'never')
@testing.parameterize(*testing.product({
'dtype': [numpy.float16, numpy.float32, numpy.float64],
'h': [5],
'k': [3],
's': [3],
'p': [0],
'cover_all': [True, False],
}))
class TestMaxPoolingUnpooling(unittest.TestCase):
def check_left_inverse(self, xp, use_cudnn='never'):
x = xp.arange(self.h * self.h).reshape(
(1, 1, self.h, self.h)).astype(self.dtype)
with chainer.using_config('use_cudnn', use_cudnn):
y = chainer.functions.unpooling_2d(
x, self.k, self.s, self.p, None, self.cover_all)
x_ = chainer.functions.max_pooling_2d(
y, self.k, self.s, self.p, self.cover_all).data
self.assertEqual(x.shape, x_.shape)
self.assertEqual(x.dtype, x_.dtype)
chainer.testing.assert_allclose(x, x_)
def test_left_inverse_cpu(self):
self.check_left_inverse(numpy)
@attr.gpu
def test_left_inverse_cupy(self):
self.check_left_inverse(cuda.cupy)
@attr.gpu
def test_left_inverse_cudnn(self):
self.check_left_inverse(cuda.cupy, 'always')
@testing.parameterize(*testing.product({
'dtype': [numpy.float16, numpy.float32, numpy.float64],
'h': [5],
'k': [3],
's': [3],
'p': [0],
}))
class TestAveragePoolingUnpooling(unittest.TestCase):
def check_left_inverse(self, xp, use_cudnn='never'):
x = xp.arange(self.h * self.h).reshape(
(1, 1, self.h, self.h)).astype(self.dtype)
with chainer.using_config('use_cudnn', use_cudnn):
# average_pooling_2d does not have cover_all option
# as max_pooling_2d has.
y = chainer.functions.unpooling_2d(
x, self.k, self.s, self.p, None, False)
x_ = chainer.functions.average_pooling_2d(
y, self.k, self.s, self.p).data
self.assertEqual(x.shape, x_.shape)
self.assertEqual(x.dtype, x_.dtype)
chainer.testing.assert_allclose(x, x_)
def test_left_inverse_cpu(self):
self.check_left_inverse(numpy)
@attr.gpu
def test_left_inverse_cupy(self):
self.check_left_inverse(cuda.cupy)
@attr.gpu
def test_left_inverse_cudnn(self):
self.check_left_inverse(cuda.cupy, 'always')
testing.run_module(__name__, __file__)
| return functions.unpooling_2d(x, self.ksize, outsize=self.outsize,
cover_all=self.cover_all) |
brocade_interface_ext.py | #!/usr/bin/env python
import xml.etree.ElementTree as ET
class brocade_interface_ext(object):
"""Auto generated class.
"""
def __init__(self, **kwargs):
self._callback = kwargs.pop('callback')
def get_vlan_brief_input_request_type_get_request_vlan_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
input = ET.SubElement(get_vlan_brief, "input")
request_type = ET.SubElement(input, "request-type")
get_request = ET.SubElement(request_type, "get-request")
vlan_id = ET.SubElement(get_request, "vlan-id")
vlan_id.text = kwargs.pop('vlan_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_vlan_brief_input_request_type_get_next_request_last_rcvd_vlan_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
input = ET.SubElement(get_vlan_brief, "input")
request_type = ET.SubElement(input, "request-type")
get_next_request = ET.SubElement(request_type, "get-next-request")
last_rcvd_vlan_id = ET.SubElement(get_next_request, "last-rcvd-vlan-id")
last_rcvd_vlan_id.text = kwargs.pop('last_rcvd_vlan_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_vlan_brief_output_configured_vlans_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
configured_vlans_count = ET.SubElement(output, "configured-vlans-count")
configured_vlans_count.text = kwargs.pop('configured_vlans_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_vlan_brief_output_provisioned_vlans_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
provisioned_vlans_count = ET.SubElement(output, "provisioned-vlans-count")
provisioned_vlans_count.text = kwargs.pop('provisioned_vlans_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_vlan_brief_output_unprovisioned_vlans_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
unprovisioned_vlans_count = ET.SubElement(output, "unprovisioned-vlans-count")
unprovisioned_vlans_count.text = kwargs.pop('unprovisioned_vlans_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_vlan_brief_output_vlan_vlan_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
vlan = ET.SubElement(output, "vlan")
vlan_id = ET.SubElement(vlan, "vlan-id")
vlan_id.text = kwargs.pop('vlan_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_vlan_brief_output_vlan_vlan_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
vlan = ET.SubElement(output, "vlan")
vlan_id_key = ET.SubElement(vlan, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
vlan_type = ET.SubElement(vlan, "vlan-type")
vlan_type.text = kwargs.pop('vlan_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_vlan_brief_output_vlan_vlan_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
vlan = ET.SubElement(output, "vlan")
vlan_id_key = ET.SubElement(vlan, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
vlan_name = ET.SubElement(vlan, "vlan-name")
vlan_name.text = kwargs.pop('vlan_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_vlan_brief_output_vlan_vlan_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
vlan = ET.SubElement(output, "vlan")
vlan_id_key = ET.SubElement(vlan, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
vlan_state = ET.SubElement(vlan, "vlan-state")
vlan_state.text = kwargs.pop('vlan_state')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_vlan_brief_output_vlan_interface_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
vlan = ET.SubElement(output, "vlan")
vlan_id_key = ET.SubElement(vlan, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
interface = ET.SubElement(vlan, "interface")
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_type = ET.SubElement(interface, "interface-type")
interface_type.text = kwargs.pop('interface_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_vlan_brief_output_vlan_interface_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
vlan = ET.SubElement(output, "vlan")
vlan_id_key = ET.SubElement(vlan, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
interface = ET.SubElement(vlan, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name = ET.SubElement(interface, "interface-name")
interface_name.text = kwargs.pop('interface_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_vlan_brief_output_vlan_interface_tag(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
vlan = ET.SubElement(output, "vlan")
vlan_id_key = ET.SubElement(vlan, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
interface = ET.SubElement(vlan, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
tag = ET.SubElement(interface, "tag")
tag.text = kwargs.pop('tag')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_vlan_brief_output_vlan_interface_classification_classification_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
vlan = ET.SubElement(output, "vlan")
vlan_id_key = ET.SubElement(vlan, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
interface = ET.SubElement(vlan, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
classification = ET.SubElement(interface, "classification")
classification_value_key = ET.SubElement(classification, "classification-value")
classification_value_key.text = kwargs.pop('classification_value')
classification_type = ET.SubElement(classification, "classification-type")
classification_type.text = kwargs.pop('classification_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_vlan_brief_output_vlan_interface_classification_classification_value(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
vlan = ET.SubElement(output, "vlan")
vlan_id_key = ET.SubElement(vlan, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
interface = ET.SubElement(vlan, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
classification = ET.SubElement(interface, "classification")
classification_type_key = ET.SubElement(classification, "classification-type")
classification_type_key.text = kwargs.pop('classification_type')
classification_value = ET.SubElement(classification, "classification-value")
classification_value.text = kwargs.pop('classification_value')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_vlan_brief_output_last_vlan_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
last_vlan_id = ET.SubElement(output, "last-vlan-id")
last_vlan_id.text = kwargs.pop('last_vlan_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_vlan_brief_output_has_more(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
has_more = ET.SubElement(output, "has-more")
has_more.text = kwargs.pop('has_more')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_switchport_output_switchport_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_switchport = ET.Element("get_interface_switchport")
config = get_interface_switchport
output = ET.SubElement(get_interface_switchport, "output")
switchport = ET.SubElement(output, "switchport")
interface_name_key = ET.SubElement(switchport, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_type = ET.SubElement(switchport, "interface-type")
interface_type.text = kwargs.pop('interface_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_switchport_output_switchport_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_switchport = ET.Element("get_interface_switchport")
config = get_interface_switchport
output = ET.SubElement(get_interface_switchport, "output")
switchport = ET.SubElement(output, "switchport")
interface_type_key = ET.SubElement(switchport, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name = ET.SubElement(switchport, "interface-name")
interface_name.text = kwargs.pop('interface_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_switchport_output_switchport_mode(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_switchport = ET.Element("get_interface_switchport")
config = get_interface_switchport
output = ET.SubElement(get_interface_switchport, "output")
switchport = ET.SubElement(output, "switchport")
interface_type_key = ET.SubElement(switchport, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(switchport, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
mode = ET.SubElement(switchport, "mode")
mode.text = kwargs.pop('mode')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_switchport_output_switchport_fcoe_port_enabled(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_switchport = ET.Element("get_interface_switchport")
config = get_interface_switchport
output = ET.SubElement(get_interface_switchport, "output")
switchport = ET.SubElement(output, "switchport")
interface_type_key = ET.SubElement(switchport, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(switchport, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
fcoe_port_enabled = ET.SubElement(switchport, "fcoe-port-enabled")
fcoe_port_enabled.text = kwargs.pop('fcoe_port_enabled')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_switchport_output_switchport_ingress_filter_enabled(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_switchport = ET.Element("get_interface_switchport")
config = get_interface_switchport
output = ET.SubElement(get_interface_switchport, "output")
switchport = ET.SubElement(output, "switchport")
interface_type_key = ET.SubElement(switchport, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(switchport, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
ingress_filter_enabled = ET.SubElement(switchport, "ingress-filter-enabled")
ingress_filter_enabled.text = kwargs.pop('ingress_filter_enabled')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_switchport_output_switchport_acceptable_frame_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_switchport = ET.Element("get_interface_switchport")
config = get_interface_switchport
output = ET.SubElement(get_interface_switchport, "output")
switchport = ET.SubElement(output, "switchport")
interface_type_key = ET.SubElement(switchport, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(switchport, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
acceptable_frame_type = ET.SubElement(switchport, "acceptable-frame-type")
acceptable_frame_type.text = kwargs.pop('acceptable_frame_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_switchport_output_switchport_default_vlan(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_switchport = ET.Element("get_interface_switchport")
config = get_interface_switchport
output = ET.SubElement(get_interface_switchport, "output")
switchport = ET.SubElement(output, "switchport")
interface_type_key = ET.SubElement(switchport, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(switchport, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
default_vlan = ET.SubElement(switchport, "default-vlan")
default_vlan.text = kwargs.pop('default_vlan')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_ip_interface_input_request_type_get_request_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
input = ET.SubElement(get_ip_interface, "input")
request_type = ET.SubElement(input, "request-type")
get_request = ET.SubElement(request_type, "get-request")
interface_type = ET.SubElement(get_request, "interface-type")
interface_type.text = kwargs.pop('interface_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_ip_interface_input_request_type_get_request_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
input = ET.SubElement(get_ip_interface, "input")
request_type = ET.SubElement(input, "request-type")
get_request = ET.SubElement(request_type, "get-request")
interface_name = ET.SubElement(get_request, "interface-name")
interface_name.text = kwargs.pop('interface_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_ip_interface_input_request_type_get_request_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
input = ET.SubElement(get_ip_interface, "input")
request_type = ET.SubElement(input, "request-type")
get_request = ET.SubElement(request_type, "get-request")
rbridge_id = ET.SubElement(get_request, "rbridge-id")
rbridge_id.text = kwargs.pop('rbridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_ip_interface_output_interface_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
output = ET.SubElement(get_ip_interface, "output")
interface = ET.SubElement(output, "interface")
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_type = ET.SubElement(interface, "interface-type")
interface_type.text = kwargs.pop('interface_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_ip_interface_output_interface_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
output = ET.SubElement(get_ip_interface, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name = ET.SubElement(interface, "interface-name")
interface_name.text = kwargs.pop('interface_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_ip_interface_output_interface_if_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
output = ET.SubElement(get_ip_interface, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
if_name = ET.SubElement(interface, "if-name")
if_name.text = kwargs.pop('if_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_ip_interface_output_interface_ip_address_ipv4(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
output = ET.SubElement(get_ip_interface, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
ip_address = ET.SubElement(interface, "ip-address")
ipv4 = ET.SubElement(ip_address, "ipv4")
ipv4.text = kwargs.pop('ipv4')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_ip_interface_output_interface_ip_address_ipv4_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
output = ET.SubElement(get_ip_interface, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
ip_address = ET.SubElement(interface, "ip-address")
ipv4_key = ET.SubElement(ip_address, "ipv4")
ipv4_key.text = kwargs.pop('ipv4')
ipv4_type = ET.SubElement(ip_address, "ipv4-type")
ipv4_type.text = kwargs.pop('ipv4_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_ip_interface_output_interface_ip_address_broadcast(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
output = ET.SubElement(get_ip_interface, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
ip_address = ET.SubElement(interface, "ip-address")
ipv4_key = ET.SubElement(ip_address, "ipv4")
ipv4_key.text = kwargs.pop('ipv4')
broadcast = ET.SubElement(ip_address, "broadcast")
broadcast.text = kwargs.pop('broadcast')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_ip_interface_output_interface_ip_address_ip_mtu(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
output = ET.SubElement(get_ip_interface, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
ip_address = ET.SubElement(interface, "ip-address")
ipv4_key = ET.SubElement(ip_address, "ipv4")
ipv4_key.text = kwargs.pop('ipv4')
ip_mtu = ET.SubElement(ip_address, "ip-mtu")
ip_mtu.text = kwargs.pop('ip_mtu')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_ip_interface_output_interface_if_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
output = ET.SubElement(get_ip_interface, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
if_state = ET.SubElement(interface, "if-state")
if_state.text = kwargs.pop('if_state')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_ip_interface_output_interface_line_protocol_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
output = ET.SubElement(get_ip_interface, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
line_protocol_state = ET.SubElement(interface, "line-protocol-state")
line_protocol_state.text = kwargs.pop('line_protocol_state')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_ip_interface_output_interface_proxy_arp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
output = ET.SubElement(get_ip_interface, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
proxy_arp = ET.SubElement(interface, "proxy-arp")
proxy_arp.text = kwargs.pop('proxy_arp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_ip_interface_output_interface_vrf(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
output = ET.SubElement(get_ip_interface, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
vrf = ET.SubElement(interface, "vrf")
vrf.text = kwargs.pop('vrf')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_ip_interface_output_has_more(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
output = ET.SubElement(get_ip_interface, "output")
has_more = ET.SubElement(output, "has-more")
has_more.text = kwargs.pop('has_more')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_input_request_type_get_request_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
input = ET.SubElement(get_interface_detail, "input")
request_type = ET.SubElement(input, "request-type")
get_request = ET.SubElement(request_type, "get-request")
interface_type = ET.SubElement(get_request, "interface-type")
interface_type.text = kwargs.pop('interface_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_input_request_type_get_request_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
input = ET.SubElement(get_interface_detail, "input")
request_type = ET.SubElement(input, "request-type")
get_request = ET.SubElement(request_type, "get-request")
interface_name = ET.SubElement(get_request, "interface-name")
interface_name.text = kwargs.pop('interface_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_input_request_type_get_next_request_last_rcvd_interface_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
input = ET.SubElement(get_interface_detail, "input")
request_type = ET.SubElement(input, "request-type")
get_next_request = ET.SubElement(request_type, "get-next-request")
last_rcvd_interface = ET.SubElement(get_next_request, "last-rcvd-interface")
interface_type = ET.SubElement(last_rcvd_interface, "interface-type")
interface_type.text = kwargs.pop('interface_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_input_request_type_get_next_request_last_rcvd_interface_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
input = ET.SubElement(get_interface_detail, "input")
request_type = ET.SubElement(input, "request-type")
get_next_request = ET.SubElement(request_type, "get-next-request")
last_rcvd_interface = ET.SubElement(get_next_request, "last-rcvd-interface")
interface_name = ET.SubElement(last_rcvd_interface, "interface-name")
interface_name.text = kwargs.pop('interface_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_type = ET.SubElement(interface, "interface-type")
interface_type.text = kwargs.pop('interface_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name = ET.SubElement(interface, "interface-name")
interface_name.text = kwargs.pop('interface_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_ifindex(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
ifindex = ET.SubElement(interface, "ifindex")
ifindex.text = kwargs.pop('ifindex')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_mtu(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
mtu = ET.SubElement(interface, "mtu")
mtu.text = kwargs.pop('mtu')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_ip_mtu(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
ip_mtu = ET.SubElement(interface, "ip-mtu")
ip_mtu.text = kwargs.pop('ip_mtu')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_if_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
if_name = ET.SubElement(interface, "if-name")
if_name.text = kwargs.pop('if_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_if_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
if_state = ET.SubElement(interface, "if-state")
if_state.text = kwargs.pop('if_state')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_line_protocol_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
line_protocol_state = ET.SubElement(interface, "line-protocol-state")
line_protocol_state.text = kwargs.pop('line_protocol_state')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_line_protocol_state_info(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
line_protocol_state_info = ET.SubElement(interface, "line-protocol-state-info")
line_protocol_state_info.text = kwargs.pop('line_protocol_state_info')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_line_protocol_exception_info(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
line_protocol_exception_info = ET.SubElement(interface, "line-protocol-exception-info")
line_protocol_exception_info.text = kwargs.pop('line_protocol_exception_info')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_hardware_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
hardware_type = ET.SubElement(interface, "hardware-type")
hardware_type.text = kwargs.pop('hardware_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_logical_hardware_address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
logical_hardware_address = ET.SubElement(interface, "logical-hardware-address")
logical_hardware_address.text = kwargs.pop('logical_hardware_address')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_current_hardware_address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
current_hardware_address = ET.SubElement(interface, "current-hardware-address")
current_hardware_address.text = kwargs.pop('current_hardware_address')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_media_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
media_type = ET.SubElement(interface, "media-type")
media_type.text = kwargs.pop('media_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_wavelength(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
wavelength = ET.SubElement(interface, "wavelength")
wavelength.text = kwargs.pop('wavelength')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_if_description(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
if_description = ET.SubElement(interface, "if-description")
if_description.text = kwargs.pop('if_description')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_actual_line_speed(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
actual_line_speed = ET.SubElement(interface, "actual-line-speed")
actual_line_speed.text = kwargs.pop('actual_line_speed')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_configured_line_speed(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
configured_line_speed = ET.SubElement(interface, "configured-line-speed")
configured_line_speed.text = kwargs.pop('configured_line_speed')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_line_duplex_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
line_duplex_state = ET.SubElement(interface, "line-duplex-state")
line_duplex_state.text = kwargs.pop('line_duplex_state')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_flow_control(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
flow_control = ET.SubElement(interface, "flow-control")
flow_control.text = kwargs.pop('flow_control')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_queuing_strategy(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
queuing_strategy = ET.SubElement(interface, "queuing-strategy")
queuing_strategy.text = kwargs.pop('queuing_strategy')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_port_role(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
port_role = ET.SubElement(interface, "port-role")
port_role.text = kwargs.pop('port_role')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_port_mode(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
port_mode = ET.SubElement(interface, "port-mode")
port_mode.text = kwargs.pop('port_mode')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_ifHCInOctets(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
ifHCInOctets = ET.SubElement(interface, "ifHCInOctets")
ifHCInOctets.text = kwargs.pop('ifHCInOctets')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_ifHCInUcastPkts(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
ifHCInUcastPkts = ET.SubElement(interface, "ifHCInUcastPkts")
ifHCInUcastPkts.text = kwargs.pop('ifHCInUcastPkts')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_ifHCInMulticastPkts(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
ifHCInMulticastPkts = ET.SubElement(interface, "ifHCInMulticastPkts")
ifHCInMulticastPkts.text = kwargs.pop('ifHCInMulticastPkts')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_ifHCInBroadcastPkts(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
ifHCInBroadcastPkts = ET.SubElement(interface, "ifHCInBroadcastPkts")
ifHCInBroadcastPkts.text = kwargs.pop('ifHCInBroadcastPkts')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_ifHCInErrors(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
ifHCInErrors = ET.SubElement(interface, "ifHCInErrors")
ifHCInErrors.text = kwargs.pop('ifHCInErrors')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_ifHCOutOctets(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
ifHCOutOctets = ET.SubElement(interface, "ifHCOutOctets")
ifHCOutOctets.text = kwargs.pop('ifHCOutOctets')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_ifHCOutUcastPkts(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
ifHCOutUcastPkts = ET.SubElement(interface, "ifHCOutUcastPkts")
ifHCOutUcastPkts.text = kwargs.pop('ifHCOutUcastPkts')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_ifHCOutMulticastPkts(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
ifHCOutMulticastPkts = ET.SubElement(interface, "ifHCOutMulticastPkts")
ifHCOutMulticastPkts.text = kwargs.pop('ifHCOutMulticastPkts')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_ifHCOutBroadcastPkts(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
ifHCOutBroadcastPkts = ET.SubElement(interface, "ifHCOutBroadcastPkts")
ifHCOutBroadcastPkts.text = kwargs.pop('ifHCOutBroadcastPkts')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_ifHCOutErrors(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
ifHCOutErrors = ET.SubElement(interface, "ifHCOutErrors")
ifHCOutErrors.text = kwargs.pop('ifHCOutErrors')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_has_more(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
has_more = ET.SubElement(output, "has-more")
has_more.text = kwargs.pop('has_more')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_input_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
input = ET.SubElement(get_media_detail, "input")
interface_type = ET.SubElement(input, "interface-type")
interface_type.text = kwargs.pop('interface_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_input_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
input = ET.SubElement(get_media_detail, "input")
interface_name = ET.SubElement(input, "interface-name")
interface_name.text = kwargs.pop('interface_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_input_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
input = ET.SubElement(get_media_detail, "input")
rbridge_id = ET.SubElement(input, "rbridge-id")
rbridge_id.text = kwargs.pop('rbridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_type = ET.SubElement(interface, "interface-type")
interface_type.text = kwargs.pop('interface_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name = ET.SubElement(interface, "interface-name")
interface_name.text = kwargs.pop('interface_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_sfp_sfp_speed(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
sfp = ET.SubElement(interface_identifier, "sfp")
sfp = ET.SubElement(sfp, "sfp")
speed = ET.SubElement(sfp, "speed")
speed.text = kwargs.pop('speed')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_sfp_sfp_connector(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
sfp = ET.SubElement(interface_identifier, "sfp")
sfp = ET.SubElement(sfp, "sfp")
connector = ET.SubElement(sfp, "connector")
connector.text = kwargs.pop('connector')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_sfp_sfp_encoding(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
sfp = ET.SubElement(interface_identifier, "sfp")
sfp = ET.SubElement(sfp, "sfp")
encoding = ET.SubElement(sfp, "encoding")
encoding.text = kwargs.pop('encoding')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_sfp_sfp_vendor_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
sfp = ET.SubElement(interface_identifier, "sfp")
sfp = ET.SubElement(sfp, "sfp")
vendor_name = ET.SubElement(sfp, "vendor-name")
vendor_name.text = kwargs.pop('vendor_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_sfp_sfp_vendor_oui(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
sfp = ET.SubElement(interface_identifier, "sfp")
sfp = ET.SubElement(sfp, "sfp")
vendor_oui = ET.SubElement(sfp, "vendor-oui")
vendor_oui.text = kwargs.pop('vendor_oui')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_sfp_sfp_vendor_pn(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
sfp = ET.SubElement(interface_identifier, "sfp")
sfp = ET.SubElement(sfp, "sfp")
vendor_pn = ET.SubElement(sfp, "vendor-pn")
vendor_pn.text = kwargs.pop('vendor_pn')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_sfp_sfp_vendor_rev(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
sfp = ET.SubElement(interface_identifier, "sfp")
sfp = ET.SubElement(sfp, "sfp")
vendor_rev = ET.SubElement(sfp, "vendor-rev")
vendor_rev.text = kwargs.pop('vendor_rev')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_sfp_sfp_distance(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
sfp = ET.SubElement(interface_identifier, "sfp")
sfp = ET.SubElement(sfp, "sfp")
distance = ET.SubElement(sfp, "distance")
distance.text = kwargs.pop('distance')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_sfp_sfp_media_form_factor(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
sfp = ET.SubElement(interface_identifier, "sfp")
sfp = ET.SubElement(sfp, "sfp")
media_form_factor = ET.SubElement(sfp, "media-form-factor")
media_form_factor.text = kwargs.pop('media_form_factor')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_sfp_sfp_wavelength(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
sfp = ET.SubElement(interface_identifier, "sfp")
sfp = ET.SubElement(sfp, "sfp")
wavelength = ET.SubElement(sfp, "wavelength")
wavelength.text = kwargs.pop('wavelength')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_sfp_sfp_serial_no(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
sfp = ET.SubElement(interface_identifier, "sfp")
sfp = ET.SubElement(sfp, "sfp")
serial_no = ET.SubElement(sfp, "serial-no")
serial_no.text = kwargs.pop('serial_no')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_sfp_sfp_date_code(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
sfp = ET.SubElement(interface_identifier, "sfp")
sfp = ET.SubElement(sfp, "sfp")
date_code = ET.SubElement(sfp, "date-code")
date_code.text = kwargs.pop('date_code')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_sfp_sfp_temperature(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
sfp = ET.SubElement(interface_identifier, "sfp")
sfp = ET.SubElement(sfp, "sfp")
temperature = ET.SubElement(sfp, "temperature")
temperature.text = kwargs.pop('temperature')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_sfp_sfp_voltage(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
sfp = ET.SubElement(interface_identifier, "sfp")
sfp = ET.SubElement(sfp, "sfp")
voltage = ET.SubElement(sfp, "voltage")
voltage.text = kwargs.pop('voltage')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_sfp_sfp_current(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
sfp = ET.SubElement(interface_identifier, "sfp")
sfp = ET.SubElement(sfp, "sfp")
current = ET.SubElement(sfp, "current")
current.text = kwargs.pop('current')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_sfp_sfp_tx_power(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
sfp = ET.SubElement(interface_identifier, "sfp")
sfp = ET.SubElement(sfp, "sfp")
tx_power = ET.SubElement(sfp, "tx-power")
tx_power.text = kwargs.pop('tx_power')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_sfp_sfp_rx_power(self, **kwargs):
|
def get_media_detail_output_interface_interface_identifier_on_board_on_board_speed(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
on_board = ET.SubElement(interface_identifier, "on-board")
on_board = ET.SubElement(on_board, "on-board")
speed = ET.SubElement(on_board, "speed")
speed.text = kwargs.pop('speed')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_on_board_on_board_connector(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
on_board = ET.SubElement(interface_identifier, "on-board")
on_board = ET.SubElement(on_board, "on-board")
connector = ET.SubElement(on_board, "connector")
connector.text = kwargs.pop('connector')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_on_board_on_board_encoding(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
on_board = ET.SubElement(interface_identifier, "on-board")
on_board = ET.SubElement(on_board, "on-board")
encoding = ET.SubElement(on_board, "encoding")
encoding.text = kwargs.pop('encoding')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_on_board_on_board_vendor_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
on_board = ET.SubElement(interface_identifier, "on-board")
on_board = ET.SubElement(on_board, "on-board")
vendor_name = ET.SubElement(on_board, "vendor-name")
vendor_name.text = kwargs.pop('vendor_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_on_board_on_board_vendor_oui(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
on_board = ET.SubElement(interface_identifier, "on-board")
on_board = ET.SubElement(on_board, "on-board")
vendor_oui = ET.SubElement(on_board, "vendor-oui")
vendor_oui.text = kwargs.pop('vendor_oui')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_on_board_on_board_vendor_pn(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
on_board = ET.SubElement(interface_identifier, "on-board")
on_board = ET.SubElement(on_board, "on-board")
vendor_pn = ET.SubElement(on_board, "vendor-pn")
vendor_pn.text = kwargs.pop('vendor_pn')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_on_board_on_board_vendor_rev(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
on_board = ET.SubElement(interface_identifier, "on-board")
on_board = ET.SubElement(on_board, "on-board")
vendor_rev = ET.SubElement(on_board, "vendor-rev")
vendor_rev.text = kwargs.pop('vendor_rev')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_gbic_gbc_vendor_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
gbic = ET.SubElement(interface_identifier, "gbic")
gbc = ET.SubElement(gbic, "gbc")
vendor_name = ET.SubElement(gbc, "vendor-name")
vendor_name.text = kwargs.pop('vendor_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_gbic_gbc_vendor_oui(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
gbic = ET.SubElement(interface_identifier, "gbic")
gbc = ET.SubElement(gbic, "gbc")
vendor_oui = ET.SubElement(gbc, "vendor-oui")
vendor_oui.text = kwargs.pop('vendor_oui')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_gbic_gbc_vendor_pn(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
gbic = ET.SubElement(interface_identifier, "gbic")
gbc = ET.SubElement(gbic, "gbc")
vendor_pn = ET.SubElement(gbc, "vendor-pn")
vendor_pn.text = kwargs.pop('vendor_pn')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_gbic_gbc_vendor_rev(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
gbic = ET.SubElement(interface_identifier, "gbic")
gbc = ET.SubElement(gbic, "gbc")
vendor_rev = ET.SubElement(gbc, "vendor-rev")
vendor_rev.text = kwargs.pop('vendor_rev')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_xfp_xfp_vendor_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
xfp = ET.SubElement(interface_identifier, "xfp")
xfp = ET.SubElement(xfp, "xfp")
vendor_name = ET.SubElement(xfp, "vendor-name")
vendor_name.text = kwargs.pop('vendor_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_xfp_xfp_vendor_oui(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
xfp = ET.SubElement(interface_identifier, "xfp")
xfp = ET.SubElement(xfp, "xfp")
vendor_oui = ET.SubElement(xfp, "vendor-oui")
vendor_oui.text = kwargs.pop('vendor_oui')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_xfp_xfp_vendor_pn(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
xfp = ET.SubElement(interface_identifier, "xfp")
xfp = ET.SubElement(xfp, "xfp")
vendor_pn = ET.SubElement(xfp, "vendor-pn")
vendor_pn.text = kwargs.pop('vendor_pn')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_xfp_xfp_vendor_rev(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
xfp = ET.SubElement(interface_identifier, "xfp")
xfp = ET.SubElement(xfp, "xfp")
vendor_rev = ET.SubElement(xfp, "vendor-rev")
vendor_rev.text = kwargs.pop('vendor_rev')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_xff_xff_vendor_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
xff = ET.SubElement(interface_identifier, "xff")
xff = ET.SubElement(xff, "xff")
vendor_name = ET.SubElement(xff, "vendor-name")
vendor_name.text = kwargs.pop('vendor_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_xff_xff_vendor_oui(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
xff = ET.SubElement(interface_identifier, "xff")
xff = ET.SubElement(xff, "xff")
vendor_oui = ET.SubElement(xff, "vendor-oui")
vendor_oui.text = kwargs.pop('vendor_oui')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_xff_xff_vendor_pn(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
xff = ET.SubElement(interface_identifier, "xff")
xff = ET.SubElement(xff, "xff")
vendor_pn = ET.SubElement(xff, "vendor-pn")
vendor_pn.text = kwargs.pop('vendor_pn')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_xff_xff_vendor_rev(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
xff = ET.SubElement(interface_identifier, "xff")
xff = ET.SubElement(xff, "xff")
vendor_rev = ET.SubElement(xff, "vendor-rev")
vendor_rev.text = kwargs.pop('vendor_rev')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_xfpe_xfpe_vendor_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
xfpe = ET.SubElement(interface_identifier, "xfpe")
xfpe = ET.SubElement(xfpe, "xfpe")
vendor_name = ET.SubElement(xfpe, "vendor-name")
vendor_name.text = kwargs.pop('vendor_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_xfpe_xfpe_vendor_oui(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
xfpe = ET.SubElement(interface_identifier, "xfpe")
xfpe = ET.SubElement(xfpe, "xfpe")
vendor_oui = ET.SubElement(xfpe, "vendor-oui")
vendor_oui.text = kwargs.pop('vendor_oui')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_xfpe_xfpe_vendor_pn(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
xfpe = ET.SubElement(interface_identifier, "xfpe")
xfpe = ET.SubElement(xfpe, "xfpe")
vendor_pn = ET.SubElement(xfpe, "vendor-pn")
vendor_pn.text = kwargs.pop('vendor_pn')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_xfpe_xfpe_vendor_rev(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
xfpe = ET.SubElement(interface_identifier, "xfpe")
xfpe = ET.SubElement(xfpe, "xfpe")
vendor_rev = ET.SubElement(xfpe, "vendor-rev")
vendor_rev.text = kwargs.pop('vendor_rev')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_unknown_unknown_vendor_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
unknown = ET.SubElement(interface_identifier, "unknown")
unknown = ET.SubElement(unknown, "unknown")
vendor_name = ET.SubElement(unknown, "vendor-name")
vendor_name.text = kwargs.pop('vendor_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_unknown_unknown_vendor_oui(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
unknown = ET.SubElement(interface_identifier, "unknown")
unknown = ET.SubElement(unknown, "unknown")
vendor_oui = ET.SubElement(unknown, "vendor-oui")
vendor_oui.text = kwargs.pop('vendor_oui')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_unknown_unknown_vendor_pn(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
unknown = ET.SubElement(interface_identifier, "unknown")
unknown = ET.SubElement(unknown, "unknown")
vendor_pn = ET.SubElement(unknown, "vendor-pn")
vendor_pn.text = kwargs.pop('vendor_pn')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_unknown_unknown_vendor_rev(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
unknown = ET.SubElement(interface_identifier, "unknown")
unknown = ET.SubElement(unknown, "unknown")
vendor_rev = ET.SubElement(unknown, "vendor-rev")
vendor_rev.text = kwargs.pop('vendor_rev')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfp_qsfp_speed(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfp = ET.SubElement(interface_identifier, "qsfp")
qsfp = ET.SubElement(qsfp, "qsfp")
speed = ET.SubElement(qsfp, "speed")
speed.text = kwargs.pop('speed')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfp_qsfp_connector(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfp = ET.SubElement(interface_identifier, "qsfp")
qsfp = ET.SubElement(qsfp, "qsfp")
connector = ET.SubElement(qsfp, "connector")
connector.text = kwargs.pop('connector')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfp_qsfp_encoding(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfp = ET.SubElement(interface_identifier, "qsfp")
qsfp = ET.SubElement(qsfp, "qsfp")
encoding = ET.SubElement(qsfp, "encoding")
encoding.text = kwargs.pop('encoding')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfp_qsfp_vendor_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfp = ET.SubElement(interface_identifier, "qsfp")
qsfp = ET.SubElement(qsfp, "qsfp")
vendor_name = ET.SubElement(qsfp, "vendor-name")
vendor_name.text = kwargs.pop('vendor_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfp_qsfp_vendor_oui(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfp = ET.SubElement(interface_identifier, "qsfp")
qsfp = ET.SubElement(qsfp, "qsfp")
vendor_oui = ET.SubElement(qsfp, "vendor-oui")
vendor_oui.text = kwargs.pop('vendor_oui')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfp_qsfp_vendor_pn(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfp = ET.SubElement(interface_identifier, "qsfp")
qsfp = ET.SubElement(qsfp, "qsfp")
vendor_pn = ET.SubElement(qsfp, "vendor-pn")
vendor_pn.text = kwargs.pop('vendor_pn')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfp_qsfp_vendor_rev(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfp = ET.SubElement(interface_identifier, "qsfp")
qsfp = ET.SubElement(qsfp, "qsfp")
vendor_rev = ET.SubElement(qsfp, "vendor-rev")
vendor_rev.text = kwargs.pop('vendor_rev')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfp_qsfp_distance(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfp = ET.SubElement(interface_identifier, "qsfp")
qsfp = ET.SubElement(qsfp, "qsfp")
distance = ET.SubElement(qsfp, "distance")
distance.text = kwargs.pop('distance')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfp_qsfp_media_form_factor(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfp = ET.SubElement(interface_identifier, "qsfp")
qsfp = ET.SubElement(qsfp, "qsfp")
media_form_factor = ET.SubElement(qsfp, "media-form-factor")
media_form_factor.text = kwargs.pop('media_form_factor')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfp_qsfp_wavelength(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfp = ET.SubElement(interface_identifier, "qsfp")
qsfp = ET.SubElement(qsfp, "qsfp")
wavelength = ET.SubElement(qsfp, "wavelength")
wavelength.text = kwargs.pop('wavelength')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfp_qsfp_serial_no(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfp = ET.SubElement(interface_identifier, "qsfp")
qsfp = ET.SubElement(qsfp, "qsfp")
serial_no = ET.SubElement(qsfp, "serial-no")
serial_no.text = kwargs.pop('serial_no')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfp_qsfp_date_code(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfp = ET.SubElement(interface_identifier, "qsfp")
qsfp = ET.SubElement(qsfp, "qsfp")
date_code = ET.SubElement(qsfp, "date-code")
date_code.text = kwargs.pop('date_code')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfp_qsfp_temperature(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfp = ET.SubElement(interface_identifier, "qsfp")
qsfp = ET.SubElement(qsfp, "qsfp")
temperature = ET.SubElement(qsfp, "temperature")
temperature.text = kwargs.pop('temperature')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfp_qsfp_voltage(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfp = ET.SubElement(interface_identifier, "qsfp")
qsfp = ET.SubElement(qsfp, "qsfp")
voltage = ET.SubElement(qsfp, "voltage")
voltage.text = kwargs.pop('voltage')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfp_qsfp_current(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfp = ET.SubElement(interface_identifier, "qsfp")
qsfp = ET.SubElement(qsfp, "qsfp")
current = ET.SubElement(qsfp, "current")
current.text = kwargs.pop('current')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfp_qsfp_tx_power(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfp = ET.SubElement(interface_identifier, "qsfp")
qsfp = ET.SubElement(qsfp, "qsfp")
tx_power = ET.SubElement(qsfp, "tx-power")
tx_power.text = kwargs.pop('tx_power')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfp_qsfp_rx_power(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfp = ET.SubElement(interface_identifier, "qsfp")
qsfp = ET.SubElement(qsfp, "qsfp")
rx_power = ET.SubElement(qsfp, "rx-power")
rx_power.text = kwargs.pop('rx_power')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfpp_qsfpp_speed(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfpp = ET.SubElement(interface_identifier, "qsfpp")
qsfpp = ET.SubElement(qsfpp, "qsfpp")
speed = ET.SubElement(qsfpp, "speed")
speed.text = kwargs.pop('speed')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfpp_qsfpp_connector(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfpp = ET.SubElement(interface_identifier, "qsfpp")
qsfpp = ET.SubElement(qsfpp, "qsfpp")
connector = ET.SubElement(qsfpp, "connector")
connector.text = kwargs.pop('connector')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfpp_qsfpp_encoding(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfpp = ET.SubElement(interface_identifier, "qsfpp")
qsfpp = ET.SubElement(qsfpp, "qsfpp")
encoding = ET.SubElement(qsfpp, "encoding")
encoding.text = kwargs.pop('encoding')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfpp_qsfpp_vendor_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfpp = ET.SubElement(interface_identifier, "qsfpp")
qsfpp = ET.SubElement(qsfpp, "qsfpp")
vendor_name = ET.SubElement(qsfpp, "vendor-name")
vendor_name.text = kwargs.pop('vendor_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfpp_qsfpp_vendor_oui(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfpp = ET.SubElement(interface_identifier, "qsfpp")
qsfpp = ET.SubElement(qsfpp, "qsfpp")
vendor_oui = ET.SubElement(qsfpp, "vendor-oui")
vendor_oui.text = kwargs.pop('vendor_oui')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfpp_qsfpp_vendor_pn(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfpp = ET.SubElement(interface_identifier, "qsfpp")
qsfpp = ET.SubElement(qsfpp, "qsfpp")
vendor_pn = ET.SubElement(qsfpp, "vendor-pn")
vendor_pn.text = kwargs.pop('vendor_pn')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfpp_qsfpp_vendor_rev(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfpp = ET.SubElement(interface_identifier, "qsfpp")
qsfpp = ET.SubElement(qsfpp, "qsfpp")
vendor_rev = ET.SubElement(qsfpp, "vendor-rev")
vendor_rev.text = kwargs.pop('vendor_rev')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfpp_qsfpp_distance(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfpp = ET.SubElement(interface_identifier, "qsfpp")
qsfpp = ET.SubElement(qsfpp, "qsfpp")
distance = ET.SubElement(qsfpp, "distance")
distance.text = kwargs.pop('distance')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfpp_qsfpp_media_form_factor(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfpp = ET.SubElement(interface_identifier, "qsfpp")
qsfpp = ET.SubElement(qsfpp, "qsfpp")
media_form_factor = ET.SubElement(qsfpp, "media-form-factor")
media_form_factor.text = kwargs.pop('media_form_factor')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfpp_qsfpp_wavelength(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfpp = ET.SubElement(interface_identifier, "qsfpp")
qsfpp = ET.SubElement(qsfpp, "qsfpp")
wavelength = ET.SubElement(qsfpp, "wavelength")
wavelength.text = kwargs.pop('wavelength')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfpp_qsfpp_serial_no(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfpp = ET.SubElement(interface_identifier, "qsfpp")
qsfpp = ET.SubElement(qsfpp, "qsfpp")
serial_no = ET.SubElement(qsfpp, "serial-no")
serial_no.text = kwargs.pop('serial_no')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfpp_qsfpp_date_code(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfpp = ET.SubElement(interface_identifier, "qsfpp")
qsfpp = ET.SubElement(qsfpp, "qsfpp")
date_code = ET.SubElement(qsfpp, "date-code")
date_code.text = kwargs.pop('date_code')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfpp_qsfpp_temperature(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfpp = ET.SubElement(interface_identifier, "qsfpp")
qsfpp = ET.SubElement(qsfpp, "qsfpp")
temperature = ET.SubElement(qsfpp, "temperature")
temperature.text = kwargs.pop('temperature')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfpp_qsfpp_voltage(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfpp = ET.SubElement(interface_identifier, "qsfpp")
qsfpp = ET.SubElement(qsfpp, "qsfpp")
voltage = ET.SubElement(qsfpp, "voltage")
voltage.text = kwargs.pop('voltage')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfpp_qsfpp_current(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfpp = ET.SubElement(interface_identifier, "qsfpp")
qsfpp = ET.SubElement(qsfpp, "qsfpp")
current = ET.SubElement(qsfpp, "current")
current.text = kwargs.pop('current')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfpp_qsfpp_tx_power(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfpp = ET.SubElement(interface_identifier, "qsfpp")
qsfpp = ET.SubElement(qsfpp, "qsfpp")
tx_power = ET.SubElement(qsfpp, "tx-power")
tx_power.text = kwargs.pop('tx_power')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfpp_qsfpp_rx_power(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfpp = ET.SubElement(interface_identifier, "qsfpp")
qsfpp = ET.SubElement(qsfpp, "qsfpp")
rx_power = ET.SubElement(qsfpp, "rx-power")
rx_power.text = kwargs.pop('rx_power')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp_cfp_speed(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp = ET.SubElement(interface_identifier, "cfp")
cfp = ET.SubElement(cfp, "cfp")
speed = ET.SubElement(cfp, "speed")
speed.text = kwargs.pop('speed')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp_cfp_connector(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp = ET.SubElement(interface_identifier, "cfp")
cfp = ET.SubElement(cfp, "cfp")
connector = ET.SubElement(cfp, "connector")
connector.text = kwargs.pop('connector')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp_cfp_encoding(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp = ET.SubElement(interface_identifier, "cfp")
cfp = ET.SubElement(cfp, "cfp")
encoding = ET.SubElement(cfp, "encoding")
encoding.text = kwargs.pop('encoding')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp_cfp_vendor_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp = ET.SubElement(interface_identifier, "cfp")
cfp = ET.SubElement(cfp, "cfp")
vendor_name = ET.SubElement(cfp, "vendor-name")
vendor_name.text = kwargs.pop('vendor_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp_cfp_vendor_oui(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp = ET.SubElement(interface_identifier, "cfp")
cfp = ET.SubElement(cfp, "cfp")
vendor_oui = ET.SubElement(cfp, "vendor-oui")
vendor_oui.text = kwargs.pop('vendor_oui')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp_cfp_vendor_pn(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp = ET.SubElement(interface_identifier, "cfp")
cfp = ET.SubElement(cfp, "cfp")
vendor_pn = ET.SubElement(cfp, "vendor-pn")
vendor_pn.text = kwargs.pop('vendor_pn')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp_cfp_vendor_rev(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp = ET.SubElement(interface_identifier, "cfp")
cfp = ET.SubElement(cfp, "cfp")
vendor_rev = ET.SubElement(cfp, "vendor-rev")
vendor_rev.text = kwargs.pop('vendor_rev')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp_cfp_distance(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp = ET.SubElement(interface_identifier, "cfp")
cfp = ET.SubElement(cfp, "cfp")
distance = ET.SubElement(cfp, "distance")
distance.text = kwargs.pop('distance')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp_cfp_media_form_factor(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp = ET.SubElement(interface_identifier, "cfp")
cfp = ET.SubElement(cfp, "cfp")
media_form_factor = ET.SubElement(cfp, "media-form-factor")
media_form_factor.text = kwargs.pop('media_form_factor')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp_cfp_wavelength(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp = ET.SubElement(interface_identifier, "cfp")
cfp = ET.SubElement(cfp, "cfp")
wavelength = ET.SubElement(cfp, "wavelength")
wavelength.text = kwargs.pop('wavelength')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp_cfp_serial_no(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp = ET.SubElement(interface_identifier, "cfp")
cfp = ET.SubElement(cfp, "cfp")
serial_no = ET.SubElement(cfp, "serial-no")
serial_no.text = kwargs.pop('serial_no')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp_cfp_date_code(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp = ET.SubElement(interface_identifier, "cfp")
cfp = ET.SubElement(cfp, "cfp")
date_code = ET.SubElement(cfp, "date-code")
date_code.text = kwargs.pop('date_code')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp_cfp_temperature(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp = ET.SubElement(interface_identifier, "cfp")
cfp = ET.SubElement(cfp, "cfp")
temperature = ET.SubElement(cfp, "temperature")
temperature.text = kwargs.pop('temperature')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp_cfp_voltage(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp = ET.SubElement(interface_identifier, "cfp")
cfp = ET.SubElement(cfp, "cfp")
voltage = ET.SubElement(cfp, "voltage")
voltage.text = kwargs.pop('voltage')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp_cfp_current(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp = ET.SubElement(interface_identifier, "cfp")
cfp = ET.SubElement(cfp, "cfp")
current = ET.SubElement(cfp, "current")
current.text = kwargs.pop('current')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp_cfp_tx_power(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp = ET.SubElement(interface_identifier, "cfp")
cfp = ET.SubElement(cfp, "cfp")
tx_power = ET.SubElement(cfp, "tx-power")
tx_power.text = kwargs.pop('tx_power')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp_cfp_rx_power(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp = ET.SubElement(interface_identifier, "cfp")
cfp = ET.SubElement(cfp, "cfp")
rx_power = ET.SubElement(cfp, "rx-power")
rx_power.text = kwargs.pop('rx_power')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_speed(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp2 = ET.SubElement(interface_identifier, "cfp2")
cfp2 = ET.SubElement(cfp2, "cfp2")
speed = ET.SubElement(cfp2, "speed")
speed.text = kwargs.pop('speed')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_connector(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp2 = ET.SubElement(interface_identifier, "cfp2")
cfp2 = ET.SubElement(cfp2, "cfp2")
connector = ET.SubElement(cfp2, "connector")
connector.text = kwargs.pop('connector')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_encoding(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp2 = ET.SubElement(interface_identifier, "cfp2")
cfp2 = ET.SubElement(cfp2, "cfp2")
encoding = ET.SubElement(cfp2, "encoding")
encoding.text = kwargs.pop('encoding')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_vendor_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp2 = ET.SubElement(interface_identifier, "cfp2")
cfp2 = ET.SubElement(cfp2, "cfp2")
vendor_name = ET.SubElement(cfp2, "vendor-name")
vendor_name.text = kwargs.pop('vendor_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_vendor_oui(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp2 = ET.SubElement(interface_identifier, "cfp2")
cfp2 = ET.SubElement(cfp2, "cfp2")
vendor_oui = ET.SubElement(cfp2, "vendor-oui")
vendor_oui.text = kwargs.pop('vendor_oui')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_vendor_pn(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp2 = ET.SubElement(interface_identifier, "cfp2")
cfp2 = ET.SubElement(cfp2, "cfp2")
vendor_pn = ET.SubElement(cfp2, "vendor-pn")
vendor_pn.text = kwargs.pop('vendor_pn')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_vendor_rev(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp2 = ET.SubElement(interface_identifier, "cfp2")
cfp2 = ET.SubElement(cfp2, "cfp2")
vendor_rev = ET.SubElement(cfp2, "vendor-rev")
vendor_rev.text = kwargs.pop('vendor_rev')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_distance(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp2 = ET.SubElement(interface_identifier, "cfp2")
cfp2 = ET.SubElement(cfp2, "cfp2")
distance = ET.SubElement(cfp2, "distance")
distance.text = kwargs.pop('distance')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_media_form_factor(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp2 = ET.SubElement(interface_identifier, "cfp2")
cfp2 = ET.SubElement(cfp2, "cfp2")
media_form_factor = ET.SubElement(cfp2, "media-form-factor")
media_form_factor.text = kwargs.pop('media_form_factor')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_wavelength(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp2 = ET.SubElement(interface_identifier, "cfp2")
cfp2 = ET.SubElement(cfp2, "cfp2")
wavelength = ET.SubElement(cfp2, "wavelength")
wavelength.text = kwargs.pop('wavelength')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_serial_no(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp2 = ET.SubElement(interface_identifier, "cfp2")
cfp2 = ET.SubElement(cfp2, "cfp2")
serial_no = ET.SubElement(cfp2, "serial-no")
serial_no.text = kwargs.pop('serial_no')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_date_code(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp2 = ET.SubElement(interface_identifier, "cfp2")
cfp2 = ET.SubElement(cfp2, "cfp2")
date_code = ET.SubElement(cfp2, "date-code")
date_code.text = kwargs.pop('date_code')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_temperature(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp2 = ET.SubElement(interface_identifier, "cfp2")
cfp2 = ET.SubElement(cfp2, "cfp2")
temperature = ET.SubElement(cfp2, "temperature")
temperature.text = kwargs.pop('temperature')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_voltage(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp2 = ET.SubElement(interface_identifier, "cfp2")
cfp2 = ET.SubElement(cfp2, "cfp2")
voltage = ET.SubElement(cfp2, "voltage")
voltage.text = kwargs.pop('voltage')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_current(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp2 = ET.SubElement(interface_identifier, "cfp2")
cfp2 = ET.SubElement(cfp2, "cfp2")
current = ET.SubElement(cfp2, "current")
current.text = kwargs.pop('current')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_tx_power(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp2 = ET.SubElement(interface_identifier, "cfp2")
cfp2 = ET.SubElement(cfp2, "cfp2")
tx_power = ET.SubElement(cfp2, "tx-power")
tx_power.text = kwargs.pop('tx_power')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_rx_power(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp2 = ET.SubElement(interface_identifier, "cfp2")
cfp2 = ET.SubElement(cfp2, "cfp2")
rx_power = ET.SubElement(cfp2, "rx-power")
rx_power.text = kwargs.pop('rx_power')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_vlan_brief_input_request_type_get_request_vlan_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
input = ET.SubElement(get_vlan_brief, "input")
request_type = ET.SubElement(input, "request-type")
get_request = ET.SubElement(request_type, "get-request")
vlan_id = ET.SubElement(get_request, "vlan-id")
vlan_id.text = kwargs.pop('vlan_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_vlan_brief_input_request_type_get_next_request_last_rcvd_vlan_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
input = ET.SubElement(get_vlan_brief, "input")
request_type = ET.SubElement(input, "request-type")
get_next_request = ET.SubElement(request_type, "get-next-request")
last_rcvd_vlan_id = ET.SubElement(get_next_request, "last-rcvd-vlan-id")
last_rcvd_vlan_id.text = kwargs.pop('last_rcvd_vlan_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_vlan_brief_output_configured_vlans_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
configured_vlans_count = ET.SubElement(output, "configured-vlans-count")
configured_vlans_count.text = kwargs.pop('configured_vlans_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_vlan_brief_output_provisioned_vlans_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
provisioned_vlans_count = ET.SubElement(output, "provisioned-vlans-count")
provisioned_vlans_count.text = kwargs.pop('provisioned_vlans_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_vlan_brief_output_unprovisioned_vlans_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
unprovisioned_vlans_count = ET.SubElement(output, "unprovisioned-vlans-count")
unprovisioned_vlans_count.text = kwargs.pop('unprovisioned_vlans_count')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_vlan_brief_output_vlan_vlan_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
vlan = ET.SubElement(output, "vlan")
vlan_id = ET.SubElement(vlan, "vlan-id")
vlan_id.text = kwargs.pop('vlan_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_vlan_brief_output_vlan_vlan_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
vlan = ET.SubElement(output, "vlan")
vlan_id_key = ET.SubElement(vlan, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
vlan_type = ET.SubElement(vlan, "vlan-type")
vlan_type.text = kwargs.pop('vlan_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_vlan_brief_output_vlan_vlan_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
vlan = ET.SubElement(output, "vlan")
vlan_id_key = ET.SubElement(vlan, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
vlan_name = ET.SubElement(vlan, "vlan-name")
vlan_name.text = kwargs.pop('vlan_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_vlan_brief_output_vlan_vlan_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
vlan = ET.SubElement(output, "vlan")
vlan_id_key = ET.SubElement(vlan, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
vlan_state = ET.SubElement(vlan, "vlan-state")
vlan_state.text = kwargs.pop('vlan_state')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_vlan_brief_output_vlan_interface_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
vlan = ET.SubElement(output, "vlan")
vlan_id_key = ET.SubElement(vlan, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
interface = ET.SubElement(vlan, "interface")
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_type = ET.SubElement(interface, "interface-type")
interface_type.text = kwargs.pop('interface_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_vlan_brief_output_vlan_interface_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
vlan = ET.SubElement(output, "vlan")
vlan_id_key = ET.SubElement(vlan, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
interface = ET.SubElement(vlan, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name = ET.SubElement(interface, "interface-name")
interface_name.text = kwargs.pop('interface_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_vlan_brief_output_vlan_interface_tag(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
vlan = ET.SubElement(output, "vlan")
vlan_id_key = ET.SubElement(vlan, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
interface = ET.SubElement(vlan, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
tag = ET.SubElement(interface, "tag")
tag.text = kwargs.pop('tag')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_vlan_brief_output_vlan_interface_classification_classification_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
vlan = ET.SubElement(output, "vlan")
vlan_id_key = ET.SubElement(vlan, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
interface = ET.SubElement(vlan, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
classification = ET.SubElement(interface, "classification")
classification_value_key = ET.SubElement(classification, "classification-value")
classification_value_key.text = kwargs.pop('classification_value')
classification_type = ET.SubElement(classification, "classification-type")
classification_type.text = kwargs.pop('classification_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_vlan_brief_output_vlan_interface_classification_classification_value(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
vlan = ET.SubElement(output, "vlan")
vlan_id_key = ET.SubElement(vlan, "vlan-id")
vlan_id_key.text = kwargs.pop('vlan_id')
interface = ET.SubElement(vlan, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
classification = ET.SubElement(interface, "classification")
classification_type_key = ET.SubElement(classification, "classification-type")
classification_type_key.text = kwargs.pop('classification_type')
classification_value = ET.SubElement(classification, "classification-value")
classification_value.text = kwargs.pop('classification_value')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_vlan_brief_output_last_vlan_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
last_vlan_id = ET.SubElement(output, "last-vlan-id")
last_vlan_id.text = kwargs.pop('last_vlan_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_vlan_brief_output_has_more(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vlan_brief = ET.Element("get_vlan_brief")
config = get_vlan_brief
output = ET.SubElement(get_vlan_brief, "output")
has_more = ET.SubElement(output, "has-more")
has_more.text = kwargs.pop('has_more')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_switchport_output_switchport_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_switchport = ET.Element("get_interface_switchport")
config = get_interface_switchport
output = ET.SubElement(get_interface_switchport, "output")
switchport = ET.SubElement(output, "switchport")
interface_name_key = ET.SubElement(switchport, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_type = ET.SubElement(switchport, "interface-type")
interface_type.text = kwargs.pop('interface_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_switchport_output_switchport_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_switchport = ET.Element("get_interface_switchport")
config = get_interface_switchport
output = ET.SubElement(get_interface_switchport, "output")
switchport = ET.SubElement(output, "switchport")
interface_type_key = ET.SubElement(switchport, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name = ET.SubElement(switchport, "interface-name")
interface_name.text = kwargs.pop('interface_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_switchport_output_switchport_mode(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_switchport = ET.Element("get_interface_switchport")
config = get_interface_switchport
output = ET.SubElement(get_interface_switchport, "output")
switchport = ET.SubElement(output, "switchport")
interface_type_key = ET.SubElement(switchport, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(switchport, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
mode = ET.SubElement(switchport, "mode")
mode.text = kwargs.pop('mode')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_switchport_output_switchport_fcoe_port_enabled(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_switchport = ET.Element("get_interface_switchport")
config = get_interface_switchport
output = ET.SubElement(get_interface_switchport, "output")
switchport = ET.SubElement(output, "switchport")
interface_type_key = ET.SubElement(switchport, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(switchport, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
fcoe_port_enabled = ET.SubElement(switchport, "fcoe-port-enabled")
fcoe_port_enabled.text = kwargs.pop('fcoe_port_enabled')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_switchport_output_switchport_ingress_filter_enabled(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_switchport = ET.Element("get_interface_switchport")
config = get_interface_switchport
output = ET.SubElement(get_interface_switchport, "output")
switchport = ET.SubElement(output, "switchport")
interface_type_key = ET.SubElement(switchport, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(switchport, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
ingress_filter_enabled = ET.SubElement(switchport, "ingress-filter-enabled")
ingress_filter_enabled.text = kwargs.pop('ingress_filter_enabled')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_switchport_output_switchport_acceptable_frame_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_switchport = ET.Element("get_interface_switchport")
config = get_interface_switchport
output = ET.SubElement(get_interface_switchport, "output")
switchport = ET.SubElement(output, "switchport")
interface_type_key = ET.SubElement(switchport, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(switchport, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
acceptable_frame_type = ET.SubElement(switchport, "acceptable-frame-type")
acceptable_frame_type.text = kwargs.pop('acceptable_frame_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_switchport_output_switchport_default_vlan(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_switchport = ET.Element("get_interface_switchport")
config = get_interface_switchport
output = ET.SubElement(get_interface_switchport, "output")
switchport = ET.SubElement(output, "switchport")
interface_type_key = ET.SubElement(switchport, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(switchport, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
default_vlan = ET.SubElement(switchport, "default-vlan")
default_vlan.text = kwargs.pop('default_vlan')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_ip_interface_input_request_type_get_request_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
input = ET.SubElement(get_ip_interface, "input")
request_type = ET.SubElement(input, "request-type")
get_request = ET.SubElement(request_type, "get-request")
interface_type = ET.SubElement(get_request, "interface-type")
interface_type.text = kwargs.pop('interface_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_ip_interface_input_request_type_get_request_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
input = ET.SubElement(get_ip_interface, "input")
request_type = ET.SubElement(input, "request-type")
get_request = ET.SubElement(request_type, "get-request")
interface_name = ET.SubElement(get_request, "interface-name")
interface_name.text = kwargs.pop('interface_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_ip_interface_input_request_type_get_request_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
input = ET.SubElement(get_ip_interface, "input")
request_type = ET.SubElement(input, "request-type")
get_request = ET.SubElement(request_type, "get-request")
rbridge_id = ET.SubElement(get_request, "rbridge-id")
rbridge_id.text = kwargs.pop('rbridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_ip_interface_output_interface_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
output = ET.SubElement(get_ip_interface, "output")
interface = ET.SubElement(output, "interface")
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_type = ET.SubElement(interface, "interface-type")
interface_type.text = kwargs.pop('interface_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_ip_interface_output_interface_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
output = ET.SubElement(get_ip_interface, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name = ET.SubElement(interface, "interface-name")
interface_name.text = kwargs.pop('interface_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_ip_interface_output_interface_if_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
output = ET.SubElement(get_ip_interface, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
if_name = ET.SubElement(interface, "if-name")
if_name.text = kwargs.pop('if_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_ip_interface_output_interface_ip_address_ipv4(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
output = ET.SubElement(get_ip_interface, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
ip_address = ET.SubElement(interface, "ip-address")
ipv4 = ET.SubElement(ip_address, "ipv4")
ipv4.text = kwargs.pop('ipv4')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_ip_interface_output_interface_ip_address_ipv4_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
output = ET.SubElement(get_ip_interface, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
ip_address = ET.SubElement(interface, "ip-address")
ipv4_key = ET.SubElement(ip_address, "ipv4")
ipv4_key.text = kwargs.pop('ipv4')
ipv4_type = ET.SubElement(ip_address, "ipv4-type")
ipv4_type.text = kwargs.pop('ipv4_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_ip_interface_output_interface_ip_address_broadcast(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
output = ET.SubElement(get_ip_interface, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
ip_address = ET.SubElement(interface, "ip-address")
ipv4_key = ET.SubElement(ip_address, "ipv4")
ipv4_key.text = kwargs.pop('ipv4')
broadcast = ET.SubElement(ip_address, "broadcast")
broadcast.text = kwargs.pop('broadcast')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_ip_interface_output_interface_ip_address_ip_mtu(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
output = ET.SubElement(get_ip_interface, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
ip_address = ET.SubElement(interface, "ip-address")
ipv4_key = ET.SubElement(ip_address, "ipv4")
ipv4_key.text = kwargs.pop('ipv4')
ip_mtu = ET.SubElement(ip_address, "ip-mtu")
ip_mtu.text = kwargs.pop('ip_mtu')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_ip_interface_output_interface_if_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
output = ET.SubElement(get_ip_interface, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
if_state = ET.SubElement(interface, "if-state")
if_state.text = kwargs.pop('if_state')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_ip_interface_output_interface_line_protocol_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
output = ET.SubElement(get_ip_interface, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
line_protocol_state = ET.SubElement(interface, "line-protocol-state")
line_protocol_state.text = kwargs.pop('line_protocol_state')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_ip_interface_output_interface_proxy_arp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
output = ET.SubElement(get_ip_interface, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
proxy_arp = ET.SubElement(interface, "proxy-arp")
proxy_arp.text = kwargs.pop('proxy_arp')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_ip_interface_output_interface_vrf(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
output = ET.SubElement(get_ip_interface, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
vrf = ET.SubElement(interface, "vrf")
vrf.text = kwargs.pop('vrf')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_ip_interface_output_has_more(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_ip_interface = ET.Element("get_ip_interface")
config = get_ip_interface
output = ET.SubElement(get_ip_interface, "output")
has_more = ET.SubElement(output, "has-more")
has_more.text = kwargs.pop('has_more')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_input_request_type_get_request_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
input = ET.SubElement(get_interface_detail, "input")
request_type = ET.SubElement(input, "request-type")
get_request = ET.SubElement(request_type, "get-request")
interface_type = ET.SubElement(get_request, "interface-type")
interface_type.text = kwargs.pop('interface_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_input_request_type_get_request_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
input = ET.SubElement(get_interface_detail, "input")
request_type = ET.SubElement(input, "request-type")
get_request = ET.SubElement(request_type, "get-request")
interface_name = ET.SubElement(get_request, "interface-name")
interface_name.text = kwargs.pop('interface_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_input_request_type_get_next_request_last_rcvd_interface_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
input = ET.SubElement(get_interface_detail, "input")
request_type = ET.SubElement(input, "request-type")
get_next_request = ET.SubElement(request_type, "get-next-request")
last_rcvd_interface = ET.SubElement(get_next_request, "last-rcvd-interface")
interface_type = ET.SubElement(last_rcvd_interface, "interface-type")
interface_type.text = kwargs.pop('interface_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_input_request_type_get_next_request_last_rcvd_interface_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
input = ET.SubElement(get_interface_detail, "input")
request_type = ET.SubElement(input, "request-type")
get_next_request = ET.SubElement(request_type, "get-next-request")
last_rcvd_interface = ET.SubElement(get_next_request, "last-rcvd-interface")
interface_name = ET.SubElement(last_rcvd_interface, "interface-name")
interface_name.text = kwargs.pop('interface_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_type = ET.SubElement(interface, "interface-type")
interface_type.text = kwargs.pop('interface_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name = ET.SubElement(interface, "interface-name")
interface_name.text = kwargs.pop('interface_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_ifindex(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
ifindex = ET.SubElement(interface, "ifindex")
ifindex.text = kwargs.pop('ifindex')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_mtu(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
mtu = ET.SubElement(interface, "mtu")
mtu.text = kwargs.pop('mtu')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_ip_mtu(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
ip_mtu = ET.SubElement(interface, "ip-mtu")
ip_mtu.text = kwargs.pop('ip_mtu')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_if_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
if_name = ET.SubElement(interface, "if-name")
if_name.text = kwargs.pop('if_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_if_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
if_state = ET.SubElement(interface, "if-state")
if_state.text = kwargs.pop('if_state')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_line_protocol_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
line_protocol_state = ET.SubElement(interface, "line-protocol-state")
line_protocol_state.text = kwargs.pop('line_protocol_state')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_line_protocol_state_info(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
line_protocol_state_info = ET.SubElement(interface, "line-protocol-state-info")
line_protocol_state_info.text = kwargs.pop('line_protocol_state_info')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_line_protocol_exception_info(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
line_protocol_exception_info = ET.SubElement(interface, "line-protocol-exception-info")
line_protocol_exception_info.text = kwargs.pop('line_protocol_exception_info')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_hardware_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
hardware_type = ET.SubElement(interface, "hardware-type")
hardware_type.text = kwargs.pop('hardware_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_logical_hardware_address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
logical_hardware_address = ET.SubElement(interface, "logical-hardware-address")
logical_hardware_address.text = kwargs.pop('logical_hardware_address')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_current_hardware_address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
current_hardware_address = ET.SubElement(interface, "current-hardware-address")
current_hardware_address.text = kwargs.pop('current_hardware_address')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_media_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
media_type = ET.SubElement(interface, "media-type")
media_type.text = kwargs.pop('media_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_wavelength(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
wavelength = ET.SubElement(interface, "wavelength")
wavelength.text = kwargs.pop('wavelength')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_if_description(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
if_description = ET.SubElement(interface, "if-description")
if_description.text = kwargs.pop('if_description')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_actual_line_speed(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
actual_line_speed = ET.SubElement(interface, "actual-line-speed")
actual_line_speed.text = kwargs.pop('actual_line_speed')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_configured_line_speed(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
configured_line_speed = ET.SubElement(interface, "configured-line-speed")
configured_line_speed.text = kwargs.pop('configured_line_speed')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_line_duplex_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
line_duplex_state = ET.SubElement(interface, "line-duplex-state")
line_duplex_state.text = kwargs.pop('line_duplex_state')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_flow_control(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
flow_control = ET.SubElement(interface, "flow-control")
flow_control.text = kwargs.pop('flow_control')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_queuing_strategy(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
queuing_strategy = ET.SubElement(interface, "queuing-strategy")
queuing_strategy.text = kwargs.pop('queuing_strategy')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_port_role(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
port_role = ET.SubElement(interface, "port-role")
port_role.text = kwargs.pop('port_role')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_port_mode(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
port_mode = ET.SubElement(interface, "port-mode")
port_mode.text = kwargs.pop('port_mode')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_ifHCInOctets(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
ifHCInOctets = ET.SubElement(interface, "ifHCInOctets")
ifHCInOctets.text = kwargs.pop('ifHCInOctets')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_ifHCInUcastPkts(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
ifHCInUcastPkts = ET.SubElement(interface, "ifHCInUcastPkts")
ifHCInUcastPkts.text = kwargs.pop('ifHCInUcastPkts')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_ifHCInMulticastPkts(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
ifHCInMulticastPkts = ET.SubElement(interface, "ifHCInMulticastPkts")
ifHCInMulticastPkts.text = kwargs.pop('ifHCInMulticastPkts')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_ifHCInBroadcastPkts(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
ifHCInBroadcastPkts = ET.SubElement(interface, "ifHCInBroadcastPkts")
ifHCInBroadcastPkts.text = kwargs.pop('ifHCInBroadcastPkts')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_ifHCInErrors(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
ifHCInErrors = ET.SubElement(interface, "ifHCInErrors")
ifHCInErrors.text = kwargs.pop('ifHCInErrors')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_ifHCOutOctets(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
ifHCOutOctets = ET.SubElement(interface, "ifHCOutOctets")
ifHCOutOctets.text = kwargs.pop('ifHCOutOctets')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_ifHCOutUcastPkts(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
ifHCOutUcastPkts = ET.SubElement(interface, "ifHCOutUcastPkts")
ifHCOutUcastPkts.text = kwargs.pop('ifHCOutUcastPkts')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_ifHCOutMulticastPkts(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
ifHCOutMulticastPkts = ET.SubElement(interface, "ifHCOutMulticastPkts")
ifHCOutMulticastPkts.text = kwargs.pop('ifHCOutMulticastPkts')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_ifHCOutBroadcastPkts(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
ifHCOutBroadcastPkts = ET.SubElement(interface, "ifHCOutBroadcastPkts")
ifHCOutBroadcastPkts.text = kwargs.pop('ifHCOutBroadcastPkts')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_interface_ifHCOutErrors(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
ifHCOutErrors = ET.SubElement(interface, "ifHCOutErrors")
ifHCOutErrors.text = kwargs.pop('ifHCOutErrors')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_interface_detail_output_has_more(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "output")
has_more = ET.SubElement(output, "has-more")
has_more.text = kwargs.pop('has_more')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_input_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
input = ET.SubElement(get_media_detail, "input")
interface_type = ET.SubElement(input, "interface-type")
interface_type.text = kwargs.pop('interface_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_input_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
input = ET.SubElement(get_media_detail, "input")
interface_name = ET.SubElement(input, "interface-name")
interface_name.text = kwargs.pop('interface_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_input_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
input = ET.SubElement(get_media_detail, "input")
rbridge_id = ET.SubElement(input, "rbridge-id")
rbridge_id.text = kwargs.pop('rbridge_id')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_type = ET.SubElement(interface, "interface-type")
interface_type.text = kwargs.pop('interface_type')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name = ET.SubElement(interface, "interface-name")
interface_name.text = kwargs.pop('interface_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_sfp_sfp_speed(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
sfp = ET.SubElement(interface_identifier, "sfp")
sfp = ET.SubElement(sfp, "sfp")
speed = ET.SubElement(sfp, "speed")
speed.text = kwargs.pop('speed')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_sfp_sfp_connector(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
sfp = ET.SubElement(interface_identifier, "sfp")
sfp = ET.SubElement(sfp, "sfp")
connector = ET.SubElement(sfp, "connector")
connector.text = kwargs.pop('connector')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_sfp_sfp_encoding(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
sfp = ET.SubElement(interface_identifier, "sfp")
sfp = ET.SubElement(sfp, "sfp")
encoding = ET.SubElement(sfp, "encoding")
encoding.text = kwargs.pop('encoding')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_sfp_sfp_vendor_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
sfp = ET.SubElement(interface_identifier, "sfp")
sfp = ET.SubElement(sfp, "sfp")
vendor_name = ET.SubElement(sfp, "vendor-name")
vendor_name.text = kwargs.pop('vendor_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_sfp_sfp_vendor_oui(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
sfp = ET.SubElement(interface_identifier, "sfp")
sfp = ET.SubElement(sfp, "sfp")
vendor_oui = ET.SubElement(sfp, "vendor-oui")
vendor_oui.text = kwargs.pop('vendor_oui')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_sfp_sfp_vendor_pn(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
sfp = ET.SubElement(interface_identifier, "sfp")
sfp = ET.SubElement(sfp, "sfp")
vendor_pn = ET.SubElement(sfp, "vendor-pn")
vendor_pn.text = kwargs.pop('vendor_pn')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_sfp_sfp_vendor_rev(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
sfp = ET.SubElement(interface_identifier, "sfp")
sfp = ET.SubElement(sfp, "sfp")
vendor_rev = ET.SubElement(sfp, "vendor-rev")
vendor_rev.text = kwargs.pop('vendor_rev')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_sfp_sfp_distance(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
sfp = ET.SubElement(interface_identifier, "sfp")
sfp = ET.SubElement(sfp, "sfp")
distance = ET.SubElement(sfp, "distance")
distance.text = kwargs.pop('distance')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_sfp_sfp_media_form_factor(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
sfp = ET.SubElement(interface_identifier, "sfp")
sfp = ET.SubElement(sfp, "sfp")
media_form_factor = ET.SubElement(sfp, "media-form-factor")
media_form_factor.text = kwargs.pop('media_form_factor')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_sfp_sfp_wavelength(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
sfp = ET.SubElement(interface_identifier, "sfp")
sfp = ET.SubElement(sfp, "sfp")
wavelength = ET.SubElement(sfp, "wavelength")
wavelength.text = kwargs.pop('wavelength')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_sfp_sfp_serial_no(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
sfp = ET.SubElement(interface_identifier, "sfp")
sfp = ET.SubElement(sfp, "sfp")
serial_no = ET.SubElement(sfp, "serial-no")
serial_no.text = kwargs.pop('serial_no')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_sfp_sfp_date_code(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
sfp = ET.SubElement(interface_identifier, "sfp")
sfp = ET.SubElement(sfp, "sfp")
date_code = ET.SubElement(sfp, "date-code")
date_code.text = kwargs.pop('date_code')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_sfp_sfp_temperature(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
sfp = ET.SubElement(interface_identifier, "sfp")
sfp = ET.SubElement(sfp, "sfp")
temperature = ET.SubElement(sfp, "temperature")
temperature.text = kwargs.pop('temperature')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_sfp_sfp_voltage(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
sfp = ET.SubElement(interface_identifier, "sfp")
sfp = ET.SubElement(sfp, "sfp")
voltage = ET.SubElement(sfp, "voltage")
voltage.text = kwargs.pop('voltage')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_sfp_sfp_current(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
sfp = ET.SubElement(interface_identifier, "sfp")
sfp = ET.SubElement(sfp, "sfp")
current = ET.SubElement(sfp, "current")
current.text = kwargs.pop('current')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_sfp_sfp_tx_power(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
sfp = ET.SubElement(interface_identifier, "sfp")
sfp = ET.SubElement(sfp, "sfp")
tx_power = ET.SubElement(sfp, "tx-power")
tx_power.text = kwargs.pop('tx_power')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_sfp_sfp_rx_power(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
sfp = ET.SubElement(interface_identifier, "sfp")
sfp = ET.SubElement(sfp, "sfp")
rx_power = ET.SubElement(sfp, "rx-power")
rx_power.text = kwargs.pop('rx_power')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_on_board_on_board_speed(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
on_board = ET.SubElement(interface_identifier, "on-board")
on_board = ET.SubElement(on_board, "on-board")
speed = ET.SubElement(on_board, "speed")
speed.text = kwargs.pop('speed')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_on_board_on_board_connector(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
on_board = ET.SubElement(interface_identifier, "on-board")
on_board = ET.SubElement(on_board, "on-board")
connector = ET.SubElement(on_board, "connector")
connector.text = kwargs.pop('connector')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_on_board_on_board_encoding(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
on_board = ET.SubElement(interface_identifier, "on-board")
on_board = ET.SubElement(on_board, "on-board")
encoding = ET.SubElement(on_board, "encoding")
encoding.text = kwargs.pop('encoding')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_on_board_on_board_vendor_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
on_board = ET.SubElement(interface_identifier, "on-board")
on_board = ET.SubElement(on_board, "on-board")
vendor_name = ET.SubElement(on_board, "vendor-name")
vendor_name.text = kwargs.pop('vendor_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_on_board_on_board_vendor_oui(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
on_board = ET.SubElement(interface_identifier, "on-board")
on_board = ET.SubElement(on_board, "on-board")
vendor_oui = ET.SubElement(on_board, "vendor-oui")
vendor_oui.text = kwargs.pop('vendor_oui')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_on_board_on_board_vendor_pn(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
on_board = ET.SubElement(interface_identifier, "on-board")
on_board = ET.SubElement(on_board, "on-board")
vendor_pn = ET.SubElement(on_board, "vendor-pn")
vendor_pn.text = kwargs.pop('vendor_pn')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_on_board_on_board_vendor_rev(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
on_board = ET.SubElement(interface_identifier, "on-board")
on_board = ET.SubElement(on_board, "on-board")
vendor_rev = ET.SubElement(on_board, "vendor-rev")
vendor_rev.text = kwargs.pop('vendor_rev')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_gbic_gbc_vendor_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
gbic = ET.SubElement(interface_identifier, "gbic")
gbc = ET.SubElement(gbic, "gbc")
vendor_name = ET.SubElement(gbc, "vendor-name")
vendor_name.text = kwargs.pop('vendor_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_gbic_gbc_vendor_oui(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
gbic = ET.SubElement(interface_identifier, "gbic")
gbc = ET.SubElement(gbic, "gbc")
vendor_oui = ET.SubElement(gbc, "vendor-oui")
vendor_oui.text = kwargs.pop('vendor_oui')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_gbic_gbc_vendor_pn(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
gbic = ET.SubElement(interface_identifier, "gbic")
gbc = ET.SubElement(gbic, "gbc")
vendor_pn = ET.SubElement(gbc, "vendor-pn")
vendor_pn.text = kwargs.pop('vendor_pn')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_gbic_gbc_vendor_rev(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
gbic = ET.SubElement(interface_identifier, "gbic")
gbc = ET.SubElement(gbic, "gbc")
vendor_rev = ET.SubElement(gbc, "vendor-rev")
vendor_rev.text = kwargs.pop('vendor_rev')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_xfp_xfp_vendor_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
xfp = ET.SubElement(interface_identifier, "xfp")
xfp = ET.SubElement(xfp, "xfp")
vendor_name = ET.SubElement(xfp, "vendor-name")
vendor_name.text = kwargs.pop('vendor_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_xfp_xfp_vendor_oui(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
xfp = ET.SubElement(interface_identifier, "xfp")
xfp = ET.SubElement(xfp, "xfp")
vendor_oui = ET.SubElement(xfp, "vendor-oui")
vendor_oui.text = kwargs.pop('vendor_oui')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_xfp_xfp_vendor_pn(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
xfp = ET.SubElement(interface_identifier, "xfp")
xfp = ET.SubElement(xfp, "xfp")
vendor_pn = ET.SubElement(xfp, "vendor-pn")
vendor_pn.text = kwargs.pop('vendor_pn')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_xfp_xfp_vendor_rev(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
xfp = ET.SubElement(interface_identifier, "xfp")
xfp = ET.SubElement(xfp, "xfp")
vendor_rev = ET.SubElement(xfp, "vendor-rev")
vendor_rev.text = kwargs.pop('vendor_rev')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_xff_xff_vendor_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
xff = ET.SubElement(interface_identifier, "xff")
xff = ET.SubElement(xff, "xff")
vendor_name = ET.SubElement(xff, "vendor-name")
vendor_name.text = kwargs.pop('vendor_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_xff_xff_vendor_oui(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
xff = ET.SubElement(interface_identifier, "xff")
xff = ET.SubElement(xff, "xff")
vendor_oui = ET.SubElement(xff, "vendor-oui")
vendor_oui.text = kwargs.pop('vendor_oui')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_xff_xff_vendor_pn(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
xff = ET.SubElement(interface_identifier, "xff")
xff = ET.SubElement(xff, "xff")
vendor_pn = ET.SubElement(xff, "vendor-pn")
vendor_pn.text = kwargs.pop('vendor_pn')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_xff_xff_vendor_rev(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
xff = ET.SubElement(interface_identifier, "xff")
xff = ET.SubElement(xff, "xff")
vendor_rev = ET.SubElement(xff, "vendor-rev")
vendor_rev.text = kwargs.pop('vendor_rev')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_xfpe_xfpe_vendor_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
xfpe = ET.SubElement(interface_identifier, "xfpe")
xfpe = ET.SubElement(xfpe, "xfpe")
vendor_name = ET.SubElement(xfpe, "vendor-name")
vendor_name.text = kwargs.pop('vendor_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_xfpe_xfpe_vendor_oui(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
xfpe = ET.SubElement(interface_identifier, "xfpe")
xfpe = ET.SubElement(xfpe, "xfpe")
vendor_oui = ET.SubElement(xfpe, "vendor-oui")
vendor_oui.text = kwargs.pop('vendor_oui')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_xfpe_xfpe_vendor_pn(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
xfpe = ET.SubElement(interface_identifier, "xfpe")
xfpe = ET.SubElement(xfpe, "xfpe")
vendor_pn = ET.SubElement(xfpe, "vendor-pn")
vendor_pn.text = kwargs.pop('vendor_pn')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_xfpe_xfpe_vendor_rev(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
xfpe = ET.SubElement(interface_identifier, "xfpe")
xfpe = ET.SubElement(xfpe, "xfpe")
vendor_rev = ET.SubElement(xfpe, "vendor-rev")
vendor_rev.text = kwargs.pop('vendor_rev')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_unknown_unknown_vendor_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
unknown = ET.SubElement(interface_identifier, "unknown")
unknown = ET.SubElement(unknown, "unknown")
vendor_name = ET.SubElement(unknown, "vendor-name")
vendor_name.text = kwargs.pop('vendor_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_unknown_unknown_vendor_oui(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
unknown = ET.SubElement(interface_identifier, "unknown")
unknown = ET.SubElement(unknown, "unknown")
vendor_oui = ET.SubElement(unknown, "vendor-oui")
vendor_oui.text = kwargs.pop('vendor_oui')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_unknown_unknown_vendor_pn(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
unknown = ET.SubElement(interface_identifier, "unknown")
unknown = ET.SubElement(unknown, "unknown")
vendor_pn = ET.SubElement(unknown, "vendor-pn")
vendor_pn.text = kwargs.pop('vendor_pn')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_unknown_unknown_vendor_rev(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
unknown = ET.SubElement(interface_identifier, "unknown")
unknown = ET.SubElement(unknown, "unknown")
vendor_rev = ET.SubElement(unknown, "vendor-rev")
vendor_rev.text = kwargs.pop('vendor_rev')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfp_qsfp_speed(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfp = ET.SubElement(interface_identifier, "qsfp")
qsfp = ET.SubElement(qsfp, "qsfp")
speed = ET.SubElement(qsfp, "speed")
speed.text = kwargs.pop('speed')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfp_qsfp_connector(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfp = ET.SubElement(interface_identifier, "qsfp")
qsfp = ET.SubElement(qsfp, "qsfp")
connector = ET.SubElement(qsfp, "connector")
connector.text = kwargs.pop('connector')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfp_qsfp_encoding(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfp = ET.SubElement(interface_identifier, "qsfp")
qsfp = ET.SubElement(qsfp, "qsfp")
encoding = ET.SubElement(qsfp, "encoding")
encoding.text = kwargs.pop('encoding')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfp_qsfp_vendor_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfp = ET.SubElement(interface_identifier, "qsfp")
qsfp = ET.SubElement(qsfp, "qsfp")
vendor_name = ET.SubElement(qsfp, "vendor-name")
vendor_name.text = kwargs.pop('vendor_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfp_qsfp_vendor_oui(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfp = ET.SubElement(interface_identifier, "qsfp")
qsfp = ET.SubElement(qsfp, "qsfp")
vendor_oui = ET.SubElement(qsfp, "vendor-oui")
vendor_oui.text = kwargs.pop('vendor_oui')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfp_qsfp_vendor_pn(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfp = ET.SubElement(interface_identifier, "qsfp")
qsfp = ET.SubElement(qsfp, "qsfp")
vendor_pn = ET.SubElement(qsfp, "vendor-pn")
vendor_pn.text = kwargs.pop('vendor_pn')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfp_qsfp_vendor_rev(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfp = ET.SubElement(interface_identifier, "qsfp")
qsfp = ET.SubElement(qsfp, "qsfp")
vendor_rev = ET.SubElement(qsfp, "vendor-rev")
vendor_rev.text = kwargs.pop('vendor_rev')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfp_qsfp_distance(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfp = ET.SubElement(interface_identifier, "qsfp")
qsfp = ET.SubElement(qsfp, "qsfp")
distance = ET.SubElement(qsfp, "distance")
distance.text = kwargs.pop('distance')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfp_qsfp_media_form_factor(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfp = ET.SubElement(interface_identifier, "qsfp")
qsfp = ET.SubElement(qsfp, "qsfp")
media_form_factor = ET.SubElement(qsfp, "media-form-factor")
media_form_factor.text = kwargs.pop('media_form_factor')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfp_qsfp_wavelength(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfp = ET.SubElement(interface_identifier, "qsfp")
qsfp = ET.SubElement(qsfp, "qsfp")
wavelength = ET.SubElement(qsfp, "wavelength")
wavelength.text = kwargs.pop('wavelength')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfp_qsfp_serial_no(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfp = ET.SubElement(interface_identifier, "qsfp")
qsfp = ET.SubElement(qsfp, "qsfp")
serial_no = ET.SubElement(qsfp, "serial-no")
serial_no.text = kwargs.pop('serial_no')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfp_qsfp_date_code(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfp = ET.SubElement(interface_identifier, "qsfp")
qsfp = ET.SubElement(qsfp, "qsfp")
date_code = ET.SubElement(qsfp, "date-code")
date_code.text = kwargs.pop('date_code')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfp_qsfp_temperature(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfp = ET.SubElement(interface_identifier, "qsfp")
qsfp = ET.SubElement(qsfp, "qsfp")
temperature = ET.SubElement(qsfp, "temperature")
temperature.text = kwargs.pop('temperature')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfp_qsfp_voltage(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfp = ET.SubElement(interface_identifier, "qsfp")
qsfp = ET.SubElement(qsfp, "qsfp")
voltage = ET.SubElement(qsfp, "voltage")
voltage.text = kwargs.pop('voltage')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfp_qsfp_current(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfp = ET.SubElement(interface_identifier, "qsfp")
qsfp = ET.SubElement(qsfp, "qsfp")
current = ET.SubElement(qsfp, "current")
current.text = kwargs.pop('current')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfp_qsfp_tx_power(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfp = ET.SubElement(interface_identifier, "qsfp")
qsfp = ET.SubElement(qsfp, "qsfp")
tx_power = ET.SubElement(qsfp, "tx-power")
tx_power.text = kwargs.pop('tx_power')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfp_qsfp_rx_power(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfp = ET.SubElement(interface_identifier, "qsfp")
qsfp = ET.SubElement(qsfp, "qsfp")
rx_power = ET.SubElement(qsfp, "rx-power")
rx_power.text = kwargs.pop('rx_power')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfpp_qsfpp_speed(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfpp = ET.SubElement(interface_identifier, "qsfpp")
qsfpp = ET.SubElement(qsfpp, "qsfpp")
speed = ET.SubElement(qsfpp, "speed")
speed.text = kwargs.pop('speed')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfpp_qsfpp_connector(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfpp = ET.SubElement(interface_identifier, "qsfpp")
qsfpp = ET.SubElement(qsfpp, "qsfpp")
connector = ET.SubElement(qsfpp, "connector")
connector.text = kwargs.pop('connector')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfpp_qsfpp_encoding(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfpp = ET.SubElement(interface_identifier, "qsfpp")
qsfpp = ET.SubElement(qsfpp, "qsfpp")
encoding = ET.SubElement(qsfpp, "encoding")
encoding.text = kwargs.pop('encoding')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfpp_qsfpp_vendor_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfpp = ET.SubElement(interface_identifier, "qsfpp")
qsfpp = ET.SubElement(qsfpp, "qsfpp")
vendor_name = ET.SubElement(qsfpp, "vendor-name")
vendor_name.text = kwargs.pop('vendor_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfpp_qsfpp_vendor_oui(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfpp = ET.SubElement(interface_identifier, "qsfpp")
qsfpp = ET.SubElement(qsfpp, "qsfpp")
vendor_oui = ET.SubElement(qsfpp, "vendor-oui")
vendor_oui.text = kwargs.pop('vendor_oui')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfpp_qsfpp_vendor_pn(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfpp = ET.SubElement(interface_identifier, "qsfpp")
qsfpp = ET.SubElement(qsfpp, "qsfpp")
vendor_pn = ET.SubElement(qsfpp, "vendor-pn")
vendor_pn.text = kwargs.pop('vendor_pn')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfpp_qsfpp_vendor_rev(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfpp = ET.SubElement(interface_identifier, "qsfpp")
qsfpp = ET.SubElement(qsfpp, "qsfpp")
vendor_rev = ET.SubElement(qsfpp, "vendor-rev")
vendor_rev.text = kwargs.pop('vendor_rev')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfpp_qsfpp_distance(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfpp = ET.SubElement(interface_identifier, "qsfpp")
qsfpp = ET.SubElement(qsfpp, "qsfpp")
distance = ET.SubElement(qsfpp, "distance")
distance.text = kwargs.pop('distance')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfpp_qsfpp_media_form_factor(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfpp = ET.SubElement(interface_identifier, "qsfpp")
qsfpp = ET.SubElement(qsfpp, "qsfpp")
media_form_factor = ET.SubElement(qsfpp, "media-form-factor")
media_form_factor.text = kwargs.pop('media_form_factor')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfpp_qsfpp_wavelength(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfpp = ET.SubElement(interface_identifier, "qsfpp")
qsfpp = ET.SubElement(qsfpp, "qsfpp")
wavelength = ET.SubElement(qsfpp, "wavelength")
wavelength.text = kwargs.pop('wavelength')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfpp_qsfpp_serial_no(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfpp = ET.SubElement(interface_identifier, "qsfpp")
qsfpp = ET.SubElement(qsfpp, "qsfpp")
serial_no = ET.SubElement(qsfpp, "serial-no")
serial_no.text = kwargs.pop('serial_no')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfpp_qsfpp_date_code(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfpp = ET.SubElement(interface_identifier, "qsfpp")
qsfpp = ET.SubElement(qsfpp, "qsfpp")
date_code = ET.SubElement(qsfpp, "date-code")
date_code.text = kwargs.pop('date_code')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfpp_qsfpp_temperature(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfpp = ET.SubElement(interface_identifier, "qsfpp")
qsfpp = ET.SubElement(qsfpp, "qsfpp")
temperature = ET.SubElement(qsfpp, "temperature")
temperature.text = kwargs.pop('temperature')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfpp_qsfpp_voltage(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfpp = ET.SubElement(interface_identifier, "qsfpp")
qsfpp = ET.SubElement(qsfpp, "qsfpp")
voltage = ET.SubElement(qsfpp, "voltage")
voltage.text = kwargs.pop('voltage')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfpp_qsfpp_current(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfpp = ET.SubElement(interface_identifier, "qsfpp")
qsfpp = ET.SubElement(qsfpp, "qsfpp")
current = ET.SubElement(qsfpp, "current")
current.text = kwargs.pop('current')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfpp_qsfpp_tx_power(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfpp = ET.SubElement(interface_identifier, "qsfpp")
qsfpp = ET.SubElement(qsfpp, "qsfpp")
tx_power = ET.SubElement(qsfpp, "tx-power")
tx_power.text = kwargs.pop('tx_power')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_qsfpp_qsfpp_rx_power(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
qsfpp = ET.SubElement(interface_identifier, "qsfpp")
qsfpp = ET.SubElement(qsfpp, "qsfpp")
rx_power = ET.SubElement(qsfpp, "rx-power")
rx_power.text = kwargs.pop('rx_power')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp_cfp_speed(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp = ET.SubElement(interface_identifier, "cfp")
cfp = ET.SubElement(cfp, "cfp")
speed = ET.SubElement(cfp, "speed")
speed.text = kwargs.pop('speed')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp_cfp_connector(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp = ET.SubElement(interface_identifier, "cfp")
cfp = ET.SubElement(cfp, "cfp")
connector = ET.SubElement(cfp, "connector")
connector.text = kwargs.pop('connector')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp_cfp_encoding(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp = ET.SubElement(interface_identifier, "cfp")
cfp = ET.SubElement(cfp, "cfp")
encoding = ET.SubElement(cfp, "encoding")
encoding.text = kwargs.pop('encoding')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp_cfp_vendor_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp = ET.SubElement(interface_identifier, "cfp")
cfp = ET.SubElement(cfp, "cfp")
vendor_name = ET.SubElement(cfp, "vendor-name")
vendor_name.text = kwargs.pop('vendor_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp_cfp_vendor_oui(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp = ET.SubElement(interface_identifier, "cfp")
cfp = ET.SubElement(cfp, "cfp")
vendor_oui = ET.SubElement(cfp, "vendor-oui")
vendor_oui.text = kwargs.pop('vendor_oui')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp_cfp_vendor_pn(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp = ET.SubElement(interface_identifier, "cfp")
cfp = ET.SubElement(cfp, "cfp")
vendor_pn = ET.SubElement(cfp, "vendor-pn")
vendor_pn.text = kwargs.pop('vendor_pn')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp_cfp_vendor_rev(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp = ET.SubElement(interface_identifier, "cfp")
cfp = ET.SubElement(cfp, "cfp")
vendor_rev = ET.SubElement(cfp, "vendor-rev")
vendor_rev.text = kwargs.pop('vendor_rev')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp_cfp_distance(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp = ET.SubElement(interface_identifier, "cfp")
cfp = ET.SubElement(cfp, "cfp")
distance = ET.SubElement(cfp, "distance")
distance.text = kwargs.pop('distance')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp_cfp_media_form_factor(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp = ET.SubElement(interface_identifier, "cfp")
cfp = ET.SubElement(cfp, "cfp")
media_form_factor = ET.SubElement(cfp, "media-form-factor")
media_form_factor.text = kwargs.pop('media_form_factor')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp_cfp_wavelength(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp = ET.SubElement(interface_identifier, "cfp")
cfp = ET.SubElement(cfp, "cfp")
wavelength = ET.SubElement(cfp, "wavelength")
wavelength.text = kwargs.pop('wavelength')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp_cfp_serial_no(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp = ET.SubElement(interface_identifier, "cfp")
cfp = ET.SubElement(cfp, "cfp")
serial_no = ET.SubElement(cfp, "serial-no")
serial_no.text = kwargs.pop('serial_no')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp_cfp_date_code(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp = ET.SubElement(interface_identifier, "cfp")
cfp = ET.SubElement(cfp, "cfp")
date_code = ET.SubElement(cfp, "date-code")
date_code.text = kwargs.pop('date_code')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp_cfp_temperature(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp = ET.SubElement(interface_identifier, "cfp")
cfp = ET.SubElement(cfp, "cfp")
temperature = ET.SubElement(cfp, "temperature")
temperature.text = kwargs.pop('temperature')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp_cfp_voltage(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp = ET.SubElement(interface_identifier, "cfp")
cfp = ET.SubElement(cfp, "cfp")
voltage = ET.SubElement(cfp, "voltage")
voltage.text = kwargs.pop('voltage')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp_cfp_current(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp = ET.SubElement(interface_identifier, "cfp")
cfp = ET.SubElement(cfp, "cfp")
current = ET.SubElement(cfp, "current")
current.text = kwargs.pop('current')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp_cfp_tx_power(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp = ET.SubElement(interface_identifier, "cfp")
cfp = ET.SubElement(cfp, "cfp")
tx_power = ET.SubElement(cfp, "tx-power")
tx_power.text = kwargs.pop('tx_power')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp_cfp_rx_power(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp = ET.SubElement(interface_identifier, "cfp")
cfp = ET.SubElement(cfp, "cfp")
rx_power = ET.SubElement(cfp, "rx-power")
rx_power.text = kwargs.pop('rx_power')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_speed(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp2 = ET.SubElement(interface_identifier, "cfp2")
cfp2 = ET.SubElement(cfp2, "cfp2")
speed = ET.SubElement(cfp2, "speed")
speed.text = kwargs.pop('speed')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_connector(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp2 = ET.SubElement(interface_identifier, "cfp2")
cfp2 = ET.SubElement(cfp2, "cfp2")
connector = ET.SubElement(cfp2, "connector")
connector.text = kwargs.pop('connector')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_encoding(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp2 = ET.SubElement(interface_identifier, "cfp2")
cfp2 = ET.SubElement(cfp2, "cfp2")
encoding = ET.SubElement(cfp2, "encoding")
encoding.text = kwargs.pop('encoding')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_vendor_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp2 = ET.SubElement(interface_identifier, "cfp2")
cfp2 = ET.SubElement(cfp2, "cfp2")
vendor_name = ET.SubElement(cfp2, "vendor-name")
vendor_name.text = kwargs.pop('vendor_name')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_vendor_oui(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp2 = ET.SubElement(interface_identifier, "cfp2")
cfp2 = ET.SubElement(cfp2, "cfp2")
vendor_oui = ET.SubElement(cfp2, "vendor-oui")
vendor_oui.text = kwargs.pop('vendor_oui')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_vendor_pn(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp2 = ET.SubElement(interface_identifier, "cfp2")
cfp2 = ET.SubElement(cfp2, "cfp2")
vendor_pn = ET.SubElement(cfp2, "vendor-pn")
vendor_pn.text = kwargs.pop('vendor_pn')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_vendor_rev(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp2 = ET.SubElement(interface_identifier, "cfp2")
cfp2 = ET.SubElement(cfp2, "cfp2")
vendor_rev = ET.SubElement(cfp2, "vendor-rev")
vendor_rev.text = kwargs.pop('vendor_rev')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_distance(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp2 = ET.SubElement(interface_identifier, "cfp2")
cfp2 = ET.SubElement(cfp2, "cfp2")
distance = ET.SubElement(cfp2, "distance")
distance.text = kwargs.pop('distance')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_media_form_factor(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp2 = ET.SubElement(interface_identifier, "cfp2")
cfp2 = ET.SubElement(cfp2, "cfp2")
media_form_factor = ET.SubElement(cfp2, "media-form-factor")
media_form_factor.text = kwargs.pop('media_form_factor')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_wavelength(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp2 = ET.SubElement(interface_identifier, "cfp2")
cfp2 = ET.SubElement(cfp2, "cfp2")
wavelength = ET.SubElement(cfp2, "wavelength")
wavelength.text = kwargs.pop('wavelength')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_serial_no(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp2 = ET.SubElement(interface_identifier, "cfp2")
cfp2 = ET.SubElement(cfp2, "cfp2")
serial_no = ET.SubElement(cfp2, "serial-no")
serial_no.text = kwargs.pop('serial_no')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_date_code(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp2 = ET.SubElement(interface_identifier, "cfp2")
cfp2 = ET.SubElement(cfp2, "cfp2")
date_code = ET.SubElement(cfp2, "date-code")
date_code.text = kwargs.pop('date_code')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_temperature(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp2 = ET.SubElement(interface_identifier, "cfp2")
cfp2 = ET.SubElement(cfp2, "cfp2")
temperature = ET.SubElement(cfp2, "temperature")
temperature.text = kwargs.pop('temperature')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_voltage(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp2 = ET.SubElement(interface_identifier, "cfp2")
cfp2 = ET.SubElement(cfp2, "cfp2")
voltage = ET.SubElement(cfp2, "voltage")
voltage.text = kwargs.pop('voltage')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_current(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp2 = ET.SubElement(interface_identifier, "cfp2")
cfp2 = ET.SubElement(cfp2, "cfp2")
current = ET.SubElement(cfp2, "current")
current.text = kwargs.pop('current')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_tx_power(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp2 = ET.SubElement(interface_identifier, "cfp2")
cfp2 = ET.SubElement(cfp2, "cfp2")
tx_power = ET.SubElement(cfp2, "tx-power")
tx_power.text = kwargs.pop('tx_power')
callback = kwargs.pop('callback', self._callback)
return callback(config)
def get_media_detail_output_interface_interface_identifier_cfp2_cfp2_rx_power(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
cfp2 = ET.SubElement(interface_identifier, "cfp2")
cfp2 = ET.SubElement(cfp2, "cfp2")
rx_power = ET.SubElement(cfp2, "rx-power")
rx_power.text = kwargs.pop('rx_power')
callback = kwargs.pop('callback', self._callback)
return callback(config)
| """Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface = ET.SubElement(output, "interface")
interface_type_key = ET.SubElement(interface, "interface-type")
interface_type_key.text = kwargs.pop('interface_type')
interface_name_key = ET.SubElement(interface, "interface-name")
interface_name_key.text = kwargs.pop('interface_name')
interface_identifier = ET.SubElement(interface, "interface-identifier")
sfp = ET.SubElement(interface_identifier, "sfp")
sfp = ET.SubElement(sfp, "sfp")
rx_power = ET.SubElement(sfp, "rx-power")
rx_power.text = kwargs.pop('rx_power')
callback = kwargs.pop('callback', self._callback)
return callback(config) |
LoginForm.js | import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import styled from 'styled-components';
import axios from 'axios';
import { backendLink } from '../assets/config';
const Login = styled.div`
display: flex;
max-width: 500px;
box-shadow: 0 1px 10px rgba(0, 0, 0, 0.15);
height: 500px;
.Login__text--link,
.Login__text {
font-weight: 100;
}
`;
const AuthInput = styled.input`
width: 90%;
padding: 10px;
border: 1px solid #e6e6e6;
margin: 10px auto;
`;
const AuthHeader = styled.h1`
padding-bottom: 25px;
font-weight: 100;
letter-spacing: 1.2px;
`;
const AuthForm = styled.form`
background: white;
width: 100%;
padding: 2rem;
input[type='submit'] {
background-color: #eed974;
font-size: 1.25rem;
margin: 10px auto;
padding: 10px;
float: center;
height: 70px;
width: 95%;
margin-bottom: 15px;
}
`;
class | extends Component {
constructor(props) {
super(props);
this.state = {
email: '',
password: ''
};
}
handleChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
};
handleSubmit = async (e) => {
e.preventDefault();
const res = await axios.post(
`${backendLink}/api/user/login`,
{
email: this.state.email,
password: this.state.password
},
{ withCredentials: 'include' }
);
if (res.status === 500) {
return alert('Login incorrect, please try again.');
}
this.props.history.push('/');
};
render() {
return (
<Login>
<AuthForm onSubmit={this.handleSubmit}>
<AuthHeader>Login to your account</AuthHeader>
<h4 className="Login__text">
Don't have an account?
<Link to="/register" className="Login__text--link">
Register here!
</Link>
</h4>
<label htmlFor="email"> Email</label>
<AuthInput type="email" name="email" onChange={this.handleChange} />
<label htmlFor="password"> Password</label>
<AuthInput type="password" name="password" onChange={this.handleChange} />
<input type="submit" value="Login" />
</AuthForm>
</Login>
);
}
}
export default LoginForm;
| LoginForm |
main.rs | #![feature(plugin, path_ext)]
#![plugin(string_cache_plugin)]
extern crate html5ever;
extern crate html5ever_dom_sink;
extern crate hyper;
#[macro_use] extern crate string_cache;
use std::io::{self, Read, Write};
use std::default::Default;
use std::env;
use std::fs::{self, PathExt, File};
use std::path::Path;
use hyper::Client;
use html5ever_dom_sink::common::{Text, Element};
use html5ever_dom_sink::rcdom::{RcDom, Handle};
use html5ever::{parse, one_input};
fn getdom(input: String) -> RcDom {
parse(one_input(input), Default::default())
}
fn to_string(handle: Handle, text: &mut String) {
let node = handle.borrow();
match node.node {
Text(ref value) => {
text.push_str(value);
},
_ => {},
}
for child in node.children.iter() {
to_string(child.clone(), text);
}
}
fn find(handle: Handle, class: String) -> Option<Handle> {
let node = handle.borrow();
match node.node {
Element(_, ref attrs) => {
for attr in attrs.iter() {
match (attr.name.local.as_slice(), attr.value.to_string()) {
("class", ref c) if c == &class => return Some(handle.clone()),
_ => continue
}
}
},
_ => {}
}
for child in node.children.iter() { | }
None
}
fn get_problem_num() -> i64 {
let args = env::args();
let mut prob = match args.last() {
Some(v) => v.parse().ok(),
None => None
};
while prob.is_none() {
print!("Which problem? ");
io::stdout().flush().unwrap();
let mut answer = String::new();
io::stdin().read_line(&mut answer).unwrap();
prob = answer.trim().parse().ok();
}
prob.unwrap()
}
const BASE: &'static str = "https://projecteuler.net/problem=";
fn main() {
let mut client = Client::new();
let mut result = String::new();
let problem = get_problem_num();
let sol_dir = format!("sol_{:04}", problem);
let dir = Path::new(&sol_dir);
let file = dir.join("main.rs");
if !dir.exists() {
fs::create_dir(dir).ok().expect("Unable to create directory!");
}
if file.exists() {
print!("File already exists. Overwrite? (y/N) ");
io::stdout().flush().unwrap();
let mut answer = String::new();
io::stdin().read_line(&mut answer).unwrap();
match answer.trim().as_ref() {
"y" | "Y" | "yes" | "Yes" => {},
_ => return
}
}
client.get(&format!("{}{}", BASE, problem))
.send().unwrap()
.read_to_string(&mut result).unwrap();
let dom = getdom(result);
let div = find(dom.document, "problem_content".to_string());
let mut problem_text = String::new();
match div {
Some(d) => to_string(d, &mut problem_text),
None => {
println!("No problem found!");
return;
}
}
let max_line_length = 100;
let mut first_line = true;
let errmsg = format!("Couldn't open `{}`", file.display());
let mut out = File::create(file).ok().expect(&errmsg);
writeln!(out, "#[macro_use] extern crate libeuler;").unwrap();
writeln!(out, "").unwrap();
for line in problem_text.split("\n") {
if line.trim().len() == 0 { continue }
if !first_line { writeln!(out, "///").unwrap(); }
write!(out, "///").unwrap();
let mut len = 3;
for word in line.split_whitespace() {
if word.len() + len + 1 > max_line_length {
writeln!(out, "").unwrap();
write!(out, "///").unwrap();
len = 3;
}
write!(out, " {}", word).unwrap();
len += word.len() + 1;
}
writeln!(out, "").unwrap();
first_line = false;
}
writeln!(out, "fn main() {{").unwrap();
writeln!(out, " solutions! {{").unwrap();
writeln!(out, " sol naive {{").unwrap();
writeln!(out, " }}").unwrap();
writeln!(out, " }}").unwrap();
writeln!(out, "}}").unwrap();
} | match find(child.clone(), class.clone()) {
Some(node) => return Some(node),
None => {}
} |
__init__.py | # -*- coding: utf-8 -*-
import time
import threading
LOADERS = {
'default': {
'interval': 0.1,
'frames': ('/', '-', '|', '\\', '-')
},
'dots': {
'interval': 0.2,
'frames': ('⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏')
},
'dots-bar': {
'interval': 0.2,
'frames': ('. ', ' . ', ' . ',' . ', ' .',
' . ', ' . ', ' . ')
},
'bar': {
'interval': 0.2,
'frames': ('- ', ' = ', ' - ',' = ', ' -',
' = ', ' - ', ' = ')
},
'arrow': {
'interval': 0.2,
'frames': ('> ', ' > ', ' > ',' > ', ' >',
' < ', ' < ', ' < ')
}
}
class Lowder:
__run = True
__loader_screen = LOADERS['default']
__result = None
__loading_message = ""
def __init__(self):
super().__init__()
def stop(self, message = None):
self.__run = False
cols = len(self.__loading_message)
if not message is None:
print(f"\x1b[${cols}D\x1b[K{message}")
else:
print(f"\x1b[${cols}D\x1b[K", end="\r")
def __loader(self, message):
while self.__run:
for char in self.__loader_screen['frames']:
cols = len(message)
self.__loading_message = f"\x1b[${cols}D\x1b[K{char} {message}"
if self.__run:
print(self.__loading_message, end="\r")
time.sleep(self.__loader_screen['interval'])
def __call(self, callback):
self.__result = callback()
def start(self, message, callback, loader = LOADERS['default']):
self.__loader_screen = loader
self.__run = True
y = threading.Thread(target=self.__call, args=(callback,)) | y.start()
x = threading.Thread(target=self.__loader, args=(message,))
x.start()
x.join()
y.join()
return self.__result | |
services.py | import inspect
import logging
import asyncio
from urllib import error
from functools import partial
from .const import DOMAIN, JLR_DATA
from .util import convert_temp_value
_LOGGER = logging.getLogger(__name__)
class JLRService:
def __init__(self, hass, config_entry, vin):
self.hass = hass
self.data = hass.data[DOMAIN][config_entry.entry_id][JLR_DATA]
self.vin = vin
self.vehicle = self.data.vehicles[vin]
self.service_code = None
self.service_name = None
self.attributes = self.vehicle.attributes
self.nickname = self.attributes.get("nickname")
async def validate_service_call(self):
if self.service_code and self.service_name:
# Check this is a valid service
if self.check_service_enabled(self.service_code):
# Check no other service calls are awaiting
if not await self.async_get_services():
# OK to make service call
return True
else:
_LOGGER.debug(
"Error calling service {} on vehicle {}. ".format(
self.service_name, self.nickname,
)
+ "Another request is still processing. "
+ "Please try again later."
)
else:
_LOGGER.debug(
"Service {} is not available on vehicle {}".format(
self.service_name, self.nickname,
)
)
else:
_LOGGER.debug(
"Error calling service {}. Invalid parameters".format(
self.service_name
)
)
return False
async def async_call_service(self, **kwargs):
self.service_code = kwargs.get("service_code")
self.service_name = kwargs.get("service_name")
if await self.validate_service_call():
service_kwargs = {}
# populate required parameters for service call
service = getattr(self.vehicle, self.service_name)
for param in inspect.signature(service).parameters:
if param in ["target_value", "target_temp"]:
# convert temp values to car requirements
service_kwargs[param] = convert_temp_value(
self.hass.config.units.temperature_unit,
self.service_code,
kwargs.get(param),
)
else:
service_kwargs[param] = kwargs.get(param)
# Call service
try:
status = await self.hass.async_add_executor_job(
partial(service, **service_kwargs)
)
_LOGGER.info(
"Service {} called on vehicle {}. ".format(
self.service_name, self.nickname,
)
+ "Awaiting feedback on success."
)
# monitor service for success / failure
monitor_status = await self.async_monitor_service_call(
status.get("customerServiceId")
)
return monitor_status
except error.HTTPError as ex:
if ex.code == 401:
_LOGGER.warning(
"Service: {} on vehicle {} ".format(
self.service_name, self.nickname,
)
+ "- not authorised error. Is your pin correct?"
)
else:
_LOGGER.debug(
"Error calling service {} on vehicle {}. ".format(
self.service_name, self.nickname
)
+ "Error is {}".format(ex.msg)
)
except Exception as ex:
_LOGGER.debug(
"Error calling service {} on vehicle {}. ".format(
self.service_name, self.nickname
)
+ "Error is {}".format(ex)
)
else:
_LOGGER.debug(
"Error calling service {}. Invalid parameters".format(
self.service_name
)
)
def check_service_enabled(self, service_code):
"""Check service code is capable and enabled"""
if service_code == "NA":
return True
else:
for service in self.attributes.get("availableServices"):
if service.get("serviceType") == service_code:
if service.get("vehicleCapable") and service.get(
"serviceEnabled"
):
return True
return False
async def async_get_services(self):
"""Check for any exisitng queued service calls to vehicle"""
services = await self.hass.async_add_executor_job(
self.vehicle.get_services
)
if services:
services = services.get("services")
# Check if duplicate
for service in services:
service_id = service.replace(
"/vehicles/{}/services/".format(self.vin), ""
)
# Check service to see if matched to this service call
# TODO: need to test for equivalents like RDL and RDU
try:
status = await self.hass.async_add_executor_job(
partial(self.vehicle.get_service_status, service_id)
)
if status:
if status.get("serviceType") == self.service_code:
return True
except Exception:
pass
return False
else:
return False
async def async_check_service_status(self, service_id):
"""Get status of current service call"""
return await self.hass.async_add_executor_job(
self.vehicle.get_service_status, service_id
)
async def | (self, service_id):
result = await self.async_check_service_status(service_id)
if result:
status = result.get("status")
while status == "Started":
_LOGGER.info(
"Checking for {} service call result status.".format(
self.service_name
)
)
await asyncio.sleep(5)
result = await self.async_check_service_status(service_id)
status = result.get("status")
if status and status in ["Successful", "MessageDelivered"]:
_LOGGER.info(
"Service call ({}) to vehicle {} was successful".format(
self.service_name, self.nickname
)
)
return "Successful"
else:
_LOGGER.info(
"InControl service call ({}) to vehicle {} ".format(
self.service_name, self.nickname,
)
+ "failed due to {}. \r\nFull return is {}".format(
result.get("failureReason"), result,
)
)
return status
else:
return None
| async_monitor_service_call |
test_stackdriver_parser.py | # Copyright 2019 The Forseti Real Time Enforcer Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import os
import pytest
from app.parsers.stackdriver import StackdriverParser
from google.oauth2.credentials import Credentials
from rpe.resources.gcp import GoogleAPIResource
test_google_args = {
'credentials': Credentials(token='bogus'),
}
def get_test_data(filename):
'''Load json data from the tests dir'''
p = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'data',
filename,
)
with open(p) as f:
return json.load(f)
# parameters for testing logs that should return a single asset
test_single_asset_log_params = [
# filename, expected_resource_type, expected_operation_type, expected_resource_name
("app-engine-debug.json", "appengine.googleapis.com/Instance", "write", "aef-default-test-instance"),
("bq-ds-set-iam-policy.json", "bigquery.googleapis.com/Dataset", "write", "wooo"),
("bigtable-set-iam-policy.json", "bigtableadmin.googleapis.com/Instance", "write", "example-instance"),
("pubsub-subscription-set-iam-policy.json", "pubsub.googleapis.com/Subscription", "write", "test-subscription"),
("pubsub-topic-set-iam-policy.json", "pubsub.googleapis.com/Topic", "write", "test-topic"),
# CloudSQL logs are inconsistent. See https://issuetracker.google.com/issues/137629452
("cloudsql-resource.labels.json", "sqladmin.googleapis.com/Instance", "write", "test-instance"),
("cloudsql-protoPayload.request.body.json", "sqladmin.googleapis.com/Instance", "write", "test-instance"),
("cloudsql-protoPayload.request.resource.instanceName.instanceId.json", "sqladmin.googleapis.com/Instance", "write", "test-instance"),
("cloudfunctions-set-iam-policy.json", "cloudfunctions.googleapis.com/CloudFunction", "write", "example_function"),
("compute-subnetworks-enable-flow-logs.json", "compute.googleapis.com/Subnetwork", "write", "example"),
("compute-subnetworks-set-private-ip-google-access.json", "compute.googleapis.com/Subnetwork", "write", "example"),
("compute-firewalls-enable-logs-policy.json", "compute.googleapis.com/Firewall", "write", "test-firewall"),
("dataproc_createcluster.json", "dataproc.googleapis.com/Cluster", "write", "test-dataproc-cluster"),
("datafusion-create-instance.json", "datafusion.googleapis.com/Instance", "create", "test-instance"),
("datafusion-update-instance.json", "datafusion.googleapis.com/Instance", "write", "test-instance"),
("gke-cluster-update.json", "container.googleapis.com/Cluster", "write", "example-cluster"),
("gke-nodepool-set.json", "container.googleapis.com/NodePool", "write", "example-pool"),
("servicemanagement-enable-service.json", "serviceusage.googleapis.com/Service", "write", "youtubeadsreach.googleapis.com"),
("servicemanagement-disable-service.json", "serviceusage.googleapis.com/Service", "write", "youtubereporting.googleapis.com"),
("servicemanagement-activate-service.json", "serviceusage.googleapis.com/Service", "write", "calendar-json.googleapis.com"),
("servicemanagement-deactivate-service.json", "serviceusage.googleapis.com/Service", "write", "zync.googleapis.com"),
("serviceusage-enable.json", "serviceusage.googleapis.com/Service", "write", "youtubereporting.googleapis.com"),
("serviceusage-disable.json", "serviceusage.googleapis.com/Service", "write", "zync.googleapis.com"),
("dataflow-job-step.json", "dataflow.googleapis.com/Job", "write", "job-id"),
("memorystore-redis.json", "redis.googleapis.com/Instance", "write", "test-instance"),
]
test_log_resource_count_params = [
("serviceusage-batchenable.json", 3),
("compute-hardened-images.json", 3),
]
@pytest.mark.parametrize(
"filename,expected_resource_type,expected_operation_type,expected_resource_name",
test_single_asset_log_params
)
def test_single_asset_log_messages(filename, expected_resource_type, expected_operation_type, expected_resource_name):
log_message = get_test_data(filename)
assets = StackdriverParser._extract_asset_info(log_message)
assert len(assets) == 1
asset_info = assets[0]
assert asset_info['resource_type'] == expected_resource_type
#assert asset_info['operation_type'] == expected_operation_type
assert asset_info['name'] == expected_resource_name
@pytest.mark.parametrize(
"filename,expected_resource_type,expected_operation_type,expected_resource_name",
test_single_asset_log_params
)
def test_rpe_from_stackdriver_data(filename, expected_resource_type, expected_operation_type, expected_resource_name):
log_message = get_test_data(filename)
assets = StackdriverParser._extract_asset_info(log_message)
asset_info = assets[0]
GoogleAPIResource.from_resource_data(client_kwargs=test_google_args, **asset_info)
@pytest.mark.parametrize(
"filename,expected_resource_count",
test_log_resource_count_params
)
def test_log_resource_count(filename, expected_resource_count):
| log_message = get_test_data(filename)
assets = StackdriverParser._extract_asset_info(log_message)
assert len(assets) == expected_resource_count
asset_info = assets[0] |
|
cursor.rs | struct Application;
impl Application {
fn new() -> Result<Self, wita::ApiError> |
}
impl wita::EventHandler for Application {
fn key_input(
&mut self,
window: &wita::Window,
key_code: wita::KeyCode,
state: wita::KeyState,
_prev_pressed: bool,
) {
if state == wita::KeyState::Pressed {
let cursor = match key_code.vkey {
wita::VirtualKey::Char('D') => wita::Cursor::Arrow,
wita::VirtualKey::Char('H') => wita::Cursor::Hand,
wita::VirtualKey::Char('I') => wita::Cursor::IBeam,
wita::VirtualKey::Char('W') => wita::Cursor::Wait,
_ => return,
};
window.set_cursor(cursor);
}
}
}
fn main() {
wita::run(wita::RunType::Wait, Application::new).unwrap();
}
| {
wita::WindowBuilder::new().title("hello, world!").build()?;
Ok(Self)
} |
custom_image_operations.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.pipeline import ClientRawResponse
from msrestazure.azure_exceptions import CloudError
from msrestazure.azure_operation import AzureOperationPoller
import uuid
from .. import models
class CustomImageOperations(object):
"""CustomImageOperations operations.
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An objec model deserializer.
"""
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self.config = config
def list(
self, resource_group_name, lab_name, filter=None, top=None, order_by=None, custom_headers=None, raw=False, **operation_config):
"""List custom images in a given lab.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param lab_name: The name of the lab.
:type lab_name: str
:param filter: The filter to apply on the operation.
:type filter: str
:param top: The maximum number of resources to return from the
operation.
:type top: int
:param order_by: The ordering expression for the results, using OData
notation.
:type order_by: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: :class:`CustomImagePaged
<azure.mgmt.devtestlabs.models.CustomImagePaged>`
"""
def internal_paging(next_link=None, raw=False):
if not next_link:
# Construct URL
url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/customimages'
path_format_arguments = {
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'labName': self._serialize.url("lab_name", lab_name, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if filter is not None:
query_parameters['$filter'] = self._serialize.query("filter", filter, 'str')
if top is not None:
query_parameters['$top'] = self._serialize.query("top", top, 'int')
if order_by is not None:
query_parameters['$orderBy'] = self._serialize.query("order_by", order_by, 'str')
query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str')
else:
url = next_link
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(
request, header_parameters, **operation_config)
if response.status_code not in [200]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
return response
# Deserialize response
deserialized = models.CustomImagePaged(internal_paging, self._deserialize.dependencies)
if raw:
header_dict = {}
client_raw_response = models.CustomImagePaged(internal_paging, self._deserialize.dependencies, header_dict)
return client_raw_response
return deserialized
def get_resource(
self, resource_group_name, lab_name, name, custom_headers=None, raw=False, **operation_config):
"""Get custom image.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param lab_name: The name of the lab.
:type lab_name: str
:param name: The name of the custom image.
:type name: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: :class:`CustomImage
<azure.mgmt.devtestlabs.models.CustomImage>`
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/customimages/{name}'
path_format_arguments = {
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'labName': self._serialize.url("lab_name", lab_name, 'str'),
'name': self._serialize.url("name", name, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str')
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('CustomImage', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
def create_or_update_resource(
self, resource_group_name, lab_name, name, custom_image, custom_headers=None, raw=False, **operation_config):
"""Create or replace an existing custom image. This operation can take a
while to complete.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param lab_name: The name of the lab.
:type lab_name: str
:param name: The name of the custom image.
:type name: str
:param custom_image:
:type custom_image: :class:`CustomImage
<azure.mgmt.devtestlabs.models.CustomImage>`
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:rtype:
:class:`AzureOperationPoller<msrestazure.azure_operation.AzureOperationPoller>`
instance that returns :class:`CustomImage
<azure.mgmt.devtestlabs.models.CustomImage>`
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/customimages/{name}'
path_format_arguments = {
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'labName': self._serialize.url("lab_name", lab_name, 'str'),
'name': self._serialize.url("name", name, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str')
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct body
body_content = self._serialize.body(custom_image, 'CustomImage')
# Construct and send request
def long_running_send():
request = self._client.put(url, query_parameters)
return self._client.send(
request, header_parameters, body_content, **operation_config)
def get_long_running_status(status_link, headers=None):
request = self._client.get(status_link)
if headers:
request.headers.update(headers)
return self._client.send(
request, header_parameters, **operation_config) | if response.status_code not in [200, 201]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('CustomImage', response)
if response.status_code == 201:
deserialized = self._deserialize('CustomImage', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
if raw:
response = long_running_send()
return get_long_running_output(response)
long_running_operation_timeout = operation_config.get(
'long_running_operation_timeout',
self.config.long_running_operation_timeout)
return AzureOperationPoller(
long_running_send, get_long_running_output,
get_long_running_status, long_running_operation_timeout)
def delete_resource(
self, resource_group_name, lab_name, name, custom_headers=None, raw=False, **operation_config):
"""Delete custom image. This operation can take a while to complete.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param lab_name: The name of the lab.
:type lab_name: str
:param name: The name of the custom image.
:type name: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:rtype:
:class:`AzureOperationPoller<msrestazure.azure_operation.AzureOperationPoller>`
instance that returns None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
"""
# Construct URL
url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevTestLab/labs/{labName}/customimages/{name}'
path_format_arguments = {
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'labName': self._serialize.url("lab_name", lab_name, 'str'),
'name': self._serialize.url("name", name, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.config.api_version", self.config.api_version, 'str')
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct and send request
def long_running_send():
request = self._client.delete(url, query_parameters)
return self._client.send(request, header_parameters, **operation_config)
def get_long_running_status(status_link, headers=None):
request = self._client.get(status_link)
if headers:
request.headers.update(headers)
return self._client.send(
request, header_parameters, **operation_config)
def get_long_running_output(response):
if response.status_code not in [202, 204]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
if raw:
response = long_running_send()
return get_long_running_output(response)
long_running_operation_timeout = operation_config.get(
'long_running_operation_timeout',
self.config.long_running_operation_timeout)
return AzureOperationPoller(
long_running_send, get_long_running_output,
get_long_running_status, long_running_operation_timeout) |
def get_long_running_output(response):
|
gobyexample_interfaces_test.go | package main
import (
"fmt" | //https://gobyexample.com/interfaces
type geometry interface {
area() float64
perim() float64
}
type rect struct {
width float64
height float64
}
type circle struct {
radius float64
}
func (r rect) area() float64 {
return r.width * r.height
}
func (r rect) perim() float64 {
return 2*r.width + 2*r.height
}
func (c circle) area() float64 {
return math.Pi * c.radius * c.radius
}
func (c circle) perim() float64 {
return 2 * math.Pi * c.radius
}
func measure(g geometry) {
fmt.Println(g)
fmt.Println(g.area())
fmt.Println(g.perim())
}
// cmd = go test -run Test_measure -v
func Test_measure(t *testing.T) {
r := rect{width: 3, height: 4}
measure(r)
c := circle{radius: 3}
measure(c)
} | "math"
"testing"
)
|
models.py | from flask_login import UserMixin
from . import db | class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
last_name = db.Column(db.String(100))
first_name = db.Column(db.String(100))
email = db.Column(db.String(100), unique=True)
password = db.Column(db.String(100)) |
#run the creat_all() command to create the database
|
admin.py | # -*- coding: utf-8 -*
# Copyright (c) 2019 BuildGroup Data Services, Inc.
# All rights reserved.
# This software is proprietary and confidential and may not under
# any circumstances be used, copied, or distributed.
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from caravaggio_rest_api.users.models import CaravaggioOrganization, CaravaggioClient, CaravaggioUser
from caravaggio_rest_api.users.forms import CaravaggioUserCreationForm, CaravaggioUserChangeForm
from django.utils.translation import gettext_lazy as _
class CaravaggioClientAdmin(admin.ModelAdmin):
model = CaravaggioClient
fieldsets = (
(None, {"fields": ("id", "email")}),
(_("Client info"), {"fields": ("name",)}),
(_("Permissions"), {"fields": ("is_active",),}),
(_("Important dates"), {"fields": ("date_joined", "date_deactivated")}),
)
add_fieldsets = ((None, {"classes": ("wide",), "fields": ("id", "email"),}),)
list_display = ("id", "email", "name", "is_active")
search_fields = ("id", "email", "name", "is_active")
ordering = ("id", "email", "name")
class CaravaggioOrganizationAdmin(admin.ModelAdmin):
model = CaravaggioOrganization
fieldsets = (
(None, {"fields": ("id", "email")}),
(_("Organization info"), {"fields": ("name",)}),
(_("Users"), {"fields": ("owner", "administrators", "members", "restricted_members"),}),
(_("Permissions"), {"fields": ("is_active",),}),
(_("Important dates"), {"fields": ("created", "updated")}),
)
add_fieldsets = ((None, {"classes": ("wide",), "fields": ("id", "email"),}),)
list_display = ("id", "email", "name", "owner", "is_active")
search_fields = ("id", "email", "name", "owner", "is_active", "created", "updated")
ordering = ("id", "email", "name", "created", "updated")
class CaravaggioUserAdmin(UserAdmin):
|
admin.site.register(CaravaggioUser, CaravaggioUserAdmin)
admin.site.register(CaravaggioClient, CaravaggioClientAdmin)
admin.site.register(CaravaggioOrganization, CaravaggioOrganizationAdmin)
| add_form = CaravaggioUserCreationForm
form = CaravaggioUserChangeForm
model = CaravaggioUser
# (_('Organizations'), {
# 'fields': ('owner_of', 'administrator_of', 'member_of',
# 'restricted_member_of'),
# }),
fieldsets = (
(None, {"fields": ("client", "email", "password")}),
(_("Personal info"), {"fields": ("first_name", "last_name")}),
(_("Permissions"), {"fields": ("is_active", "is_staff", "is_superuser", "groups", "user_permissions"),}),
(_("Important dates"), {"fields": ("last_login", "date_joined")}),
)
add_fieldsets = ((None, {"classes": ("wide",), "fields": ("client", "email", "password1", "password2"),}),)
list_display = ("client", "email", "first_name", "last_name", "is_staff")
search_fields = ("client__id", "email", "first_name", "last_name")
ordering = (
"client__id",
"email",
) |
_document.tsx | /**
* Copyright 2020 Vercel Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Document, { Html, Head, Main, NextScript } from 'next/document';
export default class | extends Document {
render() {
return (
<Html lang="en">
<Head />
<body dir="rtl">
<Main />
<NextScript />
</body>
</Html>
);
}
}
| CustomDocument |
lib.rs | //! A crate for building LLVM IR using the Inkwell LLVM wrapper.
//! A separate crate is necessary to allow for code reuse.
pub mod builtins;
pub mod codegen;
pub mod error;
pub mod int;
pub mod traits;
#[cfg(test)]
mod tests;
pub use crate::{
codegen::{create_code_gen, CodeGen},
traits::{IRRepresentableExpression, IRRepresentableNode} | }; |
|
cloudtrail.go | /*
Copyright (C) 2021 The Falco Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
///////////////////////////////////////////////////////////////////////////////
// This plugin reads reading cloudtrail files from a local directory or from a
// remote S3 bucket. Cloudtrail events are dispatched to the engine one by one,
// in their original json form, so the full data is retained.
// The plugin also exports a bunch of filter fields useful for cloudtrail
// analysis (see plugin_get_fields() for the list).
///////////////////////////////////////////////////////////////////////////////
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"math"
"sync"
"github.com/alecthomas/jsonschema"
"github.com/aws/aws-sdk-go-v2/service/sqs"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
"github.com/falcosecurity/plugin-sdk-go/pkg/sdk"
"github.com/falcosecurity/plugin-sdk-go/pkg/sdk/plugins"
"github.com/falcosecurity/plugin-sdk-go/pkg/sdk/plugins/extractor"
"github.com/falcosecurity/plugin-sdk-go/pkg/sdk/plugins/source"
"github.com/falcosecurity/plugin-sdk-go/pkg/sdk/symbols/extract"
_ "github.com/falcosecurity/plugin-sdk-go/pkg/sdk/symbols/progress"
"github.com/valyala/fastjson"
)
// Plugin info
const (
PluginRequiredApiVersion = "0.3.0"
PluginID uint32 = 2
PluginName = "cloudtrail"
PluginDescription = "reads cloudtrail JSON data saved to file in the directory specified in the settings"
PluginContact = "github.com/falcosecurity/plugins/"
PluginVersion = "0.2.0"
PluginEventSource = "aws_cloudtrail"
)
func min(a, b int) int |
type fileInfo struct {
name string
isCompressed bool
}
// This is the state that we use when reading events from an S3 bucket
type s3State struct {
bucket string
awsSvc *s3.S3
awsSess *session.Session
downloader *s3manager.Downloader
DownloadWg sync.WaitGroup
DownloadBufs [][]byte
lastDownloadedFileNum int
nFilledBufs int
curBuf int
}
type snsMessage struct {
Bucket string `json:"s3Bucket"`
Keys []string `json:"s3ObjectKey"`
}
// Struct for plugin init config
type pluginInitConfig struct {
S3DownloadConcurrency int `json:"s3DownloadConcurrency" jsonschema:"description=Controls the number of background goroutines used to download S3 files (Default: 1)"`
SQSDelete bool `json:"sqsDelete" jsonschema:"description=If true then the plugin will delete sqs messages from the queue immediately after receiving them (Default: true)"`
UseAsync bool `json:"useAsync" jsonschema:"description=If true then async extraction optimization is enabled (Default: true)"`
}
// This is the global plugin state, identifying an instance of this plugin
type pluginContext struct {
plugins.BasePlugin
jparser fastjson.Parser
jdata *fastjson.Value
jdataEvtnum uint64 // The event number jdata refers to. Used to know when we can skip the unmarshaling.
config pluginInitConfig
}
type OpenMode int
const (
fileMode OpenMode = iota
s3Mode
sqsMode
)
// This is the open state, identifying an open instance reading cloudtrail files from
// a local directory or from a remote S3 bucket (either direct or via a SQS queue)
type openContext struct {
source.BaseInstance
openMode OpenMode
cloudTrailFilesDir string
files []fileInfo
curFileNum uint32
evtJSONStrings [][]byte
evtJSONListPos int
s3 s3State
sqsClient *sqs.Client
queueURL string
nextJParser fastjson.Parser
}
// Register the plugin
func init() {
p := &pluginContext{}
source.Register(p)
extractor.Register(p)
}
func (p *pluginInitConfig) setDefault() {
p.SQSDelete = true
p.S3DownloadConcurrency = 1
p.UseAsync = true
}
func (p *pluginContext) Info() *plugins.Info {
return &plugins.Info{
ID: PluginID,
Name: PluginName,
Description: PluginDescription,
Contact: PluginContact,
Version: PluginVersion,
RequiredAPIVersion: PluginRequiredApiVersion,
EventSource: PluginEventSource,
ExtractEventSources: []string{"ct", "s3", "ec2"},
}
}
func (p *pluginContext) InitSchema() *sdk.SchemaInfo {
reflector := jsonschema.Reflector{
RequiredFromJSONSchemaTags: true, // all properties are optional by default
AllowAdditionalProperties: true, // unrecognized properties don't cause a parsing failures
}
if schema, err := reflector.Reflect(&pluginInitConfig{}).MarshalJSON(); err == nil {
return &sdk.SchemaInfo{
Schema: string(schema),
}
}
return nil
}
func (p *pluginContext) Init(cfg string) error {
// initialize state
p.jdataEvtnum = math.MaxUint64
// Set config default values and read the passed one, if available.
// Since we provide a schema through InitSchema(), the framework
// guarantees that the config is always well-formed json.
p.config.setDefault()
json.Unmarshal([]byte(cfg), &p.config)
// enable/disable async extraction optimazion (enabled by default)
extract.SetAsync(p.config.UseAsync)
return nil
}
func (p *pluginContext) Open(params string) (source.Instance, error) {
// Allocate the context struct for this open instance
oCtx := &openContext{}
// Perform the open
var err error
if len(params) >= 5 && params[:5] == "s3://" {
err = openS3(p, oCtx, params)
} else if len(params) >= 6 && params[:6] == "sqs://" {
err = openSQS(p, oCtx, params)
} else {
err = openLocal(p, oCtx, params)
}
if err != nil {
return nil, err
}
// Create an array of download buffers that will be used to concurrently
// download files from s3
oCtx.s3.DownloadBufs = make([][]byte, p.config.S3DownloadConcurrency)
return oCtx, nil
}
func (o *openContext) NextBatch(pState sdk.PluginState, evts sdk.EventWriters) (int, error) {
var n int
var err error
pCtx := pState.(*pluginContext)
for n = 0; err == nil && n < evts.Len(); n++ {
err = nextEvent(pCtx, o, evts.Get(n))
}
return n, err
}
func (o *openContext) Progress(pState sdk.PluginState) (float64, string) {
pd := float64(o.curFileNum) / float64(len(o.files))
return pd, fmt.Sprintf("%.2f%% - %v/%v files", pd*100, o.curFileNum, len(o.files))
}
func (p *pluginContext) String(in io.ReadSeeker) (string, error) {
var src string
var user string
var err error
data, err := ioutil.ReadAll(in)
if err != nil {
return "", err
}
p.jdata, err = p.jparser.ParseBytes(data)
if err != nil {
return "", fmt.Errorf("<invalid JSON: %s>" + err.Error())
}
val := p.jdata.GetStringBytes("eventSource")
if val == nil {
return "", fmt.Errorf("<invalid JSON: event did not contain a source>")
}
src = string(val)
val = p.jdata.GetStringBytes("awsRegion")
if val == nil {
return "", fmt.Errorf("<invalid JSON: event did not contain an awsRegion>")
}
region := string(val)
val = p.jdata.GetStringBytes("eventName")
if val == nil {
return "", fmt.Errorf("<invalid JSON: event did not contain an eventName>")
}
ename := string(val)
if len(src) > len(".amazonaws.com") {
srctrailer := src[len(src)-len(".amazonaws.com"):]
if srctrailer == ".amazonaws.com" {
src = src[0 : len(src)-len(".amazonaws.com")]
}
}
present, user := getUser(p.jdata)
if present && user != "" {
user = " " + user
}
info := getEvtInfo(p.jdata)
return fmt.Sprintf("%s%s %s %s %s",
region,
user,
src,
ename,
info,
), nil
}
func (p *pluginContext) Fields() []sdk.FieldEntry {
return supportedFields
}
func (p *pluginContext) Extract(req sdk.ExtractRequest, evt sdk.EventReader) error {
// Decode the json, but only if we haven't done it yet for this event
if evt.EventNum() != p.jdataEvtnum {
// Read the event data
data, err := ioutil.ReadAll(evt.Reader())
if err != nil {
return err
}
// Maybe temp--remove trailing null bytes from string
data = bytes.Trim(data, "\x00")
// For this plugin, events are always strings
evtStr := string(data)
p.jdata, err = p.jparser.Parse(evtStr)
if err != nil {
// Not a json file, so not present.
return err
}
p.jdataEvtnum = evt.EventNum()
}
// Extract the field value
var present bool
var value interface{}
if req.FieldType() == sdk.ParamTypeUint64 {
present, value = getfieldU64(p.jdata, req.Field())
} else {
present, value = getfieldStr(p.jdata, req.Field())
}
if present {
req.SetValue(value)
}
return nil
}
func main() {}
| {
if a < b {
return a
}
return b
} |
07_10goroutines.go | package main
import "fmt"
func main() | {
c := make(chan int)
const (
numGoroutines = 10
numNumbers = 10
)
for i := 0; i < numGoroutines; i++ {
go func(sv int) {
for j := 0; j < numNumbers; j++ {
c <- sv + j
}
}(i * numNumbers)
}
for i := 0; i < numGoroutines*numNumbers; i++ {
fmt.Println(<-c)
}
fmt.Println("about to exit")
} |
|
test_posix.py | "Test posix functions"
z test zaimportuj support
# Skip these tests jeżeli there jest no posix module.
posix = support.import_module('posix')
zaimportuj errno
zaimportuj sys
zaimportuj time
zaimportuj os
zaimportuj platform
zaimportuj pwd
zaimportuj shutil
zaimportuj stat
zaimportuj tempfile
zaimportuj unittest
zaimportuj warnings
_DUMMY_SYMLINK = os.path.join(tempfile.gettempdir(),
support.TESTFN + '-dummy-symlink')
klasa PosixTester(unittest.TestCase):
def setUp(self):
# create empty file
fp = open(support.TESTFN, 'w+')
fp.close()
self.teardown_files = [ support.TESTFN ]
self._warnings_manager = support.check_warnings()
self._warnings_manager.__enter__()
warnings.filterwarnings('ignore', '.* potential security risk .*',
RuntimeWarning)
def tearDown(self):
dla teardown_file w self.teardown_files:
support.unlink(teardown_file)
self._warnings_manager.__exit__(Nic, Nic, Nic)
def testNoArgFunctions(self):
# test posix functions which take no arguments oraz have
# no side-effects which we need to cleanup (e.g., fork, wait, abort)
NO_ARG_FUNCTIONS = [ "ctermid", "getcwd", "getcwdb", "uname",
"times", "getloadavg",
"getegid", "geteuid", "getgid", "getgroups",
"getpid", "getpgrp", "getppid", "getuid", "sync",
]
dla name w NO_ARG_FUNCTIONS:
posix_func = getattr(posix, name, Nic)
jeżeli posix_func jest nie Nic:
posix_func()
self.assertRaises(TypeError, posix_func, 1)
@unittest.skipUnless(hasattr(posix, 'getresuid'),
'test needs posix.getresuid()')
def test_getresuid(self):
user_ids = posix.getresuid()
self.assertEqual(len(user_ids), 3)
dla val w user_ids:
self.assertGreaterEqual(val, 0)
@unittest.skipUnless(hasattr(posix, 'getresgid'),
'test needs posix.getresgid()')
def test_getresgid(self):
group_ids = posix.getresgid()
self.assertEqual(len(group_ids), 3)
dla val w group_ids:
self.assertGreaterEqual(val, 0)
@unittest.skipUnless(hasattr(posix, 'setresuid'),
'test needs posix.setresuid()')
def test_setresuid(self):
current_user_ids = posix.getresuid()
self.assertIsNic(posix.setresuid(*current_user_ids))
# -1 means don't change that value.
self.assertIsNic(posix.setresuid(-1, -1, -1))
@unittest.skipUnless(hasattr(posix, 'setresuid'),
'test needs posix.setresuid()')
def test_setresuid_exception(self):
# Don't do this test jeżeli someone jest silly enough to run us jako root.
current_user_ids = posix.getresuid()
jeżeli 0 nie w current_user_ids:
new_user_ids = (current_user_ids[0]+1, -1, -1)
self.assertRaises(OSError, posix.setresuid, *new_user_ids)
@unittest.skipUnless(hasattr(posix, 'setresgid'),
'test needs posix.setresgid()')
def test_setresgid(self):
current_group_ids = posix.getresgid()
self.assertIsNic(posix.setresgid(*current_group_ids))
# -1 means don't change that value.
self.assertIsNic(posix.setresgid(-1, -1, -1))
@unittest.skipUnless(hasattr(posix, 'setresgid'),
'test needs posix.setresgid()')
def test_setresgid_exception(self):
# Don't do this test jeżeli someone jest silly enough to run us jako root.
current_group_ids = posix.getresgid()
jeżeli 0 nie w current_group_ids:
new_group_ids = (current_group_ids[0]+1, -1, -1)
self.assertRaises(OSError, posix.setresgid, *new_group_ids)
@unittest.skipUnless(hasattr(posix, 'initgroups'),
"test needs os.initgroups()")
def test_initgroups(self):
# It takes a string oraz an integer; check that it podnieśs a TypeError
# dla other argument lists.
self.assertRaises(TypeError, posix.initgroups)
self.assertRaises(TypeError, posix.initgroups, Nic)
self.assertRaises(TypeError, posix.initgroups, 3, "foo")
self.assertRaises(TypeError, posix.initgroups, "foo", 3, object())
# If a non-privileged user invokes it, it should fail przy OSError
# EPERM.
jeżeli os.getuid() != 0:
spróbuj:
name = pwd.getpwuid(posix.getuid()).pw_name
wyjąwszy KeyError:
# the current UID may nie have a pwd entry
podnieś unittest.SkipTest("need a pwd entry")
spróbuj:
posix.initgroups(name, 13)
wyjąwszy OSError jako e:
self.assertEqual(e.errno, errno.EPERM)
inaczej:
self.fail("Expected OSError to be podnieśd by initgroups")
@unittest.skipUnless(hasattr(posix, 'statvfs'),
'test needs posix.statvfs()')
def test_statvfs(self):
self.assertPrawda(posix.statvfs(os.curdir))
@unittest.skipUnless(hasattr(posix, 'fstatvfs'),
'test needs posix.fstatvfs()')
def test_fstatvfs(self):
fp = open(support.TESTFN)
spróbuj:
self.assertPrawda(posix.fstatvfs(fp.fileno()))
self.assertPrawda(posix.statvfs(fp.fileno()))
w_końcu:
fp.close()
@unittest.skipUnless(hasattr(posix, 'ftruncate'),
'test needs posix.ftruncate()')
def test_ftruncate(self):
fp = open(support.TESTFN, 'w+')
spróbuj:
# we need to have some data to truncate
fp.write('test')
fp.flush()
posix.ftruncate(fp.fileno(), 0)
w_końcu:
fp.close()
@unittest.skipUnless(hasattr(posix, 'truncate'), "test needs posix.truncate()")
def test_truncate(self | zy open(support.TESTFN, 'w') jako fp:
fp.write('test')
fp.flush()
posix.truncate(support.TESTFN, 0)
@unittest.skipUnless(getattr(os, 'execve', Nic) w os.supports_fd, "test needs execve() to support the fd parameter")
@unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
@unittest.skipUnless(hasattr(os, 'waitpid'), "test needs os.waitpid()")
def test_fexecve(self):
fp = os.open(sys.executable, os.O_RDONLY)
spróbuj:
pid = os.fork()
jeżeli pid == 0:
os.chdir(os.path.split(sys.executable)[0])
posix.execve(fp, [sys.executable, '-c', 'pass'], os.environ)
inaczej:
self.assertEqual(os.waitpid(pid, 0), (pid, 0))
w_końcu:
os.close(fp)
@unittest.skipUnless(hasattr(posix, 'waitid'), "test needs posix.waitid()")
@unittest.skipUnless(hasattr(os, 'fork'), "test needs os.fork()")
def test_waitid(self):
pid = os.fork()
jeżeli pid == 0:
os.chdir(os.path.split(sys.executable)[0])
posix.execve(sys.executable, [sys.executable, '-c', 'pass'], os.environ)
inaczej:
res = posix.waitid(posix.P_PID, pid, posix.WEXITED)
self.assertEqual(pid, res.si_pid)
@unittest.skipUnless(hasattr(posix, 'lockf'), "test needs posix.lockf()")
def test_lockf(self):
fd = os.open(support.TESTFN, os.O_WRONLY | os.O_CREAT)
spróbuj:
os.write(fd, b'test')
os.lseek(fd, 0, os.SEEK_SET)
posix.lockf(fd, posix.F_LOCK, 4)
# section jest locked
posix.lockf(fd, posix.F_ULOCK, 4)
w_końcu:
os.close(fd)
@unittest.skipUnless(hasattr(posix, 'pread'), "test needs posix.pread()")
def test_pread(self):
fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT)
spróbuj:
os.write(fd, b'test')
os.lseek(fd, 0, os.SEEK_SET)
self.assertEqual(b'es', posix.pread(fd, 2, 1))
# the first pread() shouldn't disturb the file offset
self.assertEqual(b'te', posix.read(fd, 2))
w_końcu:
os.close(fd)
@unittest.skipUnless(hasattr(posix, 'pwrite'), "test needs posix.pwrite()")
def test_pwrite(self):
fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT)
spróbuj:
os.write(fd, b'test')
os.lseek(fd, 0, os.SEEK_SET)
posix.pwrite(fd, b'xx', 1)
self.assertEqual(b'txxt', posix.read(fd, 4))
w_końcu:
os.close(fd)
@unittest.skipUnless(hasattr(posix, 'posix_fallocate'),
"test needs posix.posix_fallocate()")
def test_posix_fallocate(self):
fd = os.open(support.TESTFN, os.O_WRONLY | os.O_CREAT)
spróbuj:
posix.posix_fallocate(fd, 0, 10)
wyjąwszy OSError jako inst:
# issue10812, ZFS doesn't appear to support posix_fallocate,
# so skip Solaris-based since they are likely to have ZFS.
jeżeli inst.errno != errno.EINVAL albo nie sys.platform.startswith("sunos"):
podnieś
w_końcu:
os.close(fd)
@unittest.skipUnless(hasattr(posix, 'posix_fadvise'),
"test needs posix.posix_fadvise()")
def test_posix_fadvise(self):
fd = os.open(support.TESTFN, os.O_RDONLY)
spróbuj:
posix.posix_fadvise(fd, 0, 0, posix.POSIX_FADV_WILLNEED)
w_końcu:
os.close(fd)
@unittest.skipUnless(os.utime w os.supports_fd, "test needs fd support w os.utime")
def test_utime_with_fd(self):
now = time.time()
fd = os.open(support.TESTFN, os.O_RDONLY)
spróbuj:
posix.utime(fd)
posix.utime(fd, Nic)
self.assertRaises(TypeError, posix.utime, fd, (Nic, Nic))
self.assertRaises(TypeError, posix.utime, fd, (now, Nic))
self.assertRaises(TypeError, posix.utime, fd, (Nic, now))
posix.utime(fd, (int(now), int(now)))
posix.utime(fd, (now, now))
self.assertRaises(ValueError, posix.utime, fd, (now, now), ns=(now, now))
self.assertRaises(ValueError, posix.utime, fd, (now, 0), ns=(Nic, Nic))
self.assertRaises(ValueError, posix.utime, fd, (Nic, Nic), ns=(now, 0))
posix.utime(fd, (int(now), int((now - int(now)) * 1e9)))
posix.utime(fd, ns=(int(now), int((now - int(now)) * 1e9)))
w_końcu:
os.close(fd)
@unittest.skipUnless(os.utime w os.supports_follow_symlinks, "test needs follow_symlinks support w os.utime")
def test_utime_nofollow_symlinks(self):
now = time.time()
posix.utime(support.TESTFN, Nic, follow_symlinks=Nieprawda)
self.assertRaises(TypeError, posix.utime, support.TESTFN, (Nic, Nic), follow_symlinks=Nieprawda)
self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, Nic), follow_symlinks=Nieprawda)
self.assertRaises(TypeError, posix.utime, support.TESTFN, (Nic, now), follow_symlinks=Nieprawda)
posix.utime(support.TESTFN, (int(now), int(now)), follow_symlinks=Nieprawda)
posix.utime(support.TESTFN, (now, now), follow_symlinks=Nieprawda)
posix.utime(support.TESTFN, follow_symlinks=Nieprawda)
@unittest.skipUnless(hasattr(posix, 'writev'), "test needs posix.writev()")
def test_writev(self):
fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT)
spróbuj:
n = os.writev(fd, (b'test1', b'tt2', b't3'))
self.assertEqual(n, 10)
os.lseek(fd, 0, os.SEEK_SET)
self.assertEqual(b'test1tt2t3', posix.read(fd, 10))
# Issue #20113: empty list of buffers should nie crash
spróbuj:
size = posix.writev(fd, [])
wyjąwszy OSError:
# writev(fd, []) podnieśs OSError(22, "Invalid argument")
# on OpenIndiana
dalej
inaczej:
self.assertEqual(size, 0)
w_końcu:
os.close(fd)
@unittest.skipUnless(hasattr(posix, 'readv'), "test needs posix.readv()")
def test_readv(self):
fd = os.open(support.TESTFN, os.O_RDWR | os.O_CREAT)
spróbuj:
os.write(fd, b'test1tt2t3')
os.lseek(fd, 0, os.SEEK_SET)
buf = [bytearray(i) dla i w [5, 3, 2]]
self.assertEqual(posix.readv(fd, buf), 10)
self.assertEqual([b'test1', b'tt2', b't3'], [bytes(i) dla i w buf])
# Issue #20113: empty list of buffers should nie crash
spróbuj:
size = posix.readv(fd, [])
wyjąwszy OSError:
# readv(fd, []) podnieśs OSError(22, "Invalid argument")
# on OpenIndiana
dalej
inaczej:
self.assertEqual(size, 0)
w_końcu:
os.close(fd)
@unittest.skipUnless(hasattr(posix, 'dup'),
'test needs posix.dup()')
def test_dup(self):
fp = open(support.TESTFN)
spróbuj:
fd = posix.dup(fp.fileno())
self.assertIsInstance(fd, int)
os.close(fd)
w_końcu:
fp.close()
@unittest.skipUnless(hasattr(posix, 'confstr'),
'test needs posix.confstr()')
def test_confstr(self):
self.assertRaises(ValueError, posix.confstr, "CS_garbage")
self.assertEqual(len(posix.confstr("CS_PATH")) > 0, Prawda)
@unittest.skipUnless(hasattr(posix, 'dup2'),
'test needs posix.dup2()')
def test_dup2(self):
fp1 = open(support.TESTFN)
fp2 = open(support.TESTFN)
spróbuj:
posix.dup2(fp1.fileno(), fp2.fileno())
w_końcu:
fp1.close()
fp2.close()
@unittest.skipUnless(hasattr(os, 'O_CLOEXEC'), "needs os.O_CLOEXEC")
@support.requires_linux_version(2, 6, 23)
def test_oscloexec(self):
fd = os.open(support.TESTFN, os.O_RDONLY|os.O_CLOEXEC)
self.addCleanup(os.close, fd)
self.assertNieprawda(os.get_inheritable(fd))
@unittest.skipUnless(hasattr(posix, 'O_EXLOCK'),
'test needs posix.O_EXLOCK')
def test_osexlock(self):
fd = os.open(support.TESTFN,
os.O_WRONLY|os.O_EXLOCK|os.O_CREAT)
self.assertRaises(OSError, os.open, support.TESTFN,
os.O_WRONLY|os.O_EXLOCK|os.O_NONBLOCK)
os.close(fd)
jeżeli hasattr(posix, "O_SHLOCK"):
fd = os.open(support.TESTFN,
os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
self.assertRaises(OSError, os.open, support.TESTFN,
os.O_WRONLY|os.O_EXLOCK|os.O_NONBLOCK)
os.close(fd)
@unittest.skipUnless(hasattr(posix, 'O_SHLOCK'),
'test needs posix.O_SHLOCK')
def test_osshlock(self):
fd1 = os.open(support.TESTFN,
os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
fd2 = os.open(support.TESTFN,
os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
os.close(fd2)
os.close(fd1)
jeżeli hasattr(posix, "O_EXLOCK"):
fd = os.open(support.TESTFN,
os.O_WRONLY|os.O_SHLOCK|os.O_CREAT)
self.assertRaises(OSError, os.open, support.TESTFN,
os.O_RDONLY|os.O_EXLOCK|os.O_NONBLOCK)
os.close(fd)
@unittest.skipUnless(hasattr(posix, 'fstat'),
'test needs posix.fstat()')
def test_fstat(self):
fp = open(support.TESTFN)
spróbuj:
self.assertPrawda(posix.fstat(fp.fileno()))
self.assertPrawda(posix.stat(fp.fileno()))
self.assertRaisesRegex(TypeError,
'should be string, bytes albo integer, not',
posix.stat, float(fp.fileno()))
w_końcu:
fp.close()
@unittest.skipUnless(hasattr(posix, 'stat'),
'test needs posix.stat()')
def test_stat(self):
self.assertPrawda(posix.stat(support.TESTFN))
self.assertPrawda(posix.stat(os.fsencode(support.TESTFN)))
self.assertPrawda(posix.stat(bytearray(os.fsencode(support.TESTFN))))
self.assertRaisesRegex(TypeError,
'can\'t specify Nic dla path argument',
posix.stat, Nic)
self.assertRaisesRegex(TypeError,
'should be string, bytes albo integer, not',
posix.stat, list(support.TESTFN))
self.assertRaisesRegex(TypeError,
'should be string, bytes albo integer, not',
posix.stat, list(os.fsencode(support.TESTFN)))
@unittest.skipUnless(hasattr(posix, 'mkfifo'), "don't have mkfifo()")
def test_mkfifo(self):
support.unlink(support.TESTFN)
posix.mkfifo(support.TESTFN, stat.S_IRUSR | stat.S_IWUSR)
self.assertPrawda(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
@unittest.skipUnless(hasattr(posix, 'mknod') oraz hasattr(stat, 'S_IFIFO'),
"don't have mknod()/S_IFIFO")
def test_mknod(self):
# Test using mknod() to create a FIFO (the only use specified
# by POSIX).
support.unlink(support.TESTFN)
mode = stat.S_IFIFO | stat.S_IRUSR | stat.S_IWUSR
spróbuj:
posix.mknod(support.TESTFN, mode, 0)
wyjąwszy OSError jako e:
# Some old systems don't allow unprivileged users to use
# mknod(), albo only support creating device nodes.
self.assertIn(e.errno, (errno.EPERM, errno.EINVAL))
inaczej:
self.assertPrawda(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
@unittest.skipUnless(hasattr(posix, 'stat'), 'test needs posix.stat()')
@unittest.skipUnless(hasattr(posix, 'makedev'), 'test needs posix.makedev()')
def test_makedev(self):
st = posix.stat(support.TESTFN)
dev = st.st_dev
self.assertIsInstance(dev, int)
self.assertGreaterEqual(dev, 0)
major = posix.major(dev)
self.assertIsInstance(major, int)
self.assertGreaterEqual(major, 0)
self.assertEqual(posix.major(dev), major)
self.assertRaises(TypeError, posix.major, float(dev))
self.assertRaises(TypeError, posix.major)
self.assertRaises((ValueError, OverflowError), posix.major, -1)
minor = posix.minor(dev)
self.assertIsInstance(minor, int)
self.assertGreaterEqual(minor, 0)
self.assertEqual(posix.minor(dev), minor)
self.assertRaises(TypeError, posix.minor, float(dev))
self.assertRaises(TypeError, posix.minor)
self.assertRaises((ValueError, OverflowError), posix.minor, -1)
self.assertEqual(posix.makedev(major, minor), dev)
self.assertRaises(TypeError, posix.makedev, float(major), minor)
self.assertRaises(TypeError, posix.makedev, major, float(minor))
self.assertRaises(TypeError, posix.makedev, major)
self.assertRaises(TypeError, posix.makedev)
def _test_all_chown_common(self, chown_func, first_param, stat_func):
"""Common code dla chown, fchown oraz lchown tests."""
def check_stat(uid, gid):
jeżeli stat_func jest nie Nic:
stat = stat_func(first_param)
self.assertEqual(stat.st_uid, uid)
self.assertEqual(stat.st_gid, gid)
uid = os.getuid()
gid = os.getgid()
# test a successful chown call
chown_func(first_param, uid, gid)
check_stat(uid, gid)
chown_func(first_param, -1, gid)
check_stat(uid, gid)
chown_func(first_param, uid, -1)
check_stat(uid, gid)
jeżeli uid == 0:
# Try an amusingly large uid/gid to make sure we handle
# large unsigned values. (chown lets you use any
# uid/gid you like, even jeżeli they aren't defined.)
#
# This problem keeps coming up:
# http://bugs.python.org/issue1747858
# http://bugs.python.org/issue4591
# http://bugs.python.org/issue15301
# Hopefully the fix w 4591 fixes it dla good!
#
# This part of the test only runs when run jako root.
# Only scary people run their tests jako root.
big_value = 2**31
chown_func(first_param, big_value, big_value)
check_stat(big_value, big_value)
chown_func(first_param, -1, -1)
check_stat(big_value, big_value)
chown_func(first_param, uid, gid)
check_stat(uid, gid)
albo_inaczej platform.system() w ('HP-UX', 'SunOS'):
# HP-UX oraz Solaris can allow a non-root user to chown() to root
# (issue #5113)
podnieś unittest.SkipTest("Skipping because of non-standard chown() "
"behavior")
inaczej:
# non-root cannot chown to root, podnieśs OSError
self.assertRaises(OSError, chown_func, first_param, 0, 0)
check_stat(uid, gid)
self.assertRaises(OSError, chown_func, first_param, 0, -1)
check_stat(uid, gid)
jeżeli 0 nie w os.getgroups():
self.assertRaises(OSError, chown_func, first_param, -1, 0)
check_stat(uid, gid)
# test illegal types
dla t w str, float:
self.assertRaises(TypeError, chown_func, first_param, t(uid), gid)
check_stat(uid, gid)
self.assertRaises(TypeError, chown_func, first_param, uid, t(gid))
check_stat(uid, gid)
@unittest.skipUnless(hasattr(posix, 'chown'), "test needs os.chown()")
def test_chown(self):
# podnieś an OSError jeżeli the file does nie exist
os.unlink(support.TESTFN)
self.assertRaises(OSError, posix.chown, support.TESTFN, -1, -1)
# re-create the file
support.create_empty_file(support.TESTFN)
self._test_all_chown_common(posix.chown, support.TESTFN,
getattr(posix, 'stat', Nic))
@unittest.skipUnless(hasattr(posix, 'fchown'), "test needs os.fchown()")
def test_fchown(self):
os.unlink(support.TESTFN)
# re-create the file
test_file = open(support.TESTFN, 'w')
spróbuj:
fd = test_file.fileno()
self._test_all_chown_common(posix.fchown, fd,
getattr(posix, 'fstat', Nic))
w_końcu:
test_file.close()
@unittest.skipUnless(hasattr(posix, 'lchown'), "test needs os.lchown()")
def test_lchown(self):
os.unlink(support.TESTFN)
# create a symlink
os.symlink(_DUMMY_SYMLINK, support.TESTFN)
self._test_all_chown_common(posix.lchown, support.TESTFN,
getattr(posix, 'lstat', Nic))
@unittest.skipUnless(hasattr(posix, 'chdir'), 'test needs posix.chdir()')
def test_chdir(self):
posix.chdir(os.curdir)
self.assertRaises(OSError, posix.chdir, support.TESTFN)
def test_listdir(self):
self.assertPrawda(support.TESTFN w posix.listdir(os.curdir))
def test_listdir_default(self):
# When listdir jest called without argument,
# it's the same jako listdir(os.curdir).
self.assertPrawda(support.TESTFN w posix.listdir())
def test_listdir_bytes(self):
# When listdir jest called przy a bytes object,
# the returned strings are of type bytes.
self.assertPrawda(os.fsencode(support.TESTFN) w posix.listdir(b'.'))
@unittest.skipUnless(posix.listdir w os.supports_fd,
"test needs fd support dla posix.listdir()")
def test_listdir_fd(self):
f = posix.open(posix.getcwd(), posix.O_RDONLY)
self.addCleanup(posix.close, f)
self.assertEqual(
sorted(posix.listdir('.')),
sorted(posix.listdir(f))
)
# Check that the fd offset was reset (issue #13739)
self.assertEqual(
sorted(posix.listdir('.')),
sorted(posix.listdir(f))
)
@unittest.skipUnless(hasattr(posix, 'access'), 'test needs posix.access()')
def test_access(self):
self.assertPrawda(posix.access(support.TESTFN, os.R_OK))
@unittest.skipUnless(hasattr(posix, 'umask'), 'test needs posix.umask()')
def test_umask(self):
old_mask = posix.umask(0)
self.assertIsInstance(old_mask, int)
posix.umask(old_mask)
@unittest.skipUnless(hasattr(posix, 'strerror'),
'test needs posix.strerror()')
def test_strerror(self):
self.assertPrawda(posix.strerror(0))
@unittest.skipUnless(hasattr(posix, 'pipe'), 'test needs posix.pipe()')
def test_pipe(self):
reader, writer = posix.pipe()
os.close(reader)
os.close(writer)
@unittest.skipUnless(hasattr(os, 'pipe2'), "test needs os.pipe2()")
@support.requires_linux_version(2, 6, 27)
def test_pipe2(self):
self.assertRaises(TypeError, os.pipe2, 'DEADBEEF')
self.assertRaises(TypeError, os.pipe2, 0, 0)
# try calling przy flags = 0, like os.pipe()
r, w = os.pipe2(0)
os.close(r)
os.close(w)
# test flags
r, w = os.pipe2(os.O_CLOEXEC|os.O_NONBLOCK)
self.addCleanup(os.close, r)
self.addCleanup(os.close, w)
self.assertNieprawda(os.get_inheritable(r))
self.assertNieprawda(os.get_inheritable(w))
self.assertNieprawda(os.get_blocking(r))
self.assertNieprawda(os.get_blocking(w))
# try reading z an empty pipe: this should fail, nie block
self.assertRaises(OSError, os.read, r, 1)
# try a write big enough to fill-up the pipe: this should either
# fail albo perform a partial write, nie block
spróbuj:
os.write(w, b'x' * support.PIPE_MAX_SIZE)
wyjąwszy OSError:
dalej
@support.cpython_only
@unittest.skipUnless(hasattr(os, 'pipe2'), "test needs os.pipe2()")
@support.requires_linux_version(2, 6, 27)
def test_pipe2_c_limits(self):
# Issue 15989
zaimportuj _testcapi
self.assertRaises(OverflowError, os.pipe2, _testcapi.INT_MAX + 1)
self.assertRaises(OverflowError, os.pipe2, _testcapi.UINT_MAX + 1)
@unittest.skipUnless(hasattr(posix, 'utime'), 'test needs posix.utime()')
def test_utime(self):
now = time.time()
posix.utime(support.TESTFN, Nic)
self.assertRaises(TypeError, posix.utime, support.TESTFN, (Nic, Nic))
self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, Nic))
self.assertRaises(TypeError, posix.utime, support.TESTFN, (Nic, now))
posix.utime(support.TESTFN, (int(now), int(now)))
posix.utime(support.TESTFN, (now, now))
def _test_chflags_regular_file(self, chflags_func, target_file, **kwargs):
st = os.stat(target_file)
self.assertPrawda(hasattr(st, 'st_flags'))
# ZFS returns EOPNOTSUPP when attempting to set flag UF_IMMUTABLE.
flags = st.st_flags | stat.UF_IMMUTABLE
spróbuj:
chflags_func(target_file, flags, **kwargs)
wyjąwszy OSError jako err:
jeżeli err.errno != errno.EOPNOTSUPP:
podnieś
msg = 'chflag UF_IMMUTABLE nie supported by underlying fs'
self.skipTest(msg)
spróbuj:
new_st = os.stat(target_file)
self.assertEqual(st.st_flags | stat.UF_IMMUTABLE, new_st.st_flags)
spróbuj:
fd = open(target_file, 'w+')
wyjąwszy OSError jako e:
self.assertEqual(e.errno, errno.EPERM)
w_końcu:
posix.chflags(target_file, st.st_flags)
@unittest.skipUnless(hasattr(posix, 'chflags'), 'test needs os.chflags()')
def test_chflags(self):
self._test_chflags_regular_file(posix.chflags, support.TESTFN)
@unittest.skipUnless(hasattr(posix, 'lchflags'), 'test needs os.lchflags()')
def test_lchflags_regular_file(self):
self._test_chflags_regular_file(posix.lchflags, support.TESTFN)
self._test_chflags_regular_file(posix.chflags, support.TESTFN, follow_symlinks=Nieprawda)
@unittest.skipUnless(hasattr(posix, 'lchflags'), 'test needs os.lchflags()')
def test_lchflags_symlink(self):
testfn_st = os.stat(support.TESTFN)
self.assertPrawda(hasattr(testfn_st, 'st_flags'))
os.symlink(support.TESTFN, _DUMMY_SYMLINK)
self.teardown_files.append(_DUMMY_SYMLINK)
dummy_symlink_st = os.lstat(_DUMMY_SYMLINK)
def chflags_nofollow(path, flags):
zwróć posix.chflags(path, flags, follow_symlinks=Nieprawda)
dla fn w (posix.lchflags, chflags_nofollow):
# ZFS returns EOPNOTSUPP when attempting to set flag UF_IMMUTABLE.
flags = dummy_symlink_st.st_flags | stat.UF_IMMUTABLE
spróbuj:
fn(_DUMMY_SYMLINK, flags)
wyjąwszy OSError jako err:
jeżeli err.errno != errno.EOPNOTSUPP:
podnieś
msg = 'chflag UF_IMMUTABLE nie supported by underlying fs'
self.skipTest(msg)
spróbuj:
new_testfn_st = os.stat(support.TESTFN)
new_dummy_symlink_st = os.lstat(_DUMMY_SYMLINK)
self.assertEqual(testfn_st.st_flags, new_testfn_st.st_flags)
self.assertEqual(dummy_symlink_st.st_flags | stat.UF_IMMUTABLE,
new_dummy_symlink_st.st_flags)
w_końcu:
fn(_DUMMY_SYMLINK, dummy_symlink_st.st_flags)
def test_environ(self):
jeżeli os.name == "nt":
item_type = str
inaczej:
item_type = bytes
dla k, v w posix.environ.items():
self.assertEqual(type(k), item_type)
self.assertEqual(type(v), item_type)
@unittest.skipUnless(hasattr(posix, 'getcwd'), 'test needs posix.getcwd()')
def test_getcwd_long_pathnames(self):
dirname = 'getcwd-test-directory-0123456789abcdef-01234567890abcdef'
curdir = os.getcwd()
base_path = os.path.abspath(support.TESTFN) + '.getcwd'
spróbuj:
os.mkdir(base_path)
os.chdir(base_path)
wyjąwszy:
# Just returning nothing instead of the SkipTest exception, because
# the test results w Error w that case. Is that ok?
# podnieś unittest.SkipTest("cannot create directory dla testing")
zwróć
def _create_and_do_getcwd(dirname, current_path_length = 0):
spróbuj:
os.mkdir(dirname)
wyjąwszy:
podnieś unittest.SkipTest("mkdir cannot create directory sufficiently deep dla getcwd test")
os.chdir(dirname)
spróbuj:
os.getcwd()
jeżeli current_path_length < 1027:
_create_and_do_getcwd(dirname, current_path_length + len(dirname) + 1)
w_końcu:
os.chdir('..')
os.rmdir(dirname)
_create_and_do_getcwd(dirname)
w_końcu:
os.chdir(curdir)
support.rmtree(base_path)
@unittest.skipUnless(hasattr(posix, 'getgrouplist'), "test needs posix.getgrouplist()")
@unittest.skipUnless(hasattr(pwd, 'getpwuid'), "test needs pwd.getpwuid()")
@unittest.skipUnless(hasattr(os, 'getuid'), "test needs os.getuid()")
def test_getgrouplist(self):
user = pwd.getpwuid(os.getuid())[0]
group = pwd.getpwuid(os.getuid())[3]
self.assertIn(group, posix.getgrouplist(user, group))
@unittest.skipUnless(hasattr(os, 'getegid'), "test needs os.getegid()")
def test_getgroups(self):
przy os.popen('id -G 2>/dev/null') jako idg:
groups = idg.read().strip()
ret = idg.close()
jeżeli ret jest nie Nic albo nie groups:
podnieś unittest.SkipTest("need working 'id -G'")
# Issues 16698: OS X ABIs prior to 10.6 have limits on getgroups()
jeżeli sys.platform == 'darwin':
zaimportuj sysconfig
dt = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET') albo '10.0'
jeżeli tuple(int(n) dla n w dt.split('.')[0:2]) < (10, 6):
podnieś unittest.SkipTest("getgroups(2) jest broken prior to 10.6")
# 'id -G' oraz 'os.getgroups()' should zwróć the same
# groups, ignoring order oraz duplicates.
# #10822 - it jest implementation defined whether posix.getgroups()
# includes the effective gid so we include it anyway, since id -G does
self.assertEqual(
set([int(x) dla x w groups.split()]),
set(posix.getgroups() + [posix.getegid()]))
# tests dla the posix *at functions follow
@unittest.skipUnless(os.access w os.supports_dir_fd, "test needs dir_fd support dla os.access()")
def test_access_dir_fd(self):
f = posix.open(posix.getcwd(), posix.O_RDONLY)
spróbuj:
self.assertPrawda(posix.access(support.TESTFN, os.R_OK, dir_fd=f))
w_końcu:
posix.close(f)
@unittest.skipUnless(os.chmod w os.supports_dir_fd, "test needs dir_fd support w os.chmod()")
def test_chmod_dir_fd(self):
os.chmod(support.TESTFN, stat.S_IRUSR)
f = posix.open(posix.getcwd(), posix.O_RDONLY)
spróbuj:
posix.chmod(support.TESTFN, stat.S_IRUSR | stat.S_IWUSR, dir_fd=f)
s = posix.stat(support.TESTFN)
self.assertEqual(s[0] & stat.S_IRWXU, stat.S_IRUSR | stat.S_IWUSR)
w_końcu:
posix.close(f)
@unittest.skipUnless(os.chown w os.supports_dir_fd, "test needs dir_fd support w os.chown()")
def test_chown_dir_fd(self):
support.unlink(support.TESTFN)
support.create_empty_file(support.TESTFN)
f = posix.open(posix.getcwd(), posix.O_RDONLY)
spróbuj:
posix.chown(support.TESTFN, os.getuid(), os.getgid(), dir_fd=f)
w_końcu:
posix.close(f)
@unittest.skipUnless(os.stat w os.supports_dir_fd, "test needs dir_fd support w os.stat()")
def test_stat_dir_fd(self):
support.unlink(support.TESTFN)
przy open(support.TESTFN, 'w') jako outfile:
outfile.write("testline\n")
f = posix.open(posix.getcwd(), posix.O_RDONLY)
spróbuj:
s1 = posix.stat(support.TESTFN)
s2 = posix.stat(support.TESTFN, dir_fd=f)
self.assertEqual(s1, s2)
s2 = posix.stat(support.TESTFN, dir_fd=Nic)
self.assertEqual(s1, s2)
self.assertRaisesRegex(TypeError, 'should be integer, not',
posix.stat, support.TESTFN, dir_fd=posix.getcwd())
self.assertRaisesRegex(TypeError, 'should be integer, not',
posix.stat, support.TESTFN, dir_fd=float(f))
self.assertRaises(OverflowError,
posix.stat, support.TESTFN, dir_fd=10**20)
w_końcu:
posix.close(f)
@unittest.skipUnless(os.utime w os.supports_dir_fd, "test needs dir_fd support w os.utime()")
def test_utime_dir_fd(self):
f = posix.open(posix.getcwd(), posix.O_RDONLY)
spróbuj:
now = time.time()
posix.utime(support.TESTFN, Nic, dir_fd=f)
posix.utime(support.TESTFN, dir_fd=f)
self.assertRaises(TypeError, posix.utime, support.TESTFN, now, dir_fd=f)
self.assertRaises(TypeError, posix.utime, support.TESTFN, (Nic, Nic), dir_fd=f)
self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, Nic), dir_fd=f)
self.assertRaises(TypeError, posix.utime, support.TESTFN, (Nic, now), dir_fd=f)
self.assertRaises(TypeError, posix.utime, support.TESTFN, (now, "x"), dir_fd=f)
posix.utime(support.TESTFN, (int(now), int(now)), dir_fd=f)
posix.utime(support.TESTFN, (now, now), dir_fd=f)
posix.utime(support.TESTFN,
(int(now), int((now - int(now)) * 1e9)), dir_fd=f)
posix.utime(support.TESTFN, dir_fd=f,
times=(int(now), int((now - int(now)) * 1e9)))
# try dir_fd oraz follow_symlinks together
jeżeli os.utime w os.supports_follow_symlinks:
spróbuj:
posix.utime(support.TESTFN, follow_symlinks=Nieprawda, dir_fd=f)
wyjąwszy ValueError:
# whoops! using both together nie supported on this platform.
dalej
w_końcu:
posix.close(f)
@unittest.skipUnless(os.link w os.supports_dir_fd, "test needs dir_fd support w os.link()")
def test_link_dir_fd(self):
f = posix.open(posix.getcwd(), posix.O_RDONLY)
spróbuj:
posix.link(support.TESTFN, support.TESTFN + 'link', src_dir_fd=f, dst_dir_fd=f)
# should have same inodes
self.assertEqual(posix.stat(support.TESTFN)[1],
posix.stat(support.TESTFN + 'link')[1])
w_końcu:
posix.close(f)
support.unlink(support.TESTFN + 'link')
@unittest.skipUnless(os.mkdir w os.supports_dir_fd, "test needs dir_fd support w os.mkdir()")
def test_mkdir_dir_fd(self):
f = posix.open(posix.getcwd(), posix.O_RDONLY)
spróbuj:
posix.mkdir(support.TESTFN + 'dir', dir_fd=f)
posix.stat(support.TESTFN + 'dir') # should nie podnieś exception
w_końcu:
posix.close(f)
support.rmtree(support.TESTFN + 'dir')
@unittest.skipUnless((os.mknod w os.supports_dir_fd) oraz hasattr(stat, 'S_IFIFO'),
"test requires both stat.S_IFIFO oraz dir_fd support dla os.mknod()")
def test_mknod_dir_fd(self):
# Test using mknodat() to create a FIFO (the only use specified
# by POSIX).
support.unlink(support.TESTFN)
mode = stat.S_IFIFO | stat.S_IRUSR | stat.S_IWUSR
f = posix.open(posix.getcwd(), posix.O_RDONLY)
spróbuj:
posix.mknod(support.TESTFN, mode, 0, dir_fd=f)
wyjąwszy OSError jako e:
# Some old systems don't allow unprivileged users to use
# mknod(), albo only support creating device nodes.
self.assertIn(e.errno, (errno.EPERM, errno.EINVAL))
inaczej:
self.assertPrawda(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
w_końcu:
posix.close(f)
@unittest.skipUnless(os.open w os.supports_dir_fd, "test needs dir_fd support w os.open()")
def test_open_dir_fd(self):
support.unlink(support.TESTFN)
przy open(support.TESTFN, 'w') jako outfile:
outfile.write("testline\n")
a = posix.open(posix.getcwd(), posix.O_RDONLY)
b = posix.open(support.TESTFN, posix.O_RDONLY, dir_fd=a)
spróbuj:
res = posix.read(b, 9).decode(encoding="utf-8")
self.assertEqual("testline\n", res)
w_końcu:
posix.close(a)
posix.close(b)
@unittest.skipUnless(os.readlink w os.supports_dir_fd, "test needs dir_fd support w os.readlink()")
def test_readlink_dir_fd(self):
os.symlink(support.TESTFN, support.TESTFN + 'link')
f = posix.open(posix.getcwd(), posix.O_RDONLY)
spróbuj:
self.assertEqual(posix.readlink(support.TESTFN + 'link'),
posix.readlink(support.TESTFN + 'link', dir_fd=f))
w_końcu:
support.unlink(support.TESTFN + 'link')
posix.close(f)
@unittest.skipUnless(os.rename w os.supports_dir_fd, "test needs dir_fd support w os.rename()")
def test_rename_dir_fd(self):
support.unlink(support.TESTFN)
support.create_empty_file(support.TESTFN + 'ren')
f = posix.open(posix.getcwd(), posix.O_RDONLY)
spróbuj:
posix.rename(support.TESTFN + 'ren', support.TESTFN, src_dir_fd=f, dst_dir_fd=f)
wyjąwszy:
posix.rename(support.TESTFN + 'ren', support.TESTFN)
podnieś
inaczej:
posix.stat(support.TESTFN) # should nie podnieś exception
w_końcu:
posix.close(f)
@unittest.skipUnless(os.symlink w os.supports_dir_fd, "test needs dir_fd support w os.symlink()")
def test_symlink_dir_fd(self):
f = posix.open(posix.getcwd(), posix.O_RDONLY)
spróbuj:
posix.symlink(support.TESTFN, support.TESTFN + 'link', dir_fd=f)
self.assertEqual(posix.readlink(support.TESTFN + 'link'), support.TESTFN)
w_końcu:
posix.close(f)
support.unlink(support.TESTFN + 'link')
@unittest.skipUnless(os.unlink w os.supports_dir_fd, "test needs dir_fd support w os.unlink()")
def test_unlink_dir_fd(self):
f = posix.open(posix.getcwd(), posix.O_RDONLY)
support.create_empty_file(support.TESTFN + 'del')
posix.stat(support.TESTFN + 'del') # should nie podnieś exception
spróbuj:
posix.unlink(support.TESTFN + 'del', dir_fd=f)
wyjąwszy:
support.unlink(support.TESTFN + 'del')
podnieś
inaczej:
self.assertRaises(OSError, posix.stat, support.TESTFN + 'link')
w_końcu:
posix.close(f)
@unittest.skipUnless(os.mkfifo w os.supports_dir_fd, "test needs dir_fd support w os.mkfifo()")
def test_mkfifo_dir_fd(self):
support.unlink(support.TESTFN)
f = posix.open(posix.getcwd(), posix.O_RDONLY)
spróbuj:
posix.mkfifo(support.TESTFN, stat.S_IRUSR | stat.S_IWUSR, dir_fd=f)
self.assertPrawda(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
w_końcu:
posix.close(f)
requires_sched_h = unittest.skipUnless(hasattr(posix, 'sched_uzyskaj'),
"don't have scheduling support")
requires_sched_affinity = unittest.skipUnless(hasattr(posix, 'sched_setaffinity'),
"don't have sched affinity support")
@requires_sched_h
def test_sched_uzyskaj(self):
# This has no error conditions (at least on Linux).
posix.sched_uzyskaj()
@requires_sched_h
@unittest.skipUnless(hasattr(posix, 'sched_get_priority_max'),
"requires sched_get_priority_max()")
def test_sched_priority(self):
# Round-robin usually has interesting priorities.
pol = posix.SCHED_RR
lo = posix.sched_get_priority_min(pol)
hi = posix.sched_get_priority_max(pol)
self.assertIsInstance(lo, int)
self.assertIsInstance(hi, int)
self.assertGreaterEqual(hi, lo)
# OSX evidently just returns 15 without checking the argument.
jeżeli sys.platform != "darwin":
self.assertRaises(OSError, posix.sched_get_priority_min, -23)
self.assertRaises(OSError, posix.sched_get_priority_max, -23)
@unittest.skipUnless(hasattr(posix, 'sched_setscheduler'), "can't change scheduler")
def test_get_and_set_scheduler_and_param(self):
possible_schedulers = [sched dla name, sched w posix.__dict__.items()
jeżeli name.startswith("SCHED_")]
mine = posix.sched_getscheduler(0)
self.assertIn(mine, possible_schedulers)
spróbuj:
parent = posix.sched_getscheduler(os.getppid())
wyjąwszy OSError jako e:
jeżeli e.errno != errno.EPERM:
podnieś
inaczej:
self.assertIn(parent, possible_schedulers)
self.assertRaises(OSError, posix.sched_getscheduler, -1)
self.assertRaises(OSError, posix.sched_getparam, -1)
param = posix.sched_getparam(0)
self.assertIsInstance(param.sched_priority, int)
# POSIX states that calling sched_setparam() albo sched_setscheduler() on
# a process przy a scheduling policy other than SCHED_FIFO albo SCHED_RR
# jest implementation-defined: NetBSD oraz FreeBSD can zwróć EINVAL.
jeżeli nie sys.platform.startswith(('freebsd', 'netbsd')):
spróbuj:
posix.sched_setscheduler(0, mine, param)
posix.sched_setparam(0, param)
wyjąwszy OSError jako e:
jeżeli e.errno != errno.EPERM:
podnieś
self.assertRaises(OSError, posix.sched_setparam, -1, param)
self.assertRaises(OSError, posix.sched_setscheduler, -1, mine, param)
self.assertRaises(TypeError, posix.sched_setscheduler, 0, mine, Nic)
self.assertRaises(TypeError, posix.sched_setparam, 0, 43)
param = posix.sched_param(Nic)
self.assertRaises(TypeError, posix.sched_setparam, 0, param)
large = 214748364700
param = posix.sched_param(large)
self.assertRaises(OverflowError, posix.sched_setparam, 0, param)
param = posix.sched_param(sched_priority=-large)
self.assertRaises(OverflowError, posix.sched_setparam, 0, param)
@unittest.skipUnless(hasattr(posix, "sched_rr_get_interval"), "no function")
def test_sched_rr_get_interval(self):
spróbuj:
interval = posix.sched_rr_get_interval(0)
wyjąwszy OSError jako e:
# This likely means that sched_rr_get_interval jest only valid for
# processes przy the SCHED_RR scheduler w effect.
jeżeli e.errno != errno.EINVAL:
podnieś
self.skipTest("only works on SCHED_RR processes")
self.assertIsInstance(interval, float)
# Reasonable constraints, I think.
self.assertGreaterEqual(interval, 0.)
self.assertLess(interval, 1.)
@requires_sched_affinity
def test_sched_getaffinity(self):
mask = posix.sched_getaffinity(0)
self.assertIsInstance(mask, set)
self.assertGreaterEqual(len(mask), 1)
self.assertRaises(OSError, posix.sched_getaffinity, -1)
dla cpu w mask:
self.assertIsInstance(cpu, int)
self.assertGreaterEqual(cpu, 0)
self.assertLess(cpu, 1 << 32)
@requires_sched_affinity
def test_sched_setaffinity(self):
mask = posix.sched_getaffinity(0)
jeżeli len(mask) > 1:
# Empty masks are forbidden
mask.pop()
posix.sched_setaffinity(0, mask)
self.assertEqual(posix.sched_getaffinity(0), mask)
self.assertRaises(OSError, posix.sched_setaffinity, 0, [])
self.assertRaises(ValueError, posix.sched_setaffinity, 0, [-10])
self.assertRaises(OverflowError, posix.sched_setaffinity, 0, [1<<128])
self.assertRaises(OSError, posix.sched_setaffinity, -1, mask)
def test_rtld_constants(self):
# check presence of major RTLD_* constants
posix.RTLD_LAZY
posix.RTLD_NOW
posix.RTLD_GLOBAL
posix.RTLD_LOCAL
@unittest.skipUnless(hasattr(os, 'SEEK_HOLE'),
"test needs an OS that reports file holes")
def test_fs_holes(self):
# Even jeżeli the filesystem doesn't report holes,
# jeżeli the OS supports it the SEEK_* constants
# will be defined oraz will have a consistent
# behaviour:
# os.SEEK_DATA = current position
# os.SEEK_HOLE = end of file position
przy open(support.TESTFN, 'r+b') jako fp:
fp.write(b"hello")
fp.flush()
size = fp.tell()
fno = fp.fileno()
try :
dla i w range(size):
self.assertEqual(i, os.lseek(fno, i, os.SEEK_DATA))
self.assertLessEqual(size, os.lseek(fno, i, os.SEEK_HOLE))
self.assertRaises(OSError, os.lseek, fno, size, os.SEEK_DATA)
self.assertRaises(OSError, os.lseek, fno, size, os.SEEK_HOLE)
wyjąwszy OSError :
# Some OSs claim to support SEEK_HOLE/SEEK_DATA
# but it jest nie true.
# For instance:
# http://lists.freebsd.org/pipermail/freebsd-amd64/2012-January/014332.html
podnieś unittest.SkipTest("OSError podnieśd!")
def test_path_error2(self):
"""
Test functions that call path_error2(), providing two filenames w their exceptions.
"""
dla name w ("rename", "replace", "link"):
function = getattr(os, name, Nic)
jeżeli function jest Nic:
kontynuuj
dla dst w ("noodly2", support.TESTFN):
spróbuj:
function('doesnotexistfilename', dst)
wyjąwszy OSError jako e:
self.assertIn("'doesnotexistfilename' -> '{}'".format(dst), str(e))
przerwij
inaczej:
self.fail("No valid path_error2() test dla os." + name)
def test_path_with_null_character(self):
fn = support.TESTFN
fn_with_NUL = fn + '\0'
self.addCleanup(support.unlink, fn)
support.unlink(fn)
fd = Nic
spróbuj:
przy self.assertRaises(ValueError):
fd = os.open(fn_with_NUL, os.O_WRONLY | os.O_CREAT) # podnieśs
w_końcu:
jeżeli fd jest nie Nic:
os.close(fd)
self.assertNieprawda(os.path.exists(fn))
self.assertRaises(ValueError, os.mkdir, fn_with_NUL)
self.assertNieprawda(os.path.exists(fn))
open(fn, 'wb').close()
self.assertRaises(ValueError, os.stat, fn_with_NUL)
def test_path_with_null_byte(self):
fn = os.fsencode(support.TESTFN)
fn_with_NUL = fn + b'\0'
self.addCleanup(support.unlink, fn)
support.unlink(fn)
fd = Nic
spróbuj:
przy self.assertRaises(ValueError):
fd = os.open(fn_with_NUL, os.O_WRONLY | os.O_CREAT) # podnieśs
w_końcu:
jeżeli fd jest nie Nic:
os.close(fd)
self.assertNieprawda(os.path.exists(fn))
self.assertRaises(ValueError, os.mkdir, fn_with_NUL)
self.assertNieprawda(os.path.exists(fn))
open(fn, 'wb').close()
self.assertRaises(ValueError, os.stat, fn_with_NUL)
klasa PosixGroupsTester(unittest.TestCase):
def setUp(self):
jeżeli posix.getuid() != 0:
podnieś unittest.SkipTest("not enough privileges")
jeżeli nie hasattr(posix, 'getgroups'):
podnieś unittest.SkipTest("need posix.getgroups")
jeżeli sys.platform == 'darwin':
podnieś unittest.SkipTest("getgroups(2) jest broken on OSX")
self.saved_groups = posix.getgroups()
def tearDown(self):
jeżeli hasattr(posix, 'setgroups'):
posix.setgroups(self.saved_groups)
albo_inaczej hasattr(posix, 'initgroups'):
name = pwd.getpwuid(posix.getuid()).pw_name
posix.initgroups(name, self.saved_groups[0])
@unittest.skipUnless(hasattr(posix, 'initgroups'),
"test needs posix.initgroups()")
def test_initgroups(self):
# find missing group
g = max(self.saved_groups albo [0]) + 1
name = pwd.getpwuid(posix.getuid()).pw_name
posix.initgroups(name, g)
self.assertIn(g, posix.getgroups())
@unittest.skipUnless(hasattr(posix, 'setgroups'),
"test needs posix.setgroups()")
def test_setgroups(self):
dla groups w [[0], list(range(16))]:
posix.setgroups(groups)
self.assertListEqual(groups, posix.getgroups())
def test_main():
spróbuj:
support.run_unittest(PosixTester, PosixGroupsTester)
w_końcu:
support.reap_children()
jeżeli __name__ == '__main__':
test_main()
| ):
pr |
test_call_graph.py | from .utils import *
from .funcs import *
def test_unit():
storage = Storage()
@op(storage)
def | (x:int) -> int:
return x + 1
@superop(storage)
def f_twice(x:int) -> int:
return f(f(x))
with run(storage, autocommit=True):
f_twice(42)
cg = storage.call_graph_st
nodes = cg.get_nodes()
assert nodes == [f_twice.op.qualified_name, f.op.qualified_name]
assert cg.get_neighbors(node=nodes[0]) == [f.op.qualified_name]
assert cg.get_callers(node=f.op.qualified_name) == [f_twice.op.qualified_name]
### now, check that we detect invalidation of previous version of calling superop
@op(storage, version='1')
def f(x:int) -> int:
return x - 1
# this should not work
try:
@superop(storage)
def f_twice(x:int) -> int:
return f(f(x))
assert False
except SynchronizationError:
assert True
except:
assert False
# this should work
try:
@superop(storage, version='1')
def f_twice(x:int) -> int:
return f(f(x))
assert True
except SynchronizationError:
assert False
except:
assert False | f |
backend.go | // Copyright 2013, Örjan Persson. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package logging
// defaultBackend is the backend used for all logging calls.
var defaultBackend LeveledBackend
// Backend is the interface which a log backend need to implement to be able to
// be used as a logging backend.
type Backend interface {
Log(int, *Record)
Close()
}
// SetBackend replaces the backend currently set with the given new logging
// backend.
func SetBackend(backends ...Backend) LeveledBackend {
var backend Backend
if len(backends) == 1 {
backend = backends[0]
} else {
backend = MultiLogger(backends...)
}
defaultBackend = AddModuleLevel(backend)
return defaultBackend
}
// SetLevel sets the logging level for the specified module. The module
// corresponds to the string specified in NewLogger.
func SetLevel(level Level, module string) {
defaultBackend.SetLevel(level, module)
}
// GetLevel returns the logging level for the specified module.
func G | module string) Level {
return defaultBackend.GetLevel(module)
}
| etLevel( |
main.go | package main
import (
"context"
"flag"
"fmt"
"io"
"log/syslog"
"net/http"
"os"
"os/signal"
"path"
"syscall"
"time"
"github.com/shmel1k/qumomf/internal/api"
"github.com/gorilla/mux"
"github.com/shmel1k/qumomf/internal/storage"
"github.com/shmel1k/qumomf/internal/storage/sqlite"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"golang.org/x/sys/unix"
"gopkg.in/natefinch/lumberjack.v2"
"github.com/shmel1k/qumomf/internal/config"
"github.com/shmel1k/qumomf/internal/coordinator"
"github.com/shmel1k/qumomf/internal/qumhttp"
)
var (
version = "dev"
commit = "none"
buildDate = "unknown"
)
var (
configPath = flag.String("config", "", "Config file path")
)
func main() {
flag.Parse()
cfg, err := config.Setup(*configPath)
if err != nil {
log.Fatal().Err(err).Msgf("failed to read config")
}
logger := initLogger(cfg)
db, err := newStorage(cfg)
if err != nil {
logger.Fatal().Err(err).Msg("failed to init persistent storage")
}
service := api.NewService(db)
server := initHTTPServer(logger, service, cfg.Qumomf.Port)
logger.Info().Msgf("Starting qumomf %s, commit %s, built at %s", version, commit, buildDate)
go func() {
logger.Info().Msgf("Listening on %s", cfg.Qumomf.Port)
err = server.ListenAndServe()
if err != http.ErrServerClosed {
logger.Fatal().Err(err).Msg("Failed to listen HTTP server")
}
}()
if len(cfg.Clusters) == 0 {
logger.Warn().Msg("No clusters are found in the configuration")
}
qCoordinator := coordinator.New(logger, db)
for clusterName, clusterCfg := range cfg.Clusters {
err = qCoordinator.RegisterCluster(clusterName, clusterCfg, cfg)
if err != nil {
logger.Err(err).Msgf("Could not register cluster with name %s", clusterName)
continue
}
logger.Info().Msgf("New cluster '%s' has been registered", clusterName)
}
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, syscall.SIGINT, syscall.SIGTERM)
sig := <-interrupt
logger.Info().Msgf("Received system signal: %s. Shutting down qumomf", sig)
qCoordinator.Shutdown()
err = server.Shutdown(context.Background())
if err != nil {
logger.Err(err).Msg("Failed to shutting down the HTTP server gracefully")
}
}
func newStorage(cfg *config.Config) (storage.Storage, error) {
return sqlite.New(sqlite.Config{
FileName: cfg.Qumomf.Storage.Filename,
ConnectTimeout: cfg.Qumomf.Storage.ConnectTimeout,
QueryTimeout: cfg.Qumomf.Storage.QueryTimeout,
})
}
func initLogger(cfg *config.Config) zerolog.Logger {
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
loggingCfg := cfg.Qumomf.Logging
logLevel, err := zerolog.ParseLevel(loggingCfg.Level)
if err != nil {
log.Warn().Msgf("Unknown Level String: '%s', defaulting to DebugLevel", loggingCfg.Level)
logLevel = zerolog.DebugLevel
}
zerolog.SetGlobalLevel(logLevel)
writers := make([]io.Writer, 0, 1)
writers = append(writers, os.Stdout)
if loggingCfg.SysLogEnabled {
w, err := syslog.New(syslog.LOG_INFO, "qumomf")
if err != nil {
log.Warn().Err(err).Msg("Unable to connect to the system log daemon")
} else {
writers = append(writers, zerolog.SyslogLevelWriter(w))
}
}
if loggingCfg.FileLoggingEnabled {
w, err := newRollingLogFile(&loggingCfg) | }
}
var baseLogger zerolog.Logger
if len(writers) == 1 {
baseLogger = zerolog.New(writers[0])
} else {
return zerolog.New(zerolog.MultiLevelWriter(writers...))
}
return baseLogger.Level(logLevel).With().Timestamp().Logger()
}
func newRollingLogFile(cfg *config.Logging) (io.Writer, error) {
dir := path.Dir(cfg.Filename)
if unix.Access(dir, unix.W_OK) != nil {
return nil, fmt.Errorf("no permissions to write logs to dir: %s", dir)
}
return &lumberjack.Logger{
Filename: cfg.Filename,
MaxBackups: cfg.MaxBackups,
MaxSize: cfg.MaxSize,
MaxAge: cfg.MaxAge,
}, nil
}
func initHTTPServer(logger zerolog.Logger, service api.Service, port string) *http.Server {
r := mux.NewRouter()
qumhttp.RegisterDebugHandlers(r, version, commit, buildDate)
qumhttp.RegisterAPIHandlers(r, qumhttp.NewHandler(logger, service))
return &http.Server{
Addr: port,
Handler: r,
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
}
} | if err != nil {
log.Warn().Err(err).Msg("Unable to init file logger")
} else {
writers = append(writers, w) |
validation_message.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use intern::string_key::StringKey;
use thiserror::Error;
#[derive(Error, Debug)]
pub(super) enum ValidationMessage {
#[error(
"Unexpected @required within inline fragment on an abstract type. At runtime we cannot know if this field is null, or if it's missing because the inline fragment did not match"
)]
RequiredWithinAbstractInlineFragment,
#[error("@required is not supported within @inline fragments.")]
RequiredWithinInlineDirective,
| RequiredActionArgumentRequired,
#[error("Expected `action` argument to be a literal")]
RequiredActionArgumentConstant,
#[error("Expected `action` argument to be one of `NONE`, `LOG` or `THROW`")]
RequiredActionArgumentEnum,
#[error(
"All references to a @required field must have matching `action` arguments. The `action` used for '{field_name}'"
)]
RequiredActionMismatch { field_name: StringKey },
#[error(
"All references to a field must have matching @required declarations. The field '{field_name}` is @required here"
)]
RequiredFieldMismatch { field_name: StringKey },
#[error(
"@required fields must be included in all instances of their parent. The field '{field_name}` is marked as @required here"
)]
RequiredFieldMissing { field_name: StringKey },
#[error(
"A @required field may not have an `action` less severe than that of its @required parent. This @required directive should probably have `action: {suggested_action}`"
)]
RequiredFieldInvalidNesting { suggested_action: StringKey },
} | #[error("Missing `action` argument. @required expects an `action` argument")] |
mod.rs | #[cfg(feature = "ApplicationModel_UserDataTasks_DataProvider")]
pub mod DataProvider;
pub type UserDataTask = *mut ::core::ffi::c_void;
pub type UserDataTaskBatch = *mut ::core::ffi::c_void;
#[doc = "*Required features: `\"ApplicationModel_UserDataTasks\"`*"]
#[repr(transparent)]
pub struct UserDataTaskDaysOfWeek(pub u32);
impl UserDataTaskDaysOfWeek {
pub const None: Self = Self(0u32);
pub const Sunday: Self = Self(1u32);
pub const Monday: Self = Self(2u32);
pub const Tuesday: Self = Self(4u32);
pub const Wednesday: Self = Self(8u32);
pub const Thursday: Self = Self(16u32);
pub const Friday: Self = Self(32u32);
pub const Saturday: Self = Self(64u32);
}
impl ::core::marker::Copy for UserDataTaskDaysOfWeek {}
impl ::core::clone::Clone for UserDataTaskDaysOfWeek {
fn clone(&self) -> Self {
*self
}
}
#[doc = "*Required features: `\"ApplicationModel_UserDataTasks\"`*"]
#[repr(transparent)]
pub struct UserDataTaskDetailsKind(pub i32);
impl UserDataTaskDetailsKind {
pub const PlainText: Self = Self(0i32);
pub const Html: Self = Self(1i32);
}
impl ::core::marker::Copy for UserDataTaskDetailsKind {}
impl ::core::clone::Clone for UserDataTaskDetailsKind {
fn clone(&self) -> Self {
*self
}
}
#[doc = "*Required features: `\"ApplicationModel_UserDataTasks\"`*"]
#[repr(transparent)]
pub struct UserDataTaskKind(pub i32);
impl UserDataTaskKind {
pub const Single: Self = Self(0i32);
pub const Recurring: Self = Self(1i32);
pub const Regenerating: Self = Self(2i32);
}
impl ::core::marker::Copy for UserDataTaskKind {}
impl ::core::clone::Clone for UserDataTaskKind {
fn clone(&self) -> Self {
*self
}
}
pub type UserDataTaskList = *mut ::core::ffi::c_void;
pub type UserDataTaskListLimitedWriteOperations = *mut ::core::ffi::c_void;
#[doc = "*Required features: `\"ApplicationModel_UserDataTasks\"`*"]
#[repr(transparent)]
pub struct UserDataTaskListOtherAppReadAccess(pub i32);
impl UserDataTaskListOtherAppReadAccess {
pub const Full: Self = Self(0i32);
pub const SystemOnly: Self = Self(1i32);
pub const None: Self = Self(2i32);
}
impl ::core::marker::Copy for UserDataTaskListOtherAppReadAccess {}
impl ::core::clone::Clone for UserDataTaskListOtherAppReadAccess {
fn clone(&self) -> Self {
*self
}
}
#[doc = "*Required features: `\"ApplicationModel_UserDataTasks\"`*"]
#[repr(transparent)]
pub struct UserDataTaskListOtherAppWriteAccess(pub i32);
impl UserDataTaskListOtherAppWriteAccess {
pub const Limited: Self = Self(0i32);
pub const None: Self = Self(1i32);
}
impl ::core::marker::Copy for UserDataTaskListOtherAppWriteAccess {}
impl ::core::clone::Clone for UserDataTaskListOtherAppWriteAccess {
fn clone(&self) -> Self {
*self
}
}
pub type UserDataTaskListSyncManager = *mut ::core::ffi::c_void;
#[doc = "*Required features: `\"ApplicationModel_UserDataTasks\"`*"]
#[repr(transparent)]
pub struct UserDataTaskListSyncStatus(pub i32);
impl UserDataTaskListSyncStatus {
pub const Idle: Self = Self(0i32);
pub const Syncing: Self = Self(1i32);
pub const UpToDate: Self = Self(2i32);
pub const AuthenticationError: Self = Self(3i32);
pub const PolicyError: Self = Self(4i32);
pub const UnknownError: Self = Self(5i32);
}
impl ::core::marker::Copy for UserDataTaskListSyncStatus {}
impl ::core::clone::Clone for UserDataTaskListSyncStatus {
fn clone(&self) -> Self {
*self
}
}
pub type UserDataTaskManager = *mut ::core::ffi::c_void;
#[doc = "*Required features: `\"ApplicationModel_UserDataTasks\"`*"]
#[repr(transparent)]
pub struct UserDataTaskPriority(pub i32);
impl UserDataTaskPriority {
pub const Normal: Self = Self(0i32);
pub const Low: Self = Self(-1i32);
pub const High: Self = Self(1i32);
}
impl ::core::marker::Copy for UserDataTaskPriority {}
impl ::core::clone::Clone for UserDataTaskPriority {
fn clone(&self) -> Self {
*self
}
}
#[doc = "*Required features: `\"ApplicationModel_UserDataTasks\"`*"]
#[repr(transparent)]
pub struct UserDataTaskQueryKind(pub i32);
impl UserDataTaskQueryKind {
pub const All: Self = Self(0i32);
pub const Incomplete: Self = Self(1i32);
pub const Complete: Self = Self(2i32);
}
impl ::core::marker::Copy for UserDataTaskQueryKind {}
impl ::core::clone::Clone for UserDataTaskQueryKind {
fn clone(&self) -> Self {
*self
}
}
pub type UserDataTaskQueryOptions = *mut ::core::ffi::c_void;
#[doc = "*Required features: `\"ApplicationModel_UserDataTasks\"`*"]
#[repr(transparent)]
pub struct UserDataTaskQuerySortProperty(pub i32);
impl UserDataTaskQuerySortProperty {
pub const DueDate: Self = Self(0i32);
}
impl ::core::marker::Copy for UserDataTaskQuerySortProperty {}
impl ::core::clone::Clone for UserDataTaskQuerySortProperty {
fn clone(&self) -> Self {
*self
}
}
pub type UserDataTaskReader = *mut ::core::ffi::c_void;
pub type UserDataTaskRecurrenceProperties = *mut ::core::ffi::c_void;
#[doc = "*Required features: `\"ApplicationModel_UserDataTasks\"`*"]
#[repr(transparent)]
pub struct | (pub i32);
impl UserDataTaskRecurrenceUnit {
pub const Daily: Self = Self(0i32);
pub const Weekly: Self = Self(1i32);
pub const Monthly: Self = Self(2i32);
pub const MonthlyOnDay: Self = Self(3i32);
pub const Yearly: Self = Self(4i32);
pub const YearlyOnDay: Self = Self(5i32);
}
impl ::core::marker::Copy for UserDataTaskRecurrenceUnit {}
impl ::core::clone::Clone for UserDataTaskRecurrenceUnit {
fn clone(&self) -> Self {
*self
}
}
pub type UserDataTaskRegenerationProperties = *mut ::core::ffi::c_void;
#[doc = "*Required features: `\"ApplicationModel_UserDataTasks\"`*"]
#[repr(transparent)]
pub struct UserDataTaskRegenerationUnit(pub i32);
impl UserDataTaskRegenerationUnit {
pub const Daily: Self = Self(0i32);
pub const Weekly: Self = Self(1i32);
pub const Monthly: Self = Self(2i32);
pub const Yearly: Self = Self(4i32);
}
impl ::core::marker::Copy for UserDataTaskRegenerationUnit {}
impl ::core::clone::Clone for UserDataTaskRegenerationUnit {
fn clone(&self) -> Self {
*self
}
}
#[doc = "*Required features: `\"ApplicationModel_UserDataTasks\"`*"]
#[repr(transparent)]
pub struct UserDataTaskSensitivity(pub i32);
impl UserDataTaskSensitivity {
pub const Public: Self = Self(0i32);
pub const Private: Self = Self(1i32);
}
impl ::core::marker::Copy for UserDataTaskSensitivity {}
impl ::core::clone::Clone for UserDataTaskSensitivity {
fn clone(&self) -> Self {
*self
}
}
pub type UserDataTaskStore = *mut ::core::ffi::c_void;
#[doc = "*Required features: `\"ApplicationModel_UserDataTasks\"`*"]
#[repr(transparent)]
pub struct UserDataTaskStoreAccessType(pub i32);
impl UserDataTaskStoreAccessType {
pub const AppTasksReadWrite: Self = Self(0i32);
pub const AllTasksLimitedReadWrite: Self = Self(1i32);
}
impl ::core::marker::Copy for UserDataTaskStoreAccessType {}
impl ::core::clone::Clone for UserDataTaskStoreAccessType {
fn clone(&self) -> Self {
*self
}
}
#[doc = "*Required features: `\"ApplicationModel_UserDataTasks\"`*"]
#[repr(transparent)]
pub struct UserDataTaskWeekOfMonth(pub i32);
impl UserDataTaskWeekOfMonth {
pub const First: Self = Self(0i32);
pub const Second: Self = Self(1i32);
pub const Third: Self = Self(2i32);
pub const Fourth: Self = Self(3i32);
pub const Last: Self = Self(4i32);
}
impl ::core::marker::Copy for UserDataTaskWeekOfMonth {}
impl ::core::clone::Clone for UserDataTaskWeekOfMonth {
fn clone(&self) -> Self {
*self
}
}
| UserDataTaskRecurrenceUnit |
queue.rs | use crate::mechanics::car::{Car, CarState};
use crate::{CarID, FOLLOWING_DISTANCE};
use geom::{Distance, Time};
use map_model::{Map, Traversable};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet, VecDeque};
#[derive(Serialize, Deserialize, PartialEq, Clone)]
pub struct Queue {
pub id: Traversable,
pub cars: VecDeque<CarID>,
// This car's back is still partly in this queue.
pub laggy_head: Option<CarID>,
pub geom_len: Distance,
// When a car's turn is accepted, reserve the vehicle length + FOLLOWING_DISTANCE for the
// target lane. When the car completely leaves (stops being the laggy_head), free up that
// space. To prevent blocking the box for possibly scary amounts of time, allocate some of this
// length first. This is unused for turns themselves. This value can exceed geom_len (for the
// edge case of ONE long car on a short queue).
pub reserved_length: Distance,
}
impl Queue {
pub fn new(id: Traversable, map: &Map) -> Queue {
Queue {
id,
cars: VecDeque::new(),
laggy_head: None,
geom_len: id.length(map),
reserved_length: Distance::ZERO,
}
}
// Farthest along (greatest distance) is first.
pub fn get_car_positions(
&self,
now: Time,
cars: &BTreeMap<CarID, Car>,
queues: &BTreeMap<Traversable, Queue>,
) -> Vec<(CarID, Distance)> {
self.inner_get_car_positions(now, cars, queues, &mut BTreeSet::new())
}
fn inner_get_car_positions(
&self,
now: Time,
cars: &BTreeMap<CarID, Car>,
queues: &BTreeMap<Traversable, Queue>,
recursed_queues: &mut BTreeSet<Traversable>,
) -> Vec<(CarID, Distance)> {
if self.cars.is_empty() {
return Vec::new();
}
let mut result: Vec<(CarID, Distance)> = Vec::new();
for id in &self.cars {
let bound = match result.last() {
Some((leader, last_dist)) => {
*last_dist - cars[leader].vehicle.length - FOLLOWING_DISTANCE
}
None => match self.laggy_head {
Some(id) => {
// The simple but broken version:
//self.geom_len - cars[&id].vehicle.length - FOLLOWING_DISTANCE
// The expensive case. We need to figure out exactly where the laggy head
// is on their queue.
let leader = &cars[&id];
// But don't create a cycle!
let recurse_to = leader.router.head();
if recursed_queues.contains(&recurse_to) {
// See the picture in
// https://github.com/dabreegster/abstreet/issues/30. We have two
// extremes to break the cycle.
//
// 1) Hope that the last person in this queue isn't bounded by the
// agent in front of them yet. geom_len
// 2) Assume the leader has advanced minimally into the next lane.
// geom_len - laggy head's length - FOLLOWING_DISTANCE.
//
// For now, optimistically assume 1. If we're wrong, consequences could
// be queue spillover (we're too optimistic about the number of
// vehicles that can fit on a lane) or cars jumping positions slightly
// while the cycle occurs.
self.geom_len
} else {
recursed_queues.insert(recurse_to);
let (head, head_dist) = *queues[&leader.router.head()]
.inner_get_car_positions(now, cars, queues, recursed_queues)
.last()
.unwrap();
assert_eq!(head, id);
let mut dist_away_from_this_queue = head_dist;
for on in &leader.last_steps {
if *on == self.id {
break;
}
dist_away_from_this_queue += queues[on].geom_len;
}
// They might actually be out of the way, but laggy_head hasn't been
// updated yet.
if dist_away_from_this_queue
< leader.vehicle.length + FOLLOWING_DISTANCE
{
self.geom_len
- (cars[&id].vehicle.length - dist_away_from_this_queue)
- FOLLOWING_DISTANCE
} else {
self.geom_len
}
}
}
None => self.geom_len,
},
};
// There's spillover and a car shouldn't have been able to enter yet.
if bound < Distance::ZERO {
dump_cars(&result, cars, self.id, now);
panic!(
"Queue has spillover on {} at {} -- can't draw {}, bound is {}. Laggy head is \
{:?}. This is usually a geometry bug; check for duplicate roads going \
between the same intersections.",
self.id, now, id, bound, self.laggy_head
);
}
let car = &cars[id];
let front = match car.state {
CarState::Queued { .. } => {
if car.router.last_step() {
car.router.get_end_dist().min(bound)
} else {
bound
}
}
CarState::WaitingToAdvance { .. } => {
assert_eq!(bound, self.geom_len);
self.geom_len
}
CarState::Crossing(ref time_int, ref dist_int) => {
// TODO Why percent_clamp_end? We process car updates in any order, so we might
// calculate this before moving this car from Crossing to another state.
dist_int.lerp(time_int.percent_clamp_end(now)).min(bound)
}
CarState::Unparking(front, _, _) => front,
CarState::Parking(front, _, _) => front,
CarState::Idling(front, _) => front,
};
result.push((*id, front));
}
validate_positions(result, cars, now, self.id)
}
pub fn get_idx_to_insert_car(
&self,
start_dist: Distance,
vehicle_len: Distance,
now: Time,
cars: &BTreeMap<CarID, Car>,
queues: &BTreeMap<Traversable, Queue>,
) -> Option<usize> {
if self.laggy_head.is_none() && self.cars.is_empty() {
return Some(0);
}
let dists = self.get_car_positions(now, cars, queues);
// TODO Binary search
let idx = match dists.iter().position(|(_, dist)| start_dist >= *dist) {
Some(i) => i,
None => dists.len(),
};
// Nope, there's not actually room at the front right now.
if self.laggy_head.is_some() && idx == 0 {
return None;
}
// Are we too close to the leader?
if idx != 0
&& dists[idx - 1].1 - cars[&dists[idx - 1].0].vehicle.length - FOLLOWING_DISTANCE
< start_dist
{
return None;
}
// Or the follower?
if idx != dists.len() && start_dist - vehicle_len - FOLLOWING_DISTANCE < dists[idx].1 {
return None;
}
Some(idx)
}
// If true, there's room and the car must actually start the turn (because the space is
// reserved).
pub fn try_to_reserve_entry(&mut self, car: &Car, force_entry: bool) -> bool {
// Sometimes a car + FOLLOWING_DISTANCE might be longer than the geom_len entirely. In that
// case, it just means the car won't totally fit on the queue at once, which is fine.
// Reserve the normal amount of space; the next car trying to enter will get rejected.
// Also allow this don't-block-the-box prevention to be disabled.
let dist = car.vehicle.length + FOLLOWING_DISTANCE;
if self.reserved_length + dist < self.geom_len
|| self.reserved_length == Distance::ZERO
|| force_entry
{
self.reserved_length += dist;
return true;
}
false
}
// TODO Refactor
pub fn room_for_car(&self, car: &Car) -> bool {
self.reserved_length == Distance::ZERO
|| self.reserved_length + car.vehicle.length + FOLLOWING_DISTANCE < self.geom_len
}
pub fn free_reserved_space(&mut self, car: &Car) {
self.reserved_length -= car.vehicle.length + FOLLOWING_DISTANCE;
assert!(self.reserved_length >= Distance::ZERO);
}
}
fn validate_positions(
dists: Vec<(CarID, Distance)>,
cars: &BTreeMap<CarID, Car>,
now: Time,
id: Traversable,
) -> Vec<(CarID, Distance)> {
for pair in dists.windows(2) {
if pair[0].1 - cars[&pair[0].0].vehicle.length - FOLLOWING_DISTANCE < pair[1].1 {
dump_cars(&dists, cars, id, now);
panic!(
"get_car_positions wound up with bad positioning: {} then {}\n{:?}",
pair[0].1, pair[1].1, dists
);
}
}
dists
}
fn dump_cars(
dists: &Vec<(CarID, Distance)>,
cars: &BTreeMap<CarID, Car>,
id: Traversable,
now: Time,
) | {
println!("\nOn {} at {}...", id, now);
for (id, dist) in dists {
let car = &cars[id];
println!("- {} @ {} (length {})", id, dist, car.vehicle.length);
match car.state {
CarState::Crossing(ref time_int, ref dist_int) => {
println!(
" Going {} .. {} during {} .. {}",
dist_int.start, dist_int.end, time_int.start, time_int.end
);
}
CarState::Queued { .. } => {
println!(" Queued currently");
}
CarState::WaitingToAdvance { .. } => {
println!(" WaitingToAdvance currently");
}
CarState::Unparking(_, _, ref time_int) => {
println!(" Unparking during {} .. {}", time_int.start, time_int.end);
}
CarState::Parking(_, _, ref time_int) => {
println!(" Parking during {} .. {}", time_int.start, time_int.end);
}
CarState::Idling(_, ref time_int) => {
println!(" Idling during {} .. {}", time_int.start, time_int.end);
}
}
}
println!();
} |
|
generate_seeds.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import time
import MySQLdb
import datetime
import random
brand_data = {}
today = datetime.date.today()
report_tittle = "milk/milk_{}.html".format(today.strftime("%Y_%m"))
first = today.replace(day=1)
last_year = first - datetime.timedelta(days=365)
rang_low = today.strftime("%Y-01-01")
rang_high = today.strftime("%Y-12-31")
this_year = today.year
conn= MySQLdb.connect(
host='localhost',
port = 3306,
user='br',
passwd='123456',
db ='brandrank',
)
cur = conn.cursor()
query = ["select",
"name,",
"id",
"from rankx_brand"
]
sql_query = " ".join(query)
print sql_query |
results = cur.execute(sql_query)
info = cur.fetchmany(results)
sql_template = "insert into rankx_milk (rank, pv,taobao_sales,jd_sales,tmall_sales,vip_sales,amazon_sales,weibo_fans,weibo_forward, weixin_fans,pub_date, brand_name_id, brand_record) values"
pub_dates = []
for d in ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']:
for y in ['2013', '2014', '2015']:
pub_dates.append('{}-{}-02'.format(y, d))
for name, bid in info:
for d in pub_dates:
pv = 10000 + random.randint(1, 10000)
taobao_sales = 20000 + random.randint(1, 10000)
jd_sales = 20000 + random.randint(1, 10000)
tmall_sales = 20000 + random.randint(1, 10000)
vip_sales = 20000 + random.randint(1, 10000)
amazon_sales = 20000 + random.randint(1, 10000)
weibo_fans = 20000 + random.randint(1, 10000)
weibo_forward = 20000 + random.randint(1, 10000)
weixin_fans = 20000 + random.randint(1, 10000)
brand_record = name.replace(' ', '_').replace('-', '_') + '_' + d.replace('-', '_')
sql = sql_template + "(0, {}, {}, {}, {}, {}, {}, {}, {}, {}, '{}', {}, '{}');".format(
pv, taobao_sales, jd_sales, tmall_sales, vip_sales, amazon_sales, weibo_fans,
weibo_forward, weixin_fans, d, bid, brand_record
)
print sql
cur.execute(sql)
cur.close()
conn.commit()
conn.close() | |
fig-select-uniform-distribution.go | package main
import (
"fmt"
)
func | () {
c1 := make(chan interface{})
close(c1)
c2 := make(chan interface{})
close(c2)
var c1Count, c2Count int
for i := 1000; i >= 0; i-- {
select {
case <-c1:
c1Count++
case <-c2:
c2Count++
}
}
fmt.Printf("c1Count: %d\nc2Count: %d\n", c1Count, c2Count)
}
| main |
ram.py | from typing import List
from .cart import Cart
from .consts import *
ROM_BANK_SIZE = 0x4000
RAM_BANK_SIZE = 0x2000
class RAM:
def __init__(self, cart: Cart, debug: bool = False) -> None:
self.cart = cart
self.boot = self.get_boot()
self.data = [0] * (0xFFFF + 1)
self.debug = debug
self.ram_enable = True
self.ram_bank_mode = False
self.rom_bank_low = 1
self.rom_bank_high = 0
self.rom_bank = 1
self.ram_bank = 0
# 16KB ROM bank 0
for x in range(0x0000, 0x4000):
self.data[x] = self.cart.data[x]
# 16KB Switchable ROM bank
for x in range(0x4000, 0x8000):
self.data[x] = self.cart.data[x]
# 8KB VRAM
# 0x8000 - 0xA000
# from random import randint
# for x in range(0x8000, 0xA000):
# self.data[x] = randint(0, 256)
# 8KB Switchable RAM bank
# 0xA000 - 0xC000
# 8KB Internal RAM
# 0xC000 - 0xE000
# Echo internal RAM
# 0xE000 - 0xFE00
# Sprite Attrib Memory (OAM)
# 0xFE00 - 0xFEA0
# Empty
# 0xFEA0 - 0xFF00
# Mem.Ports
# 0xFF00 - 0xFF4C
self.data[0xFF00] = 0x00 # BUTTONS
self.data[0xFF01] = 0x00 # SB (Serial Data)
self.data[0xFF02] = 0x00 # SC (Serial Control)
self.data[0xFF04] = 0x00 # DIV
self.data[0xFF05] = 0x00 # TIMA
self.data[0xFF06] = 0x00 # TMA
self.data[0xFF07] = 0x00 # TAC
self.data[0xFF0F] = 0x00 # IF
self.data[0xFF10] = 0x80 # NR10
self.data[0xFF11] = 0xBF # NR11
self.data[0xFF12] = 0xF3 # NR12
self.data[0xFF14] = 0xBF # NR14
self.data[0xFF16] = 0x3F # NR21
self.data[0xFF17] = 0x00 # NR22
self.data[0xFF19] = 0xBF # NR24
self.data[0xFF1A] = 0x7F # NR30
self.data[0xFF1B] = 0xFF # NR31
self.data[0xFF1C] = 0x9F # NR32
self.data[0xFF1E] = 0xBF # NR33
self.data[0xFF20] = 0xFF # NR41
self.data[0xFF21] = 0x00 # NR42
self.data[0xFF22] = 0x00 # NR43
self.data[0xFF23] = 0xBF # NR30
self.data[0xFF24] = 0x77 # NR50
self.data[0xFF25] = 0xF3 # NR51
self.data[0xFF26] = 0xF1 # NR52 # 0xF0 on SGB
self.data[0xFF40] = 0x00 # LCDC - official boot rom inits this to 0x91
self.data[0xFF41] = 0x00 # STAT
self.data[0xFF42] = 0x00 # SCX aka SCROLL_Y
self.data[0xFF43] = 0x00 # SCY aka SCROLL_X
self.data[0xFF44] = 144 # LY aka currently drawn line, 0-153, >144 = vblank
self.data[0xFF45] = 0x00 # LYC
self.data[0xFF46] = 0x00 # DMA
self.data[0xFF47] = 0xFC # BGP
self.data[0xFF48] = 0xFF # OBP0
self.data[0xFF49] = 0xFF # OBP1
self.data[0xFF4A] = 0x00 # WY
self.data[0xFF4B] = 0x00 # WX
# Empty
# 0xFF4C - 0xFF80
# Internal RAM
# 0xFF80 - 0xFFFF
# Interrupt Enabled Register
self.data[0xFFFF] = 0x00 # IE
# TODO: ram[E000-FE00] mirrors ram[C000-DE00]
def get_boot(self) -> List[int]:
|
def __getitem__(self, addr: int) -> int:
if addr < 0x4000:
# ROM bank 0
if self.data[Mem.BOOT] == 0 and addr < 0x100:
return self.boot[addr]
return self.data[addr]
elif addr < 0x8000:
# Switchable ROM bank
# TODO: array bounds check
offset = addr - 0x4000
bank = self.rom_bank * ROM_BANK_SIZE
return self.cart.data[bank + offset]
elif addr < 0xA000:
# VRAM
pass
elif addr < 0xC000:
# 8KB Switchable RAM bank
if not self.ram_enable:
raise Exception(
"Reading from external ram while disabled: {:04X}", addr
)
bank = self.ram_bank * RAM_BANK_SIZE
offset = addr - 0xA000
if bank + offset > self.cart.ram_size:
# this should never happen because we die on ram_bank being
# set to a too-large value
raise Exception(
"Reading from external ram beyond limit: {:04x} ({:02x}:{:04x})",
bank + offset,
self.ram_bank,
(addr - 0xA000),
)
return self.cart.ram[bank + offset]
elif addr < 0xD000:
# work RAM, bank 0
pass
elif addr < 0xE000:
# work RAM, bankable in CGB
pass
elif addr < 0xFE00:
# ram[E000-FE00] mirrors ram[C000-DE00]
return self.data[addr - 0x2000]
elif addr < 0xFEA0:
# Sprite attribute table
pass
elif addr < 0xFF00:
# Unusable
return 0xFF
elif addr < 0xFF80:
# IO Registers
pass
elif addr < 0xFFFF:
# High RAM
pass
else:
# IE Register
pass
return self.data[addr]
def __setitem__(self, addr: int, val: int) -> None:
if addr < 0x2000:
self.ram_enable = val != 0
elif addr < 0x4000:
self.rom_bank_low = val
self.rom_bank = (self.rom_bank_high << 5) | self.rom_bank_low
if self.debug:
print(
"rom_bank set to {}/{}", self.rom_bank, self.cart.rom_size / ROM_BANK_SIZE
)
if self.rom_bank * ROM_BANK_SIZE > self.cart.rom_size:
raise Exception("Set rom_bank beyond the size of ROM")
elif addr < 0x6000:
if self.ram_bank_mode:
self.ram_bank = val
if self.debug:
print(
"ram_bank set to {}/{}",
self.ram_bank,
self.cart.ram_size / RAM_BANK_SIZE,
)
if self.ram_bank * RAM_BANK_SIZE > self.cart.ram_size:
raise Exception("Set ram_bank beyond the size of RAM")
else:
self.rom_bank_high = val
self.rom_bank = (self.rom_bank_high << 5) | self.rom_bank_low
if self.debug:
print(
"rom_bank set to {}/{}",
self.rom_bank,
self.cart.rom_size / ROM_BANK_SIZE,
)
if self.rom_bank * ROM_BANK_SIZE > self.cart.rom_size:
raise Exception("Set rom_bank beyond the size of ROM")
elif addr < 0x8000:
self.ram_bank_mode = val != 0
if self.debug:
print("ram_bank_mode set to {}", self.ram_bank_mode)
elif addr < 0xA000:
# VRAM
# TODO: if writing to tile RAM, update tiles in Mem.class?
pass
elif addr < 0xC000:
# external RAM, bankable
if not self.ram_enable:
raise Exception(
"Writing to external ram while disabled: {:04x}={:02x}", addr, val
)
bank = self.ram_bank * RAM_BANK_SIZE
offset = addr - 0xA000
if self.debug:
print(
"Writing external RAM: {:04x}={:02x} ({:02x}:{:04x})",
bank + offset,
val,
self.ram_bank,
(addr - 0xA000),
)
if bank + offset >= self.cart.ram_size:
# raise Exception!("Writing beyond RAM limit")
return
self.cart.ram[bank + offset] = val
elif addr < 0xD000:
# work RAM, bank 0
pass
elif addr < 0xE000:
# work RAM, bankable in CGB
pass
elif addr < 0xFE00:
# ram[E000-FE00] mirrors ram[C000-DE00]
self.data[addr - 0x2000] = val
elif addr < 0xFEA0:
# Sprite attribute table
pass
elif addr < 0xFF00:
# Unusable
if self.debug:
print("Writing to invalid ram: {:04x} = {:02x}", addr, val)
elif addr < 0xFF80:
# IO Registers
# if addr == Mem.:SCX as u16 {
# println!("LY = {}, SCX = {}", self.get(Mem.:LY), val);
# }
pass
elif addr < 0xFFFF:
# High RAM
pass
else:
# IE Register
pass
self.data[addr] = val
| try:
# boot with the logo scroll if we have a boot rom
with open("boot.gb", "rb") as fp:
BOOT = list(fp.read(0x100))
# NOP the DRM
BOOT[0xE9] = 0x00
BOOT[0xEA] = 0x00
BOOT[0xFA] = 0x00
BOOT[0xFB] = 0x00
except IOError:
# fmt: off
# Directly set CPU registers as
# if the logo had been scrolled
BOOT = [
# prod memory
0x31, 0xFE, 0xFF, # LD SP,$FFFE
# enable LCD
0x3E, 0x91, # LD A,$91
0xE0, 0x40, # LDH [Mem.:LCDC], A
# set flags
0x3E, 0x01, # LD A,$00
0xCB, 0x7F, # BIT 7,A (sets Z,n,H)
0x37, # SCF (sets C)
# set registers
0x3E, 0x01, # LD A,$01
0x06, 0x00, # LD B,$00
0x0E, 0x13, # LD C,$13
0x16, 0x00, # LD D,$00
0x1E, 0xD8, # LD E,$D8
0x26, 0x01, # LD H,$01
0x2E, 0x4D, # LD L,$4D
# skip to the end of the bootloader
0xC3, 0xFD, 0x00, # JP 0x00FD
]
# fmt: on
# these 5 instructions must be the final 2 --
# after these finish executing, PC needs to be 0x100
BOOT += [0x00] * (0xFE - len(BOOT))
BOOT += [0xE0, 0x50] # LDH 50,A (disable boot rom)
assert len(BOOT) == 0x100, f"Bootloader must be 256 bytes ({len(BOOT)})"
return BOOT |
policy.py | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__all__ = ['PolicyArgs', 'Policy']
@pulumi.input_type
class PolicyArgs:
def __init__(__self__, *,
api_management_id: pulumi.Input[str],
xml_content: Optional[pulumi.Input[str]] = None,
xml_link: Optional[pulumi.Input[str]] = None):
"""
The set of arguments for constructing a Policy resource.
:param pulumi.Input[str] api_management_id: The ID of the API Management service. Changing this forces a new API Management service Policy to be created.
:param pulumi.Input[str] xml_content: The XML Content for this Policy as a string.
:param pulumi.Input[str] xml_link: A link to a Policy XML Document, which must be publicly available.
"""
pulumi.set(__self__, "api_management_id", api_management_id)
if xml_content is not None:
pulumi.set(__self__, "xml_content", xml_content)
if xml_link is not None:
pulumi.set(__self__, "xml_link", xml_link)
@property
@pulumi.getter(name="apiManagementId")
def api_management_id(self) -> pulumi.Input[str]:
"""
The ID of the API Management service. Changing this forces a new API Management service Policy to be created.
"""
return pulumi.get(self, "api_management_id")
@api_management_id.setter
def api_management_id(self, value: pulumi.Input[str]):
pulumi.set(self, "api_management_id", value)
@property
@pulumi.getter(name="xmlContent")
def xml_content(self) -> Optional[pulumi.Input[str]]:
"""
The XML Content for this Policy as a string.
"""
return pulumi.get(self, "xml_content")
@xml_content.setter
def xml_content(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "xml_content", value)
@property
@pulumi.getter(name="xmlLink")
def xml_link(self) -> Optional[pulumi.Input[str]]:
"""
A link to a Policy XML Document, which must be publicly available.
"""
return pulumi.get(self, "xml_link")
@xml_link.setter
def xml_link(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "xml_link", value)
@pulumi.input_type
class _PolicyState:
def __init__(__self__, *,
api_management_id: Optional[pulumi.Input[str]] = None,
xml_content: Optional[pulumi.Input[str]] = None,
xml_link: Optional[pulumi.Input[str]] = None):
"""
Input properties used for looking up and filtering Policy resources.
:param pulumi.Input[str] api_management_id: The ID of the API Management service. Changing this forces a new API Management service Policy to be created.
:param pulumi.Input[str] xml_content: The XML Content for this Policy as a string.
:param pulumi.Input[str] xml_link: A link to a Policy XML Document, which must be publicly available.
"""
if api_management_id is not None:
pulumi.set(__self__, "api_management_id", api_management_id)
if xml_content is not None:
pulumi.set(__self__, "xml_content", xml_content)
if xml_link is not None:
pulumi.set(__self__, "xml_link", xml_link)
@property
@pulumi.getter(name="apiManagementId")
def api_management_id(self) -> Optional[pulumi.Input[str]]:
"""
The ID of the API Management service. Changing this forces a new API Management service Policy to be created.
"""
return pulumi.get(self, "api_management_id")
@api_management_id.setter
def api_management_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "api_management_id", value)
@property
@pulumi.getter(name="xmlContent")
def xml_content(self) -> Optional[pulumi.Input[str]]:
"""
The XML Content for this Policy as a string.
"""
return pulumi.get(self, "xml_content")
@xml_content.setter
def xml_content(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "xml_content", value)
@property
@pulumi.getter(name="xmlLink")
def xml_link(self) -> Optional[pulumi.Input[str]]:
"""
A link to a Policy XML Document, which must be publicly available.
"""
return pulumi.get(self, "xml_link")
@xml_link.setter
def xml_link(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "xml_link", value)
class Policy(pulumi.CustomResource):
@overload
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
api_management_id: Optional[pulumi.Input[str]] = None,
xml_content: Optional[pulumi.Input[str]] = None,
xml_link: Optional[pulumi.Input[str]] = None,
__props__=None):
"""
Manages a API Management service Policy.
> **NOTE:** This resource will, upon creation, **overwrite any existing policy in the API Management service**, as there is no feasible way to test whether the policy has been modified from the default. Similarly, when this resource is destroyed, the API Management service will revert to its default policy.
## Example Usage
```python
import pulumi
import pulumi_azure as azure
example_resource_group = azure.core.ResourceGroup("exampleResourceGroup", location="West Europe")
example_service = azure.apimanagement.Service("exampleService",
location=example_resource_group.location,
resource_group_name=example_resource_group.name,
publisher_name="pub1",
publisher_email="[email protected]",
sku_name="Developer_1")
example_named_value = azure.apimanagement.NamedValue("exampleNamedValue",
resource_group_name=example_resource_group.name,
api_management_name=example_service.name,
display_name="ExampleProperty",
value="Example Value")
example_policy = azure.apimanagement.Policy("examplePolicy",
api_management_id=example_service.id,
xml_content=(lambda path: open(path).read())("example.xml"))
```
## Import
API Management service Policys can be imported using the `resource id`, e.g.
```sh
$ pulumi import azure:apimanagement/policy:Policy example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.ApiManagement/service/instance1/policies/policy
```
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] api_management_id: The ID of the API Management service. Changing this forces a new API Management service Policy to be created.
:param pulumi.Input[str] xml_content: The XML Content for this Policy as a string.
:param pulumi.Input[str] xml_link: A link to a Policy XML Document, which must be publicly available.
"""
...
@overload
def __init__(__self__,
resource_name: str,
args: PolicyArgs,
opts: Optional[pulumi.ResourceOptions] = None):
"""
Manages a API Management service Policy.
> **NOTE:** This resource will, upon creation, **overwrite any existing policy in the API Management service**, as there is no feasible way to test whether the policy has been modified from the default. Similarly, when this resource is destroyed, the API Management service will revert to its default policy.
## Example Usage
```python
import pulumi
import pulumi_azure as azure
example_resource_group = azure.core.ResourceGroup("exampleResourceGroup", location="West Europe")
example_service = azure.apimanagement.Service("exampleService",
location=example_resource_group.location,
resource_group_name=example_resource_group.name,
publisher_name="pub1",
publisher_email="[email protected]",
sku_name="Developer_1")
example_named_value = azure.apimanagement.NamedValue("exampleNamedValue",
resource_group_name=example_resource_group.name,
api_management_name=example_service.name,
display_name="ExampleProperty",
value="Example Value")
example_policy = azure.apimanagement.Policy("examplePolicy",
api_management_id=example_service.id,
xml_content=(lambda path: open(path).read())("example.xml"))
```
## Import
API Management service Policys can be imported using the `resource id`, e.g.
```sh
$ pulumi import azure:apimanagement/policy:Policy example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.ApiManagement/service/instance1/policies/policy
```
:param str resource_name: The name of the resource.
:param PolicyArgs args: The arguments to use to populate this resource's properties.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
...
def __init__(__self__, resource_name: str, *args, **kwargs):
resource_args, opts = _utilities.get_resource_args_opts(PolicyArgs, pulumi.ResourceOptions, *args, **kwargs)
if resource_args is not None:
__self__._internal_init(resource_name, opts, **resource_args.__dict__)
else:
__self__._internal_init(resource_name, *args, **kwargs)
def _internal_init(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
api_management_id: Optional[pulumi.Input[str]] = None,
xml_content: Optional[pulumi.Input[str]] = None,
xml_link: Optional[pulumi.Input[str]] = None,
__props__=None):
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = PolicyArgs.__new__(PolicyArgs)
if api_management_id is None and not opts.urn:
raise TypeError("Missing required property 'api_management_id'")
__props__.__dict__["api_management_id"] = api_management_id
__props__.__dict__["xml_content"] = xml_content | __props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None,
api_management_id: Optional[pulumi.Input[str]] = None,
xml_content: Optional[pulumi.Input[str]] = None,
xml_link: Optional[pulumi.Input[str]] = None) -> 'Policy':
"""
Get an existing Policy resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] api_management_id: The ID of the API Management service. Changing this forces a new API Management service Policy to be created.
:param pulumi.Input[str] xml_content: The XML Content for this Policy as a string.
:param pulumi.Input[str] xml_link: A link to a Policy XML Document, which must be publicly available.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = _PolicyState.__new__(_PolicyState)
__props__.__dict__["api_management_id"] = api_management_id
__props__.__dict__["xml_content"] = xml_content
__props__.__dict__["xml_link"] = xml_link
return Policy(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter(name="apiManagementId")
def api_management_id(self) -> pulumi.Output[str]:
"""
The ID of the API Management service. Changing this forces a new API Management service Policy to be created.
"""
return pulumi.get(self, "api_management_id")
@property
@pulumi.getter(name="xmlContent")
def xml_content(self) -> pulumi.Output[str]:
"""
The XML Content for this Policy as a string.
"""
return pulumi.get(self, "xml_content")
@property
@pulumi.getter(name="xmlLink")
def xml_link(self) -> pulumi.Output[Optional[str]]:
"""
A link to a Policy XML Document, which must be publicly available.
"""
return pulumi.get(self, "xml_link") | __props__.__dict__["xml_link"] = xml_link
super(Policy, __self__).__init__(
'azure:apimanagement/policy:Policy',
resource_name, |
swimmer_env.py | from rllab.envs.base import Step
from rllab.misc.overrides import overrides
from rllab.envs.mujoco.mujoco_env import MujocoEnv
import numpy as np
from rllab.core.serializable import Serializable
from rllab.misc import logger
from rllab.misc import autoargs
from contextlib import contextmanager
class | (MujocoEnv, Serializable):
FILE = 'swimmer.xml'
@autoargs.arg('ctrl_cost_coeff', type=float,
help='cost coefficient for controls')
def __init__(
self,
ctrl_cost_coeff=1e-2,
*args, **kwargs):
self.ctrl_cost_coeff = ctrl_cost_coeff
super(SwimmerEnv, self).__init__(*args, **kwargs)
Serializable.quick_init(self, locals())
def get_current_obs(self):
return np.concatenate([
self.model.data.qpos.flat,
self.model.data.qvel.flat,
self.get_body_com("torso").flat,
]).reshape(-1)
def step(self, action):
self.forward_dynamics(action)
next_obs = self.get_current_obs()
lb, ub = self.action_bounds
scaling = (ub - lb) * 0.5
ctrl_cost = 0.5 * self.ctrl_cost_coeff * np.sum(
np.square(action / scaling))
forward_reward = self.get_body_comvel("torso")[0]
reward = forward_reward - ctrl_cost
done = False
return Step(next_obs, reward, done)
# @overrides
# def reset_mujoco(self, init_state=None):
# super(SwimmerEnv, self).reset_mujoco(init)
# if init_state is not None:
# idx = self.model.body_names.index("torso")
# self.model.data.com_subtree[idx][0] = init_state[0]
# self.model.data.com_subtree[idx][1] = init_state[1]
@overrides # ignoring the goal
def reset(self, *args, **kwargs):
return super(SwimmerEnv, self).reset(*args, **kwargs) # passing in keyword arguments
@overrides
def log_diagnostics(self, paths):
if len(paths) > 0:
progs = [
path["observations"][-1][-3] - path["observations"][0][-3]
for path in paths
]
logger.record_tabular('AverageForwardProgress', np.mean(progs))
logger.record_tabular('MaxForwardProgress', np.max(progs))
logger.record_tabular('MinForwardProgress', np.min(progs))
logger.record_tabular('StdForwardProgress', np.std(progs))
else:
logger.record_tabular('AverageForwardProgress', np.nan)
logger.record_tabular('MaxForwardProgress', np.nan)
logger.record_tabular('MinForwardProgress', np.nan)
logger.record_tabular('StdForwardProgress', np.nan)
@contextmanager
def set_kill_outside(self):
self.kill_outside = True
try:
yield
finally:
self.kill_outside = False | SwimmerEnv |
yarn.js | module.exports = yarn;
const debug = require('debug')('snyk');
const exec = require('child_process').exec;
function yarn(method, packages, live, cwd, flags) {
flags = flags || [];
if (!packages) {
packages = [];
}
if (!Array.isArray(packages)) {
packages = [packages];
}
method += ' ' + flags.join(' ');
return new Promise((resolve, reject) => {
const cmd = 'yarn ' + method + ' ' + packages.join(' ');
if (!cwd) {
cwd = process.cwd();
} | debug('%s$ %s', cwd, cmd);
if (!live) {
debug('[skipping - dry run]');
return resolve();
}
exec(
cmd,
{
cwd: cwd,
},
(error, stdout, stderr) => {
if (error) {
return reject(error);
}
if (stderr.indexOf('ERR!') !== -1) {
console.error(stderr.trim());
const e = new Error('Yarn update issues: ' + stderr.trim());
e.code = 'FAIL_UPDATE';
return reject(e);
}
debug('yarn %s complete', method);
resolve();
},
);
});
} | |
git.go | // Copyright 2015 The Gogs Authors. All rights reserved.
// Copyright 2017 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package git
import (
"context"
"fmt"
"os/exec"
"runtime"
"strings"
"time"
"github.com/jolheiser/gitea/modules/process"
"github.com/mcuadros/go-version"
)
// Version return this package's current version
func Version() string {
return "0.4.2"
}
var (
// Debug enables verbose logging on everything.
// This should be false in case Gogs starts in SSH mode.
Debug = false
// Prefix the log prefix
Prefix = "[git-module] "
// GitVersionRequired is the minimum Git version required
GitVersionRequired = "1.7.2"
// GitExecutable is the command name of git
// Could be updated to an absolute path while initialization
GitExecutable = "git"
// DefaultContext is the default context to run git commands in
DefaultContext = context.Background()
gitVersion string
)
func log(format string, args ...interface{}) {
if !Debug {
return
}
fmt.Print(Prefix)
if len(args) == 0 {
fmt.Println(format)
} else {
fmt.Printf(format+"\n", args...)
}
}
// BinVersion returns current Git version from shell.
func BinVersion() (string, error) |
// SetExecutablePath changes the path of git executable and checks the file permission and version.
func SetExecutablePath(path string) error {
// If path is empty, we use the default value of GitExecutable "git" to search for the location of git.
if path != "" {
GitExecutable = path
}
absPath, err := exec.LookPath(GitExecutable)
if err != nil {
return fmt.Errorf("Git not found: %v", err)
}
GitExecutable = absPath
gitVersion, err := BinVersion()
if err != nil {
return fmt.Errorf("Git version missing: %v", err)
}
if version.Compare(gitVersion, GitVersionRequired, "<") {
return fmt.Errorf("Git version not supported. Requires version > %v", GitVersionRequired)
}
return nil
}
// Init initializes git module
func Init(ctx context.Context) error {
DefaultContext = ctx
// Git requires setting user.name and user.email in order to commit changes.
for configKey, defaultValue := range map[string]string{"user.name": "Gitea", "user.email": "[email protected]"} {
if stdout, stderr, err := process.GetManager().Exec("git.Init(get setting)", GitExecutable, "config", "--get", configKey); err != nil || strings.TrimSpace(stdout) == "" {
// ExitError indicates this config is not set
if _, ok := err.(*exec.ExitError); ok || strings.TrimSpace(stdout) == "" {
if _, stderr, gerr := process.GetManager().Exec("git.Init(set "+configKey+")", "git", "config", "--global", configKey, defaultValue); gerr != nil {
return fmt.Errorf("Failed to set git %s(%s): %s", configKey, gerr, stderr)
}
} else {
return fmt.Errorf("Failed to get git %s(%s): %s", configKey, err, stderr)
}
}
}
// Set git some configurations.
if _, stderr, err := process.GetManager().Exec("git.Init(git config --global core.quotepath false)",
GitExecutable, "config", "--global", "core.quotepath", "false"); err != nil {
return fmt.Errorf("Failed to execute 'git config --global core.quotepath false': %s", stderr)
}
if version.Compare(gitVersion, "2.18", ">=") {
if _, stderr, err := process.GetManager().Exec("git.Init(git config --global core.commitGraph true)",
GitExecutable, "config", "--global", "core.commitGraph", "true"); err != nil {
return fmt.Errorf("Failed to execute 'git config --global core.commitGraph true': %s", stderr)
}
if _, stderr, err := process.GetManager().Exec("git.Init(git config --global gc.writeCommitGraph true)",
GitExecutable, "config", "--global", "gc.writeCommitGraph", "true"); err != nil {
return fmt.Errorf("Failed to execute 'git config --global gc.writeCommitGraph true': %s", stderr)
}
}
if runtime.GOOS == "windows" {
if _, stderr, err := process.GetManager().Exec("git.Init(git config --global core.longpaths true)",
GitExecutable, "config", "--global", "core.longpaths", "true"); err != nil {
return fmt.Errorf("Failed to execute 'git config --global core.longpaths true': %s", stderr)
}
}
return nil
}
// Fsck verifies the connectivity and validity of the objects in the database
func Fsck(repoPath string, timeout time.Duration, args ...string) error {
// Make sure timeout makes sense.
if timeout <= 0 {
timeout = -1
}
_, err := NewCommand("fsck").AddArguments(args...).RunInDirTimeout(timeout, repoPath)
return err
}
| {
if len(gitVersion) > 0 {
return gitVersion, nil
}
stdout, err := NewCommand("version").Run()
if err != nil {
return "", err
}
fields := strings.Fields(stdout)
if len(fields) < 3 {
return "", fmt.Errorf("not enough output: %s", stdout)
}
// Handle special case on Windows.
i := strings.Index(fields[2], "windows")
if i >= 1 {
gitVersion = fields[2][:i-1]
return gitVersion, nil
}
gitVersion = fields[2]
return gitVersion, nil
} |
line6.py | #!/usr/bin/env python3
# Some useful POD-Variables
# The Program names:
PROGRAMS = [ "1A", "1B", "1C", "1D",
"2A", "2B", "2C", "2D",
"3A", "3B", "3C", "3D",
"4A", "4B", "4C", "4D",
"5A", "5B", "5C", "5D",
"6A", "6B", "6C", "6D",
"7A", "7B", "7C", "7D",
"8A", "8B", "8C", "8D",
"9A", "9B", "9C", "9D" ]
# The Amp Models:
amp_names = [
'Tube Preamp',
'POD Clean Line 6',
'POD Crunch Line 6',
'POD Drive Line 6',
'POD Layer Line 6',
'Small Tweed',
'Tweed Blues',
'Black Panel',
'Modern Class A',
'Brit Class A',
'Brit Blues',
'Brit Classic',
'Brit Hi Gain',
'Rectified ’94',
'Modern Hi Gain',
'Fuzz Box',
'Jazz Clean',
'Boutique #1',
'Boutique #2',
'Brit Class A #2',
'Brit Class A #3',
'Small Tweed #2',
'Black Panel #2',
'Boutique #3',
'California Crunch #1',
'California Crunch #2',
'Rectified #2',
'Modern Hi Gain #2',
'Line 6 Twang',
'Line 6 Crunch #2',
'Line 6 Blues',
'Line 6 Insane' ]
# The Cab names:
cab_names = [
"1x 8 ’60 Fender Tweed Champ",
"1x12 ’52 Fender Tweed Deluxe",
"1x12 ’60 Vox AC15",
"1x12 ’64 Fender Blackface Deluxe", | "1x12 ’98 Line 6 Flextone",
"2x12 ’65 Fender Blackface Twin",
"2x12 ’67 VOX AC30",
"2x12 ’95 Matchless Chieftain",
"2x12 ’98 Pod custom 2x12",
"4x10 ’59 Fender Bassman",
"4x10 ’98 Pod custom 4x10 cab",
"4x12 ’96 Marshall with V30s",
"4x12 ’78 Marshall with 70s",
"4x12 ’97 Marshall off axis",
"4x12 ’98 Pod custom 4x12",
"No Cabinet" ]
# The effect types:
fx_names = [
"Chorus2",
"Flanger1",
"Rotary",
"Flanger2",
"Delay/Chorus1",
"Delay/Tremolo",
"Delay",
"Delay/Comp",
"Chorus1",
"Tremolo",
"Bypass",
"Compressor",
"Delay/Chorus2",
"Delay/Flanger1",
"Delay/Swell",
"Delay/Flanger2" ]
cc_commands = {
"AmpModel (0-32)": 12, # 0-32 (0=Tube Preamp,...)
"Drive": 13, # 0-127
"Bass": 14, # 0-127
"Mid": 15, # 0-127
"Treble": 16, # 0-127
"BrightSwitch (0-63: OFF, 64-127: ON)": 73, # 0-63: OFF, 64-127: ON
"Channel Vol": 17, # 0-127
"Presence": 21, # 0-127
"Noise Gate (0-63: OFF, 64-127: ON)": 22, # 0-63: OFF, 64-127: ON
"GateThreshhold": 23, # 0-127
"GateDecay": 24, # 0-127
"Effect": 19, # 0-15 (0=Bypass,...)
"EffectTweak": 1, # 0-127
"Distortion (0-63: OFF, 64-127: ON)": 25, # 0-63: OFF, 64-127: ON
"DriveBoost (0-63: OFF, 64-127: ON)": 26, # 0-63: OFF, 64-127: ON
"Presence (0-63: OFF, 64-127: ON)": 27, # 0-63: OFF, 64-127: ON
"Delay (0-63: OFF, 64-127: ON)": 28, # 0-63: OFF, 64-127: ON
"DelayTime": 30, # 0-127 = 0-3150ms
"DelayTime2": 62, # 0-127 (Extra precision (???))
"DelayRepeats": 32, # 0-127
"DelayLevel": 34, # 0-127
"Reverb (0-63: OFF, 64-127: ON)": 36, # 0-63: OFF; 64-127: ON
"ReverbType (0-63: Spring, 64-127: Hall)": 37, # 0-63: SPRING, 64-127: HALL
"ReverbDecay": 38, # 0-127
"ReverbTone": 39, # 0-127
"ReverbDiffusion": 40, # 0-127
"ReverbDensity": 41, # 0-127
"ReverbLevel": 18, # 0-127
"CompressionRatio": 42, # 0-21=OFF, 22-44=1.4:1, 45-67=2:1, 68-90=3:1, 91-113=6:1, 114-127=INF
"Wah (0-63: OFF, 64-127: ON)": 43, # 0-63: OFF, 64-127: ON
"WahPedal": 4, # 0-127 (Pedal Position)
"WahBottom": 44, # 0-127 (Bottom frequency)
"WahTop": 45, # 0-127 (Top frequency)
"Volume": 7, # 0-127 (Volume Pedal)
"VolumeMin": 46, # 0-127 ???
"VolumePrePost (0-63: Pre Tube, 64-127: Post Tube)": 47, # 0-63: PRE TUBE, 64-127: POST TUBE
"VolSwell (0-63: OFF, 64-127: ON)": 48, # 0-63: OFF, 64-127: ON
"VolSwellRamp": 49, # 0-127
#"TapTempo": 64, # 64-127 = A TAP (=sending 2 in a second sets to 120bpm?)
"Modulation (0-63: OFF, 64-127: ON)": 50, # 0-63: OFF, 64-127: ON (Chorus/Rotary/Tremolo)
"Speed": 51, # 0-127 (Chorus/Flanger)
"Depth": 52, # 0-127 (Chorus/Flanger)
"Feedback": 53, # 0-63: NEGATIVE: 64-127: POSITIVE
"ChorusPreDelay": 54, # 0-127
"RotarySpeed": 55, # 0-127
"RotaryMaxSpeed": 56, # 0-127
"RotaryMinSpeed": 57, # 0-127
"TremoloSpeed": 58, # 0-127
"TremoloDepth": 59, # 0-127
"CabinetType (0-15)": 71, # 0-15 (0=No Cab, ...)
"AIRAmbienceLevel": 72 # 0-127
}
compression_values = [ [ 0, "Off" ],
[ 22, "1.4:1" ],
[ 45, "2:1" ],
[ 68, "3:1" ],
[ 91, "6:1" ],
[ 114, "INF" ] ]
reverb_types = [ [ 0, "Spring" ], [ 64, "Hall" ] ]
volume_pos = [ [ 0, "Pre-Tube" ], [ 64, "Post-Tube" ] ] | |
test_trustworthiness.py | # Copyright (c) 2018-2019, NVIDIA CORPORATION.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
from sklearn.manifold.t_sne import trustworthiness as sklearn_trustworthiness
from cuml.metrics import trustworthiness as cuml_trustworthiness
from sklearn.datasets.samples_generator import make_blobs
from umap import UMAP
import cudf
import numpy as np
@pytest.mark.parametrize('input_type', ['ndarray'])
@pytest.mark.parametrize('n_samples', [10, 100])
@pytest.mark.parametrize('n_features', [10, 100])
@pytest.mark.parametrize('n_components', [2, 8]) | def test_trustworthiness(input_type, n_samples, n_features, n_components):
centers = round(n_samples*0.4)
X, y = make_blobs(n_samples=n_samples, centers=centers,
n_features=n_features)
X_embedded = \
UMAP(n_components=n_components).fit_transform(X)
X = X.astype(np.float32)
X_embedded = X_embedded.astype(np.float32)
if input_type == 'dataframe':
gdf = cudf.DataFrame()
for i in range(X.shape[1]):
gdf[str(i)] = np.asarray(X[:, i], dtype=np.float32)
gdf_embedded = cudf.DataFrame()
for i in range(X_embedded.shape[1]):
gdf_embedded[str(i)] = np.asarray(X_embedded[:, i],
dtype=np.float32)
score = cuml_trustworthiness(gdf, gdf_embedded)
else:
score = cuml_trustworthiness(X, X_embedded)
sk_score = sklearn_trustworthiness(X, X_embedded)
eps = 0.001
assert (sk_score * (1 - eps) <= score and
score <= sk_score * (1 + eps))
# assert cu_score == sk_score ideally | |
parser.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
:mod:`Quantulum` parser.
"""
# Standard library
import re
import logging
from fractions import Fraction
from collections import defaultdict
from math import pow
# Quantulum
from . import load
from . import regex as reg
from . import classes as cls
from . import disambiguate as dis
from . import language
def _get_parser(lang='en_US'):
"""
Get parser module for given language
:param lang:
:return:
"""
return language.get('parser', lang)
###############################################################################
def extract_spellout_values(text, lang='en_US'):
"""
Convert spelled out numbers in a given text to digits.
"""
return _get_parser(lang).extract_spellout_values(text)
###############################################################################
def substitute_values(text, values):
"""
Convert spelled out numbers in a given text to digits.
"""
shift, final_text, shifts = 0, text, defaultdict(int)
for value in values:
first = value['old_span'][0] + shift
second = value['old_span'][1] + shift
final_text = final_text[0:first] + value['new_surface'] + \
final_text[second:]
shift += len(value['new_surface']) - len(value['old_surface'])
for char in range(first + 1, len(final_text)):
shifts[char] = shift
logging.debug('Text after numeric conversion: "%s"', final_text)
return final_text, shifts
###############################################################################
def get_values(item, lang='en_US'):
"""
Extract value from regex hit.
"""
def callback(pattern):
return ' %s' % (reg.unicode_fractions()[pattern.group(0)])
fracs = r'|'.join(reg.unicode_fractions())
value = item.group('value')
# Remove grouping operators
value = re.sub(
r'(?<=\d)[%s](?=\d{3})' % reg.grouping_operators_regex(lang), '',
value)
# Replace unusual exponents by e (including e)
value = re.sub(
r'(?<=\d)(%s)(e|E|10)\^?' % reg.multiplication_operators_regex(lang),
'e', value)
# calculate other exponents
value, factors = resolve_exponents(value)
logging.debug("After exponent resolution: {}".format(value))
value = re.sub(fracs, callback, value, re.IGNORECASE)
range_separator = re.findall(
r'\d+ ?((?:-\ )?(?:%s)) ?\d' % '|'.join(reg.ranges(lang)), value)
uncer_separator = re.findall(
r'\d+ ?(%s) ?\d' % '|'.join(reg.uncertainties(lang)), value)
fract_separator = re.findall(r'\d+/\d+', value)
value = re.sub(' +', ' ', value)
uncertainty = None
if range_separator:
# A range just describes an uncertain quantity
values = value.split(range_separator[0])
values = [
float(re.sub(r'-$', '', v)) * factors[i]
for i, v in enumerate(values)
]
if values[1] < values[0]:
raise ValueError(
"Invalid range, with second item being smaller than the first "
"item"
)
mean = sum(values) / len(values)
uncertainty = mean - min(values)
values = [mean]
elif uncer_separator:
values = [float(i) for i in value.split(uncer_separator[0])]
uncertainty = values[1] * factors[1]
values = [values[0] * factors[0]]
elif fract_separator:
values = value.split()
try:
if len(values) > 1:
values = [
float(values[0]) * factors[0] + float(Fraction(values[1]))
]
else:
values = [float(Fraction(values[0]))]
except ZeroDivisionError as e:
raise ValueError('{} is not a number'.format(values[0]), e)
else:
values = [float(re.sub(r'-$', '', value)) * factors[0]]
logging.debug('\tUncertainty: %s', uncertainty)
logging.debug('\tValues: %s', values)
return uncertainty, values
###############################################################################
def resolve_exponents(value, lang='en_US'):
"""Resolve unusual exponents (like 2^4) and return substituted string and
factor
Params:
value: str, string with only one value
Returns:
str, string with basis and exponent removed
array of float, factors for multiplication
"""
factors = []
matches = re.finditer(
reg.number_pattern_groups(lang), value, re.IGNORECASE | re.VERBOSE)
for item in matches:
if item.group('base') and item.group('exponent'):
base = item.group('base')
exp = item.group('exponent')
if base in ['e', 'E']:
# already handled by float
factors.append(1)
continue
# exp = '10'
# Expect that in a pure decimal base,
# either ^ or superscript notation is used
if re.match(r'\d+\^?', base):
if not ('^' in base or re.match(
r'[%s]' % reg.unicode_superscript_regex(), exp)):
factors.append(1)
continue
for superscript, substitute in reg.unicode_superscript().items():
exp.replace(superscript, substitute)
exp = float(exp)
base = float(base.replace('^', ''))
factor = pow(base, exp)
stripped = str(value).replace(item.group('scale'), '')
value = stripped
factors.append(factor)
logging.debug("Replaced {} by factor {}".format(
item.group('scale'), factor))
else:
factors.append(1)
continue
return value, factors
###############################################################################
def build_unit_name(dimensions, lang='en_US'):
"""
Build the name of the unit from its dimensions.
"""
name = _get_parser(lang).name_from_dimensions(dimensions)
logging.debug('\tUnit inferred name: %s', name)
return name
###############################################################################
def get_unit_from_dimensions(dimensions, text, lang='en_US'):
"""
Reconcile a unit based on its dimensionality.
"""
key = load.get_key_from_dimensions(dimensions)
try:
unit = load.units(lang).derived[key]
except KeyError:
logging.debug(u'\tCould not find unit for: %s', key)
unit = cls.Unit(
name=build_unit_name(dimensions, lang),
dimensions=dimensions,
entity=get_entity_from_dimensions(dimensions, text, lang))
# Carry on original composition
unit.original_dimensions = dimensions
return unit
def name_from_dimensions(dimensions, lang='en_US'):
"""
Build the name of a unit from its dimensions.
Param:
dimensions: List of dimensions
"""
return _get_parser(lang).name_from_dimensions(dimensions)
def infer_name(unit):
"""
Return unit name based on dimensions
:return: new name of this unit
"""
name = name_from_dimensions(unit.dimensions) if unit.dimensions else None
return name
###############################################################################
def get_entity_from_dimensions(dimensions, text, lang='en_US'):
"""
Infer the underlying entity of a unit (e.g. "volume" for "m^3") based on
its dimensionality.
"""
new_derived = [{
'base': load.units(lang).names[i['base']].entity.name,
'power': i['power']
} for i in dimensions]
final_derived = sorted(new_derived, key=lambda x: x['base'])
key = load.get_key_from_dimensions(final_derived)
ent = dis.disambiguate_entity(key, text, lang)
if ent is None:
logging.debug('\tCould not find entity for: %s', key)
ent = cls.Entity(name='unknown', dimensions=new_derived)
return ent
###############################################################################
def parse_unit(item, unit, slash, lang='en_US'):
"""
Parse surface and power from unit text.
"""
return _get_parser(lang).parse_unit(item, unit, slash)
###############################################################################
def get_unit(item, text, lang='en_US'):
"""
Extract unit from regex hit.
"""
group_units = ['prefix', 'unit1', 'unit2', 'unit3', 'unit4']
group_operators = ['operator1', 'operator2', 'operator3', 'operator4']
# How much of the end is removed because of an "incorrect" regex match
unit_shortening = 0
item_units = [item.group(i) for i in group_units if item.group(i)]
if len(item_units) == 0:
unit = load.units(lang).names['dimensionless']
else:
derived, slash = [], False
multiplication_operator = False
for index in range(0, 5):
unit = item.group(group_units[index])
operator_index = None if index < 1 else group_operators[index - 1]
operator = None if index < 1 else item.group(operator_index)
# disallow spaces as operators in units expressed in their symbols
# Enforce consistency among multiplication and division operators
# Single exceptions are colloquial number abbreviations (5k miles)
if operator in reg.multiplication_operators(lang) or (
operator is None and unit and
not (index == 1 and unit in reg.suffixes(lang))):
if multiplication_operator != operator and not (
index == 1 and str(operator).isspace()):
if multiplication_operator is False:
multiplication_operator = operator
else:
# Cut if inconsistent multiplication operator
# treat the None operator differently - remove the
# whole word of it
if operator is None:
# For this, use the last consistent operator
# (before the current) with a space
# which should always be the preceding operator
derived.pop()
operator_index = group_operators[index - 2]
# Remove (original length - new end) characters
unit_shortening = item.end() - item.start(
operator_index)
logging.debug(
"Because operator inconsistency, cut from "
"operator: '{}', new surface: {}"
.format(
operator, text[item.start():item.end() -
unit_shortening]))
break
# Determine whether a negative power has to be applied to following
# units
if operator and not slash:
slash = any(
i in operator for i in reg.division_operators(lang))
# Determine which unit follows
if unit:
unit_surface, power = parse_unit(item, unit, slash, lang)
base = dis.disambiguate_unit(unit_surface, text, lang)
derived += [{
'base': base,
'power': power,
'surface': unit_surface
}]
unit = get_unit_from_dimensions(derived, text, lang)
logging.debug('\tUnit: %s', unit)
logging.debug('\tEntity: %s', unit.entity)
return unit, unit_shortening
###############################################################################
def get_surface(shifts, orig_text, item, text, unit_shortening=0):
|
###############################################################################
def is_quote_artifact(orig_text, span):
"""
Distinguish between quotes and units.
"""
res = False
cursor = re.finditer(r'["\'][^ .,:;?!()*+-].*?["\']', orig_text)
for item in cursor:
if span[0] <= item.span()[1] <= span[1]:
res = item
break
return res
###############################################################################
def build_quantity(orig_text,
text,
item,
values,
unit,
surface,
span,
uncert,
lang='en_US'):
"""
Build a Quantity object out of extracted information.
Takes care of caveats and common errors
"""
return _get_parser(lang).build_quantity(orig_text, text, item, values,
unit, surface, span, uncert)
###############################################################################
def clean_text(text, lang='en_US'):
"""
Clean text before parsing.
"""
# Replace a few nasty unicode characters with their ASCII equivalent
maps = {'×': 'x', '–': '-', '−': '-'}
for element in maps:
text = text.replace(element, maps[element])
# Language specific cleaning
text = _get_parser(lang).clean_text(text)
logging.debug('Clean text: "%s"', text)
return text
###############################################################################
def parse(text, lang='en_US', verbose=False):
"""
Extract all quantities from unstructured text.
"""
log_format = '%(asctime)s --- %(message)s'
logging.basicConfig(format=log_format)
root = logging.getLogger()
if verbose: # pragma: no cover
level = root.level
root.setLevel(logging.DEBUG)
logging.debug('Verbose mode')
orig_text = text
logging.debug('Original text: "%s"', orig_text)
text = clean_text(text, lang)
values = extract_spellout_values(text, lang)
text, shifts = substitute_values(text, values)
quantities = []
for item in reg.units_regex(lang).finditer(text):
groups = dict(
[i for i in item.groupdict().items() if i[1] and i[1].strip()])
logging.debug(u'Quantity found: %s', groups)
try:
uncert, values = get_values(item, lang)
unit, unit_shortening = get_unit(item, text)
surface, span = get_surface(shifts, orig_text, item, text,
unit_shortening)
objs = build_quantity(orig_text, text, item, values, unit, surface,
span, uncert, lang)
if objs is not None:
quantities += objs
except ValueError as err:
logging.debug('Could not parse quantity: %s', err)
if verbose: # pragma: no cover
root.level = level
return quantities
###############################################################################
def inline_parse(text, verbose=False): # pragma: no cover
"""
Extract all quantities from unstructured text.
"""
parsed = parse(text, verbose=verbose)
shift = 0
for quantity in parsed:
index = quantity.span[1] + shift
to_add = u' {' + str(quantity) + u'}'
text = text[0:index] + to_add + text[index:]
shift += len(to_add)
return text
###############################################################################
def inline_parse_and_replace(text, lang='en_US',
verbose=False): # pragma: no cover
"""
Parse text and replace with the standardised quantities as string
"""
parsed = parse(text, lang=lang, verbose=verbose)
shift = 0
for quantity in parsed:
index_start = quantity.span[0] + shift
index_end = quantity.span[1] + shift
to_add = str(quantity)
text = text[0:index_start] + to_add + text[index_end:]
shift += len(to_add) - (quantity.span[1] - quantity.span[0])
return text
###############################################################################
def inline_parse_and_expand(text, lang='en_US', verbose=False):
"""
Parse text and replace qunatities with speakable version
"""
parsed = parse(text, verbose=verbose)
shift = 0
for quantity in parsed:
index_start = quantity.span[0] + shift
index_end = quantity.span[1] + shift
to_add = quantity.to_spoken()
text = text[0:index_start] + to_add + text[index_end:]
shift += len(to_add) - (quantity.span[1] - quantity.span[0])
return text
| """
Extract surface from regex hit.
"""
# handle cut end
span = (item.start(), item.end() - unit_shortening)
logging.debug('\tInitial span: %s ("%s")', span, text[span[0]:span[1]])
real_span = (span[0] - shifts[span[0]], span[1] - shifts[span[1] - 1])
surface = orig_text[real_span[0]:real_span[1]]
logging.debug('\tShifted span: %s ("%s")', real_span, surface)
while any(surface.endswith(i) for i in [' ', '-']):
surface = surface[:-1]
real_span = (real_span[0], real_span[1] - 1)
while surface.startswith(' '):
surface = surface[1:]
real_span = (real_span[0] + 1, real_span[1])
logging.debug('\tFinal span: %s ("%s")', real_span, surface)
return surface, real_span |
ops.go | package network
import (
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/network"
)
// WithDriver sets the driver of the network
func WithDriver(driver string) func(*types.NetworkCreate) {
return func(n *types.NetworkCreate) {
n.Driver = driver
}
}
// WithIPv6 Enables IPv6 on the network
func WithIPv6() func(*types.NetworkCreate) {
return func(n *types.NetworkCreate) {
n.EnableIPv6 = true
}
}
// WithMacvlan sets the network as macvlan with the specified parent
func WithMacvlan(parent string) func(*types.NetworkCreate) |
// WithOption adds the specified key/value pair to network's options
func WithOption(key, value string) func(*types.NetworkCreate) {
return func(n *types.NetworkCreate) {
if n.Options == nil {
n.Options = map[string]string{}
}
n.Options[key] = value
}
}
// WithIPAM adds an IPAM with the specified Subnet and Gateway to the network
func WithIPAM(subnet, gateway string) func(*types.NetworkCreate) {
return func(n *types.NetworkCreate) {
if n.IPAM == nil {
n.IPAM = &network.IPAM{}
}
n.IPAM.Config = append(n.IPAM.Config, network.IPAMConfig{
Subnet: subnet,
Gateway: gateway,
AuxAddress: map[string]string{},
})
}
}
| {
return func(n *types.NetworkCreate) {
n.Driver = "macvlan"
if parent != "" {
n.Options = map[string]string{
"parent": parent,
}
}
}
} |
run.py | #! /usr/bin/python2
import subprocess
import sys
import os
import time
from subprocess import PIPE
import socket
default_params = ''
output_file_prefix = 'output'
if len(sys.argv) > 1:
output_file_prefix = sys.argv[1]
#
# http://stackoverflow.com/questions/4675728/redirect-stdout-to-a-file-in-python
#
class Logger(object):
def __init__(self, filename="Default.log"):
self.terminal = sys.stdout
self.log = open(filename, "w")
def write(self, message):
self.terminal.write(message)
self.log.write(message)
#
# SCENARIO
#
# 0: radial dam break
# 1: gaussian
# 2: balanced steady state u
# 3: balanced steady state v
# 4: diamond initial condition
# 5: waves
scenario_name = "Sin*cos waves"
curdir_name = os.getcwd()
print ("Current working directory: "+curdir_name)
os.chdir('../../../')
if socket.gethostname() == "inwest":
print "Running on inwest"
os.environ['OMP_PROC_BIND'] = "TRUE"
os.environ['OMP_NUM_THREADS'] = "10"
elif socket.gethostname() == "martinium":
print "Running on martinium"
os.environ['OMP_PROC_BIND'] = "TRUE"
os.environ['OMP_NUM_THREADS'] = "4"
subprocess.call('scons --program=swe_rexi --plane-spectral-space=enable --plane-spectral-dealiasing=disable --threading=off --rexi-parallel-sum=enable --mode=release '.split(' '), shell=False)
binary = './build/swe_rexi_spectral_libfft_rexipar_gnu_release'
if not os.path.isfile(binary):
print "Binary "+binary+" not found"
sys.exit(1)
#
# run for 1 seconds
#
max_time = 1
#
# order of time step for RK
# Use order 4 to make time errors very small to make the spatial error dominate
#
timestep_order = 4
#
# default params
#
default_params += ' -X 1 -Y 1 --compute-error 1 '
#
# Use higher-order time stepping?
#
default_params += ' -R '+str(timestep_order)
#
# waves
#
W_list = [i for i in range(1, 8)]
#
# time step size for coarse time steps
#
dt_list = [16/pow(2.0, i) for i in range(18, 0, -1)]
# resolutions
#N_list = [16, 32, 64, 128, 256, 512]
#N_list = [16, 32, 64, 128, 256]
N_list = [16, 32, 64, 128]
# M values for REXI
M_list = []
M = 16
while M < 40000:
M_list.append(M)
M *= 2;
# http://math.boisestate.edu/~wright/research/FlyerEtAl2012.pdf
hyperviscosity = {}
for n in N_list:
hyperviscosity[n] = 4.*pow(float(n), float(-4))
hyperviscosity[n] = 0
print "Time step size for coarse time step: "+str(dt_list)
print "Time step order: "+str(timestep_order)
print "Search range for W: "+str(W_list)
print "Search range for M: "+str(M_list)
print "Used hyperviscosity: "+str(hyperviscosity)
def extract_errors(output):
match_list = [
'DIAGNOSTICS ANALYTICAL RMS H:',
'DIAGNOSTICS ANALYTICAL RMS U:',
'DIAGNOSTICS ANALYTICAL RMS V:',
'DIAGNOSTICS ANALYTICAL MAXABS H:',
'DIAGNOSTICS ANALYTICAL MAXABS U:',
'DIAGNOSTICS ANALYTICAL MAXABS V:'
]
vals = ["x" for i in range(6)]
ol = output.splitlines(True)
for o in ol:
o = o.replace('\n', '')
o = o.replace('\r', '')
for i in range(0, len(match_list)):
m = match_list[i]
if o[0:len(m)] == m:
vals[i] = o[len(m)+1:]
return vals
print
print "Running with time stepping mode 1 (search) L_rms:"
| eps = 1
for n in N_list:
print
print "Creating study with resolution "+str(n)+"x"+str(n)
filename = curdir_name+'/'+output_file_prefix+"_n"+str(n)+"_dt"+str(dt)+".csv"
print "Writing output to "+filename
fd = open(filename, "w")
fd.write("#TI res="+str(n)+"x"+str(n)+", dt="+str(dt)+", DT="+str(max_time)+", "+scenario_name+"\n")
fd.write("#TX REXI parameter M\n")
fd.write("#TY Wave parameter W\n")
fd.write("W\M")
for M in M_list:
fd.write("\t"+str(M))
fd.write("\n")
for w in W_list:
fd.write(str(w))
fd.flush()
for M in M_list:
command = binary+' '+default_params
command += ' -C '+str(-dt)
command += ' --timestepping-mode 1 '
command += ' -N '+str(n)
command += ' --rexi-h '+str(h)
command += ' --rexi-m '+str(M)
command += ' -g '+str(eps)
command += ' -H '+str(eps)
command += ' -f '+str(eps)
command += ' -t '+str(dt)
command += ' -S 1 '
command += ' --use-specdiff-for-complex-array 1 '
command += " --initial-freq-x-mul="+str(2*w)+" --initial-freq-y-mul="+str(1*w)+" "
p = subprocess.Popen(command.split(' '), stdout=PIPE, stderr=PIPE, env=os.environ)
output, err = p.communicate()
print command
vals = extract_errors(output)
fd.write("\t"+str(vals[0]))
fd.flush()
print vals
fd.write("\n")
print("FIN") | dt = max_time
h = 0.2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.