file_name
stringlengths 3
137
| prefix
stringlengths 0
918k
| suffix
stringlengths 0
962k
| middle
stringlengths 0
812k
|
---|---|---|---|
Header.mock.test.js | /*
Copyright 2020-2021 Lowdefy, 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 { runMockRenderTests } from '@lowdefy/block-dev';
import Block from './Header.js';
import examples from './examples.yaml';
import schema from './schema.json';
const testConfig = {
validation: true,
required: true,
values: [],
};
jest.mock('antd', () => {
const comp = jest.fn(() => 'mocked');
comp.Header = jest.fn(() => 'mocked');
return {
Layout: comp,
};
});
const mocks = [
{
getMockFns: async () => {
const antd = await import('antd'); | return Block.default;
},
name: 'Header',
},
];
runMockRenderTests({ Block, examples, mocks, schema, testConfig }); | return [antd.Layout];
},
getBlock: async () => {
const Block = await import('./Header.js'); |
pwrstat.rs | #[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::PWRSTAT {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = r" Value of the field"]
pub struct RESERVED10R {
bits: u32,
}
impl RESERVED10R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
}
#[doc = r" Value of the field"]
pub struct AUX_PWR_DWNR {
bits: bool,
}
impl AUX_PWR_DWNR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct RESERVED7R {
bits: u8,
}
impl RESERVED7R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Value of the field"]
pub struct JTAG_PD_ONR {
bits: bool,
}
impl JTAG_PD_ONR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct AUX_PD_ONR {
bits: bool,
}
impl AUX_PD_ONR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct MCU_PD_ONR {
bits: bool,
}
impl MCU_PD_ONR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct RESERVED3R {
bits: bool,
}
impl RESERVED3R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct AUX_BUS_CONNECTEDR {
bits: bool,
}
impl AUX_BUS_CONNECTEDR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct AUX_RESET_DONER {
bits: bool,
}
impl AUX_RESET_DONER {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Value of the field"]
pub struct RESERVED0R {
bits: bool,
}
impl RESERVED0R {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r" Proxy"]
pub struct _RESERVED10W<'a> {
w: &'a mut W,
}
impl<'a> _RESERVED10W<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u32) -> &'a mut W {
const MASK: u32 = 4194303;
const OFFSET: u8 = 10;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _AUX_PWR_DWNW<'a> {
w: &'a mut W,
}
impl<'a> _AUX_PWR_DWNW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 9;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _RESERVED7W<'a> {
w: &'a mut W,
}
impl<'a> _RESERVED7W<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 7;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _JTAG_PD_ONW<'a> {
w: &'a mut W,
}
impl<'a> _JTAG_PD_ONW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 6;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _AUX_PD_ONW<'a> {
w: &'a mut W,
}
impl<'a> _AUX_PD_ONW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 5;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _MCU_PD_ONW<'a> {
w: &'a mut W,
}
impl<'a> _MCU_PD_ONW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 4;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _RESERVED3W<'a> {
w: &'a mut W,
}
impl<'a> _RESERVED3W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 3;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _AUX_BUS_CONNECTEDW<'a> {
w: &'a mut W,
}
impl<'a> _AUX_BUS_CONNECTEDW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 2;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _AUX_RESET_DONEW<'a> {
w: &'a mut W,
}
impl<'a> _AUX_RESET_DONEW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 1;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _RESERVED0W<'a> {
w: &'a mut W,
}
impl<'a> _RESERVED0W<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 10:31 - 31:10\\] Software should not rely on the value of a reserved. Writing any other value than the reset value may result in undefined behavior."]
#[inline]
pub fn reserved10(&self) -> RESERVED10R {
let bits = {
const MASK: u32 = 4194303;
const OFFSET: u8 = 10;
((self.bits >> OFFSET) & MASK as u32) as u32
};
RESERVED10R { bits }
}
#[doc = "Bit 9 - 9:9\\] Indicates the AUX powerdown state when AUX domain is powered up. 0: Active mode 1: AUX Powerdown request has been granted"]
#[inline]
pub fn aux_pwr_dwn(&self) -> AUX_PWR_DWNR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 9;
((self.bits >> OFFSET) & MASK as u32) != 0
};
AUX_PWR_DWNR { bits }
}
#[doc = "Bits 7:8 - 8:7\\] Software should not rely on the value of a reserved. Writing any other value than the reset value may result in undefined behavior."]
#[inline]
pub fn reserved7(&self) -> RESERVED7R {
let bits = {
const MASK: u8 = 3;
const OFFSET: u8 = 7;
((self.bits >> OFFSET) & MASK as u32) as u8
};
RESERVED7R { bits }
}
#[doc = "Bit 6 - 6:6\\] Indicates JTAG power state: 0: JTAG is powered off 1: JTAG is powered on"]
#[inline]
pub fn jtag_pd_on(&self) -> JTAG_PD_ONR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 6;
((self.bits >> OFFSET) & MASK as u32) != 0
};
JTAG_PD_ONR { bits }
}
#[doc = "Bit 5 - 5:5\\] Indicates AUX power state: 0: AUX is not ready for use ( may be powered off or in power state transition ) 1: AUX is powered on, connected to bus and ready for use,"]
#[inline]
pub fn aux_pd_on(&self) -> AUX_PD_ONR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 5;
((self.bits >> OFFSET) & MASK as u32) != 0
};
AUX_PD_ONR { bits }
}
#[doc = "Bit 4 - 4:4\\] Indicates MCU power state: 0: MCU Power sequencing is not yet finalized and MCU_AONIF registers may not be reliable 1: MCU Power sequencing is finalized and all MCU_AONIF registers are reliable"]
#[inline]
pub fn mcu_pd_on(&self) -> MCU_PD_ONR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 4;
((self.bits >> OFFSET) & MASK as u32) != 0
};
MCU_PD_ONR { bits }
}
#[doc = "Bit 3 - 3:3\\] Software should not rely on the value of a reserved. Writing any other value than the reset value may result in undefined behavior."]
#[inline]
pub fn reserved3(&self) -> RESERVED3R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 3;
((self.bits >> OFFSET) & MASK as u32) != 0
};
RESERVED3R { bits }
}
#[doc = "Bit 2 - 2:2\\] Indicates that AUX Bus is connected: 0: AUX bus is not connected 1: AUX bus is connected ( idle_ack = 0 )"]
#[inline]
pub fn aux_bus_connected(&self) -> AUX_BUS_CONNECTEDR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 2;
((self.bits >> OFFSET) & MASK as u32) != 0
};
AUX_BUS_CONNECTEDR { bits }
}
#[doc = "Bit 1 - 1:1\\] Indicates Reset Done from AUX: 0: AUX is being reset 1: AUX reset is released"]
#[inline]
pub fn aux_reset_done(&self) -> AUX_RESET_DONER {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 1;
((self.bits >> OFFSET) & MASK as u32) != 0
};
AUX_RESET_DONER { bits }
}
#[doc = "Bit 0 - 0:0\\] Software should not rely on the value of a reserved. Writing any other value than the reset value may result in undefined behavior."]
#[inline]
pub fn reserved0(&self) -> RESERVED0R {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) != 0
};
RESERVED0R { bits }
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 58720256 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { | self
}
#[doc = "Bits 10:31 - 31:10\\] Software should not rely on the value of a reserved. Writing any other value than the reset value may result in undefined behavior."]
#[inline]
pub fn reserved10(&mut self) -> _RESERVED10W {
_RESERVED10W { w: self }
}
#[doc = "Bit 9 - 9:9\\] Indicates the AUX powerdown state when AUX domain is powered up. 0: Active mode 1: AUX Powerdown request has been granted"]
#[inline]
pub fn aux_pwr_dwn(&mut self) -> _AUX_PWR_DWNW {
_AUX_PWR_DWNW { w: self }
}
#[doc = "Bits 7:8 - 8:7\\] Software should not rely on the value of a reserved. Writing any other value than the reset value may result in undefined behavior."]
#[inline]
pub fn reserved7(&mut self) -> _RESERVED7W {
_RESERVED7W { w: self }
}
#[doc = "Bit 6 - 6:6\\] Indicates JTAG power state: 0: JTAG is powered off 1: JTAG is powered on"]
#[inline]
pub fn jtag_pd_on(&mut self) -> _JTAG_PD_ONW {
_JTAG_PD_ONW { w: self }
}
#[doc = "Bit 5 - 5:5\\] Indicates AUX power state: 0: AUX is not ready for use ( may be powered off or in power state transition ) 1: AUX is powered on, connected to bus and ready for use,"]
#[inline]
pub fn aux_pd_on(&mut self) -> _AUX_PD_ONW {
_AUX_PD_ONW { w: self }
}
#[doc = "Bit 4 - 4:4\\] Indicates MCU power state: 0: MCU Power sequencing is not yet finalized and MCU_AONIF registers may not be reliable 1: MCU Power sequencing is finalized and all MCU_AONIF registers are reliable"]
#[inline]
pub fn mcu_pd_on(&mut self) -> _MCU_PD_ONW {
_MCU_PD_ONW { w: self }
}
#[doc = "Bit 3 - 3:3\\] Software should not rely on the value of a reserved. Writing any other value than the reset value may result in undefined behavior."]
#[inline]
pub fn reserved3(&mut self) -> _RESERVED3W {
_RESERVED3W { w: self }
}
#[doc = "Bit 2 - 2:2\\] Indicates that AUX Bus is connected: 0: AUX bus is not connected 1: AUX bus is connected ( idle_ack = 0 )"]
#[inline]
pub fn aux_bus_connected(&mut self) -> _AUX_BUS_CONNECTEDW {
_AUX_BUS_CONNECTEDW { w: self }
}
#[doc = "Bit 1 - 1:1\\] Indicates Reset Done from AUX: 0: AUX is being reset 1: AUX reset is released"]
#[inline]
pub fn aux_reset_done(&mut self) -> _AUX_RESET_DONEW {
_AUX_RESET_DONEW { w: self }
}
#[doc = "Bit 0 - 0:0\\] Software should not rely on the value of a reserved. Writing any other value than the reset value may result in undefined behavior."]
#[inline]
pub fn reserved0(&mut self) -> _RESERVED0W {
_RESERVED0W { w: self }
}
} | self.bits = bits; |
icon_settings_system_daydream.rs |
pub struct IconSettingsSystemDaydream {
props: crate::Props,
}
impl yew::Component for IconSettingsSystemDaydream {
type Properties = crate::Props;
type Message = ();
fn create(props: Self::Properties, _: yew::prelude::ComponentLink<Self>) -> Self
{
Self { props }
}
fn update(&mut self, _: Self::Message) -> yew::prelude::ShouldRender
|
fn change(&mut self, _: Self::Properties) -> yew::prelude::ShouldRender
{
false
}
fn view(&self) -> yew::prelude::Html
{
yew::prelude::html! {
<svg
class=self.props.class.unwrap_or("")
width=self.props.size.unwrap_or(24).to_string()
height=self.props.size.unwrap_or(24).to_string()
viewBox="0 0 24 24"
fill=self.props.fill.unwrap_or("none")
stroke=self.props.color.unwrap_or("currentColor")
stroke-width=self.props.stroke_width.unwrap_or(2).to_string()
stroke-linecap=self.props.stroke_linecap.unwrap_or("round")
stroke-linejoin=self.props.stroke_linejoin.unwrap_or("round")
>
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M15.5 17H9c-2.21 0-4-1.79-4-4 0-1.93 1.36-3.56 3.22-3.92C9.04 7.8 10.47 7 12 7c1.95 0 3.66 1.28 4.26 3.09 1.58.36 2.74 1.75 2.74 3.41 0 1.93-1.57 3.5-3.5 3.5zm-6.76-5.98C7.74 11.15 7 11.99 7 13c0 1.1.9 2 2 2h6.5c.83 0 1.5-.67 1.5-1.5s-.67-1.5-1.5-1.5h-.87l-.17-.86C14.29 9.92 13.23 9 12 9c-.96 0-1.84.57-2.26 1.45l-.27.57h-.73zM21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16.01H3V4.99h18v14.02z"/></svg>
</svg>
}
}
}
| {
true
} |
index.ts | export * from './initializer';
export * from './initializerbase';
export * from './alphainitializer';
export * from './rangeinitializer';
export * from './propertyinitializer';
export * from './choiceinitializer';
export * from './colorinitializer';
export * from './datainitializer'; | export * from './rotation';
export * from './absoluterotation';
export * from './scaleallinit';
export * from './velocity';
export * from './weightedpropertyinitializer'; | export * from './initializergroup';
export * from './position';
export * from './absoluteposition';
export * from './rotatevelocity'; |
transaction_input_checker.rs | // Copyright (c) 2022, Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
use std::collections::HashSet;
use sui_types::{
base_types::{ObjectRef, SequenceNumber, SuiAddress},
error::{SuiError, SuiResult},
fp_ensure, gas,
messages::{InputObjectKind, SingleTransactionKind, Transaction},
object::{Object, Owner},
};
use tracing::debug;
/// Check all the objects used in the transaction against the database, and ensure
/// that they are all the correct version and number.
pub fn check_locks(
transaction: &Transaction,
input_objects: Vec<InputObjectKind>,
objects: Vec<Option<Object>>,
) -> Result<Vec<(InputObjectKind, Object)>, SuiError> {
// Constructing the list of objects that could be used to authenticate other
// objects. Any mutable object (either shared or owned) can be used to
// authenticate other objects. Hence essentially we are building the list
// of mutable objects.
// We require that mutable objects cannot show up more than once.
// In [`SingleTransactionKind::input_objects`] we checked that there is no
// duplicate objects in the same SingleTransactionKind. However for a Batch | // up in more than one SingleTransactionKind.
// TODO: We should be able to allow the same shared mutable object to show up
// in more than one SingleTransactionKind. We need to ensure that their
// version number only increases once at the end of the Batch execution.
let mut owned_object_authenticators: HashSet<SuiAddress> = HashSet::new();
for object in objects.iter().flatten() {
if !object.is_read_only() {
fp_ensure!(
owned_object_authenticators.insert(object.id().into()),
SuiError::InvalidBatchTransaction {
error: format!("Mutable object {} cannot appear in more than one single transactions in a batch", object.id()),
}
);
}
}
// Gather all objects and errors.
let mut all_objects = Vec::with_capacity(input_objects.len());
let mut errors = Vec::new();
for (object_kind, object) in input_objects.into_iter().zip(objects) {
// All objects must exist in the DB.
let object = match object {
Some(object) => object,
None => {
errors.push(object_kind.object_not_found_error());
continue;
}
};
// Check if the object contents match the type of lock we need for
// this object.
match check_one_lock(
transaction,
object_kind,
&object,
&owned_object_authenticators,
) {
Ok(()) => all_objects.push((object_kind, object)),
Err(e) => {
errors.push(e);
}
}
}
// If any errors with the locks were detected, we return all errors to give the client
// a chance to update the authority if possible.
if !errors.is_empty() {
return Err(SuiError::LockErrors { errors });
}
fp_ensure!(!all_objects.is_empty(), SuiError::ObjectInputArityViolation);
check_gas_requirement(transaction, &all_objects)?;
Ok(all_objects)
}
pub fn filter_owned_objects(all_objects: Vec<(InputObjectKind, Object)>) -> Vec<ObjectRef> {
let owned_objects: Vec<_> = all_objects
.into_iter()
.filter_map(|(object_kind, object)| match object_kind {
InputObjectKind::MovePackage(_) => None,
InputObjectKind::OwnedMoveObject(object_ref) => {
if object.is_read_only() {
None
} else {
Some(object_ref)
}
}
InputObjectKind::SharedMoveObject(..) => None,
})
.collect();
debug!(
num_mutable_objects = owned_objects.len(),
"Checked locks and found mutable objects"
);
owned_objects
}
/// The logic to check one object against a reference, and return the object if all is well
/// or an error if not.
fn check_one_lock(
transaction: &Transaction,
object_kind: InputObjectKind,
object: &Object,
owned_object_authenticators: &HashSet<SuiAddress>,
) -> SuiResult {
match object_kind {
InputObjectKind::MovePackage(package_id) => {
fp_ensure!(
object.data.try_as_package().is_some(),
SuiError::MoveObjectAsPackage {
object_id: package_id
}
);
}
InputObjectKind::OwnedMoveObject((object_id, sequence_number, object_digest)) => {
fp_ensure!(
sequence_number <= SequenceNumber::MAX,
SuiError::InvalidSequenceNumber
);
// Check that the seq number is the same
fp_ensure!(
object.version() == sequence_number,
SuiError::UnexpectedSequenceNumber {
object_id,
expected_sequence: object.version(),
given_sequence: sequence_number,
}
);
// Check the digest matches
fp_ensure!(
object.digest() == object_digest,
SuiError::InvalidObjectDigest {
object_id,
expected_digest: object_digest
}
);
match object.owner {
Owner::SharedImmutable => {
// Nothing else to check for SharedImmutable.
}
Owner::AddressOwner(owner) => {
// Check the owner is the transaction sender.
fp_ensure!(
transaction.sender_address() == owner,
SuiError::IncorrectSigner {
error: format!("Object {:?} is owned by account address {:?}, but signer address is {:?}", object.id(), owner, transaction.sender_address()),
}
);
}
Owner::ObjectOwner(owner) => {
// Check that the object owner is another mutable object in the input.
fp_ensure!(
owned_object_authenticators.contains(&owner),
SuiError::IncorrectSigner {
error: format!(
"Object {:?} is owned by object {:?}, which is not in the input",
object.id(),
owner
),
}
);
}
Owner::SharedMutable => {
// This object is a mutable shared object. However the transaction
// specifies it as an owned object. This is inconsistent.
return Err(SuiError::NotSharedObjectError);
}
};
}
InputObjectKind::SharedMoveObject(..) => {
// When someone locks an object as shared it must be shared already.
fp_ensure!(object.is_shared(), SuiError::NotSharedObjectError);
}
};
Ok(())
}
/// This function does 3 things:
/// 1. Check if the gas object has enough balance to pay for this transaction.
/// Since the transaction may be a batch transaction, we need to walk through
/// each single transaction in it and accumulate their gas cost. For Move call
/// and publish we can simply use their budget, for transfer we will calculate
/// the cost on the spot since it's deterministic (See comments inside the function).
/// 2. Check if the gas budget for each single transction is above some minimum amount.
/// This can help reduce DDos attacks.
/// 3. Check that the objects used in transfers are mutable. We put the check here
/// because this is the most convenient spot to check.
fn check_gas_requirement(
transaction: &Transaction,
input_objects: &[(InputObjectKind, Object)],
) -> SuiResult {
let mut total_cost = 0;
let mut idx = 0;
for tx in transaction.single_transactions() {
match tx {
SingleTransactionKind::Transfer(_) => {
// Index access safe because the inputs were constructed in order.
let transfer_object = &input_objects[idx].1;
fp_ensure!(
!transfer_object.is_read_only(),
SuiError::TransferImmutableError
);
// TODO: Make Transfer transaction to also contain gas_budget.
// By @gdanezis: Now his is the only part of this function that requires
// an input object besides the gas object. It would be a major win if we
// can get rid of the requirement to have all objects to check the transfer
// requirement. If we can go this, then we could execute this check before
// we check for signatures.
// This would allow us to shore up out DoS defences: we only need to do a
// read on the gas object balance before we do anything expensive,
// such as checking signatures.
total_cost += gas::calculate_object_transfer_cost(transfer_object);
idx += tx.input_object_count();
}
SingleTransactionKind::Call(op) => {
gas::check_move_gas_requirement(op.gas_budget)?;
total_cost += op.gas_budget;
idx += tx.input_object_count();
}
SingleTransactionKind::Publish(op) => {
gas::check_move_gas_requirement(op.gas_budget)?;
total_cost += op.gas_budget;
// No need to update idx because Publish cannot show up in batch.
}
}
}
// The last element in the inputs is always gas object.
let gas_object = &input_objects.last().unwrap().1;
gas::check_gas_balance(gas_object, total_cost)
} | // Transaction, we still need to make sure that the same mutable object don't show |
post.js | import React, { useState, useEffect } from "react";
import { axiosWithAuth } from "./axiosAuth";
import "./post.css";
import '../index.css'
class Post extends React.Component {
state = {
recipe: {
name: "",
category: "1",
img: "",
ingredients: "", | },
isFetching: false
};
handleChange = e => {
this.setState({
recipe: {
...this.state.recipe,
[e.target.name]: e.target.value
}
});
};
post = e => {
e.preventDefault();
this.setState({
value: e.target.value,
isFetching: true
});
//axios goes here
console.log("first", this.state.recipe);
axiosWithAuth()
.post("https://bwchefhub.herokuapp.com/api/recipes", this.state.recipe)
.then(res => {
console.log(res.data);
// this.setState({ recipe: [...res.data, res.data.payload] });
this.props.history.push("/profile");
})
.catch(err => console.log(err));
};
render() {
return (
<div className="main account2">
<h1>Enter all the details for your recipe</h1>
<form className="formStyle" onSubmit={this.post}>
<input
type="text"
name="name"
placeholder="Recipe Name"
value={this.state.recipe.name}
onChange={this.handleChange}
/>
<select
name="category"
onChange={this.handleChange}
value={this.state.recipe.category}
>
<option value="1">Breakfast</option>
<option value="2">Lunch</option>
<option selected value="3">
Dinner
</option>
<option value="4">Snack</option>
</select>
<input
type="text"
name="img"
placeholder="Image Link"
value={this.state.recipe.img}
onChange={this.handleChange}
/>
<input
className="area"
type="textarea"
cols={40}
rows={10}
name="ingredients"
placeholder="Ingredients"
value={this.state.recipe.ingredients}
onChange={this.handleChange}
/>
<input
className="area"
type="textarea"
name="instructions"
placeholder="Instructions"
value={this.state.recipe.instructions}
onChange={this.handleChange}
/>
<div className='button-container'>
<button className='add-button'> Post </button>
<br />
<button className="add-button" onClick={()=>this.props.history.goBack()}> Cancel </button>
</div>
</form>
</div>
);
}
}
export default Post; | instructions: "" |
topic.go | package main
import "sort"
// Topic represents a CLI topic.
// For example, in the command `heroku apps:create` the topic would be `apps`.
type Topic struct {
Name string `json:"name"`
Description string `json:"description"`
Hidden bool `json:"hidden"`
Commands []*Command
}
func (t *Topic) String() string {
return t.Name
}
// Topics are a list of topics
type Topics []*Topic
// ByName returns a topic in the set matching the name.
func (topics Topics) ByName(name string) *Topic {
for _, topic := range topics {
if topic.Name == name |
}
return nil
}
// Concat joins 2 topic sets together
func (topics Topics) Concat(more Topics) Topics {
for _, topic := range more {
if topics.ByName(topic.Name) == nil {
topics = append(topics, topic)
}
}
return topics
}
func (topics Topics) Len() int {
return len(topics)
}
func (topics Topics) Less(i, j int) bool {
return topics[i].Name < topics[j].Name
}
func (topics Topics) Swap(i, j int) {
topics[i], topics[j] = topics[j], topics[i]
}
// AllTopics gets all go/core/user topics
func AllTopics() Topics {
topics := CLITopics
topics = topics.Concat(CorePlugins.Topics())
topics = topics.Concat(UserPlugins.Topics())
return topics
}
// NonHidden returns a set of topics that are not hidden
func (topics Topics) NonHidden() Topics {
to := make(Topics, 0, len(topics))
for _, topic := range topics {
if !topic.Hidden {
to = append(to, topic)
}
}
return to
}
// Sort sorts the set
func (topics Topics) Sort() Topics {
sort.Sort(topics)
return topics
}
// Commands returns all the commands of all the topics
func (topics Topics) Commands() Commands {
commands := Commands{}
for _, topic := range topics {
for _, command := range topic.Commands {
command.Topic = topic.Name
commands = append(commands, command)
}
}
return commands
}
| {
return topic
} |
util.go | package golomb
func min32(a int32, b int32) int32 {
if a > b {
return b
}
return a
}
func | (a int32, b int32) int32 {
if a < b {
return b
}
return a
}
func abs32(n int32) int32 {
if n >= 0 {
return n
}
return -1 * n
}
| max32 |
queues.py | #
# Module implementing queues
#
# multiprocessing/queues.py
#
# Copyright (c) 2006-2008, R Oudkerk
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 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.
# 3. Neither the name of author nor the names of any contributors may be
# used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
#
__all__ = ['Queue', 'SimpleQueue', 'JoinableQueue']
import sys
import os
import threading
import collections
import time
import atexit
import weakref
from queue import Empty, Full
try:
import _multiprocess as _multiprocessing
except ImportError:
import _multiprocessing
from multiprocess import Pipe
from multiprocess.synchronize import Lock, BoundedSemaphore, Semaphore, Condition
from multiprocess.util import debug, info, Finalize, register_after_fork
from multiprocess.forking import assert_spawning
#
# Queue type using a pipe, buffer and thread
#
class Queue(object):
def __init__(self, maxsize=0):
if maxsize <= 0:
maxsize = _multiprocessing.SemLock.SEM_VALUE_MAX
self._maxsize = maxsize
self._reader, self._writer = Pipe(duplex=False)
self._rlock = Lock()
self._opid = os.getpid()
if sys.platform == 'win32':
self._wlock = None
else:
self._wlock = Lock()
self._sem = BoundedSemaphore(maxsize)
self._after_fork()
if sys.platform != 'win32':
register_after_fork(self, Queue._after_fork)
def __getstate__(self):
assert_spawning(self)
return (self._maxsize, self._reader, self._writer,
self._rlock, self._wlock, self._sem, self._opid)
def __setstate__(self, state):
(self._maxsize, self._reader, self._writer,
self._rlock, self._wlock, self._sem, self._opid) = state
self._after_fork()
def _after_fork(self):
debug('Queue._after_fork()')
self._notempty = threading.Condition(threading.Lock())
self._buffer = collections.deque()
self._thread = None
self._jointhread = None
self._joincancelled = False
self._closed = False
self._close = None
self._send = self._writer.send
self._recv = self._reader.recv
self._poll = self._reader.poll
def put(self, obj, block=True, timeout=None):
assert not self._closed
if not self._sem.acquire(block, timeout):
raise Full
self._notempty.acquire()
try:
if self._thread is None:
self._start_thread()
self._buffer.append(obj)
self._notempty.notify()
finally:
self._notempty.release()
def get(self, block=True, timeout=None):
if block and timeout is None:
self._rlock.acquire()
try:
res = self._recv()
self._sem.release()
return res
finally:
self._rlock.release()
else:
if block:
deadline = time.time() + timeout
if not self._rlock.acquire(block, timeout):
raise Empty
try:
if not self._poll(block and (deadline-time.time()) or 0.0):
raise Empty
res = self._recv()
self._sem.release()
return res
finally:
self._rlock.release()
def qsize(self):
# Raises NotImplementedError on Mac OSX because of broken sem_getvalue()
return self._maxsize - self._sem._semlock._get_value()
def empty(self):
return not self._poll()
def full(self):
return self._sem._semlock._is_zero()
def get_nowait(self):
return self.get(False)
def put_nowait(self, obj):
return self.put(obj, False)
def close(self):
self._closed = True
self._reader.close()
if self._close:
self._close()
def join_thread(self):
debug('Queue.join_thread()')
assert self._closed
if self._jointhread:
self._jointhread()
def cancel_join_thread(self):
debug('Queue.cancel_join_thread()')
self._joincancelled = True
try:
self._jointhread.cancel()
except AttributeError:
pass
def _start_thread(self):
debug('Queue._start_thread()')
# Start thread which transfers data from buffer to pipe
self._buffer.clear()
self._thread = threading.Thread(
target=Queue._feed,
args=(self._buffer, self._notempty, self._send,
self._wlock, self._writer.close),
name='QueueFeederThread'
)
self._thread.daemon = True
debug('doing self._thread.start()')
self._thread.start()
debug('... done self._thread.start()')
# On process exit we will wait for data to be flushed to pipe.
#
# However, if this process created the queue then all
# processes which use the queue will be descendants of this
# process. Therefore waiting for the queue to be flushed
# is pointless once all the child processes have been joined.
created_by_this_process = (self._opid == os.getpid())
if not self._joincancelled and not created_by_this_process:
self._jointhread = Finalize(
self._thread, Queue._finalize_join,
[weakref.ref(self._thread)],
exitpriority=-5
)
# Send sentinel to the thread queue object when garbage collected
self._close = Finalize(
self, Queue._finalize_close,
[self._buffer, self._notempty],
exitpriority=10
)
@staticmethod
def _finalize_join(twr):
debug('joining queue thread')
thread = twr()
if thread is not None:
thread.join()
debug('... queue thread joined')
else:
debug('... queue thread already dead')
@staticmethod
def _finalize_close(buffer, notempty):
debug('telling queue thread to quit')
notempty.acquire()
try:
buffer.append(_sentinel)
notempty.notify()
finally:
notempty.release()
@staticmethod
def _feed(buffer, notempty, send, writelock, close):
debug('starting thread to feed data to pipe')
from .util import is_exiting
nacquire = notempty.acquire
nrelease = notempty.release
nwait = notempty.wait
bpopleft = buffer.popleft
sentinel = _sentinel
if sys.platform != 'win32':
wacquire = writelock.acquire
wrelease = writelock.release
else:
wacquire = None
try:
while 1:
nacquire()
try:
if not buffer:
nwait()
finally:
nrelease()
try:
while 1:
obj = bpopleft()
if obj is sentinel:
debug('feeder thread got sentinel -- exiting')
close()
return
if wacquire is None:
send(obj)
else:
wacquire()
try:
send(obj)
finally:
wrelease()
except IndexError:
pass
except Exception as e:
# Since this runs in a daemon thread the resources it uses
# may be become unusable while the process is cleaning up.
# We ignore errors which happen after the process has
# started to cleanup.
try:
if is_exiting():
info('error in queue thread: %s', e)
else:
import traceback
traceback.print_exc()
except Exception:
pass
_sentinel = object()
#
# A queue type which also supports join() and task_done() methods
#
# Note that if you do not call task_done() for each finished task then
# eventually the counter's semaphore may overflow causing Bad Things
# to happen.
#
class JoinableQueue(Queue):
def __init__(self, maxsize=0):
Queue.__init__(self, maxsize)
self._unfinished_tasks = Semaphore(0)
self._cond = Condition()
def __getstate__(self):
return Queue.__getstate__(self) + (self._cond, self._unfinished_tasks)
def __setstate__(self, state):
Queue.__setstate__(self, state[:-2])
self._cond, self._unfinished_tasks = state[-2:]
def put(self, obj, block=True, timeout=None):
assert not self._closed
if not self._sem.acquire(block, timeout):
raise Full
self._notempty.acquire()
self._cond.acquire()
try:
if self._thread is None:
self._start_thread()
self._buffer.append(obj)
self._unfinished_tasks.release()
self._notempty.notify()
finally:
self._cond.release()
self._notempty.release()
def task_done(self):
self._cond.acquire()
try:
if not self._unfinished_tasks.acquire(False):
raise ValueError('task_done() called too many times')
if self._unfinished_tasks._semlock._is_zero():
self._cond.notify_all()
finally:
self._cond.release()
def join(self):
|
#
# Simplified Queue type -- really just a locked pipe
#
class SimpleQueue(object):
def __init__(self):
self._reader, self._writer = Pipe(duplex=False)
self._rlock = Lock()
if sys.platform == 'win32':
self._wlock = None
else:
self._wlock = Lock()
self._make_methods()
def empty(self):
return not self._reader.poll()
def __getstate__(self):
assert_spawning(self)
return (self._reader, self._writer, self._rlock, self._wlock)
def __setstate__(self, state):
(self._reader, self._writer, self._rlock, self._wlock) = state
self._make_methods()
def _make_methods(self):
recv = self._reader.recv
racquire, rrelease = self._rlock.acquire, self._rlock.release
def get():
racquire()
try:
return recv()
finally:
rrelease()
self.get = get
if self._wlock is None:
# writes to a message oriented win32 pipe are atomic
self.put = self._writer.send
else:
send = self._writer.send
wacquire, wrelease = self._wlock.acquire, self._wlock.release
def put(obj):
wacquire()
try:
return send(obj)
finally:
wrelease()
self.put = put
| self._cond.acquire()
try:
if not self._unfinished_tasks._semlock._is_zero():
self._cond.wait()
finally:
self._cond.release() |
shared.py | # Copyright 2011 The Emscripten Authors. All rights reserved.
# Emscripten is available under two separate licenses, the MIT license and the
# University of Illinois/NCSA Open Source License. Both these licenses can be
# found in the LICENSE file.
from __future__ import print_function
from distutils.spawn import find_executable
from subprocess import PIPE, STDOUT
import atexit
import base64
import json
import logging
import math
import multiprocessing
import os
import re
import shlex
import shutil
import subprocess
import sys
import tempfile
from .toolchain_profiler import ToolchainProfiler
from .tempfiles import try_delete
from . import jsrun, cache, tempfiles, colored_logger
from . import response_file
colored_logger.enable()
__rootpath__ = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
WINDOWS = sys.platform.startswith('win')
MACOS = sys.platform == 'darwin'
LINUX = sys.platform.startswith('linux')
def exit_with_error(msg, *args):
logging.error(msg, *args)
sys.exit(1)
# On Windows python suffers from a particularly nasty bug if python is spawning
# new processes while python itself is spawned from some other non-console
# process.
# Use a custom replacement for Popen on Windows to avoid the "WindowsError:
# [Error 6] The handle is invalid" errors when emcc is driven through cmake or
# mingw32-make.
# See http://bugs.python.org/issue3905
class WindowsPopen(object):
def __init__(self, args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False,
shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0):
self.stdin = stdin
self.stdout = stdout
self.stderr = stderr
# (stdin, stdout, stderr) store what the caller originally wanted to be done with the streams.
# (stdin_, stdout_, stderr_) will store the fixed set of streams that workaround the bug.
self.stdin_ = stdin
self.stdout_ = stdout
self.stderr_ = stderr
# If the caller wants one of these PIPEd, we must PIPE them all to avoid the 'handle is invalid' bug.
if self.stdin_ == PIPE or self.stdout_ == PIPE or self.stderr_ == PIPE:
if self.stdin_ is None:
self.stdin_ = PIPE
if self.stdout_ is None:
self.stdout_ = PIPE
if self.stderr_ is None:
self.stderr_ = PIPE
# emscripten.py supports reading args from a response file instead of cmdline.
# Use .rsp to avoid cmdline length limitations on Windows.
if len(args) >= 2 and args[1].endswith("emscripten.py"):
response_filename = response_file.create_response_file(args[2:], TEMP_DIR)
args = args[0:2] + ['@' + response_filename]
try:
# Call the process with fixed streams.
self.process = subprocess.Popen(args, bufsize, executable, self.stdin_, self.stdout_, self.stderr_, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags)
self.pid = self.process.pid
except Exception as e:
logging.error('\nsubprocess.Popen(args=%s) failed! Exception %s\n' % (' '.join(args), str(e)))
raise e
def communicate(self, input=None):
output = self.process.communicate(input)
self.returncode = self.process.returncode
# If caller never wanted to PIPE stdout or stderr, route the output back to screen to avoid swallowing output.
if self.stdout is None and self.stdout_ == PIPE and len(output[0].strip()):
print(output[0], file=sys.stdout)
if self.stderr is None and self.stderr_ == PIPE and len(output[1].strip()):
print(output[1], file=sys.stderr)
# Return a mock object to the caller. This works as long as all emscripten code immediately .communicate()s the result, and doesn't
# leave the process object around for longer/more exotic uses.
if self.stdout is None and self.stderr is None:
return (None, None)
if self.stdout is None:
return (None, output[1])
if self.stderr is None:
return (output[0], None)
return (output[0], output[1])
def poll(self):
return self.process.poll()
def kill(self):
return self.process.kill()
def path_from_root(*pathelems):
return os.path.join(__rootpath__, *pathelems)
# This is a workaround for https://bugs.python.org/issue9400
class Py2CalledProcessError(subprocess.CalledProcessError):
def __init__(self, returncode, cmd, output=None, stderr=None):
super(Exception, self).__init__(returncode, cmd, output, stderr)
self.returncode = returncode
self.cmd = cmd
self.output = output
self.stderr = stderr
# https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess
class Py2CompletedProcess:
def __init__(self, args, returncode, stdout, stderr):
self.args = args
self.returncode = returncode
self.stdout = stdout
self.stderr = stderr
def __repr__(self):
_repr = ['args=%s, returncode=%s' % (self.args, self.returncode)]
if self.stdout is not None:
_repr += 'stdout=' + repr(self.stdout)
if self.stderr is not None:
_repr += 'stderr=' + repr(self.stderr)
return 'CompletedProcess(%s)' % ', '.join(_repr)
def check_returncode(self):
if self.returncode != 0:
raise Py2CalledProcessError(returncode=self.returncode, cmd=self.args, output=self.stdout, stderr=self.stderr)
def run_base(cmd, check=False, input=None, *args, **kw):
if hasattr(subprocess, "run"):
return subprocess.run(cmd, check=check, input=input, *args, **kw)
# Python 2 compatibility: Introduce Python 3 subprocess.run-like behavior
if input is not None:
kw['stdin'] = subprocess.PIPE
proc = Popen(cmd, *args, **kw)
stdout, stderr = proc.communicate(input)
result = Py2CompletedProcess(cmd, proc.returncode, stdout, stderr)
if check:
result.check_returncode()
return result
def run_process(cmd, universal_newlines=True, check=True, *args, **kw):
return run_base(cmd, universal_newlines=universal_newlines, check=check, *args, **kw)
def check_call(cmd, *args, **kw):
try:
proc = run_process(cmd, *args, **kw)
logging.debug('Successfully executed %s' % ' '.join(cmd))
return proc
except subprocess.CalledProcessError as e:
exit_with_error("'%s' failed (%d)", ' '.join(cmd), e.returncode)
def generate_config(path, first_time=False):
# Note: repr is used to ensure the paths are escaped correctly on Windows.
# The full string is replaced so that the template stays valid Python.
config_file = open(path_from_root('tools', 'settings_template_readonly.py')).read().split('\n')
config_file = config_file[1:] # remove "this file will be copied..."
config_file = '\n'.join(config_file)
# autodetect some default paths
config_file = config_file.replace('\'{{{ EMSCRIPTEN_ROOT }}}\'', repr(__rootpath__))
llvm_root = os.path.dirname(find_executable('llvm-dis') or '/usr/bin/llvm-dis')
config_file = config_file.replace('\'{{{ LLVM_ROOT }}}\'', repr(llvm_root))
node = find_executable('nodejs') or find_executable('node') or 'node'
config_file = config_file.replace('\'{{{ NODE }}}\'', repr(node))
if WINDOWS:
tempdir = os.environ.get('TEMP') or os.environ.get('TMP') or 'c:\\temp'
else:
tempdir = '/tmp'
config_file = config_file.replace('\'{{{ TEMP }}}\'', repr(tempdir))
abspath = os.path.abspath(os.path.expanduser(path))
# write
open(abspath, 'w').write(config_file)
if first_time:
print('''
==============================================================================
Welcome to Emscripten!
This is the first time any of the Emscripten tools has been run.
A settings file has been copied to %s, at absolute path: %s
It contains our best guesses for the important paths, which are:
LLVM_ROOT = %s
NODE_JS = %s
EMSCRIPTEN_ROOT = %s
Please edit the file if any of those are incorrect.
This command will now exit. When you are done editing those paths, re-run it.
==============================================================================
''' % (path, abspath, llvm_root, node, __rootpath__), file=sys.stderr)
# Emscripten configuration is done through the --em-config command line option or
# the EM_CONFIG environment variable. If the specified string value contains newline
# or semicolon-separated definitions, then these definitions will be used to configure
# Emscripten. Otherwise, the string is understood to be a path to a settings
# file that contains the required definitions.
try:
EM_CONFIG = sys.argv[sys.argv.index('--em-config') + 1]
# And now remove it from sys.argv
skip = False
newargs = []
for arg in sys.argv:
if not skip and arg != '--em-config':
newargs += [arg]
elif arg == '--em-config':
skip = True
elif skip:
skip = False
sys.argv = newargs
# Emscripten compiler spawns other processes, which can reimport shared.py, so make sure that
# those child processes get the same configuration file by setting it to the currently active environment.
os.environ['EM_CONFIG'] = EM_CONFIG
except:
EM_CONFIG = os.environ.get('EM_CONFIG')
if EM_CONFIG and not os.path.isfile(EM_CONFIG):
if EM_CONFIG.startswith('-'):
raise Exception('Passed --em-config without an argument. Usage: --em-config /path/to/.emscripten or --em-config EMSCRIPTEN_ROOT=/path/;LLVM_ROOT=/path;...')
if '=' not in EM_CONFIG:
raise Exception('File ' + EM_CONFIG + ' passed to --em-config does not exist!')
else:
EM_CONFIG = EM_CONFIG.replace(';', '\n') + '\n'
if not EM_CONFIG:
EM_CONFIG = '~/.emscripten'
if '\n' in EM_CONFIG:
CONFIG_FILE = None
logging.debug('EM_CONFIG is specified inline without a file')
else:
CONFIG_FILE = os.path.expanduser(EM_CONFIG)
logging.debug('EM_CONFIG is located in ' + CONFIG_FILE)
if not os.path.exists(CONFIG_FILE):
generate_config(EM_CONFIG, first_time=True)
sys.exit(0)
# The following globals can be overridden by the config file.
NODE_JS = None
BINARYEN_ROOT = None
EM_POPEN_WORKAROUND = None
SPIDERMONKEY_ENGINE = None
V8_ENGINE = None
LLVM_ROOT = None
COMPILER_ENGINE = None
LLVM_ADD_VERSION = None
CLANG_ADD_VERSION = None
CLOSURE_COMPILER = None
JAVA = None
PYTHON = None
JS_ENGINE = None
COMPILER_OPTS = []
try:
config_text = open(CONFIG_FILE, 'r').read() if CONFIG_FILE else EM_CONFIG
exec(config_text)
except Exception as e:
logging.error('Error in evaluating %s (at %s): %s, text: %s' % (EM_CONFIG, CONFIG_FILE, str(e), config_text))
sys.exit(1)
# Returns a suggestion where current .emscripten config file might be located
# (if EM_CONFIG env. var is used without a file, this hints to "default"
# location at ~/.emscripten)
def hint_config_file_location():
if CONFIG_FILE:
return CONFIG_FILE
else:
return '~/.emscripten'
def listify(x):
if type(x) is not list:
return [x]
return x
def fix_js_engine(old, new):
if old is None:
return
global JS_ENGINES
JS_ENGINES = [new if x == old else x for x in JS_ENGINES]
return new
SPIDERMONKEY_ENGINE = fix_js_engine(SPIDERMONKEY_ENGINE, listify(SPIDERMONKEY_ENGINE))
NODE_JS = fix_js_engine(NODE_JS, listify(NODE_JS))
V8_ENGINE = fix_js_engine(V8_ENGINE, listify(V8_ENGINE))
COMPILER_ENGINE = listify(COMPILER_ENGINE)
JS_ENGINES = [listify(engine) for engine in JS_ENGINES]
if EM_POPEN_WORKAROUND is None:
EM_POPEN_WORKAROUND = os.environ.get('EM_POPEN_WORKAROUND')
# Install our replacement Popen handler if we are running on Windows to avoid
# python spawn process function.
# nb. This is by default disabled since it has the adverse effect of buffering
# up all logging messages, which makes builds look unresponsive (messages are
# printed only after the whole build finishes). Whether this workaround is
# needed seems to depend on how the host application that invokes emcc has set
# up its stdout and stderr.
if EM_POPEN_WORKAROUND and os.name == 'nt':
logging.debug('Installing Popen workaround handler to avoid bug http://bugs.python.org/issue3905')
Popen = WindowsPopen
else:
Popen = subprocess.Popen
# Verbosity level control for any intermediate subprocess spawns from the compiler. Useful for internal debugging.
# 0: disabled.
# 1: Log stderr of subprocess spawns.
# 2: Log stdout and stderr of subprocess spawns. Print out subprocess commands that were executed.
# 3: Log stdout and stderr, and pass VERBOSE=1 to CMake configure steps.
EM_BUILD_VERBOSE = int(os.getenv('EM_BUILD_VERBOSE', '0'))
# Expectations
actual_clang_version = None
def expected_llvm_version():
if get_llvm_target() == WASM_TARGET:
return "8.0"
else:
return "6.0"
def get_clang_version():
global actual_clang_version
if actual_clang_version is None:
response = run_process([CLANG, '-v'], stderr=PIPE).stderr
m = re.search(r'[Vv]ersion\s+(\d+\.\d+)', response)
actual_clang_version = m and m.group(1)
return actual_clang_version
def check_clang_version():
expected = expected_llvm_version()
actual = get_clang_version()
if expected in actual:
return True
logging.warning('LLVM version appears incorrect (seeing "%s", expected "%s")' % (actual, expected))
return False
def check_llvm_version():
try:
check_clang_version()
except Exception as e:
logging.critical('Could not verify LLVM version: %s' % str(e))
# look for emscripten-version.txt files under or alongside the llvm source dir
def get_fastcomp_src_dir():
d = LLVM_ROOT
emroot = path_from_root() # already abspath
# look for version file in llvm repo, making sure not to mistake the emscripten repo for it
while d != os.path.dirname(d):
d = os.path.abspath(d)
# when the build directory lives below the source directory
if os.path.exists(os.path.join(d, 'emscripten-version.txt')) and not d == emroot:
return d
# when the build directory lives alongside the source directory
elif os.path.exists(os.path.join(d, 'src', 'emscripten-version.txt')) and not os.path.join(d, 'src') == emroot:
return os.path.join(d, 'src')
else:
d = os.path.dirname(d)
return None
def get_llc_targets():
try:
llc_version_info = run_process([LLVM_COMPILER, '--version'], stdout=PIPE).stdout
pre, targets = llc_version_info.split('Registered Targets:')
return targets
except Exception as e:
return '(no targets could be identified: ' + str(e) + ')'
def has_asm_js_target(targets):
return 'js' in targets and 'JavaScript (asm.js, emscripten) backend' in targets
def has_wasm_target(targets):
return 'wasm32' in targets and 'WebAssembly 32-bit' in targets
def check_fastcomp():
try:
targets = get_llc_targets()
if not Settings.WASM_BACKEND:
if not has_asm_js_target(targets):
logging.critical('fastcomp in use, but LLVM has not been built with the JavaScript backend as a target, llc reports:')
print('===========================================================================', file=sys.stderr)
print(targets, file=sys.stderr)
print('===========================================================================', file=sys.stderr)
logging.critical('you can fall back to the older (pre-fastcomp) compiler core, although that is not recommended, see http://kripken.github.io/emscripten-site/docs/building_from_source/LLVM-Backend.html')
return False
else:
if not has_wasm_target(targets):
logging.critical('WebAssembly set as target, but LLVM has not been built with the WebAssembly backend, llc reports:')
print('===========================================================================', file=sys.stderr)
print(targets, file=sys.stderr)
print('===========================================================================', file=sys.stderr)
return False
if not Settings.WASM_BACKEND:
# check repo versions
d = get_fastcomp_src_dir()
shown_repo_version_error = False
if d is not None:
llvm_version = get_emscripten_version(os.path.join(d, 'emscripten-version.txt'))
if os.path.exists(os.path.join(d, 'tools', 'clang', 'emscripten-version.txt')):
clang_version = get_emscripten_version(os.path.join(d, 'tools', 'clang', 'emscripten-version.txt'))
elif os.path.exists(os.path.join(d, 'tools', 'clang')):
clang_version = '?' # Looks like the LLVM compiler tree has an old checkout from the time before it contained a version.txt: Should update!
else:
clang_version = llvm_version # This LLVM compiler tree does not have a tools/clang, so it's probably an out-of-source build directory. No need for separate versioning.
if EMSCRIPTEN_VERSION != llvm_version or EMSCRIPTEN_VERSION != clang_version:
logging.error('Emscripten, llvm and clang repo versions do not match, this is dangerous (%s, %s, %s)', EMSCRIPTEN_VERSION, llvm_version, clang_version)
logging.error('Make sure to use the same branch in each repo, and to be up-to-date on each. See http://kripken.github.io/emscripten-site/docs/building_from_source/LLVM-Backend.html')
shown_repo_version_error = True
else:
logging.warning('did not see a source tree above or next to the LLVM root directory (guessing based on directory of %s), could not verify version numbers match' % LLVM_COMPILER)
# check build versions. don't show it if the repos are wrong, user should fix that first
if not shown_repo_version_error:
clang_v = run_process([CLANG, '--version'], stdout=PIPE).stdout
llvm_build_version, clang_build_version = clang_v.split('(emscripten ')[1].split(')')[0].split(' : ')
if EMSCRIPTEN_VERSION != llvm_build_version or EMSCRIPTEN_VERSION != clang_build_version:
logging.error('Emscripten, llvm and clang build versions do not match, this is dangerous (%s, %s, %s)', EMSCRIPTEN_VERSION, llvm_build_version, clang_build_version)
logging.error('Make sure to rebuild llvm and clang after updating repos')
return True
except Exception as e:
logging.warning('could not check fastcomp: %s' % str(e))
return True
EXPECTED_NODE_VERSION = (4, 1, 1)
def check_node_version():
jsrun.check_engine(NODE_JS)
try:
actual = run_process(NODE_JS + ['--version'], stdout=PIPE).stdout.strip()
version = tuple(map(int, actual.replace('v', '').replace('-pre', '').split('.')))
if version >= EXPECTED_NODE_VERSION:
return True
logging.warning('node version appears too old (seeing "%s", expected "%s")' % (actual, 'v' + ('.'.join(map(str, EXPECTED_NODE_VERSION)))))
return False
except Exception as e:
logging.warning('cannot check node version: %s', e)
return False
def check_closure_compiler():
try:
run_process([JAVA, '-version'], stdout=PIPE, stderr=PIPE)
except:
logging.warning('java does not seem to exist, required for closure compiler, which is optional (define JAVA in ' + hint_config_file_location() + ' if you want it)')
return False
if not os.path.exists(CLOSURE_COMPILER):
logging.warning('Closure compiler (%s) does not exist, check the paths in %s' % (CLOSURE_COMPILER, EM_CONFIG))
return False
return True
# Finds the system temp directory without resorting to using the one configured in .emscripten
def find_temp_directory():
if WINDOWS:
if os.getenv('TEMP') and os.path.isdir(os.getenv('TEMP')):
return os.getenv('TEMP')
elif os.getenv('TMP') and os.path.isdir(os.getenv('TMP')):
return os.getenv('TMP')
elif os.path.isdir('C:\\temp'):
return os.getenv('C:\\temp')
else:
return None # No luck!
else:
return '/tmp'
def get_emscripten_version(path):
return open(path).read().strip().replace('"', '')
EMSCRIPTEN_VERSION = get_emscripten_version(path_from_root('emscripten-version.txt'))
parts = [int(x) for x in EMSCRIPTEN_VERSION.split('.')]
EMSCRIPTEN_VERSION_MAJOR, EMSCRIPTEN_VERSION_MINOR, EMSCRIPTEN_VERSION_TINY = parts
def generate_sanity():
return EMSCRIPTEN_VERSION + '|' + LLVM_ROOT + '|' + get_clang_version() + ('_wasm' if Settings.WASM_BACKEND else '')
def check_sanity(force=False):
"""Check that basic stuff we need (a JS engine to compile, Node.js, and Clang
and LLVM) exists.
The test runner always does this check (through |force|). emcc does this less
frequently, only when ${EM_CONFIG}_sanity does not exist or is older than
EM_CONFIG (so, we re-check sanity when the settings are changed). We also
re-check sanity and clear the cache when the version changes"""
ToolchainProfiler.enter_block('sanity')
try:
if os.environ.get('EMCC_SKIP_SANITY_CHECK') == '1':
return
reason = None
if not CONFIG_FILE:
return # config stored directly in EM_CONFIG => skip sanity checks
else:
settings_mtime = os.stat(CONFIG_FILE).st_mtime
sanity_file = CONFIG_FILE + '_sanity'
if Settings.WASM_BACKEND:
sanity_file += '_wasm'
if os.path.exists(sanity_file):
try:
sanity_mtime = os.stat(sanity_file).st_mtime
if sanity_mtime <= settings_mtime:
reason = 'settings file has changed'
else:
sanity_data = open(sanity_file).read().rstrip('\n\r') # workaround weird bug with read() that appends new line char in some old python version
if sanity_data != generate_sanity():
reason = 'system change: %s vs %s' % (generate_sanity(), sanity_data)
else:
if not force:
return # all is well
except Exception as e:
reason = 'unknown: ' + str(e)
if reason:
logging.warning('(Emscripten: %s, clearing cache)' % reason)
Cache.erase()
force = False # the check actually failed, so definitely write out the sanity file, to avoid others later seeing failures too
# some warning, mostly not fatal checks - do them even if EM_IGNORE_SANITY is on
check_llvm_version()
check_node_version()
if os.environ.get('EMCC_FAST_COMPILER') == '0':
logging.critical('Non-fastcomp compiler is no longer available, please use fastcomp or an older version of emscripten')
sys.exit(1)
fastcomp_ok = check_fastcomp()
if os.environ.get('EM_IGNORE_SANITY'):
logging.info('EM_IGNORE_SANITY set, ignoring sanity checks')
return
logging.info('(Emscripten: Running sanity checks)')
with ToolchainProfiler.profile_block('sanity compiler_engine'):
if not jsrun.check_engine(COMPILER_ENGINE):
exit_with_error('The JavaScript shell used for compiling (%s) does not seem to work, check the paths in %s', COMPILER_ENGINE, EM_CONFIG)
with ToolchainProfiler.profile_block('sanity LLVM'):
for cmd in [CLANG, LLVM_LINK, LLVM_AR, LLVM_OPT, LLVM_AS, LLVM_DIS, LLVM_NM, LLVM_INTERPRETER]:
if not os.path.exists(cmd) and not os.path.exists(cmd + '.exe'): # .exe extension required for Windows
exit_with_error('Cannot find %s, check the paths in %s', cmd, EM_CONFIG)
if not os.path.exists(PYTHON) and not os.path.exists(cmd + '.exe'):
try:
run_process([PYTHON, '--xversion'], stdout=PIPE, stderr=PIPE)
except:
exit_with_error('Cannot find %s, check the paths in %s', PYTHON, EM_CONFIG)
if not fastcomp_ok:
exit_with_error('failing sanity checks due to previous fastcomp failure')
# Sanity check passed!
with ToolchainProfiler.profile_block('sanity closure compiler'):
if not check_closure_compiler():
logging.warning('closure compiler will not be available')
if not force:
# Only create/update this file if the sanity check succeeded, i.e., we got here
f = open(sanity_file, 'w')
f.write(generate_sanity())
f.close()
except Exception as e:
# Any error here is not worth failing on
print('WARNING: sanity check failed to run', e)
finally:
ToolchainProfiler.exit_block('sanity')
# Tools/paths
if LLVM_ADD_VERSION is None:
LLVM_ADD_VERSION = os.getenv('LLVM_ADD_VERSION')
if CLANG_ADD_VERSION is None:
CLANG_ADD_VERSION = os.getenv('CLANG_ADD_VERSION')
# Some distributions ship with multiple llvm versions so they add
# the version to the binaries, cope with that
def build_llvm_tool_path(tool):
if LLVM_ADD_VERSION:
return os.path.join(LLVM_ROOT, tool + "-" + LLVM_ADD_VERSION)
else:
return os.path.join(LLVM_ROOT, tool)
# Some distributions ship with multiple clang versions so they add
# the version to the binaries, cope with that
def build_clang_tool_path(tool):
if CLANG_ADD_VERSION:
return os.path.join(LLVM_ROOT, tool + "-" + CLANG_ADD_VERSION)
else:
return os.path.join(LLVM_ROOT, tool)
# Whenever building a native executable for macOS, we must provide the macOS SDK
# version we want to target.
def macos_find_native_sdk_path():
try:
sdk_root = '/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs'
sdks = os.walk(sdk_root).next()[1]
sdk_path = os.path.join(sdk_root, sdks[0]) # Just pick first one found, we don't care which one we found.
logging.debug('Targeting macOS SDK found at ' + sdk_path)
return sdk_path
except:
logging.warning('Could not find native macOS SDK path to target!')
return None
# These extra args need to be passed to Clang when targeting a native host system executable
CACHED_CLANG_NATIVE_ARGS = None
def get_clang_native_args():
global CACHED_CLANG_NATIVE_ARGS
if CACHED_CLANG_NATIVE_ARGS is not None:
return CACHED_CLANG_NATIVE_ARGS
CACHED_CLANG_NATIVE_ARGS = []
if MACOS:
sdk_path = macos_find_native_sdk_path()
if sdk_path:
CACHED_CLANG_NATIVE_ARGS = ['-isysroot', macos_find_native_sdk_path()]
elif os.name == 'nt':
CACHED_CLANG_NATIVE_ARGS = ['-DWIN32']
# TODO: If Windows.h et al. are needed, will need to add something like '-isystemC:/Program Files (x86)/Microsoft SDKs/Windows/v7.1A/Include'.
return CACHED_CLANG_NATIVE_ARGS
# This environment needs to be present when targeting a native host system executable
CACHED_CLANG_NATIVE_ENV = None
def get_clang_native_env():
global CACHED_CLANG_NATIVE_ENV
if CACHED_CLANG_NATIVE_ENV is not None:
return CACHED_CLANG_NATIVE_ENV
env = os.environ.copy()
if WINDOWS:
# If already running in Visual Studio Command Prompt manually, no need to
# add anything here, so just return.
if 'VSINSTALLDIR' in env and 'INCLUDE' in env and 'LIB' in env:
CACHED_CLANG_NATIVE_ENV = env
return env
# Guess where VS2015 is installed (VSINSTALLDIR env. var in VS2015 X64 Command Prompt)
if 'VSINSTALLDIR' in env:
visual_studio_path = env['VSINSTALLDIR']
elif 'VS140COMNTOOLS' in env:
visual_studio_path = os.path.normpath(os.path.join(env['VS140COMNTOOLS'], '../..'))
elif 'ProgramFiles(x86)' in env:
visual_studio_path = os.path.normpath(os.path.join(env['ProgramFiles(x86)'], 'Microsoft Visual Studio 14.0'))
elif 'ProgramFiles' in env:
visual_studio_path = os.path.normpath(os.path.join(env['ProgramFiles'], 'Microsoft Visual Studio 14.0'))
else:
visual_studio_path = 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0'
if not os.path.isdir(visual_studio_path):
raise Exception('Visual Studio 2015 was not found in "' + visual_studio_path + '"! Run in Visual Studio X64 command prompt to avoid the need to autoguess this location (or set VSINSTALLDIR env var).')
# Guess where Program Files (x86) is located
if 'ProgramFiles(x86)' in env:
prog_files_x86 = env['ProgramFiles(x86)']
elif 'ProgramFiles' in env:
prog_files_x86 = env['ProgramFiles']
elif os.path.isdir('C:\\Program Files (x86)'):
prog_files_x86 = 'C:\\Program Files (x86)'
elif os.path.isdir('C:\\Program Files'):
prog_files_x86 = 'C:\\Program Files'
else:
raise Exception('Unable to detect Program files directory for native Visual Studio build!')
# Guess where Windows 8.1 SDK is located
if 'WindowsSdkDir' in env:
windows8_sdk_dir = env['WindowsSdkDir']
elif os.path.isdir(os.path.join(prog_files_x86, 'Windows Kits', '8.1')):
windows8_sdk_dir = os.path.join(prog_files_x86, 'Windows Kits', '8.1')
if not os.path.isdir(windows8_sdk_dir):
raise Exception('Windows 8.1 SDK was not found in "' + windows8_sdk_dir + '"! Run in Visual Studio command prompt to avoid the need to autoguess this location (or set WindowsSdkDir env var).')
# Guess where Windows 10 SDK is located
if os.path.isdir(os.path.join(prog_files_x86, 'Windows Kits', '10')):
windows10_sdk_dir = os.path.join(prog_files_x86, 'Windows Kits', '10')
if not os.path.isdir(windows10_sdk_dir):
raise Exception('Windows 10 SDK was not found in "' + windows10_sdk_dir + '"! Run in Visual Studio command prompt to avoid the need to autoguess this location.')
env.setdefault('VSINSTALLDIR', visual_studio_path)
env.setdefault('VCINSTALLDIR', os.path.join(visual_studio_path, 'VC'))
windows10sdk_kits_include_dir = os.path.join(windows10_sdk_dir, 'Include')
windows10sdk_kit_version_name = [x for x in os.listdir(windows10sdk_kits_include_dir) if os.path.isdir(os.path.join(windows10sdk_kits_include_dir, x))][0] # e.g. "10.0.10150.0" or "10.0.10240.0"
def append_item(key, item):
if key not in env or len(env[key].strip()) == 0:
env[key] = item
else:
env[key] = env[key] + ';' + item
append_item('INCLUDE', os.path.join(env['VCINSTALLDIR'], 'INCLUDE'))
append_item('INCLUDE', os.path.join(env['VCINSTALLDIR'], 'ATLMFC', 'INCLUDE'))
append_item('INCLUDE', os.path.join(windows10_sdk_dir, 'include', windows10sdk_kit_version_name, 'ucrt'))
# append_item('INCLUDE', 'C:\\Program Files (x86)\\Windows Kits\\NETFXSDK\\4.6.1\\include\\um') # VS2015 X64 command prompt has this, but not needed for Emscripten
append_item('INCLUDE', os.path.join(env['VCINSTALLDIR'], 'ATLMFC', 'INCLUDE'))
append_item('INCLUDE', os.path.join(windows8_sdk_dir, 'include', 'shared'))
append_item('INCLUDE', os.path.join(windows8_sdk_dir, 'include', 'um'))
append_item('INCLUDE', os.path.join(windows8_sdk_dir, 'include', 'winrt'))
logging.debug('VS2015 native build INCLUDE: ' + env['INCLUDE'])
append_item('LIB', os.path.join(env['VCINSTALLDIR'], 'LIB', 'amd64'))
append_item('LIB', os.path.join(env['VCINSTALLDIR'], 'ATLMFC', 'LIB', 'amd64'))
append_item('LIB', os.path.join(windows10_sdk_dir, 'lib', windows10sdk_kit_version_name, 'ucrt', 'x64'))
# append_item('LIB', 'C:\\Program Files (x86)\\Windows Kits\\NETFXSDK\\4.6.1\\lib\\um\\x64') # VS2015 X64 command prompt has this, but not needed for Emscripten
append_item('LIB', os.path.join(windows8_sdk_dir, 'lib', 'winv6.3', 'um', 'x64'))
logging.debug('VS2015 native build LIB: ' + env['LIB'])
env['PATH'] = env['PATH'] + ';' + os.path.join(env['VCINSTALLDIR'], 'BIN')
logging.debug('VS2015 native build PATH: ' + env['PATH'])
# Current configuration above is all Visual Studio -specific, so on non-Windowses, no action needed.
CACHED_CLANG_NATIVE_ENV = env
return env
def exe_suffix(cmd):
return cmd + '.exe' if WINDOWS else cmd
CLANG_CC = os.path.expanduser(build_clang_tool_path(exe_suffix('clang')))
CLANG_CPP = os.path.expanduser(build_clang_tool_path(exe_suffix('clang++')))
CLANG = CLANG_CPP
LLVM_LINK = build_llvm_tool_path(exe_suffix('llvm-link'))
LLVM_AR = build_llvm_tool_path(exe_suffix('llvm-ar'))
LLVM_OPT = os.path.expanduser(build_llvm_tool_path(exe_suffix('opt')))
LLVM_AS = os.path.expanduser(build_llvm_tool_path(exe_suffix('llvm-as')))
LLVM_DIS = os.path.expanduser(build_llvm_tool_path(exe_suffix('llvm-dis')))
LLVM_NM = os.path.expanduser(build_llvm_tool_path(exe_suffix('llvm-nm')))
LLVM_INTERPRETER = os.path.expanduser(build_llvm_tool_path(exe_suffix('lli')))
LLVM_COMPILER = os.path.expanduser(build_llvm_tool_path(exe_suffix('llc')))
LLVM_DWARFDUMP = os.path.expanduser(build_llvm_tool_path(exe_suffix('llvm-dwarfdump')))
WASM_LD = os.path.expanduser(build_llvm_tool_path(exe_suffix('wasm-ld')))
EMSCRIPTEN = path_from_root('emscripten.py')
EMCC = path_from_root('emcc.py')
EMXX = path_from_root('em++.py')
EMAR = path_from_root('emar.py')
EMRANLIB = path_from_root('emranlib')
EMCONFIG = path_from_root('em-config')
EMLINK = path_from_root('emlink.py')
EMMAKEN = path_from_root('tools', 'emmaken.py')
AUTODEBUGGER = path_from_root('tools', 'autodebugger.py')
EXEC_LLVM = path_from_root('tools', 'exec_llvm.py')
FILE_PACKAGER = path_from_root('tools', 'file_packager.py')
# Temp dir. Create a random one, unless EMCC_DEBUG is set, in which case use TEMP_DIR/emscripten_temp
def safe_ensure_dirs(dirname):
try:
os.makedirs(dirname)
except OSError as e:
# Python 2 compatibility: makedirs does not support exist_ok parameter
# Ignore error for already existing dirname as exist_ok does
if not os.path.isdir(dirname):
raise e
# Returns a path to EMSCRIPTEN_TEMP_DIR, creating one if it didn't exist.
def get_emscripten_temp_dir():
global configuration, EMSCRIPTEN_TEMP_DIR
if not EMSCRIPTEN_TEMP_DIR:
EMSCRIPTEN_TEMP_DIR = tempfile.mkdtemp(prefix='emscripten_temp_', dir=configuration.TEMP_DIR)
def prepare_to_clean_temp(d):
def clean_temp():
try_delete(d)
atexit.register(clean_temp)
prepare_to_clean_temp(EMSCRIPTEN_TEMP_DIR) # this global var might change later
return EMSCRIPTEN_TEMP_DIR
def get_canonical_temp_dir(temp_dir):
return os.path.join(temp_dir, 'emscripten_temp')
class WarningManager(object):
warnings = {
'ABSOLUTE_PATHS': {
'enabled': False, # warning about absolute-paths is disabled by default
'printed': False,
'message': '-I or -L of an absolute path encountered. If this is to a local system header/library, it may cause problems (local system files make sense for compiling natively on your system, but not necessarily to JavaScript).',
},
'SEPARATE_ASM': {
'enabled': True,
'printed': False,
'message': "--separate-asm works best when compiling to HTML. Otherwise, you must yourself load the '.asm.js' file that is emitted separately, and must do so before loading the main '.js' file.",
},
'ALMOST_ASM': {
'enabled': True,
'printed': False,
'message': 'not all asm.js optimizations are possible with ALLOW_MEMORY_GROWTH, disabling those.',
},
}
@staticmethod
def capture_warnings(cmd_args):
for i in range(len(cmd_args)):
if not cmd_args[i].startswith('-W'):
continue
# special case pre-existing warn-absolute-paths
if cmd_args[i] == '-Wwarn-absolute-paths':
cmd_args[i] = ''
WarningManager.warnings['ABSOLUTE_PATHS']['enabled'] = True
elif cmd_args[i] == '-Wno-warn-absolute-paths':
cmd_args[i] = ''
WarningManager.warnings['ABSOLUTE_PATHS']['enabled'] = False
else:
# convert to string representation of Warning
warning_enum = cmd_args[i].replace('-Wno-', '').replace('-W', '')
warning_enum = warning_enum.upper().replace('-', '_')
if warning_enum in WarningManager.warnings:
WarningManager.warnings[warning_enum]['enabled'] = not cmd_args[i].startswith('-Wno-')
cmd_args[i] = ''
return cmd_args
@staticmethod
def warn(warning_type, message=None):
warning = WarningManager.warnings[warning_type]
if warning['enabled'] and not warning['printed']:
warning['printed'] = True
logging.warning((message or warning['message']) + ' [-W' + warning_type.lower().replace('_', '-') + ']')
class Configuration(object):
def __init__(self, environ=os.environ):
self.DEBUG = int(environ.get('EMCC_DEBUG', '0'))
self.EMSCRIPTEN_TEMP_DIR = None
if "EMCC_TEMP_DIR" in environ:
TEMP_DIR = environ.get("EMCC_TEMP_DIR")
try:
self.TEMP_DIR = TEMP_DIR
except NameError:
self.TEMP_DIR = find_temp_directory()
if self.TEMP_DIR is None:
logging.critical('TEMP_DIR not defined in ' + hint_config_file_location() + ", and could not detect a suitable directory! Please configure .emscripten to contain a variable TEMP_DIR='/path/to/temp/dir'.")
logging.debug('TEMP_DIR not defined in ' + hint_config_file_location() + ', using ' + self.TEMP_DIR)
if not os.path.isdir(self.TEMP_DIR):
logging.critical("The temp directory TEMP_DIR='" + self.TEMP_DIR + "' doesn't seem to exist! Please make sure that the path is correct.")
self.CANONICAL_TEMP_DIR = get_canonical_temp_dir(self.TEMP_DIR)
if self.DEBUG:
try:
self.EMSCRIPTEN_TEMP_DIR = self.CANONICAL_TEMP_DIR
safe_ensure_dirs(self.EMSCRIPTEN_TEMP_DIR)
except Exception as e:
logging.error(str(e) + 'Could not create canonical temp dir. Check definition of TEMP_DIR in ' + hint_config_file_location())
def get_temp_files(self):
return tempfiles.TempFiles(
tmp=self.TEMP_DIR if not self.DEBUG else get_emscripten_temp_dir(),
save_debug_files=os.environ.get('EMCC_DEBUG_SAVE'))
def apply_configuration():
global configuration, DEBUG, EMSCRIPTEN_TEMP_DIR, CANONICAL_TEMP_DIR, TEMP_DIR
configuration = Configuration()
DEBUG = configuration.DEBUG
EMSCRIPTEN_TEMP_DIR = configuration.EMSCRIPTEN_TEMP_DIR
CANONICAL_TEMP_DIR = configuration.CANONICAL_TEMP_DIR
TEMP_DIR = configuration.TEMP_DIR
def set_logging():
logging.basicConfig(format='%(levelname)-8s %(name)s: %(message)s') # can add %(asctime)s to see timestamps
logger = logging.getLogger()
logger.setLevel(logging.DEBUG if DEBUG else logging.INFO)
apply_configuration()
set_logging()
# EM_CONFIG stuff
if JS_ENGINES is None:
if JS_ENGINE is None:
raise 'ERROR: %s does not seem to have JS_ENGINES or JS_ENGINE set up' % EM_CONFIG
else:
JS_ENGINES = [JS_ENGINE]
if CLOSURE_COMPILER is None:
CLOSURE_COMPILER = path_from_root('third_party', 'closure-compiler', 'compiler.jar')
if PYTHON is None:
logging.debug('PYTHON not defined in ' + hint_config_file_location() + ', using "%s"' % (sys.executable,))
PYTHON = sys.executable
if JAVA is None:
logging.debug('JAVA not defined in ' + hint_config_file_location() + ', using "java"')
JAVA = 'java'
# Additional compiler options
# Target choice.
ASM_JS_TARGET = 'asmjs-unknown-emscripten'
WASM_TARGET = 'wasm32-unknown-unknown-wasm'
def check_vanilla():
global LLVM_TARGET
# if the env var tells us what to do, do that
if 'EMCC_WASM_BACKEND' in os.environ:
if os.environ['EMCC_WASM_BACKEND'] != '0':
logging.debug('EMCC_WASM_BACKEND tells us to use wasm backend')
LLVM_TARGET = WASM_TARGET
else:
logging.debug('EMCC_WASM_BACKEND tells us to use asm.js backend')
LLVM_TARGET = ASM_JS_TARGET
else:
# if we are using vanilla LLVM, i.e. we don't have our asm.js backend, then we
# must use wasm (or at least try to). to know that, we have to run llc to
# see which backends it has. we cache this result.
temp_cache = cache.Cache(use_subdir=False)
def check_vanilla():
logging.debug('testing for asm.js target, because if not present (i.e. this is plain vanilla llvm, not emscripten fastcomp), we will use the wasm target instead (set EMCC_WASM_BACKEND to skip this check)')
targets = get_llc_targets()
return has_wasm_target(targets) and not has_asm_js_target(targets)
def get_vanilla_file():
saved_file = os.path.join(temp_cache.dirname, 'is_vanilla.txt')
open(saved_file, 'w').write(('1' if check_vanilla() else '0') + ':' + LLVM_ROOT)
return saved_file
is_vanilla_file = temp_cache.get('is_vanilla', get_vanilla_file, extension='.txt')
if CONFIG_FILE and os.stat(CONFIG_FILE).st_mtime > os.stat(is_vanilla_file).st_mtime:
logging.debug('config file changed since we checked vanilla; re-checking')
is_vanilla_file = temp_cache.get('is_vanilla', get_vanilla_file, extension='.txt', force=True)
try:
contents = open(is_vanilla_file).read()
middle = contents.index(':')
is_vanilla = int(contents[:middle])
llvm_used = contents[middle + 1:]
if llvm_used != LLVM_ROOT:
logging.debug('regenerating vanilla check since other llvm')
temp_cache.get('is_vanilla', get_vanilla_file, extension='.txt', force=True)
is_vanilla = check_vanilla()
except Exception as e:
logging.debug('failed to use vanilla file, will re-check: ' + str(e))
is_vanilla = check_vanilla()
temp_cache = None
if is_vanilla:
logging.debug('check tells us to use wasm backend')
LLVM_TARGET = WASM_TARGET
else:
logging.debug('check tells us to use asm.js backend')
LLVM_TARGET = ASM_JS_TARGET
check_vanilla()
def get_llvm_target():
assert LLVM_TARGET is not None
return LLVM_TARGET
# Set the LIBCPP ABI version to at least 2 so that we get nicely aligned string
# data and other nice fixes.
COMPILER_OPTS += [# '-fno-threadsafe-statics', # disabled due to issue 1289
'-target', get_llvm_target(),
'-D__EMSCRIPTEN_major__=' + str(EMSCRIPTEN_VERSION_MAJOR),
'-D__EMSCRIPTEN_minor__=' + str(EMSCRIPTEN_VERSION_MINOR),
'-D__EMSCRIPTEN_tiny__=' + str(EMSCRIPTEN_VERSION_TINY),
'-D_LIBCPP_ABI_VERSION=2']
if get_llvm_target() == WASM_TARGET:
# wasm target does not automatically define emscripten stuff, so do it here.
COMPILER_OPTS += ['-D__EMSCRIPTEN__',
'-Dunix',
'-D__unix',
'-D__unix__',
'--wasm-host-triple=x86_64-unknown-linux-gnu']
# Changes to default clang behavior
# Implicit functions can cause horribly confusing function pointer type errors, see #2175
# If your codebase really needs them - very unrecommended! - you can disable the error with
# -Wno-error=implicit-function-declaration
# or disable even a warning about it with
# -Wno-implicit-function-declaration
COMPILER_OPTS += ['-Werror=implicit-function-declaration']
USE_EMSDK = not os.environ.get('EMMAKEN_NO_SDK')
if USE_EMSDK:
# Disable system C and C++ include directories, and add our own (using -idirafter so they are last, like system dirs, which
# allows projects to override them)
C_INCLUDE_PATHS = [
path_from_root('system', 'include', 'compat'),
path_from_root('system', 'include'),
path_from_root('system', 'include', 'SSE'),
path_from_root('system', 'include', 'libc'),
path_from_root('system', 'lib', 'libc', 'musl', 'arch', 'emscripten'),
path_from_root('system', 'local', 'include')
]
CXX_INCLUDE_PATHS = [
path_from_root('system', 'include', 'libcxx'),
path_from_root('system', 'lib', 'libcxxabi', 'include')
]
C_OPTS = ['-nostdinc', '-Xclang', '-nobuiltininc', '-Xclang', '-nostdsysteminc', '--wasm-host-triple=x86_64-unknown-linux-gnu']
def include_directive(paths):
result = []
for path in paths:
result += ['-Xclang', '-isystem' + path]
return result
# libcxx include paths must be defined before libc's include paths otherwise libcxx will not build
EMSDK_OPTS = C_OPTS + include_directive(CXX_INCLUDE_PATHS) + include_directive(C_INCLUDE_PATHS)
EMSDK_CXX_OPTS = []
COMPILER_OPTS += EMSDK_OPTS
else:
EMSDK_OPTS = []
EMSDK_CXX_OPTS = []
COMPILER_OPTS += ['--wasm-host-triple=x86_64-unknown-linux-gnu']
# Engine tweaks
try:
if SPIDERMONKEY_ENGINE:
new_spidermonkey = SPIDERMONKEY_ENGINE
if '-w' not in str(new_spidermonkey):
new_spidermonkey += ['-w']
SPIDERMONKEY_ENGINE = fix_js_engine(SPIDERMONKEY_ENGINE, new_spidermonkey)
except NameError:
pass
# Utilities
def make_js_command(filename, engine=None, *args):
if engine is None:
engine = JS_ENGINES[0]
return jsrun.make_command(filename, engine, *args)
def run_js(filename, engine=None, *args, **kw):
if engine is None:
engine = JS_ENGINES[0]
return jsrun.run_js(filename, engine, *args, **kw)
def to_cc(cxx):
# By default, LLVM_GCC and CLANG are really the C++ versions. This gets an explicit C version
return cxx.replace('clang++', 'clang').replace('g++', 'gcc')
def line_splitter(data):
"""Silly little tool to split JSON arrays over many lines."""
out = ''
counter = 0
for i in range(len(data)):
out += data[i]
if data[i] == ' ' and counter > 60:
out += '\n'
counter = 0
else:
counter += 1
return out
def limit_size(string, MAX=800 * 20):
if len(string) < MAX:
return string
return string[0:MAX / 2] + '\n[..]\n' + string[-MAX / 2:]
def read_pgo_data(filename):
'''
Reads the output of PGO and generates proper information for CORRECT_* == 2 's *_LINES options
'''
signs_lines = []
overflows_lines = []
for line in open(filename, 'r'):
try:
if line.rstrip() == '':
continue
if '%0 failures' in line:
continue
left, right = line.split(' : ')
signature = left.split('|')[1]
if 'Sign' in left:
signs_lines.append(signature)
elif 'Overflow' in left:
overflows_lines.append(signature)
except:
pass
return {
'signs_lines': signs_lines,
'overflows_lines': overflows_lines
}
def unique_ordered(values):
"""return a list of unique values in an input list, without changing order
(list(set(.)) would change order randomly).
"""
seen = set()
def check(value):
if value in seen:
return False
seen.add(value)
return True
return list(filter(check, values))
def expand_response(data):
if type(data) == str and data[0] == '@':
return json.loads(open(data[1:]).read())
return data
def expand_byte_size_suffixes(value):
"""Given a string with arithmetic and/or KB/MB size suffixes, such as
"1024*1024" or "32MB", computes how many bytes that is and returns it as an
integer.
"""
value = value.lower().replace('tb', '*1024*1024*1024*1024').replace('gb', '*1024*1024*1024').replace('mb', '*1024*1024').replace('kb', '*1024').replace('b', '')
try:
return eval(value)
except:
raise Exception("Invalid byte size, valid suffixes: KB, MB, GB, TB")
# Settings. A global singleton. Not pretty, but nicer than passing |, settings| everywhere
class SettingsManager(object):
class __impl(object):
attrs = {}
def __init__(self):
self.reset()
@classmethod
def reset(self):
self.attrs = {}
self.load()
# Given some emcc-type args (-O3, -s X=Y, etc.), fill Settings with the right settings
@classmethod
def load(self, args=[]):
# Load the JS defaults into python
settings = open(path_from_root('src', 'settings.js')).read().replace('//', '#')
settings = re.sub(r'var ([\w\d]+)', r'self.attrs["\1"]', settings)
exec(settings)
# Apply additional settings. First -O, then -s
for arg in args:
if arg.startswith('-O'):
v = arg[2]
shrink = 0
if v in ['s', 'z']:
shrink = 1 if v == 's' else 2
v = '2'
level = int(v)
self.apply_opt_level(level, shrink)
for i in range(len(args)):
if args[i] == '-s':
declare = re.sub(r'([\w\d]+)\s*=\s*(.+)', r'self.attrs["\1"]=\2;', args[i + 1])
exec(declare)
if get_llvm_target() == WASM_TARGET:
self.attrs['WASM_BACKEND'] = 1
# Transforms the Settings information into emcc-compatible args (-s X=Y, etc.). Basically
# the reverse of load_settings, except for -Ox which is relevant there but not here
@classmethod
def serialize(self):
ret = []
for key, value in self.attrs.items():
if key == key.upper(): # this is a hack. all of our settings are ALL_CAPS, python internals are not
jsoned = json.dumps(value, sort_keys=True)
ret += ['-s', key + '=' + jsoned]
return ret
@classmethod
def to_dict(self):
return self.attrs.copy()
@classmethod
def copy(self, values):
self.attrs = values
@classmethod
def apply_opt_level(self, opt_level, shrink_level=0, noisy=False):
if opt_level >= 1:
self.attrs['ASM_JS'] = 1
self.attrs['ASSERTIONS'] = 0
self.attrs['ALIASING_FUNCTION_POINTERS'] = 1
if shrink_level >= 2:
self.attrs['EVAL_CTORS'] = 1
def __getattr__(self, attr):
if attr in self.attrs:
return self.attrs[attr]
else:
raise AttributeError
def __setattr__(self, attr, value):
if attr not in self.attrs:
import difflib
logging.warning('''Assigning a non-existent settings attribute "%s"''' % attr)
suggestions = ', '.join(difflib.get_close_matches(attr, list(self.attrs.keys())))
if suggestions:
logging.warning(''' - did you mean one of %s?''' % suggestions)
logging.warning(''' - perhaps a typo in emcc's -s X=Y notation?''')
logging.warning(''' - (see src/settings.js for valid values)''')
self.attrs[attr] = value
@classmethod
def get(self, key):
return self.attrs.get(key)
@classmethod
def __getitem__(self, key):
return self.attrs[key]
__instance = None
@staticmethod
def instance():
if SettingsManager.__instance is None:
SettingsManager.__instance = SettingsManager.__impl()
return SettingsManager.__instance
def __getattr__(self, attr):
return getattr(self.instance(), attr)
def __setattr__(self, attr, value):
return setattr(self.instance(), attr, value)
def get(self, key):
return self.instance().get(key)
def __getitem__(self, key):
return self.instance()[key]
def verify_settings():
if Settings.WASM_BACKEND:
if not Settings.WASM:
# TODO(sbc): Make this into a hard error. We still have a few places that
# pass WASM=0 before we can do this (at least Platform/Emscripten.cmake and
# generate_struct_info).
logging.warn('emcc: WASM_BACKEND is not compatible with asmjs (WASM=0), forcing WASM=1')
Settings.WASM = 1
if not BINARYEN_ROOT:
exit_with_error('emcc: BINARYEN_ROOT must be set in the .emscripten config'
' when using the LLVM wasm backend')
if Settings.CYBERDWARF:
exit_with_error('emcc: CYBERDWARF is not supported by the LLVM wasm backend')
if Settings.EMTERPRETIFY:
exit_with_error('emcc: EMTERPRETIFY is not supported by the LLVM wasm backend')
if not os.path.exists(WASM_LD) or run_process([WASM_LD, '--version'], stdout=PIPE, stderr=PIPE, check=False).returncode != 0:
exit_with_error('WASM_BACKEND selected but could not find lld (wasm-ld): %s', WASM_LD)
if Settings.SIDE_MODULE or Settings.MAIN_MODULE:
exit_with_error('emcc: MAIN_MODULE and SIDE_MODULE are not yet supported by the LLVM wasm backend')
Settings = SettingsManager()
verify_settings()
# llvm-ar appears to just use basenames inside archives. as a result, files with the same basename
# will trample each other when we extract them. to help warn of such situations, we warn if there
# are duplicate entries in the archive
def warn_if_duplicate_entries(archive_contents, archive_filename_hint=''):
if len(archive_contents) != len(set(archive_contents)):
logging.warning('loading from archive %s, which has duplicate entries (files with identical base names). this is dangerous as only the last will be taken into account, and you may see surprising undefined symbols later. you should rename source files to avoid this problem (or avoid .a archives, and just link bitcode together to form libraries for later linking)' % archive_filename_hint)
warned = set()
for i in range(len(archive_contents)):
curr = archive_contents[i]
if curr not in warned and curr in archive_contents[i + 1:]:
logging.warning(' duplicate: %s' % curr)
warned.add(curr)
# This function creates a temporary directory specified by the 'dir' field in
# the returned dictionary. Caller is responsible for cleaning up those files
# after done.
def extract_archive_contents(archive_file):
lines = run_process([LLVM_AR, 't', archive_file], stdout=PIPE).stdout.splitlines()
# ignore empty lines
contents = [l for l in lines if len(l)]
if len(contents) == 0:
logging.debug('Archive %s appears to be empty (recommendation: link an .so instead of .a)' % archive_file)
return {
'returncode': 0,
'dir': None,
'files': []
}
# `ar` files can only contains filenames. Just to be sure, verify that each
# file has only as filename component and is not absolute
for f in contents:
assert not os.path.dirname(f)
assert not os.path.isabs(f)
warn_if_duplicate_entries(contents, f)
# create temp dir
temp_dir = tempfile.mkdtemp('_archive_contents', 'emscripten_temp_')
# extract file in temp dir
proc = run_process([LLVM_AR, 'xo', archive_file], stdout=PIPE, stderr=STDOUT, cwd=temp_dir)
abs_contents = [os.path.join(temp_dir, c) for c in contents]
# check that all files were created
missing_contents = [x for x in abs_contents if not os.path.exists(x)]
if missing_contents:
exit_with_error('llvm-ar failed to extract file(s) ' + str(missing_contents) + ' from archive file ' + f + '! Error:' + str(proc.stdout))
return {
'returncode': proc.returncode,
'dir': temp_dir,
'files': abs_contents
}
class ObjectFileInfo(object):
def __init__(self, returncode, output, defs=set(), undefs=set(), commons=set()):
self.returncode = returncode
self.output = output
self.defs = defs
self.undefs = undefs
self.commons = commons
def is_valid_for_nm(self):
return self.returncode == 0
# Due to a python pickling issue, the following two functions must be at top
# level, or multiprocessing pool spawn won't find them.
def g_llvm_nm_uncached(filename):
return Building.llvm_nm_uncached(filename)
def g_multiprocessing_initializer(*args):
for item in args:
(key, value) = item.split('=', 1)
if key == 'EMCC_POOL_CWD':
os.chdir(value)
else:
os.environ[key] = value
# Building
class Building(object):
COMPILER = CLANG
LLVM_OPTS = False
COMPILER_TEST_OPTS = [] # For use of the test runner
JS_ENGINE_OVERRIDE = None # Used to pass the JS engine override from runner.py -> test_benchmark.py
multiprocessing_pool = None
@staticmethod
def get_num_cores():
return int(os.environ.get('EMCC_CORES', multiprocessing.cpu_count()))
# Multiprocessing pools are very slow to build up and tear down, and having several pools throughout
# the application has a problem of overallocating child processes. Therefore maintain a single
# centralized pool that is shared between all pooled task invocations.
@staticmethod
def get_multiprocessing_pool():
if not Building.multiprocessing_pool:
cores = Building.get_num_cores()
# If running with one core only, create a mock instance of a pool that does not
# actually spawn any new subprocesses. Very useful for internal debugging.
if cores == 1:
class FakeMultiprocessor(object):
def map(self, func, tasks):
results = []
for t in tasks:
results += [func(t)]
return results
Building.multiprocessing_pool = FakeMultiprocessor()
else:
child_env = [
# Multiprocessing pool children must have their current working
# directory set to a safe path that is guaranteed not to die in
# between of executing commands, or otherwise the pool children will
# have trouble spawning subprocesses of their own.
'EMCC_POOL_CWD=' + path_from_root(),
# Multiprocessing pool children need to avoid all calling
# check_vanilla() again and again, otherwise the compiler can deadlock
# when building system libs, because the multiprocess parent can have
# the Emscripten cache directory locked for write access, and the
# EMCC_WASM_BACKEND check also requires locked access to the cache,
# which the multiprocess children would not get.
'EMCC_WASM_BACKEND=%s' % Settings.WASM_BACKEND,
# Multiprocessing pool children can't spawn their own linear number of
# children, that could cause a quadratic amount of spawned processes.
'EMCC_CORES=1'
]
Building.multiprocessing_pool = multiprocessing.Pool(processes=cores, initializer=g_multiprocessing_initializer, initargs=child_env)
def close_multiprocessing_pool():
try:
# Shut down the pool explicitly, because leaving that for Python to do at process shutdown is buggy and can generate
# noisy "WindowsError: [Error 5] Access is denied" spam which is not fatal.
Building.multiprocessing_pool.terminate()
Building.multiprocessing_pool.join()
Building.multiprocessing_pool = None
except OSError as e:
# Mute the "WindowsError: [Error 5] Access is denied" errors, raise all others through
if not (sys.platform.startswith('win') and isinstance(e, WindowsError) and e.winerror == 5):
raise
atexit.register(close_multiprocessing_pool)
return Building.multiprocessing_pool
# When creating environment variables for Makefiles to execute, we need to doublequote the commands if they have spaces in them..
@staticmethod
def doublequote_spaces(arg):
arg = arg[:] # Operate on a copy of the input string/list
if isinstance(arg, list):
for i in range(len(arg)):
arg[i] = Building.doublequote_spaces(arg[i])
return arg
if ' ' in arg and (not (arg.startswith('"') and arg.endswith('"'))) and (not (arg.startswith("'") and arg.endswith("'"))):
return '"' + arg.replace('"', '\\"') + '"'
return arg
# .. but for Popen, we cannot have doublequotes, so provide functionality to remove them when needed.
@staticmethod
def remove_quotes(arg):
arg = arg[:] # Operate on a copy of the input string/list
if isinstance(arg, list):
for i in range(len(arg)):
arg[i] = Building.remove_quotes(arg[i])
return arg
if arg.startswith('"') and arg.endswith('"'):
return arg[1:-1].replace('\\"', '"')
elif arg.startswith("'") and arg.endswith("'"):
return arg[1:-1].replace("\\'", "'")
else:
return arg
@staticmethod
def get_building_env(native=False, doublequote_commands=False):
def nop(arg):
return arg
quote = Building.doublequote_spaces if doublequote_commands else nop
env = os.environ.copy()
if native:
env['CC'] = quote(CLANG_CC)
env['CXX'] = quote(CLANG_CPP)
env['LD'] = quote(CLANG)
env['CFLAGS'] = '-O2 -fno-math-errno'
# get a non-native one, and see if we have some of its effects - remove them if so
non_native = Building.get_building_env()
# the ones that a non-native would modify
EMSCRIPTEN_MODIFIES = ['LDSHARED', 'AR', 'CROSS_COMPILE', 'NM', 'RANLIB']
for dangerous in EMSCRIPTEN_MODIFIES:
if env.get(dangerous) and env.get(dangerous) == non_native.get(dangerous):
del env[dangerous] # better to delete it than leave it, as the non-native one is definitely wrong
return env
# point CC etc. to the em* tools.
# on windows, we must specify python explicitly. on other platforms, we prefer
# not to, as some configure scripts expect e.g. CC to be a literal executable
# (but "python emcc.py" is not a file that exists).
# note that we point to emcc etc. here, without a suffix, instead of to
# emcc.py etc. The unsuffixed versions have the python_selector logic that can
# pick the right version as needed (which is not crucial right now as we support
# both 2 and 3, but eventually we may be 3-only).
env['CC'] = quote(unsuffixed(EMCC)) if not WINDOWS else 'python %s' % quote(EMCC)
env['CXX'] = quote(unsuffixed(EMXX)) if not WINDOWS else 'python %s' % quote(EMXX)
env['AR'] = quote(unsuffixed(EMAR)) if not WINDOWS else 'python %s' % quote(EMAR)
env['LD'] = quote(unsuffixed(EMCC)) if not WINDOWS else 'python %s' % quote(EMCC)
env['NM'] = quote(LLVM_NM)
env['LDSHARED'] = quote(unsuffixed(EMCC)) if not WINDOWS else 'python %s' % quote(EMCC)
env['RANLIB'] = quote(unsuffixed(EMRANLIB)) if not WINDOWS else 'python %s' % quote(EMRANLIB)
env['EMMAKEN_COMPILER'] = quote(Building.COMPILER)
env['EMSCRIPTEN_TOOLS'] = path_from_root('tools')
env['CFLAGS'] = env['EMMAKEN_CFLAGS'] = ' '.join(Building.COMPILER_TEST_OPTS)
env['HOST_CC'] = quote(CLANG_CC)
env['HOST_CXX'] = quote(CLANG_CPP)
env['HOST_CFLAGS'] = "-W" # if set to nothing, CFLAGS is used, which we don't want
env['HOST_CXXFLAGS'] = "-W" # if set to nothing, CXXFLAGS is used, which we don't want
env['PKG_CONFIG_LIBDIR'] = path_from_root('system', 'local', 'lib', 'pkgconfig') + os.path.pathsep + path_from_root('system', 'lib', 'pkgconfig')
env['PKG_CONFIG_PATH'] = os.environ.get('EM_PKG_CONFIG_PATH', '')
env['EMSCRIPTEN'] = path_from_root()
env['PATH'] = path_from_root('system', 'bin') + os.pathsep + env['PATH']
env['CROSS_COMPILE'] = path_from_root('em') # produces /path/to/emscripten/em , which then can have 'cc', 'ar', etc appended to it
return env
# if we are in emmake mode, i.e., we changed the env to run emcc etc., then show the message and abort
@staticmethod
def ensure_no_emmake(message):
non_native = Building.get_building_env()
if os.environ.get('CC') == non_native.get('CC'):
# the environment CC is the one we change to when forcing our em* tools
exit_with_error(message)
# Finds the given executable 'program' in PATH. Operates like the Unix tool 'which'.
@staticmethod
def which(program):
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
if os.path.isabs(program):
if os.path.isfile(program):
return program
if WINDOWS:
for suffix in ['.exe', '.cmd', '.bat']:
if is_exe(program + suffix):
return program + suffix
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
if WINDOWS:
for suffix in ('.exe', '.cmd', '.bat'):
if is_exe(exe_file + suffix):
return exe_file + suffix
return None
# Returns a clone of the given environment with all directories that contain sh.exe removed from the PATH.
# Used to work around CMake limitation with MinGW Makefiles, where sh.exe is not allowed to be present.
@staticmethod
def remove_sh_exe_from_path(env):
env = env.copy()
if not WINDOWS:
return env
path = env['PATH'].split(';')
path = [p for p in path if not os.path.exists(os.path.join(p, 'sh.exe'))]
env['PATH'] = ';'.join(path)
return env
@staticmethod
def handle_CMake_toolchain(args, env):
def has_substr(array, substr):
for arg in array:
if substr in arg:
return True
return False
# Append the Emscripten toolchain file if the user didn't specify one.
if not has_substr(args, '-DCMAKE_TOOLCHAIN_FILE'):
args.append('-DCMAKE_TOOLCHAIN_FILE=' + path_from_root('cmake', 'Modules', 'Platform', 'Emscripten.cmake'))
# On Windows specify MinGW Makefiles if we have MinGW and no other toolchain was specified, to avoid CMake
# pulling in a native Visual Studio, or Unix Makefiles.
if WINDOWS and '-G' not in args and Building.which('mingw32-make'):
args += ['-G', 'MinGW Makefiles']
# CMake has a requirement that it wants sh.exe off PATH if MinGW Makefiles is being used. This happens quite often,
# so do this automatically on behalf of the user. See http://www.cmake.org/Wiki/CMake_MinGW_Compiler_Issues
if WINDOWS and 'MinGW Makefiles' in args:
env = Building.remove_sh_exe_from_path(env)
return (args, env)
@staticmethod
def configure(args, stdout=None, stderr=None, env=None):
if not args:
return
if env is None:
env = Building.get_building_env()
if 'cmake' in args[0]:
# Note: EMMAKEN_JUST_CONFIGURE shall not be enabled when configuring with CMake. This is because CMake
# does expect to be able to do config-time builds with emcc.
args, env = Building.handle_CMake_toolchain(args, env)
else:
# When we configure via a ./configure script, don't do config-time compilation with emcc, but instead
# do builds natively with Clang. This is a heuristic emulation that may or may not work.
env['EMMAKEN_JUST_CONFIGURE'] = '1'
try:
if EM_BUILD_VERBOSE >= 3:
print('configure: ' + str(args), file=sys.stderr)
if EM_BUILD_VERBOSE >= 2:
stdout = None
if EM_BUILD_VERBOSE >= 1:
stderr = None
res = run_process(args, check=False, stdout=stdout, stderr=stderr, env=env)
except Exception:
logging.error('Error running configure: "%s"' % ' '.join(args))
raise
if 'EMMAKEN_JUST_CONFIGURE' in env:
del env['EMMAKEN_JUST_CONFIGURE']
if res.returncode is not 0:
logging.error('Configure step failed with non-zero return code: %s. Command line: %s at %s' % (res.returncode, ' '.join(args), os.getcwd()))
raise subprocess.CalledProcessError(cmd=args, returncode=res.returncode)
@staticmethod
def make(args, stdout=None, stderr=None, env=None):
if env is None:
env = Building.get_building_env()
if not args:
exit_with_error('Executable to run not specified.')
# args += ['VERBOSE=1']
# On Windows prefer building with mingw32-make instead of make, if it exists.
if WINDOWS:
if args[0] == 'make':
mingw32_make = Building.which('mingw32-make')
if mingw32_make:
args[0] = mingw32_make
if 'mingw32-make' in args[0]:
env = Building.remove_sh_exe_from_path(env)
try:
# On Windows, run the execution through shell to get PATH expansion and executable extension lookup, e.g. 'sdl2-config' will match with 'sdl2-config.bat' in PATH.
if EM_BUILD_VERBOSE >= 3:
print('make: ' + str(args), file=sys.stderr)
if EM_BUILD_VERBOSE >= 2:
stdout = None
if EM_BUILD_VERBOSE >= 1:
stderr = None
res = run_process(args, stdout=stdout, stderr=stderr, env=env, shell=WINDOWS, check=False)
except Exception:
logging.error('Error running make: "%s"' % ' '.join(args))
raise
if res.returncode != 0:
raise subprocess.CalledProcessError(cmd=args, returncode=res.returncode)
@staticmethod
def build_library(name,
build_dir,
output_dir,
generated_libs,
configure=['sh', './configure'],
configure_args=[],
make=['make'],
make_args='help',
cache=None,
cache_name=None,
copy_project=False,
env_init={},
source_dir=None,
native=False):
"""Build a library into a .bc file. We build the .bc file once and cache it
for all our tests. (We cache in memory since the test directory is destroyed
and recreated for each test. Note that we cache separately for different
compilers). This cache is just during the test runner. There is a different
concept of caching as well, see |Cache|.
"""
if type(generated_libs) is not list:
generated_libs = [generated_libs]
if source_dir is None:
source_dir = path_from_root('tests', name.replace('_native', ''))
if make_args == 'help':
make_args = ['-j', str(multiprocessing.cpu_count())]
temp_dir = build_dir
if copy_project:
project_dir = os.path.join(temp_dir, name)
if os.path.exists(project_dir):
shutil.rmtree(project_dir)
shutil.copytree(source_dir, project_dir) # Useful in debugging sometimes to comment this out, and two lines above
else:
project_dir = build_dir
try:
old_dir = os.getcwd()
except:
old_dir = None
os.chdir(project_dir)
generated_libs = [os.path.join(project_dir, lib) for lib in generated_libs]
# for lib in generated_libs:
# try:
# os.unlink(lib) # make sure compilation completed successfully
# except:
# pass
env = Building.get_building_env(native, True)
for k, v in env_init.items():
env[k] = v
if configure:
# Useful in debugging sometimes to comment this out (and the lines below
# up to and including the |link| call)
if EM_BUILD_VERBOSE < 2:
stdout = open(os.path.join(project_dir, 'configure_out'), 'w')
else:
stdout = None
if EM_BUILD_VERBOSE < 1:
stderr = open(os.path.join(project_dir, 'configure_err'), 'w')
else:
stderr = None
try:
Building.configure(configure + configure_args, env=env, stdout=stdout, stderr=stderr)
except subprocess.CalledProcessError as e:
pass # Ignore exit code != 0
def open_make_out(i, mode='r'):
return open(os.path.join(project_dir, 'make_out' + str(i)), mode)
def open_make_err(i, mode='r'):
return open(os.path.join(project_dir, 'make_err' + str(i)), mode)
if EM_BUILD_VERBOSE >= 3:
make_args += ['VERBOSE=1']
# FIXME: Sad workaround for some build systems that need to be run twice to succeed (e.g. poppler)
for i in range(2):
with open_make_out(i, 'w') as make_out:
with open_make_err(i, 'w') as make_err:
stdout = make_out if EM_BUILD_VERBOSE < 2 else None
stderr = make_err if EM_BUILD_VERBOSE < 1 else None
try:
Building.make(make + make_args, stdout=stdout, stderr=stderr, env=env)
except subprocess.CalledProcessError as e:
pass # Ignore exit code != 0
try:
if cache is not None:
cache[cache_name] = []
for f in generated_libs:
basename = os.path.basename(f)
cache[cache_name].append((basename, open(f, 'rb').read()))
break
except Exception as e:
if i > 0:
if EM_BUILD_VERBOSE == 0:
# Due to the ugly hack above our best guess is to output the first run
with open_make_err(0) as ferr:
for line in ferr:
sys.stderr.write(line)
raise Exception('could not build library ' + name + ' due to exception ' + str(e))
if old_dir:
os.chdir(old_dir)
return generated_libs
@staticmethod
def make_paths_absolute(f):
if f.startswith('-'): # skip flags
return f
else:
return os.path.abspath(f)
# Runs llvm-nm in parallel for the given list of files.
# The results are populated in Building.uninternal_nm_cache
# multiprocessing_pool: An existing multiprocessing pool to reuse for the operation, or None
# to have the function allocate its own.
@staticmethod
def parallel_llvm_nm(files):
with ToolchainProfiler.profile_block('parallel_llvm_nm'):
pool = Building.get_multiprocessing_pool()
object_contents = pool.map(g_llvm_nm_uncached, files)
for i in range(len(files)):
if object_contents[i].returncode != 0:
logging.debug('llvm-nm failed on file ' + files[i] + ': return code ' + str(object_contents[i].returncode) + ', error: ' + object_contents[i].output)
Building.uninternal_nm_cache[files[i]] = object_contents[i]
return object_contents
@staticmethod
def read_link_inputs(files):
with ToolchainProfiler.profile_block('read_link_inputs'):
# Before performing the link, we need to look at each input file to determine which symbols
# each of them provides. Do this in multiple parallel processes.
archive_names = [] # .a files passed in to the command line to the link
object_names = [] # .o/.bc files passed in to the command line to the link
for f in files:
absolute_path_f = Building.make_paths_absolute(f)
if absolute_path_f not in Building.ar_contents and Building.is_ar(absolute_path_f):
archive_names.append(absolute_path_f)
elif absolute_path_f not in Building.uninternal_nm_cache and Building.is_bitcode(absolute_path_f):
object_names.append(absolute_path_f)
# Archives contain objects, so process all archives first in parallel to obtain the object files in them.
pool = Building.get_multiprocessing_pool()
object_names_in_archives = pool.map(extract_archive_contents, archive_names)
def clean_temporary_archive_contents_directory(directory):
def clean_at_exit():
try_delete(directory)
if directory:
atexit.register(clean_at_exit)
for n in range(len(archive_names)):
if object_names_in_archives[n]['returncode'] != 0:
raise Exception('llvm-ar failed on archive ' + archive_names[n] + '!')
Building.ar_contents[archive_names[n]] = object_names_in_archives[n]['files']
clean_temporary_archive_contents_directory(object_names_in_archives[n]['dir'])
for o in object_names_in_archives:
for f in o['files']:
if f not in Building.uninternal_nm_cache:
object_names.append(f)
# Next, extract symbols from all object files (either standalone or inside archives we just extracted)
# The results are not used here directly, but populated to llvm-nm cache structure.
Building.parallel_llvm_nm(object_names)
@staticmethod
def llvm_backend_args():
# disable slow and relatively unimportant optimization passes
args = ['-combiner-global-alias-analysis=false']
# asm.js-style exception handling
if Settings.DISABLE_EXCEPTION_CATCHING != 1:
args += ['-enable-emscripten-cxx-exceptions']
if Settings.DISABLE_EXCEPTION_CATCHING == 2:
whitelist = ','.join(Settings.EXCEPTION_CATCHING_WHITELIST or ['__fake'])
args += ['-emscripten-cxx-exceptions-whitelist=' + whitelist]
# asm.js-style setjmp/longjmp handling
args += ['-enable-emscripten-sjlj']
return args
@staticmethod
def link_lld(args, target, opts=[], lto_level=0):
# lld doesn't currently support --start-group/--end-group since the
# semantics are more like the windows linker where there is no need for
# grouping.
args = [a for a in args if a not in ('--start-group', '--end-group')]
cmd = [
WASM_LD,
'--export-dynamic',
'-z',
'stack-size=%s' % Settings.TOTAL_STACK,
'--global-base=%s' % Settings.GLOBAL_BASE,
'--initial-memory=%d' % Settings.TOTAL_MEMORY,
'-o',
target,
'--no-entry',
'--allow-undefined',
'--import-memory',
'--export',
'__wasm_call_ctors',
'--export',
'__data_end',
'--lto-O%d' % lto_level,
] + args
if Settings.WASM_MEM_MAX != -1:
cmd.append('--max-memory=%d' % Settings.WASM_MEM_MAX)
elif not Settings.ALLOW_MEMORY_GROWTH:
cmd.append('--max-memory=%d' % Settings.TOTAL_MEMORY)
for a in Building.llvm_backend_args():
cmd += ['-mllvm', a]
# emscripten-wasm-finalize currently depends on the presence of debug
# symbols for renaming of the __invoke symbols
# TODO(sbc): Re-enable once emscripten-wasm-finalize is fixed or we
# no longer need to rename these symbols.
# if Settings.DEBUG_LEVEL < 2 and not Settings.PROFILING_FUNCS:
# cmd.append('--strip-debug')
if Settings.EXPORT_ALL:
cmd += ['--no-gc-sections', '--export-all']
else:
for export in expand_response(Settings.EXPORTED_FUNCTIONS):
cmd += ['--export', export[1:]] # Strip the leading underscore
logging.debug('emcc: lld-linking: %s to %s', args, target)
check_call(cmd)
return target
@staticmethod
def link(files, target, force_archive_contents=False, temp_files=None, just_calculate=False):
if not temp_files:
temp_files = configuration.get_temp_files()
actual_files = []
# Tracking unresolveds is necessary for .a linking, see below.
# Specify all possible entry points to seed the linking process.
# For a simple application, this would just be "main".
unresolved_symbols = set([func[1:] for func in Settings.EXPORTED_FUNCTIONS])
resolved_symbols = set()
# Paths of already included object files from archives.
added_contents = set()
has_ar = False
for f in files:
if not f.startswith('-'):
has_ar = has_ar or Building.is_ar(Building.make_paths_absolute(f))
# If we have only one archive or the force_archive_contents flag is set,
# then we will add every object file we see, regardless of whether it
# resolves any undefined symbols.
force_add_all = len(files) == 1 or force_archive_contents
# Considers an object file for inclusion in the link. The object is included
# if force_add=True or if the object provides a currently undefined symbol.
# If the object is included, the symbol tables are updated and the function
# returns True.
def consider_object(f, force_add=False):
new_symbols = Building.llvm_nm(f)
# Check if the object was valid according to llvm-nm. It also accepts
# native object files.
if not new_symbols.is_valid_for_nm():
logging.warning('object %s is not valid according to llvm-nm, cannot link' % (f))
return False
# Check the object is valid for us, and not a native object file.
if not Building.is_bitcode(f):
logging.warning('object %s is not LLVM bitcode, cannot link' % (f))
return False
provided = new_symbols.defs.union(new_symbols.commons)
do_add = force_add or not unresolved_symbols.isdisjoint(provided)
if do_add:
logging.debug('adding object %s to link' % (f))
# Update resolved_symbols table with newly resolved symbols
resolved_symbols.update(provided)
# Update unresolved_symbols table by adding newly unresolved symbols and
# removing newly resolved symbols.
unresolved_symbols.update(new_symbols.undefs.difference(resolved_symbols))
unresolved_symbols.difference_update(provided)
actual_files.append(f)
return do_add
# Traverse a single archive. The object files are repeatedly scanned for
# newly satisfied symbols until no new symbols are found. Returns true if
# any object files were added to the link.
def consider_archive(f, force_add):
added_any_objects = False
loop_again = True
logging.debug('considering archive %s' % (f))
contents = Building.ar_contents[f]
while loop_again: # repeatedly traverse until we have everything we need
loop_again = False
for content in contents:
if content in added_contents:
continue
# Link in the .o if it provides symbols, *or* this is a singleton archive (which is apparently an exception in gcc ld)
if consider_object(content, force_add=force_add):
added_contents.add(content)
loop_again = True
added_any_objects = True
logging.debug('done running loop of archive %s' % (f))
return added_any_objects
Building.read_link_inputs([x for x in files if not x.startswith('-')])
# Rescan a group of archives until we don't find any more objects to link.
def scan_archive_group(group):
loop_again = True
logging.debug('starting archive group loop')
while loop_again:
loop_again = False
for archive in group:
if consider_archive(archive, force_add=False):
loop_again = True
logging.debug('done with archive group loop')
current_archive_group = None
in_whole_archive = False
for f in files:
absolute_path_f = Building.make_paths_absolute(f)
if f.startswith('-'):
if f in ['--start-group', '-(']:
assert current_archive_group is None, 'Nested --start-group, missing --end-group?'
current_archive_group = []
elif f in ['--end-group', '-)']:
assert current_archive_group is not None, '--end-group without --start-group'
scan_archive_group(current_archive_group)
current_archive_group = None
elif f in ['--whole-archive', '-whole-archive']:
in_whole_archive = True
elif f in ['--no-whole-archive', '-no-whole-archive']:
in_whole_archive = False
else:
# Command line flags should already be vetted by the time this method
# is called, so this is an internal error
assert False, 'unsupported link flag: ' + f
elif not Building.is_ar(absolute_path_f):
if Building.is_bitcode(absolute_path_f):
if has_ar:
consider_object(absolute_path_f, force_add=True)
else:
# If there are no archives then we can simply link all valid bitcode
# files and skip the symbol table stuff.
actual_files.append(f)
else:
# Extract object files from ar archives, and link according to gnu ld semantics
# (link in an entire .o from the archive if it supplies symbols still unresolved)
consider_archive(absolute_path_f, in_whole_archive or force_add_all)
# If we're inside a --start-group/--end-group section, add to the list
# so we can loop back around later.
if current_archive_group is not None:
current_archive_group.append(absolute_path_f)
# We have to consider the possibility that --start-group was used without a matching
# --end-group; GNU ld permits this behavior and implicitly treats the end of the
# command line as having an --end-group.
if current_archive_group:
logging.debug('--start-group without matching --end-group, rescanning')
scan_archive_group(current_archive_group)
current_archive_group = None
try_delete(target)
# Finish link
actual_files = unique_ordered(actual_files) # tolerate people trying to link a.so a.so etc.
# check for too-long command line
link_args = actual_files
# 8k is a bit of an arbitrary limit, but a reasonable one
# for max command line size before we use a response file
response_file = None
if len(' '.join(link_args)) > 8192:
logging.debug('using response file for llvm-link')
response_file = temp_files.get(suffix='.response').name
link_args = ["@" + response_file]
response_fh = open(response_file, 'w')
for arg in actual_files:
# Starting from LLVM 3.9.0 trunk around July 2016, LLVM escapes backslashes in response files, so Windows paths
# "c:\path\to\file.txt" with single slashes no longer work. LLVM upstream dev 3.9.0 from January 2016 still treated
# backslashes without escaping. To preserve compatibility with both versions of llvm-link, don't pass backslash
# path delimiters at all to response files, but always use forward slashes.
if WINDOWS:
arg = arg.replace('\\', '/')
# escaped double quotes allows 'space' characters in pathname the response file can use
response_fh.write("\"" + arg + "\"\n")
response_fh.close()
if not just_calculate:
logging.debug('emcc: llvm-linking: %s to %s', actual_files, target)
output = run_process([LLVM_LINK] + link_args + ['-o', target], stdout=PIPE).stdout
assert os.path.exists(target) and (output is None or 'Could not open input file' not in output), 'Linking error: ' + output
return target
else:
# just calculating; return the link arguments which is the final list of files to link
return link_args
# LLVM optimizations
# @param opt A list of LLVM optimization parameters
@staticmethod
def llvm_opt(filename, opts, out=None):
inputs = filename
if not isinstance(inputs, list):
inputs = [inputs]
else:
assert out, 'must provide out if llvm_opt on a list of inputs'
assert len(opts), 'should not call opt with nothing to do'
opts = opts[:]
# TODO: disable inlining when needed
# if not Building.can_inline():
# opts.append('-disable-inlining')
# opts += ['-debug-pass=Arguments']
if not Settings.SIMD:
opts += ['-disable-loop-vectorization', '-disable-slp-vectorization', '-vectorize-loops=false', '-vectorize-slp=false']
else:
opts += ['-force-vector-width=4']
logging.debug('emcc: LLVM opts: ' + ' '.join(opts) + ' [num inputs: ' + str(len(inputs)) + ']')
target = out or (filename + '.opt.bc')
try:
run_process([LLVM_OPT] + inputs + opts + ['-o', target], stdout=PIPE)
assert os.path.exists(target), 'llvm optimizer emitted no output.'
except subprocess.CalledProcessError as e:
for i in inputs:
if not os.path.exists(i):
logging.warning('Note: Input file "' + i + '" did not exist.')
elif not Building.is_bitcode(i):
logging.warning('Note: Input file "' + i + '" exists but was not an LLVM bitcode file suitable for Emscripten. Perhaps accidentally mixing native built object files with Emscripten?')
exit_with_error('Failed to run llvm optimizations: ' + e.output)
if not out:
shutil.move(filename + '.opt.bc', filename)
return target
@staticmethod
def llvm_opts(filename): # deprecated version, only for test runner. TODO: remove
if Building.LLVM_OPTS:
shutil.move(filename + '.o', filename + '.o.pre')
output = run_process([LLVM_OPT, filename + '.o.pre'] + Building.LLVM_OPT_OPTS + ['-o', filename + '.o'], stdout=PIPE).stdout
assert os.path.exists(filename + '.o'), 'Failed to run llvm optimizations: ' + output
@staticmethod
def llvm_dis(input_filename, output_filename=None):
# LLVM binary ==> LLVM assembly
if output_filename is None:
# use test runner conventions
output_filename = input_filename + '.o.ll'
input_filename = input_filename + '.o'
try_delete(output_filename)
output = run_process([LLVM_DIS, input_filename, '-o', output_filename], stdout=PIPE).stdout
assert os.path.exists(output_filename), 'Could not create .ll file: ' + output
return output_filename
@staticmethod
def llvm_as(input_filename, output_filename=None):
# LLVM assembly ==> LLVM binary
if output_filename is None:
# use test runner conventions
output_filename = input_filename + '.o'
input_filename = input_filename + '.o.ll'
try_delete(output_filename)
output = run_process([LLVM_AS, input_filename, '-o', output_filename], stdout=PIPE).stdout
assert os.path.exists(output_filename), 'Could not create bc file: ' + output
return output_filename
@staticmethod
def parse_symbols(output, include_internal=False):
defs = []
undefs = []
commons = []
for line in output.split('\n'):
if len(line) == 0:
continue
if ':' in line:
continue # e.g. filename.o: , saying which file it's from
parts = [seg for seg in line.split(' ') if len(seg)]
# pnacl-nm will print zero offsets for bitcode, and newer llvm-nm will print present symbols as -------- T name
if len(parts) == 3 and parts[0] in ["00000000", "--------"]:
parts.pop(0)
if len(parts) == 2: # ignore lines with absolute offsets, these are not bitcode anyhow (e.g. |00000630 t d_source_name|)
status, symbol = parts
if status == 'U':
undefs.append(symbol)
elif status == 'C':
commons.append(symbol)
elif (not include_internal and status == status.upper()) or \
(include_internal and status in ['W', 't', 'T', 'd', 'D']): # FIXME: using WTD in the previous line fails due to llvm-nm behavior on macOS,
# so for now we assume all uppercase are normally defined external symbols
defs.append(symbol)
return ObjectFileInfo(0, None, set(defs), set(undefs), set(commons))
internal_nm_cache = {} # cache results of nm - it can be slow to run
uninternal_nm_cache = {}
ar_contents = {} # Stores the object files contained in different archive files passed as input
@staticmethod
def llvm_nm_uncached(filename, stdout=PIPE, stderr=PIPE, include_internal=False):
# LLVM binary ==> list of symbols
proc = run_process([LLVM_NM, filename], stdout=stdout, stderr=stderr, check=False)
if proc.returncode == 0:
return Building.parse_symbols(proc.stdout, include_internal)
else:
return ObjectFileInfo(proc.returncode, str(proc.stdout) + str(proc.stderr))
@staticmethod
def llvm_nm(filename, stdout=PIPE, stderr=PIPE, include_internal=False):
# Always use absolute paths to maximize cache usage
filename = os.path.abspath(filename)
if include_internal and filename in Building.internal_nm_cache:
return Building.internal_nm_cache[filename]
elif not include_internal and filename in Building.uninternal_nm_cache:
return Building.uninternal_nm_cache[filename]
ret = Building.llvm_nm_uncached(filename, stdout, stderr, include_internal)
if ret.returncode != 0:
logging.debug('llvm-nm failed on file ' + filename + ': return code ' + str(ret.returncode) + ', error: ' + ret.output)
# Even if we fail, write the results to the NM cache so that we don't keep trying to llvm-nm the failing file again later.
if include_internal:
Building.internal_nm_cache[filename] = ret
else:
Building.uninternal_nm_cache[filename] = ret
return ret
@staticmethod
def emcc(filename, args=[], output_filename=None, stdout=None, stderr=None, env=None):
if output_filename is None:
output_filename = filename + '.o'
try_delete(output_filename)
run_process([PYTHON, EMCC, filename] + args + ['-o', output_filename], stdout=stdout, stderr=stderr, env=env)
@staticmethod
def emar(action, output_filename, filenames, stdout=None, stderr=None, env=None):
try_delete(output_filename)
run_process([PYTHON, EMAR, action, output_filename] + filenames, stdout=stdout, stderr=stderr, env=env)
if 'c' in action:
assert os.path.exists(output_filename), 'emar could not create output file: ' + output_filename
@staticmethod
def emscripten(filename, append_ext=True, extra_args=[]):
if path_from_root() not in sys.path:
sys.path += [path_from_root()]
import emscripten
# Run Emscripten
cmdline = [filename + ('.o.ll' if append_ext else ''), '-o', filename + '.o.js'] + extra_args
if jsrun.TRACK_PROCESS_SPAWNS:
logging.info('Executing emscripten.py compiler with cmdline "' + ' '.join(cmdline) + '"')
with ToolchainProfiler.profile_block('emscripten.py'):
emscripten._main(cmdline)
# Detect compilation crashes and errors
assert os.path.exists(filename + '.o.js'), 'Emscripten failed to generate .js'
return filename + '.o.js'
# TODO: deprecate this method, we should just need Settings.LINKABLE anyhow
@staticmethod
def can_build_standalone():
return not Settings.BUILD_AS_SHARED_LIB and not Settings.LINKABLE
@staticmethod
def can_inline():
return Settings.INLINING_LIMIT == 0
@staticmethod
def is_wasm_only():
# not even wasm, much less wasm-only
if not Settings.WASM:
return False
# llvm backend can only ever produce wasm
if Settings.WASM_BACKEND:
return True
# fastcomp can emit wasm-only code.
# also disable this mode if it depends on special optimizations that are not yet
# compatible with it.
if not Settings.LEGALIZE_JS_FFI:
# the user has requested no legalization for JS, and so we are not
# emitting code compatible with JS, and there is no reason not to
# be wasm-only, regardless of everything else
return True
if 'asmjs' in Settings.BINARYEN_METHOD or 'interpret-asm2wasm' in Settings.BINARYEN_METHOD:
# code compatible with asm.js cannot be wasm-only
return False
if Settings.RUNNING_JS_OPTS:
# if the JS optimizer runs, it must run on valid asm.js
return False
if Settings.EMULATE_FUNCTION_POINTER_CASTS:
# FIXME this is a current limitation
return False
if Settings.RELOCATABLE and Settings.EMULATED_FUNCTION_POINTERS:
# FIXME emulation function pointers work properly, but calling between
# modules as wasm-only needs more work
return False
return True
@staticmethod
def get_safe_internalize():
if not Building.can_build_standalone():
return [] # do not internalize anything
exps = expand_response(Settings.EXPORTED_FUNCTIONS)
internalize_public_api = '-internalize-public-api-'
internalize_list = ','.join([exp[1:] for exp in exps])
# EXPORTED_FUNCTIONS can potentially be very large.
# 8k is a bit of an arbitrary limit, but a reasonable one
# for max command line size before we use a response file
if len(internalize_list) > 8192:
logging.debug('using response file for EXPORTED_FUNCTIONS in internalize')
finalized_exports = '\n'.join([exp[1:] for exp in exps])
internalize_list_file = configuration.get_temp_files().get(suffix='.response').name
internalize_list_fh = open(internalize_list_file, 'w')
internalize_list_fh.write(finalized_exports)
internalize_list_fh.close()
internalize_public_api += 'file=' + internalize_list_file
else:
internalize_public_api += 'list=' + internalize_list
# internalize carefully, llvm 3.2 will remove even main if not told not to
return ['-internalize', internalize_public_api]
@staticmethod
def opt_level_to_str(opt_level, shrink_level=0):
# convert opt_level/shrink_level pair to a string argument like -O1
|
@staticmethod
def js_optimizer(filename, passes, debug=False, extra_info=None, output_filename=None, just_split=False, just_concat=False):
from . import js_optimizer
ret = js_optimizer.run(filename, passes, NODE_JS, debug, extra_info, just_split, just_concat)
if output_filename:
safe_move(ret, output_filename)
ret = output_filename
return ret
# run JS optimizer on some JS, ignoring asm.js contents if any - just run on it all
@staticmethod
def js_optimizer_no_asmjs(filename, passes, return_output=False, extra_info=None):
from . import js_optimizer
original_filename = filename
if extra_info is not None:
temp_files = configuration.get_temp_files()
temp = temp_files.get('.js').name
shutil.copyfile(filename, temp)
with open(temp, 'a') as f:
f.write('// EXTRA_INFO: ' + extra_info)
filename = temp
if not return_output:
next = original_filename + '.jso.js'
configuration.get_temp_files().note(next)
check_call(NODE_JS + [js_optimizer.JS_OPTIMIZER, filename] + passes, stdout=open(next, 'w'))
return next
else:
return run_process(NODE_JS + [js_optimizer.JS_OPTIMIZER, filename] + passes, stdout=PIPE).stdout
# evals ctors. if binaryen_bin is provided, it is the dir of the binaryen tool for this, and we are in wasm mode
@staticmethod
def eval_ctors(js_file, binary_file, binaryen_bin='', debug_info=False):
check_call([PYTHON, path_from_root('tools', 'ctor_evaller.py'), js_file, binary_file, str(Settings.TOTAL_MEMORY), str(Settings.TOTAL_STACK), str(Settings.GLOBAL_BASE), binaryen_bin, str(int(debug_info))])
@staticmethod
def eliminate_duplicate_funcs(filename):
from . import duplicate_function_eliminator
duplicate_function_eliminator.eliminate_duplicate_funcs(filename)
@staticmethod
def calculate_reachable_functions(infile, initial_list, can_reach=True):
with ToolchainProfiler.profile_block('calculate_reachable_functions'):
from . import asm_module
temp = configuration.get_temp_files().get('.js').name
Building.js_optimizer(infile, ['dumpCallGraph'], output_filename=temp, just_concat=True)
asm = asm_module.AsmModule(temp)
lines = asm.funcs_js.split('\n')
can_call = {}
for i in range(len(lines)):
line = lines[i]
if line.startswith('// REACHABLE '):
curr = json.loads(line[len('// REACHABLE '):])
func = curr[0]
targets = curr[2]
can_call[func] = set(targets)
# function tables too - treat a function all as a function that can call anything in it, which is effectively what it is
for name, funcs in asm.tables.items():
can_call[name] = set([x.strip() for x in funcs[1:-1].split(',')])
# print can_call
# Note: We ignore calls in from outside the asm module, so you could do emterpreted => outside => emterpreted, and we would
# miss the first one there. But this is acceptable to do, because we can't save such a stack anyhow, due to the outside!
# print 'can call', can_call, '\n!!!\n', asm.tables, '!'
reachable_from = {}
for func, targets in can_call.items():
for target in targets:
if target not in reachable_from:
reachable_from[target] = set()
reachable_from[target].add(func)
# print 'reachable from', reachable_from
to_check = initial_list[:]
advised = set()
if can_reach:
# find all functions that can reach the initial list
while len(to_check):
curr = to_check.pop()
if curr in reachable_from:
for reacher in reachable_from[curr]:
if reacher not in advised:
if not JS.is_dyn_call(reacher) and not JS.is_function_table(reacher):
advised.add(str(reacher))
to_check.append(reacher)
else:
# find all functions that are reachable from the initial list, including it
# all tables are assumed reachable, as they can be called from dyncall from outside
for name, funcs in asm.tables.items():
to_check.append(name)
while len(to_check):
curr = to_check.pop()
if not JS.is_function_table(curr):
advised.add(curr)
if curr in can_call:
for target in can_call[curr]:
if target not in advised:
advised.add(str(target))
to_check.append(target)
return {'reachable': list(advised), 'total_funcs': len(can_call)}
@staticmethod
def closure_compiler(filename, pretty=True):
with ToolchainProfiler.profile_block('closure_compiler'):
if not check_closure_compiler():
logging.error('Cannot run closure compiler')
raise Exception('closure compiler check failed')
CLOSURE_EXTERNS = path_from_root('src', 'closure-externs.js')
NODE_EXTERNS_BASE = path_from_root('third_party', 'closure-compiler', 'node-externs')
NODE_EXTERNS = os.listdir(NODE_EXTERNS_BASE)
NODE_EXTERNS = [os.path.join(NODE_EXTERNS_BASE, name) for name in NODE_EXTERNS
if name.endswith('.js')]
BROWSER_EXTERNS_BASE = path_from_root('third_party', 'closure-compiler', 'browser-externs')
BROWSER_EXTERNS = os.listdir(BROWSER_EXTERNS_BASE)
BROWSER_EXTERNS = [os.path.join(BROWSER_EXTERNS_BASE, name) for name in BROWSER_EXTERNS
if name.endswith('.js')]
# Something like this (adjust memory as needed):
# java -Xmx1024m -jar CLOSURE_COMPILER --compilation_level ADVANCED_OPTIMIZATIONS --variable_map_output_file src.cpp.o.js.vars --js src.cpp.o.js --js_output_file src.cpp.o.cc.js
args = [JAVA,
'-Xmx' + (os.environ.get('JAVA_HEAP_SIZE') or '1024m'), # if you need a larger Java heap, use this environment variable
'-jar', CLOSURE_COMPILER,
'--compilation_level', 'ADVANCED_OPTIMIZATIONS',
'--language_in', 'ECMASCRIPT5',
'--externs', CLOSURE_EXTERNS,
# '--variable_map_output_file', filename + '.vars',
'--js', filename, '--js_output_file', filename + '.cc.js']
for extern in NODE_EXTERNS:
args.append('--externs')
args.append(extern)
for extern in BROWSER_EXTERNS:
args.append('--externs')
args.append(extern)
if Settings.IGNORE_CLOSURE_COMPILER_ERRORS:
args.append('--jscomp_off=*')
if pretty:
args += ['--formatting', 'PRETTY_PRINT']
if os.environ.get('EMCC_CLOSURE_ARGS'):
args += shlex.split(os.environ.get('EMCC_CLOSURE_ARGS'))
logging.debug('closure compiler: ' + ' '.join(args))
process = run_process(args, stdout=PIPE, stderr=STDOUT, check=False)
if process.returncode != 0 or not os.path.exists(filename + '.cc.js'):
raise Exception('closure compiler error: ' + process.stdout + ' (rc: %d)' % process.returncode)
return filename + '.cc.js'
# minify the final wasm+JS combination. this is done after all the JS
# and wasm optimizations; here we do the very final optimizations on them
@staticmethod
def minify_wasm_js(js_file, wasm_file, expensive_optimizations, minify_whitespace, use_closure_compiler, debug_info, emit_symbol_map):
# start with JSDCE, to clean up obvious JS garbage. When optimizing for size,
# use AJSDCE (aggressive JS DCE, performs multiple iterations). Clean up
# whitespace if necessary too.
passes = []
if not Settings.LINKABLE:
passes.append('JSDCE' if not expensive_optimizations else 'AJSDCE')
if minify_whitespace:
passes.append('minifyWhitespace')
if passes:
logging.debug('running cleanup on shell code: ' + ' '.join(passes))
js_file = Building.js_optimizer_no_asmjs(js_file, ['noPrintMetadata'] + passes)
# if we can optimize this js+wasm combination under the assumption no one else
# will see the internals, do so
if not Settings.LINKABLE:
# if we are optimizing for size, shrink the combined wasm+JS
# TODO: support this when a symbol map is used
if expensive_optimizations and not emit_symbol_map:
js_file = Building.metadce(js_file, wasm_file, minify_whitespace=minify_whitespace, debug_info=debug_info)
# now that we removed unneeded communication between js and wasm, we can clean up
# the js some more.
passes = ['noPrintMetadata', 'AJSDCE']
if minify_whitespace:
passes.append('minifyWhitespace')
logging.debug('running post-meta-DCE cleanup on shell code: ' + ' '.join(passes))
js_file = Building.js_optimizer_no_asmjs(js_file, passes)
# finally, optionally use closure compiler to finish cleaning up the JS
if use_closure_compiler:
logging.debug('running closure on shell code')
js_file = Building.closure_compiler(js_file, pretty=not minify_whitespace)
return js_file
# run binaryen's wasm-metadce to dce both js and wasm
@staticmethod
def metadce(js_file, wasm_file, minify_whitespace, debug_info):
logging.debug('running meta-DCE')
temp_files = configuration.get_temp_files()
# first, get the JS part of the graph
txt = Building.js_optimizer_no_asmjs(js_file, ['emitDCEGraph', 'noEmitAst'], return_output=True)
graph = json.loads(txt)
# ensure that functions expected to be exported to the outside are roots
for item in graph:
if 'export' in item:
export = item['export']
# wasm backend's exports are prefixed differently inside the wasm
if Settings.WASM_BACKEND:
export = '_' + export
if export in Building.user_requested_exports or Settings.EXPORT_ALL:
item['root'] = True
if Settings.WASM_BACKEND:
# wasm backend's imports are prefixed differently inside the wasm
for item in graph:
if 'import' in item:
if item['import'][1][0] == '_':
item['import'][1] = item['import'][1][1:]
temp = temp_files.get('.txt').name
txt = json.dumps(graph)
with open(temp, 'w') as f:
f.write(txt)
# run wasm-metadce
cmd = [os.path.join(Building.get_binaryen_bin(), 'wasm-metadce'), '--graph-file=' + temp, wasm_file, '-o', wasm_file]
if debug_info:
cmd += ['-g']
out = run_process(cmd, stdout=PIPE).stdout
# find the unused things in js
unused = []
PREFIX = 'unused: '
for line in out.split('\n'):
if line.startswith(PREFIX):
name = line.replace(PREFIX, '').strip()
unused.append(name)
# remove them
passes = ['applyDCEGraphRemovals']
if minify_whitespace:
passes.append('minifyWhitespace')
extra_info = {'unused': unused}
return Building.js_optimizer_no_asmjs(js_file, passes, extra_info=json.dumps(extra_info))
# the exports the user requested
user_requested_exports = []
_is_ar_cache = {}
@staticmethod
def is_ar(filename):
try:
if Building._is_ar_cache.get(filename):
return Building._is_ar_cache[filename]
header = open(filename, 'rb').read(8)
sigcheck = header == b'!<arch>\n'
Building._is_ar_cache[filename] = sigcheck
return sigcheck
except Exception as e:
logging.debug('Building.is_ar failed to test whether file \'%s\' is a llvm archive file! Failed on exception: %s' % (filename, e))
return False
@staticmethod
def is_bitcode(filename):
# look for magic signature
b = open(filename, 'rb').read(4)
if b[:2] == b'BC':
return True
# look for ar signature
elif Building.is_ar(filename):
return True
# on macOS, there is a 20-byte prefix which starts with little endian
# encoding of 0x0B17C0DE
elif b == b'\xDE\xC0\x17\x0B':
b = bytearray(open(filename, 'rb').read(22))
return b[20:] == b'BC'
return False
@staticmethod
def is_wasm(filename):
magic = bytearray(open(filename, 'rb').read(4))
return magic == '\0asm'
@staticmethod
# Given the name of a special Emscripten-implemented system library, returns an array of absolute paths to JS library
# files inside emscripten/src/ that corresponds to the library name.
def path_to_system_js_libraries(library_name):
# Some native libraries are implemented in Emscripten as system side JS libraries
js_system_libraries = {
'c': '',
'dl': '',
'EGL': 'library_egl.js',
'GL': 'library_gl.js',
'GLESv2': 'library_gl.js',
'GLEW': 'library_glew.js',
'glfw': 'library_glfw.js',
'glfw3': 'library_glfw.js',
'GLU': '',
'glut': 'library_glut.js',
'm': '',
'openal': 'library_openal.js',
'rt': '',
'pthread': '',
'X11': 'library_xlib.js',
'SDL': 'library_sdl.js',
'stdc++': '',
'uuid': 'library_uuid.js'
}
library_files = []
if library_name in js_system_libraries:
if len(js_system_libraries[library_name]):
library_files += [js_system_libraries[library_name]]
# TODO: This is unintentional due to historical reasons. Improve EGL to use HTML5 API to avoid depending on GLUT.
if library_name == 'EGL':
library_files += ['library_glut.js']
elif library_name.endswith('.js') and os.path.isfile(path_from_root('src', 'library_' + library_name)):
library_files += ['library_' + library_name]
else:
if Settings.ERROR_ON_MISSING_LIBRARIES:
exit_with_error('emcc: cannot find library "%s"', library_name)
else:
logging.warning('emcc: cannot find library "%s"', library_name)
return library_files
@staticmethod
# Given a list of Emscripten link settings, returns a list of paths to system JS libraries
# that should get linked automatically in to the build when those link settings are present.
def path_to_system_js_libraries_for_settings(link_settings):
system_js_libraries = []
if 'EMTERPRETIFY_ASYNC=1' in link_settings:
system_js_libraries += ['library_async.js']
if 'ASYNCIFY=1' in link_settings:
system_js_libraries += ['library_async.js']
if 'LZ4=1' in link_settings:
system_js_libraries += ['library_lz4.js']
if 'USE_SDL=1' in link_settings:
system_js_libraries += ['library_sdl.js']
if 'USE_SDL=2' in link_settings:
system_js_libraries += ['library_egl.js', 'library_glut.js', 'library_gl.js']
return [path_from_root('src', x) for x in system_js_libraries]
@staticmethod
def get_binaryen():
# fetch the port, so we have binaryen set up. indicate we need binaryen
# using the settings
from . import system_libs
old = Settings.WASM
Settings.WASM = 1
system_libs.get_port('binaryen', Settings)
Settings.WASM = old
@staticmethod
def get_binaryen_bin():
Building.get_binaryen()
return os.path.join(Settings.BINARYEN_ROOT, 'bin')
@staticmethod
def get_binaryen_lib():
Building.get_binaryen()
# The wasm.js and binaryen.js libraries live in 'bin' in the binaryen
# source tree, but are installed to share/binaryen.
paths = (os.path.join(Settings.BINARYEN_ROOT, 'bin'),
os.path.join(Settings.BINARYEN_ROOT, 'share', 'binaryen'))
for dirname in paths:
if os.path.exists(os.path.join(dirname, 'wasm.js')):
return dirname
exit_with_error('emcc: cannot find binaryen js libraries (tried: %s)', str(paths))
# compatibility with existing emcc, etc. scripts
Cache = cache.Cache()
chunkify = cache.chunkify
def reconfigure_cache():
global Cache
Cache = cache.Cache()
# Placeholder strings used for SINGLE_FILE
class FilenameReplacementStrings:
WASM_TEXT_FILE = '{{{ FILENAME_REPLACEMENT_STRINGS_WASM_TEXT_FILE }}}'
WASM_BINARY_FILE = '{{{ FILENAME_REPLACEMENT_STRINGS_WASM_BINARY_FILE }}}'
ASMJS_CODE_FILE = '{{{ FILENAME_REPLACEMENT_STRINGS_ASMJS_CODE_FILE }}}'
class JS(object):
memory_initializer_pattern = '/\* memory initializer \*/ allocate\(\[([\d, ]*)\], "i8", ALLOC_NONE, ([\d+\.GLOBAL_BASEHgb]+)\);'
no_memory_initializer_pattern = '/\* no memory initializer \*/'
memory_staticbump_pattern = 'STATICTOP = STATIC_BASE \+ (\d+);'
global_initializers_pattern = '/\* global initializers \*/ __ATINIT__.push\((.+)\);'
module_export_name_substitution_pattern = '"__EMSCRIPTEN_PRIVATE_MODULE_EXPORT_NAME_SUBSTITUTION__"'
@staticmethod
def to_nice_ident(ident): # limited version of the JS function toNiceIdent
return ident.replace('%', '$').replace('@', '_').replace('.', '_')
# Returns the given string with escapes added so that it can safely be placed inside a string in JS code.
@staticmethod
def escape_for_js_string(s):
s = s.replace('\\', '/').replace("'", "\\'").replace('"', '\\"')
return s
# Returns the subresource location for run-time access
@staticmethod
def get_subresource_location(path, data_uri=None):
if data_uri is None:
data_uri = Settings.SINGLE_FILE
if data_uri:
with open(path, 'rb') as f:
data = base64.b64encode(f.read())
return 'data:application/octet-stream;base64,' + asstr(data)
else:
return os.path.basename(path)
@staticmethod
def make_initializer(sig, settings=None):
settings = settings or Settings
if sig == 'i':
return '0'
elif sig == 'f' and settings.get('PRECISE_F32'):
return 'Math_fround(0)'
elif sig == 'j':
if settings:
assert settings['WASM'], 'j aka i64 only makes sense in wasm-only mode in binaryen'
return 'i64(0)'
elif sig == 'F':
return 'SIMD_Float32x4_check(SIMD_Float32x4(0,0,0,0))'
elif sig == 'D':
return 'SIMD_Float64x2_check(SIMD_Float64x2(0,0,0,0))'
elif sig == 'B':
return 'SIMD_Int8x16_check(SIMD_Int8x16(0,0,0,0))'
elif sig == 'S':
return 'SIMD_Int16x8_check(SIMD_Int16x8(0,0,0,0))'
elif sig == 'I':
return 'SIMD_Int32x4_check(SIMD_Int32x4(0,0,0,0))'
else:
return '+0'
FLOAT_SIGS = ['f', 'd']
@staticmethod
def make_coercion(value, sig, settings=None, ffi_arg=False, ffi_result=False, convert_from=None):
settings = settings or Settings
if sig == 'i':
if convert_from in JS.FLOAT_SIGS:
value = '(~~' + value + ')'
return value + '|0'
if sig in JS.FLOAT_SIGS and convert_from == 'i':
value = '(' + value + '|0)'
if sig == 'f' and settings.get('PRECISE_F32'):
if ffi_arg:
return '+Math_fround(' + value + ')'
elif ffi_result:
return 'Math_fround(+(' + value + '))'
else:
return 'Math_fround(' + value + ')'
elif sig == 'd' or sig == 'f':
return '+' + value
elif sig == 'j':
if settings:
assert settings['WASM'], 'j aka i64 only makes sense in wasm-only mode in binaryen'
return 'i64(' + value + ')'
elif sig == 'F':
return 'SIMD_Float32x4_check(' + value + ')'
elif sig == 'D':
return 'SIMD_Float64x2_check(' + value + ')'
elif sig == 'B':
return 'SIMD_Int8x16_check(' + value + ')'
elif sig == 'S':
return 'SIMD_Int16x8_check(' + value + ')'
elif sig == 'I':
return 'SIMD_Int32x4_check(' + value + ')'
else:
return value
@staticmethod
def legalize_sig(sig):
ret = [sig[0]]
for s in sig[1:]:
if s != 'j':
ret.append(s)
else:
# an i64 is legalized into i32, i32
ret.append('i')
ret.append('i')
return ''.join(ret)
@staticmethod
def make_extcall(sig, named=True):
args = ','.join(['a' + str(i) for i in range(1, len(sig))])
args = 'index' + (',' if args else '') + args
# C++ exceptions are numbers, and longjmp is a string 'longjmp'
ret = '''function%s(%s) {
%sModule["dynCall_%s"](%s);
}''' % ((' extCall_' + sig) if named else '', args, 'return ' if sig[0] != 'v' else '', sig, args)
return ret
@staticmethod
def make_jscall(sig, sig_order=0, named=True):
fnargs = ','.join(['a' + str(i) for i in range(1, len(sig))])
args = 'index' + (',' if fnargs else '') + fnargs
# While asm.js/fastcomp's addFunction support preallocates
# Settings.RESERVED_FUNCTION_POINTERS slots in functionPointers array, on
# the Wasm backend we reserve that number of slots for each possible
# function signature, so it is (Settings.RESERVED_FUNCTION_POINTERS * # of
# indirectly called function signatures) slots in total. So the index to
# functionPointers array should be adjusted according to the order of the
# function signature. The reason we do this is Wasm has a single unified
# function table while asm.js maintains separate function table per
# signature.
# e.g. When there are three possible function signature, ['v', 'ii', 'ff'],
# the 'sig_order' parameter will be 0 for 'v', 1 for 'ii', and so on.
if Settings.WASM_BACKEND:
index = 'index + %d' % (Settings.RESERVED_FUNCTION_POINTERS * sig_order)
else:
index = 'index'
ret = '''function%s(%s) {
%sfunctionPointers[%s](%s);
}''' % ((' jsCall_' + sig) if named else '', args, 'return ' if sig[0] != 'v' else '', index, fnargs)
return ret
@staticmethod
def make_invoke(sig, named=True):
if sig == 'X':
# 'X' means the generic unknown signature, used in wasm dynamic linking
# to indicate an invoke that the main JS may not have defined, so we
# go through this (which may be slower, as we don't declare the
# arguments explicitly). In non-wasm dynamic linking, the other modules
# have JS and so can define their own invokes to be linked in.
# This only makes sense in function pointer emulation mode, where we
# can do a direct table call.
assert Settings.WASM
assert Settings.EMULATED_FUNCTION_POINTERS
args = ''
body = '''
var args = Array.prototype.slice.call(arguments);
return Module['wasmTable'].get(args[0]).apply(null, args.slice(1));
'''
else:
legal_sig = JS.legalize_sig(sig) # TODO: do this in extcall, jscall?
args = ','.join(['a' + str(i) for i in range(1, len(legal_sig))])
args = 'index' + (',' if args else '') + args
ret = 'return ' if sig[0] != 'v' else ''
body = '%sModule["dynCall_%s"](%s);' % (ret, sig, args)
# C++ exceptions are numbers, and longjmp is a string 'longjmp'
ret = '''function%s(%s) {
var sp = stackSave();
try {
%s
} catch(e) {
stackRestore(sp);
if (typeof e !== 'number' && e !== 'longjmp') throw e;
Module["setThrew"](1, 0);
}
}''' % ((' invoke_' + sig) if named else '', args, body)
return ret
@staticmethod
def align(x, by):
while x % by != 0:
x += 1
return x
@staticmethod
def generate_string_initializer(s):
if Settings.ASSERTIONS:
# append checksum of length and content
crcTable = []
for i in range(256):
crc = i
for bit in range(8):
crc = (crc >> 1) ^ ((crc & 1) * 0xedb88320)
crcTable.append(crc)
crc = 0xffffffff
n = len(s)
crc = crcTable[(crc ^ n) & 0xff] ^ (crc >> 8)
crc = crcTable[(crc ^ (n >> 8)) & 0xff] ^ (crc >> 8)
for i in s:
crc = crcTable[(crc ^ i) & 0xff] ^ (crc >> 8)
for i in range(4):
s.append((crc >> (8 * i)) & 0xff)
s = ''.join(map(chr, s))
s = s.replace('\\', '\\\\').replace("'", "\\'")
s = s.replace('\n', '\\n').replace('\r', '\\r')
# Escape the ^Z (= 0x1a = substitute) ASCII character and all characters higher than 7-bit ASCII.
def escape(x):
return '\\x{:02x}'.format(ord(x.group()))
return re.sub('[\x1a\x80-\xff]', escape, s)
@staticmethod
def is_dyn_call(func):
return func.startswith('dynCall_')
@staticmethod
def is_function_table(name):
return name.startswith('FUNCTION_TABLE_')
class WebAssembly(object):
@staticmethod
def lebify(x):
assert x >= 0, 'TODO: signed'
ret = []
while 1:
byte = x & 127
x >>= 7
more = x != 0
if more:
byte = byte | 128
ret.append(byte)
if not more:
break
return bytearray(ret)
@staticmethod
def make_shared_library(js_file, wasm_file):
# a wasm shared library has a special "dylink" section, see tools-conventions repo
js = open(js_file).read()
m = re.search("var STATIC_BUMP = (\d+);", js)
mem_size = int(m.group(1))
m = re.search("Module\['wasmTableSize'\] = (\d+);", js)
table_size = int(m.group(1))
m = re.search('gb = alignMemory\(getMemory\(\d+ \+ (\d+)\), (\d+) \|\| 1\);', js)
assert m.group(1) == m.group(2), 'js must contain a clear alignment for the wasm shared library'
mem_align = int(m.group(1))
mem_align = int(math.log(mem_align, 2))
logging.debug('creating wasm dynamic library with mem size %d, table size %d, align %d' % (mem_size, table_size, mem_align))
wso = js_file + '.wso'
# write the binary
wasm = open(wasm_file, 'rb').read()
f = open(wso, 'wb')
f.write(wasm[0:8]) # copy magic number and version
# write the special section
f.write(b'\0') # user section is code 0
# need to find the size of this section
name = b"\06dylink" # section name, including prefixed size
contents = (WebAssembly.lebify(mem_size) + WebAssembly.lebify(mem_align) +
WebAssembly.lebify(table_size) + WebAssembly.lebify(0))
size = len(name) + len(contents)
f.write(WebAssembly.lebify(size))
f.write(name)
f.write(contents)
f.write(wasm[8:]) # copy rest of binary
f.close()
return wso
# Python 2-3 compatibility helper function:
# Converts a string to the native str type.
def asstr(s):
if str is bytes:
if isinstance(s, unicode):
return s.encode('utf-8')
elif isinstance(s, bytes):
return s.decode('utf-8')
return s
def asbytes(s):
if str is bytes:
# Python 2 compatibility:
# s.encode implicitly will first call s.decode('ascii') which may fail when with Unicode characters
return s
return s.encode('utf-8')
def suffix(name):
"""Return the file extension *not* including the '.'."""
return os.path.splitext(name)[1][1:]
def unsuffixed(name):
"""Return the filename without the extention.
If there are multiple extensions this strips only the final one.
"""
return os.path.splitext(name)[0]
def unsuffixed_basename(name):
return os.path.basename(unsuffixed(name))
def safe_move(src, dst):
src = os.path.abspath(src)
dst = os.path.abspath(dst)
if os.path.isdir(dst):
dst = os.path.join(dst, os.path.basename(src))
if src == dst:
return
if dst == '/dev/null':
return
shutil.move(src, dst)
def safe_copy(src, dst):
src = os.path.abspath(src)
dst = os.path.abspath(dst)
if os.path.isdir(dst):
dst = os.path.join(dst, os.path.basename(src))
if src == dst:
return
if dst == '/dev/null':
return
shutil.copyfile(src, dst)
def clang_preprocess(filename):
# TODO: REMOVE HACK AND PASS PREPROCESSOR FLAGS TO CLANG.
return run_process([CLANG_CC, '-DFETCH_DEBUG=1', '-E', '-P', '-C', '-x', 'c', filename], check=True, stdout=subprocess.PIPE).stdout
def read_and_preprocess(filename):
temp_dir = get_emscripten_temp_dir()
# Create a settings file with the current settings to pass to the JS preprocessor
# Note: Settings.serialize returns an array of -s options i.e. ['-s', '<setting1>', '-s', '<setting2>', ...]
# we only want the actual settings, hence the [1::2] slice operation.
settings_str = "var " + ";\nvar ".join(Settings.serialize()[1::2])
settings_file = os.path.join(temp_dir, 'settings.js')
open(settings_file, 'w').write(settings_str)
# Run the JS preprocessor
# N.B. We can't use the default stdout=PIPE here as it only allows 64K of output before it hangs
# and shell.html is bigger than that!
# See https://thraxil.org/users/anders/posts/2008/03/13/Subprocess-Hanging-PIPE-is-your-enemy/
(path, file) = os.path.split(filename)
if not path:
path = None
stdout = os.path.join(temp_dir, 'stdout')
args = [settings_file, file]
run_js(path_from_root('tools/preprocessor.js'), NODE_JS, args, True, stdout=open(stdout, 'w'), cwd=path)
out = open(stdout, 'r').read()
return out
# Generates a suitable fetch-worker.js script from the given input source JS file (which is an asm.js build output),
# and writes it out to location output_file. fetch-worker.js is the root entry point for a dedicated filesystem web
# worker in -s ASMFS=1 mode.
def make_fetch_worker(source_file, output_file):
src = open(source_file, 'r').read()
funcs_to_import = ['alignUp', 'getTotalMemory', 'stringToUTF8', 'intArrayFromString', 'lengthBytesUTF8', 'stringToUTF8Array', '_emscripten_is_main_runtime_thread', '_emscripten_futex_wait']
asm_funcs_to_import = ['_malloc', '_free', '_sbrk', '___pthread_mutex_lock', '___pthread_mutex_unlock']
function_prologue = '''this.onerror = function(e) {
console.error(e);
}
'''
asm_start = src.find('// EMSCRIPTEN_START_ASM')
for func in funcs_to_import + asm_funcs_to_import:
loc = src.find('function ' + func + '(', asm_start if func in asm_funcs_to_import else 0)
if loc == -1:
exit_with_error('failed to find function %s!', func)
end_loc = src.find('{', loc) + 1
nesting_level = 1
while nesting_level > 0:
if src[end_loc] == '{':
nesting_level += 1
if src[end_loc] == '}':
nesting_level -= 1
end_loc += 1
func_code = src[loc:end_loc]
function_prologue = function_prologue + '\n' + func_code
fetch_worker_src = function_prologue + '\n' + clang_preprocess(path_from_root('src', 'fetch-worker.js'))
open(output_file, 'w').write(fetch_worker_src)
| if opt_level == 0:
return '-O0'
if shrink_level == 1:
return '-Os'
elif shrink_level >= 2:
return '-Oz'
else:
return '-O' + str(min(opt_level, 3)) |
credential.py |
class Credential:
'''
Class that generates instances of a users credentials
'''
# Empty list of credentials
credential_list = []
def __init__(self, user_password, credential_name, credential_password):
'''
__init__ method to define the properties of a User object
Args:
credential_name : name of an account
user_password : password of the user
credential_password : password for the user account
'''
self.user_password = user_password
self.credential_name = credential_name
self.credential_password = credential_password
def save_credential(self):
'''
Method that saves a user's credentials to credential list
'''
Credential.credential_list.append(self)
@classmethod
def generate_password(cls):
'''
Method that generates a random alphanumeric password
'''
# Length of the generated password
size = 8
# Generate random alphanumeric
alphanum = string.ascii_uppercase + string.digits + string.ascii_lowercase
# Create password
password = ''.join( choice(alphanum) for num in range(size) )
return password
@classmethod
def | (cls,password):
'''
Method that returns the credential list
Args:
password : the user password
'''
user_credential_list = []
for credential in cls.credential_list:
if credential.user_password == password:
user_credential_list.append(credential)
return user_credential_list
@classmethod
def credential_exist(cls, name):
'''
Method that checks if a credential exists in the credential list
Args:
name: name of the credential to search
Returns:
Boolean: true or false depending if the contact exists
'''
for credential in cls.credential_list:
if credential.credential_name == name:
return True
return False | display_credential |
buffered-data-source.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ObservableHandler = /** @class */ (function () {
function | () {
this.observers = {};
}
ObservableHandler.prototype.subscribe = function (eventType, callback) {
var _this = this;
var index = (ObservableHandler.currentIndex++).toString();
this.observers[index] = {
handler: callback,
eventType: eventType
};
return function () { return delete _this.observers[index]; };
};
ObservableHandler.prototype.notify = function (event) {
var _this = this;
Object.keys(this.observers).filter(function (e) { return _this.observers[e].eventType === event.eventType; }).forEach(function (key) {
if (_this.observers[key]) {
_this.observers[key].handler(event);
}
});
};
ObservableHandler.currentIndex = 0;
return ObservableHandler;
}());
exports.ObservableHandler = ObservableHandler;
var DataSourceEventHandlerImpl = /** @class */ (function () {
function DataSourceEventHandlerImpl() {
this.handler = new ObservableHandler();
this.invalidateCache = this.subscriber('INVALIDATE_CACHE');
}
DataSourceEventHandlerImpl.prototype.subscriber = function (eventType, rowNumber) {
var _this = this;
var disposer;
var self = {
subscribe: function (handler) {
disposer = _this.handler.subscribe(eventType, function (event) {
if (typeof event.value.rowNumber === 'undefined' || event.value.rowNumber === rowNumber || typeof rowNumber === 'undefined') {
handler(event);
}
});
return self;
},
dispose: function () {
if (disposer) {
disposer();
}
return self;
}
};
return self;
};
;
DataSourceEventHandlerImpl.prototype.rowEvent = function (rowNumber) {
return {
addRow: this.subscriber('ADD_ROW', rowNumber),
deleteRow: this.subscriber('DELETE_ROW', rowNumber),
updateRow: this.subscriber('UPDATE_ROW', rowNumber),
invalidateRow: this.subscriber('INVALIDATE_ROW', rowNumber)
};
};
;
return DataSourceEventHandlerImpl;
}());
exports.DataSourceEventHandlerImpl = DataSourceEventHandlerImpl;
var BufferedDataSource = /** @class */ (function () {
function BufferedDataSource(options) {
this.pageCache = {};
this.cntCacheEntries = 0;
this.lastRowNumber = -1;
this.lruEntries = [];
this.direction = 1;
this.observable = new DataSourceEventHandlerImpl();
this.options = options;
this.pageCache = [];
this.pageSize = options.dataSource.pageSize;
this.prefetchCnt = options.prefetchCnt === undefined ? 1 : options.prefetchCnt;
this.cacheSize = (options.cacheSize === undefined ? 4 : options.cacheSize) + this.prefetchCnt;
this.eventHandlers = options.eventHandlers;
if (this.prefetchCnt >= this.cacheSize) {
throw new Error('prefetchCnt should be less than cacheSize to prefent');
}
}
BufferedDataSource.prototype.setDirection = function (direction) {
this.direction = direction;
};
BufferedDataSource.prototype.getRow = function (rowNum) {
var _this = this;
// Optimisation specially for components which iterate through a number of columns
// retrieving the same row
if (rowNum !== this.lastRowNumber) {
this.lastRow = this.getPage(this.toPageNum(rowNum)).then(function (page) { return page[rowNum % _this.pageSize]; });
this.lastRowNumber = rowNum;
}
return this.lastRow;
};
BufferedDataSource.prototype.getPage = function (pageNumber) {
return this.internalGetPage(pageNumber, false);
};
BufferedDataSource.prototype.internalGetPage = function (pageNumber, isPrefetching) {
var _this = this;
var cacheEntry = this.pageCache[pageNumber];
var result;
if (cacheEntry) {
cacheEntry.updatedTs = Date.now();
var lruIndex = this.lruEntries.indexOf(pageNumber);
if (lruIndex !== 0) {
this.lruEntries.splice(lruIndex, 1);
this.lruEntries.unshift(pageNumber);
}
result = cacheEntry.pagePromise;
}
else {
result = this.fetch(pageNumber);
}
if (!isPrefetching) {
if (this.direction === 1) {
if (this.options.dataSource.totalRows === undefined) {
this.prefetchForward(pageNumber, Number.MAX_VALUE);
}
else if (typeof this.options.dataSource.totalRows === 'number') {
this.prefetchForward(pageNumber, this.options.dataSource.totalRows);
}
else {
this.options.dataSource.totalRows.then(function (t) { return _this.prefetchForward(pageNumber, t); });
}
}
else {
for (var i = pageNumber - 1; i >= pageNumber - this.prefetchCnt && i >= 0; i--) {
this.internalGetPage(i, true);
}
}
}
return result;
};
BufferedDataSource.prototype.prefetchForward = function (pageNumber, end) {
var endPage = Math.ceil(end / this.pageSize);
for (var i = pageNumber + 1; i <= pageNumber + this.prefetchCnt && i < endPage; i++) {
this.internalGetPage(i, true);
}
};
BufferedDataSource.prototype.invalidateCache = function () {
this.pageCache = {};
this.cntCacheEntries = 0;
this.lastRowNumber = -1;
this.observable.handler.notify({
eventType: 'INVALIDATE_CACHE',
value: {}
});
};
BufferedDataSource.prototype.invalidatePageEntry = function (pageNum) {
delete this.pageCache[pageNum];
var index = this.lruEntries.indexOf(pageNum);
if (index > -1) {
this.lruEntries.splice(index, 1);
}
if (this.lastRowNumber >= pageNum * this.pageSize && this.lastRowNumber < (pageNum + 1) * this.pageSize) {
this.lastRowNumber = -1;
}
var baseNum = pageNum * this.pageSize;
for (var i = 0; i < this.pageSize; i++) {
this.notifyInvalidateRow(baseNum + i);
}
};
BufferedDataSource.prototype.addNewPage = function (pageNum, pagePromise) {
if (this.cntCacheEntries < this.cacheSize) {
this.cntCacheEntries++;
this.lruEntries.unshift(pageNum);
}
else {
var removedPageNo = this.lruEntries.pop();
this.lruEntries.unshift(pageNum);
delete this.pageCache[removedPageNo];
}
this.pageCache[pageNum] = {
pagePromise: pagePromise,
updatedTs: Date.now()
};
};
BufferedDataSource.prototype.fetch = function (pageNum) {
var pagePromise = this.options.dataSource.getPage(pageNum);
this.addNewPage(pageNum, pagePromise);
return pagePromise;
};
BufferedDataSource.prototype.toPageNum = function (rowNum) {
return Math.floor(rowNum / this.pageSize);
};
Object.defineProperty(BufferedDataSource.prototype, "totalRows", {
get: function () {
return this.options.dataSource.totalRows;
},
enumerable: true,
configurable: true
});
BufferedDataSource.prototype.notifyDeleteRow = function (rowNumber) {
this.observable.handler.notify({
eventType: 'DELETE_ROW',
value: {
rowNumber: rowNumber
}
});
};
BufferedDataSource.prototype.notifyInvalidateRow = function (rowNumber) {
this.observable.handler.notify({
eventType: 'INVALIDATE_ROW',
value: {
rowNumber: rowNumber
}
});
};
BufferedDataSource.prototype.notifyUpdateRow = function (rowNumber, row) {
this.observable.handler.notify({
eventType: 'UPDATE_ROW',
value: {
rowNumber: rowNumber,
row: row
}
});
};
BufferedDataSource.prototype.updateRow = function (param) {
var _this = this;
var pageNum = this.toPageNum(param.rowNumber);
var pagePromise = this.pageCache[pageNum];
if (pagePromise) {
pagePromise.pagePromise.then(function (page) {
page[param.rowNumber % _this.pageSize] = param.row;
_this.notifyUpdateRow(param.rowNumber, param.row);
});
}
};
BufferedDataSource.prototype.deleteRow = function (param) {
var _this = this;
if (this.lastRowNumber >= param.rowNumber) {
this.lastRowNumber = -1;
}
return this.options.dataSource.deleteRow(param)
.then(function () { return _this.deleteRowFromCache(param.rowNumber); })
.then(function () { return _this.notifyDeleteRow(param.rowNumber); });
};
BufferedDataSource.prototype.invalidateCacheFromPageNumber = function (pageNumber) {
var _this = this;
Object.keys(this.pageCache)
.map(function (key) { return Number(key); })
.filter(function (key) { return key >= pageNumber; })
.forEach(function (key) { return _this.invalidatePageEntry(key); });
};
BufferedDataSource.prototype.deleteRowFromCache = function (rowNumber) {
var _this = this;
var pageNumber = this.toPageNum(rowNumber);
var entry = this.pageCache[pageNumber];
var firstRowPromise;
if (entry) {
firstRowPromise = entry.pagePromise.then(function (page) { return page[0]; });
}
else {
firstRowPromise = Promise.resolve(null);
}
if (!entry || !this.pageCache[pageNumber + 1]) {
this.invalidateCacheFromPageNumber(pageNumber);
}
else {
var nextPageFirstRow_1 = (pageNumber + 1) * this.pageSize;
entry.pagePromise = entry.pagePromise.then(function (page) {
page.splice(rowNumber % _this.pageSize, 1);
if (page.length === _this.pageSize - 1) {
return _this.deleteRowFromCache(nextPageFirstRow_1)
.then(function (row) {
if (row) {
page.push(row);
}
return page;
});
}
else {
return page;
}
}).then(function (page) {
for (var i = rowNumber + 1; i < (pageNumber + 1) * _this.pageSize; i++) {
_this.notifyUpdateRow(rowNumber, page[rowNumber % _this.pageSize]);
}
return page;
});
}
return firstRowPromise;
};
BufferedDataSource.prototype.notifyAddRow = function (value) {
this.observable.handler.notify({
eventType: 'ADD_ROW',
value: value
});
};
BufferedDataSource.prototype.addRow = function (param) {
var _this = this;
if (param.noUpdateDataSource) {
if (this.totalRows.then) {
this.totalRows.then(function (totalRows) {
_this.addRowToCache(totalRows, param.row);
_this.notifyAddRow({ row: param.row, rowNumber: totalRows });
});
}
else {
this.addRowToCache(this.totalRows, param.row);
this.notifyAddRow({ row: param.row, rowNumber: this.totalRows });
}
}
else {
var result_1 = this.options.dataSource.addRow(param);
return result_1.then(function (r) {
return _this.addRowToCache(r.rowNumber, r.row)
.then(function () {
_this.notifyAddRow(r);
return result_1;
});
});
}
};
BufferedDataSource.prototype.addRowToCache = function (rowNumber, row) {
var _this = this;
var pageNumber = this.toPageNum(rowNumber);
var entry = this.pageCache[pageNumber];
if (entry) {
var nextPageFirstRow_2 = (pageNumber + 1) * this.pageSize;
this.pageCache[pageNumber].pagePromise =
entry.pagePromise.then(function (page) {
page.splice(rowNumber % _this.pageSize, 0, row);
if (page.length > _this.pageSize) {
return _this.addRowToCache(nextPageFirstRow_2, page.pop()).then(function () { return page; });
}
else {
return page;
}
});
return this.pageCache[pageNumber].pagePromise.then(function (page) {
for (var i = rowNumber + 1; i < nextPageFirstRow_2; i++) {
_this.notifyUpdateRow(rowNumber, page[rowNumber % _this.pageSize]);
}
});
}
else {
this.invalidateCacheFromPageNumber(pageNumber);
return Promise.resolve();
}
};
return BufferedDataSource;
}());
exports.BufferedDataSource = BufferedDataSource;
exports.default = BufferedDataSource;
| ObservableHandler |
braille_translator.py | from .braille_cell import BrailleCell
from .braille_string import BrailleString
class | (object):
_simple_cells = None
def __init__(self, text):
self.__raw_text = text
if BrailleTranslator._simple_cells is None:
self.__setup_class_simple_cells()
@property
def as_grade_1(self):
cell_list = []
for c in self.__raw_text:
cell = self._simple_cells[c]
cell_list.append(cell)
bs = BrailleString(self.__raw_text, cell_list)
return bs
def __setup_class_simple_cells(self):
cd = {}
cd['a'] = BrailleCell('a', '*..', '...')
cd['b'] = BrailleCell('b', '**.', '...')
cd['c'] = BrailleCell('c', '*..', '*..')
cd['d'] = BrailleCell('d', '*..', '**.')
cd['e'] = BrailleCell('e', '*..', '.*.')
cd['f'] = BrailleCell('f', '**.', '*..')
cd['g'] = BrailleCell('g', '**.', '**.')
cd['h'] = BrailleCell('h', '**.', '.*.')
cd['i'] = BrailleCell('i', '.*.', '*..')
cd['j'] = BrailleCell('j', '.*.', '**.')
cd['k'] = BrailleCell('k', '*.*', '...')
cd['l'] = BrailleCell('l', '***', '...')
cd['m'] = BrailleCell('m', '*.*', '*..')
cd['n'] = BrailleCell('n', '*.*', '**.')
cd['o'] = BrailleCell('o', '*.*', '.*.')
cd['p'] = BrailleCell('p', '***', '*..')
cd['q'] = BrailleCell('q', '***', '**.')
cd['r'] = BrailleCell('r', '***', '.*.')
cd['s'] = BrailleCell('s', '.**', '*..')
cd['t'] = BrailleCell('t', '.**', '**.')
cd['u'] = BrailleCell('u', '*.*', '..*')
cd['v'] = BrailleCell('v', '***', '..*')
cd['w'] = BrailleCell('w', '.*.', '***')
cd['x'] = BrailleCell('x', '*.*', '*.*')
cd['y'] = BrailleCell('y', '*.*', '***')
cd['z'] = BrailleCell('z', '*.*', '.**')
BrailleTranslator._simple_cells = cd
| BrailleTranslator |
t3ammy.py | class Teammy:
def __init__(self):
self.name = 'T3ammy'
self.lastname = 'Sit_Uncle_Engineer'
self.nickname = 'teammy'
def WhoIAM(self):
'''
นี่คือฟังชั่่นที่ใช้ในการแสดงชื่อของคราสนี้
'''
print('My name is: {}'.format(self.name))
print('My lastname is: {}'.format(self.lastname))
print('My nickname is: {}'.format(self.nickname))
@property
def email(self):
'''
This function will show my email
'''
return '{}.{}@teammy.engineer.com'.format(self.name.lower(),self.lastname.lower())
def thainame(self):
print('ทีมมี่ ศิษย์ลุงวิศวกร')
return 'ทีมมี่ ศิษย์ล | '
def __str__(self):
return 'This is a book'
class Spiderman:
def __init__(self):
self.name = 'Peter'
self.lastname = 'Parker'
self.nickname = 'peter'
self.thainame = 'ปีเตอร์'
if __name__ == '__main__':
myName = Teammy()
print(help(myName.WhoIAM))
print('-------------')
print(myName) # __str__ work when call variable
print('-------------')
print(myName.name)
print(myName.lastname)
print(myName.nickname)
print('-------------')
myName.thainame()
print('-------------')
myName.WhoIAM()
print('-------------')
print(myName.email) # is Property not use ()
print('-------------')
myFriend = Teammy()
myFriend.WhoIAM()
print('-------------')
myFriend.name = 'Peter'
myFriend.lastname = 'Parker'
myFriend.nickname = 'peter'
myFriend.WhoIAM()
print('-------------')
print(myFriend.name)
print(myFriend.lastname)
print(myFriend.nickname)
print('-------------')
pt = Spiderman()
print(pt.name)
print(pt.thainame)
| ุงวิศวกร |
sessionModelFactory.ts | /* eslint-disable @typescript-eslint/no-explicit-any */
import { lazy } from 'react'
import { AnyConfigurationModel } from '@jbrowse/core/configuration/configurationSchema'
import {
readConfObject,
isConfigurationModel,
} from '@jbrowse/core/configuration'
import {
Region,
TrackViewModel,
DialogComponentType,
} from '@jbrowse/core/util/types'
import addSnackbarToModel from '@jbrowse/core/ui/SnackbarModel'
import { getContainingView } from '@jbrowse/core/util'
import { observable } from 'mobx'
import {
getMembers,
getParent,
getSnapshot,
getType,
IAnyStateTreeNode,
isAlive,
isModelType,
isReferenceType,
SnapshotIn,
types,
walk,
} from 'mobx-state-tree'
import PluginManager from '@jbrowse/core/PluginManager'
import TextSearchManager from '@jbrowse/core/TextSearch/TextSearchManager'
import SettingsIcon from '@material-ui/icons/Settings'
import CopyIcon from '@material-ui/icons/FileCopy'
import DeleteIcon from '@material-ui/icons/Delete'
import InfoIcon from '@material-ui/icons/Info'
const AboutDialog = lazy(() => import('@jbrowse/core/ui/AboutDialog'))
declare interface ReferringNode {
node: IAnyStateTreeNode
key: string
}
export default function | (
pluginManager: PluginManager,
assemblyConfigSchemasType = types.frozen(), // if not using sessionAssemblies
) {
const minDrawerWidth = 128
const sessionModel = types
.model('JBrowseDesktopSessionModel', {
name: types.identifier,
margin: 0,
drawerWidth: types.optional(
types.refinement(types.integer, width => width >= minDrawerWidth),
384,
),
views: types.array(pluginManager.pluggableMstType('view', 'stateModel')),
widgets: types.map(
pluginManager.pluggableMstType('widget', 'stateModel'),
),
activeWidgets: types.map(
types.safeReference(
pluginManager.pluggableMstType('widget', 'stateModel'),
),
),
connectionInstances: types.array(
pluginManager.pluggableMstType('connection', 'stateModel'),
),
sessionAssemblies: types.array(assemblyConfigSchemasType),
minimized: types.optional(types.boolean, false),
drawerPosition: types.optional(
types.string,
localStorage.getItem('drawerPosition') || 'right',
),
})
.volatile((/* self */) => ({
/**
* this is the globally "selected" object. can be anything.
* code that wants to deal with this should examine it to see what
* kind of thing it is.
*/
selection: undefined,
/**
* this is the current "task" that is being performed in the UI.
* this is usually an object of the form
* `{ taskName: "configure", target: thing_being_configured }`
*/
task: undefined,
queueOfDialogs: observable.array([] as [DialogComponentType, any][]),
}))
.views(self => ({
get DialogComponent() {
if (self.queueOfDialogs.length) {
const firstInQueue = self.queueOfDialogs[0]
return firstInQueue && firstInQueue[0]
}
return undefined
},
get DialogProps() {
if (self.queueOfDialogs.length) {
const firstInQueue = self.queueOfDialogs[0]
return firstInQueue && firstInQueue[1]
}
return undefined
},
get rpcManager() {
return getParent(self).jbrowse.rpcManager
},
get configuration() {
return getParent(self).jbrowse.configuration
},
get assemblies() {
return getParent(self).jbrowse.assemblies
},
get assemblyNames() {
return getParent(self).jbrowse.assemblyNames
},
get tracks() {
return getParent(self).jbrowse.tracks
},
get textSearchManager(): TextSearchManager {
return getParent(self).textSearchManager
},
get connections() {
return getParent(self).jbrowse.connections
},
get savedSessions() {
return getParent(self).jbrowse.savedSessions
},
get savedSessionNames() {
return getParent(self).jbrowse.savedSessionNames
},
get history() {
return getParent(self).history
},
get menus() {
return getParent(self).menus
},
get assemblyManager() {
return getParent(self).assemblyManager
},
get version() {
return getParent(self).version
},
renderProps() {
return { theme: readConfObject(this.configuration, 'theme') }
},
get visibleWidget() {
if (isAlive(self)) {
// returns most recently added item in active widgets
return Array.from(self.activeWidgets.values())[
self.activeWidgets.size - 1
]
}
return undefined
},
get adminMode() {
return true
},
/**
* See if any MST nodes currently have a types.reference to this object.
* @param object - object
* @returns An array where the first element is the node referring
* to the object and the second element is they property name the node is
* using to refer to the object
*/
getReferring(object: IAnyStateTreeNode) {
const refs: ReferringNode[] = []
walk(getParent(self), node => {
if (isModelType(getType(node))) {
const members = getMembers(node)
Object.entries(members.properties).forEach(([key, value]) => {
// @ts-ignore
if (isReferenceType(value) && node[key] === object) {
refs.push({ node, key })
}
})
}
})
return refs
},
}))
.actions(self => ({
setDrawerPosition(arg: string) {
self.drawerPosition = arg
localStorage.setItem('drawerPosition', arg)
},
queueDialog(
callback: (doneCallback: Function) => [DialogComponentType, any],
): void {
const [component, props] = callback(() => {
self.queueOfDialogs.shift()
})
self.queueOfDialogs.push([component, props])
},
makeConnection(
configuration: AnyConfigurationModel,
initialSnapshot = {},
) {
const { type } = configuration
if (!type) {
throw new Error('track configuration has no `type` listed')
}
const name = readConfObject(configuration, 'name')
const connectionType = pluginManager.getConnectionType(type)
if (!connectionType) {
throw new Error(`unknown connection type ${type}`)
}
const connectionData = {
...initialSnapshot,
name,
type,
configuration,
}
const length = self.connectionInstances.push(connectionData)
return self.connectionInstances[length - 1]
},
prepareToBreakConnection(configuration: AnyConfigurationModel) {
const callbacksToDereferenceTrack: Function[] = []
const dereferenceTypeCount: Record<string, number> = {}
const name = readConfObject(configuration, 'name')
const connection = self.connectionInstances.find(c => c.name === name)
if (connection) {
connection.tracks.forEach((track: any) => {
const referring = self.getReferring(track)
this.removeReferring(
referring,
track,
callbacksToDereferenceTrack,
dereferenceTypeCount,
)
})
const safelyBreakConnection = () => {
callbacksToDereferenceTrack.forEach(cb => cb())
this.breakConnection(configuration)
}
return [safelyBreakConnection, dereferenceTypeCount]
}
return undefined
},
breakConnection(configuration: AnyConfigurationModel) {
const name = readConfObject(configuration, 'name')
const connection = self.connectionInstances.find(c => c.name === name)
self.connectionInstances.remove(connection)
},
deleteConnection(configuration: AnyConfigurationModel) {
return getParent(self).jbrowse.deleteConnectionConf(configuration)
},
updateDrawerWidth(drawerWidth: number) {
if (drawerWidth === self.drawerWidth) {
return self.drawerWidth
}
let newDrawerWidth = drawerWidth
if (newDrawerWidth < minDrawerWidth) {
newDrawerWidth = minDrawerWidth
}
self.drawerWidth = newDrawerWidth
return newDrawerWidth
},
resizeDrawer(distance: number) {
const oldDrawerWidth = self.drawerWidth
const newDrawerWidth = this.updateDrawerWidth(oldDrawerWidth - distance)
const actualDistance = oldDrawerWidth - newDrawerWidth
return actualDistance
},
addView(typeName: string, initialState = {}) {
const typeDefinition = pluginManager.getElementType('view', typeName)
if (!typeDefinition) {
throw new Error(`unknown view type ${typeName}`)
}
const length = self.views.push({
...initialState,
type: typeName,
})
return self.views[length - 1]
},
removeView(view: any) {
for (const [, widget] of self.activeWidgets) {
if (widget.view && widget.view.id === view.id) {
this.hideWidget(widget)
}
}
self.views.remove(view)
},
addAssembly(assemblyConfig: any) {
self.sessionAssemblies.push(assemblyConfig)
},
addAssemblyConf(assemblyConf: any) {
return getParent(self).jbrowse.addAssemblyConf(assemblyConf)
},
addTrackConf(trackConf: any) {
return getParent(self).jbrowse.addTrackConf(trackConf)
},
hasWidget(widget: any) {
return self.activeWidgets.has(widget.id)
},
removeReferring(
referring: any,
track: any,
callbacks: Function[],
dereferenceTypeCount: Record<string, number>,
) {
referring.forEach(({ node }: ReferringNode) => {
let dereferenced = false
try {
// If a view is referring to the track config, remove the track
// from the view
const type = 'open track(s)'
const view = getContainingView(node) as TrackViewModel
callbacks.push(() => view.hideTrack(track.trackId))
dereferenced = true
if (!dereferenceTypeCount[type]) {
dereferenceTypeCount[type] = 0
}
dereferenceTypeCount[type] += 1
} catch (err1) {
// ignore
}
// @ts-ignore
if (self.widgets.has(node.id)) {
// If a configuration editor widget has the track config
// open, close the widget
const type = 'configuration editor widget(s)'
callbacks.push(() => this.hideWidget(node))
dereferenced = true
if (!dereferenceTypeCount[type]) {
dereferenceTypeCount[type] = 0
}
dereferenceTypeCount[type] += 1
}
if (!dereferenced) {
throw new Error(
`Error when closing this connection, the following node is still referring to a track configuration: ${JSON.stringify(
getSnapshot(node),
)}`,
)
}
})
},
/**
* See if any MST nodes currently have a types.reference to this object.
* @param object - object
* @returns An array where the first element is the node referring
* to the object and the second element is they property name the node is
* using to refer to the object
*/
getReferring(object: IAnyStateTreeNode) {
const refs: ReferringNode[] = []
walk(getParent(self), node => {
if (isModelType(getType(node))) {
const members = getMembers(node)
Object.entries(members.properties).forEach(([key, value]) => {
// @ts-ignore
if (isReferenceType(value) && node[key] === object) {
refs.push({ node, key })
}
})
}
})
return refs
},
deleteTrackConf(trackConf: AnyConfigurationModel) {
const callbacksToDereferenceTrack: Function[] = []
const dereferenceTypeCount: Record<string, number> = {}
const referring = self.getReferring(trackConf)
this.removeReferring(
referring,
trackConf,
callbacksToDereferenceTrack,
dereferenceTypeCount,
)
callbacksToDereferenceTrack.forEach(cb => cb())
return getParent(self).jbrowse.deleteTrackConf(trackConf)
},
addConnectionConf(connectionConf: any) {
return getParent(self).jbrowse.addConnectionConf(connectionConf)
},
addLinearGenomeViewOfAssembly(assemblyName: string, initialState = {}) {
return this.addViewOfAssembly(
'LinearGenomeView',
assemblyName,
initialState,
)
},
addViewOfAssembly(
viewType: any,
assemblyName: string,
initialState: any = {},
) {
const assembly = self.assemblies.find(
(s: AnyConfigurationModel) =>
readConfObject(s, 'name') === assemblyName,
)
if (!assembly) {
throw new Error(
`Could not add view of assembly "${assemblyName}", assembly name not found`,
)
}
initialState.displayRegionsFromAssemblyName = readConfObject(
assembly,
'name',
)
return this.addView(viewType, initialState)
},
addViewFromAnotherView(
viewType: string,
otherView: any,
initialState: { displayedRegions?: Region[] } = {},
) {
const state = { ...initialState }
state.displayedRegions = getSnapshot(otherView.displayedRegions)
return this.addView(viewType, state)
},
addWidget(
typeName: string,
id: string,
initialState = {},
configuration = { type: typeName },
) {
const typeDefinition = pluginManager.getElementType('widget', typeName)
if (!typeDefinition) {
throw new Error(`unknown widget type ${typeName}`)
}
const data = {
...initialState,
id,
type: typeName,
configuration,
}
self.widgets.set(id, data)
return self.widgets.get(id)
},
showWidget(widget: any) {
if (self.activeWidgets.has(widget.id)) {
self.activeWidgets.delete(widget.id)
}
self.activeWidgets.set(widget.id, widget)
},
hideWidget(widget: any) {
self.activeWidgets.delete(widget.id)
},
minimizeWidgetDrawer() {
self.minimized = true
},
showWidgetDrawer() {
self.minimized = false
},
hideAllWidgets() {
self.activeWidgets.clear()
},
/**
* set the global selection, i.e. the globally-selected object.
* can be a feature, a view, just about anything
* @param thing -
*/
setSelection(thing: any) {
self.selection = thing
},
/**
* clears the global selection
*/
clearSelection() {
self.selection = undefined
},
/**
* opens a configuration editor to configure the given thing,
* and sets the current task to be configuring it
* @param configuration -
*/
editConfiguration(configuration: AnyConfigurationModel) {
if (!isConfigurationModel(configuration)) {
throw new Error(
'must pass a configuration model to editConfiguration',
)
}
const editor = this.addWidget(
'ConfigurationEditorWidget',
'configEditor',
{ target: configuration },
)
this.showWidget(editor)
},
editTrackConfiguration(configuration: AnyConfigurationModel) {
this.editConfiguration(configuration)
},
clearConnections() {
self.connectionInstances.length = 0
},
addSavedSession(sessionSnapshot: SnapshotIn<typeof self>) {
return getParent(self).jbrowse.addSavedSession(sessionSnapshot)
},
removeSavedSession(sessionSnapshot: any) {
return getParent(self).jbrowse.removeSavedSession(sessionSnapshot)
},
renameCurrentSession(sessionName: string) {
return getParent(self).renameCurrentSession(sessionName)
},
duplicateCurrentSession() {
return getParent(self).duplicateCurrentSession()
},
activateSession(sessionName: any) {
return getParent(self).activateSession(sessionName)
},
setDefaultSession() {
return getParent(self).setDefaultSession()
},
setSession(sessionSnapshot: SnapshotIn<typeof self>) {
return getParent(self).setSession(sessionSnapshot)
},
}))
.views(self => ({
getTrackActionMenuItems(config: any) {
const session = self
return [
{
label: 'About track',
onClick: () => {
session.queueDialog((doneCallback: Function) => [
AboutDialog,
{ config, handleClose: doneCallback },
])
},
icon: InfoIcon,
},
{
label: 'Settings',
onClick: () => {
session.editConfiguration(config)
},
icon: SettingsIcon,
},
{
label: 'Delete track',
onClick: () => {
session.deleteTrackConf(config)
},
icon: DeleteIcon,
},
{
label: 'Copy track',
onClick: () => {
const trackSnapshot = JSON.parse(
JSON.stringify(getSnapshot(config)),
)
const now = Date.now()
trackSnapshot.trackId += `-${now}`
trackSnapshot.displays.forEach(
(display: { displayId: string }) => {
display.displayId += `-${now}`
},
)
trackSnapshot.name += ' (copy)'
trackSnapshot.category = undefined
session.addTrackConf(trackSnapshot)
},
icon: CopyIcon,
},
]
},
}))
return types.snapshotProcessor(addSnackbarToModel(sessionModel), {
// @ts-ignore
preProcessor(snapshot) {
if (snapshot) {
// @ts-ignore
const { connectionInstances, ...rest } = snapshot || {}
// connectionInstances schema changed from object to an array, so any
// old connectionInstances as object is in snapshot, filter it out
// https://github.com/GMOD/jbrowse-components/issues/1903
if (!Array.isArray(connectionInstances)) {
return rest
}
}
return snapshot
},
})
}
export type SessionStateModel = ReturnType<typeof sessionModelFactory>
// a track is a combination of an assembly and a renderer, along with some conditions
// specifying in which contexts it is available (which assemblies, which views, etc)
| sessionModelFactory |
network_security_group_py3.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 .resource import Resource
class | (Resource):
"""NetworkSecurityGroup resource.
Variables are only populated by the server, and will be ignored when
sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: Resource tags.
:type tags: dict[str, str]
:param security_rules: A collection of security rules of the network
security group.
:type security_rules:
list[~azure.mgmt.network.v2018_01_01.models.SecurityRule]
:param default_security_rules: The default security rules of network
security group.
:type default_security_rules:
list[~azure.mgmt.network.v2018_01_01.models.SecurityRule]
:ivar network_interfaces: A collection of references to network
interfaces.
:vartype network_interfaces:
list[~azure.mgmt.network.v2018_01_01.models.NetworkInterface]
:ivar subnets: A collection of references to subnets.
:vartype subnets: list[~azure.mgmt.network.v2018_01_01.models.Subnet]
:param resource_guid: The resource GUID property of the network security
group resource.
:type resource_guid: str
:param provisioning_state: The provisioning state of the public IP
resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
:param etag: A unique read-only string that changes whenever the resource
is updated.
:type etag: str
"""
_validation = {
'name': {'readonly': True},
'type': {'readonly': True},
'network_interfaces': {'readonly': True},
'subnets': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'location': {'key': 'location', 'type': 'str'},
'tags': {'key': 'tags', 'type': '{str}'},
'security_rules': {'key': 'properties.securityRules', 'type': '[SecurityRule]'},
'default_security_rules': {'key': 'properties.defaultSecurityRules', 'type': '[SecurityRule]'},
'network_interfaces': {'key': 'properties.networkInterfaces', 'type': '[NetworkInterface]'},
'subnets': {'key': 'properties.subnets', 'type': '[Subnet]'},
'resource_guid': {'key': 'properties.resourceGuid', 'type': 'str'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
}
def __init__(self, *, id: str=None, location: str=None, tags=None, security_rules=None, default_security_rules=None, resource_guid: str=None, provisioning_state: str=None, etag: str=None, **kwargs) -> None:
super(NetworkSecurityGroup, self).__init__(id=id, location=location, tags=tags, **kwargs)
self.security_rules = security_rules
self.default_security_rules = default_security_rules
self.network_interfaces = None
self.subnets = None
self.resource_guid = resource_guid
self.provisioning_state = provisioning_state
self.etag = etag
| NetworkSecurityGroup |
__main__.py | #!/usr/bin/env python
from __future__ import unicode_literals
# Execute with
# $ python yt_dlp/__main__.py (2.6+)
# $ python -m yt_dlp (2.7+)
import sys
if __package__ is None and not hasattr(sys, 'frozen'):
# direct call of __main__.py
import os.path
path = os.path.realpath(os.path.abspath(__file__))
sys.path.insert(0, os.path.dirname(os.path.dirname(path)))
import yt_dlp
if __name__ == '__main__':
yt_dlp.main() | ||
log.py | import datetime
from flask import jsonify
from flask import request
from flask.views import MethodView
from chainerui.database import db
from chainerui.models.log import Log
from chainerui.models.project import Project
from chainerui.models.result import Result
class | (MethodView):
def post(self, project_id=None, result_id=None):
project = db.session.query(Project).filter_by(id=project_id).first()
if project is None:
return jsonify({
'project': None,
'message': 'No interface defined for URL.'
}), 404
result = db.session.query(Result).filter_by(id=result_id).first()
if result is None:
return jsonify({
'result': None,
'message': 'No interface defined for URL.'
}), 404
data = request.get_json()
log_json = data.get('log')
modified_at = log_json.get('modifiedAt', None)
if modified_at is not None:
result.log_modified_at = datetime.datetime.fromtimestamp(
modified_at)
log_values = log_json.get('values', [])
reset = log_json.get('reset', False)
if reset:
result.logs = []
for value in log_values:
result.logs.append(Log(value))
db.session.commit()
return jsonify({
'logs': {
'resultId': result.id,
'insertedLogCount': len(log_values),
'totalLogCount': len(result.logs)
}
})
| LogAPI |
md_test.go | // Protocol Buffers for Go with Gadgets
//
// Copyright (c) 2013, The GoGo Authors. All rights reserved.
// http://github.com/gogo/protobuf
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * 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
// OWNER 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.
package moredefaults
import (
"testing"
test "github.com/gogo/protobuf/test/example"
)
func TestDefaults(t *testing.T) {
b := MoreDefaultsB{}
| a := &MoreDefaultsA{}
b2 := a.GetB2()
a2 := a.GetA2()
if a.GetField1() != 1234 {
t.Fatalf("Field1 wrong")
}
if a.GetField2() != 0 {
t.Fatalf("Field2 wrong")
}
if a.GetB1() != nil {
t.Fatalf("B1 wrong")
}
if b2.GetField1() != b.GetField1() {
t.Fatalf("B2 wrong")
}
if a.GetA1() != nil {
t.Fatalf("A1 wrong")
}
if a2.GetNumber() != aa.GetNumber() {
t.Fatalf("A2 wrong")
}
} | aa := test.A{}
|
users.js | $(function () {
$.noConflict();
user_tbl = $('#user-table').DataTable({
processing: true,
serverSide: false,
order: [[1, 'asc']],
ajax: 'users/data',
columns: [
{data: 'checkmark', name:'id', orderable: false, searchable: false},
{data: 'first_name', name: 'first_name'},
{data: 'last_name', name: 'last_name'},
{data: 'email', name: 'email'},
{data: 'role', name: 'role'},
{data: 'action', name: 'action', orderable: false, searchable: false, class:"text-center"}
]
});
});
function | ($user){
if(confirm('¿Seguro que desea eliminar esta usuario?') == true)
{
var id = $user;
var csrf_token = $('meta[name="csrf-token"]').attr('content');
$.ajax(
{
url: "user/delete/"+id,
type: 'DELETE',
dataType: "JSON",
data: {
"id": id,
"_method": 'DELETE',
"_token": csrf_token ,
},
success: function (data)
{
if (data.success == 'yes')
{
user_tbl.ajax.reload();
}
}
});
event.preventDefault();
$(".alert").remove();
}
else
{
event.preventDefault();
return false;
}
console.log("It failed");
}
$(document).on("click",".delete_multiple",function(e){
e.preventDefault();
if ( !$(".case").is(':checked') )
{
alert("Por favor, seleccione al menos una casilla de verificación!..");
return false;
}
else
{
if(confirm('¿Está seguro de que desea eliminar estos usuarios?') == true)
{
$("#user_listing_form").attr("action", "/admin/user/delete_multi_user");
var url = $("#user_listing_form").attr("action");
var data = $("#user_listing_form").serialize();
$.ajax({
url : url ,
method : 'post',
data : data,
success : function(data){
//Reload Table Data
user_tbl.ajax.reload();
$("#checkall").prop("checked","");
var json_data = $.parseJSON(data);
if( json_data.status == 200 )
{
msg_display( 200, json_data.message );
}
else
{
msg_display( 500, json_data.message );
}
}
});
}
else
{
return false;
}
}
});
$('#checkall').click(function(event) { //on click
if(this.checked) { // check select status
$('.case').each(function() { //loop through each checkbox
//alert("check");
this.checked = true; //select all checkboxes with class "checkbox1"
});
}else{
$('.case').each(function() { //loop through each checkbox
this.checked = false; //deselect all checkboxes with class "checkbox1"
//alert("uncheck");
});
}
});
| deleteUser |
scheduler_job.py | """
Copyright 2015 Hewlett-Packard
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 datetime
import json
import os
import subprocess
import tempfile
import time
from freezer.utils import utils
from oslo_config import cfg
from oslo_log import log
from six.moves import configparser
CONF = cfg.CONF
LOG = log.getLogger(__name__)
class StopState(object):
@staticmethod
def stop(job, doc):
job.job_doc = doc
job.event = Job.NO_EVENT
job.job_doc_status = Job.STOP_STATUS
job.scheduler.update_job(job.id, job.job_doc)
return Job.NO_EVENT
@staticmethod
def abort(job, doc):
return StopState.stop(job, doc)
@staticmethod
def start(job, doc):
job.job_doc = doc
job.event = Job.NO_EVENT
job.job_doc_status = Job.STOP_STATUS
job.schedule()
job.scheduler.update_job(job.id, job.job_doc)
return Job.NO_EVENT
@staticmethod
def remove(job):
job.unschedule()
job.job_doc_status = Job.REMOVED_STATUS
return Job.NO_EVENT
class ScheduledState(object):
@staticmethod
def stop(job, doc):
job.unschedule()
job.scheduler.update_job(job.id, job.job_doc)
return Job.STOP_EVENT
@staticmethod
def abort(job, doc):
return StopState.stop(job, doc)
@staticmethod
def start(job, doc):
job.event = Job.NO_EVENT
job.scheduler.update_job(job.id, job.job_doc)
return Job.NO_EVENT
@staticmethod
def remove(job):
job.unschedule()
job.job_doc_status = Job.REMOVED_STATUS
return Job.NO_EVENT
class RunningState(object):
@staticmethod
def stop(job, doc):
job.event = Job.STOP_EVENT
return Job.NO_EVENT
@staticmethod
def abort(job, doc):
job.event = Job.ABORT_EVENT
job.scheduler.update_job(job.id, job.job_doc)
return Job.ABORTED_RESULT
@staticmethod
def start(job, doc):
job.event = Job.NO_EVENT
job.scheduler.update_job(job.id, job.job_doc)
return Job.NO_EVENT
@staticmethod
def remove(job):
job.event = Job.REMOVE_EVENT
return Job.NO_EVENT
class Job(object):
NO_EVENT = ''
STOP_EVENT = 'stop'
START_EVENT = 'start'
ABORT_EVENT = 'abort'
REMOVE_EVENT = 'remove'
STOP_STATUS = 'stop'
SCHEDULED_STATUS = 'scheduled'
RUNNING_STATUS = 'running'
REMOVED_STATUS = 'removed'
COMPLETED_STATUS = 'completed'
FAIL_RESULT = 'fail'
SUCCESS_RESULT = 'success'
ABORTED_RESULT = 'aborted'
TIME_NULL = -1
@staticmethod
def create(scheduler, executable, job_doc):
job = Job(scheduler, executable, job_doc)
if job.job_doc_status in ['running', 'scheduled']:
LOG.warning('Resetting {0} status from job {1}'
.format(job.job_doc_status, job.id))
if job.job_doc_status == 'stop' and not job.event:
LOG.info('Job {0} was stopped.'.format(job.id))
job.event = Job.STOP_EVENT
elif not job.event:
LOG.info('Autostart Job {0}'.format(job.id))
job.event = Job.START_EVENT
return job
def __init__(self, scheduler, executable, job_doc):
self.scheduler = scheduler
self.executable = executable
self.job_doc = job_doc
self.process = None
self.state = StopState
def remove(self):
with self.scheduler.lock:
# delegate to state object
LOG.info('REMOVE job {0}'.format(self.id))
self.state.remove(self)
@property
def id(self):
return self.job_doc['job_id']
@property
def session_id(self):
return self.job_doc.get('session_id', '')
@session_id.setter
def session_id(self, value):
self.job_doc['session_id'] = value
@property
def session_tag(self):
return self.job_doc.get('session_tag', 0)
@session_tag.setter
def session_tag(self, value):
self.job_doc['session_tag'] = value
@property
def event(self):
return self.job_doc['job_schedule'].get('event', '')
@event.setter
def event(self, value):
self.job_doc['job_schedule']['event'] = value
@property
def job_doc_status(self):
return self.job_doc['job_schedule'].get('status', '')
@job_doc_status.setter
def job_doc_status(self, value):
self.job_doc['job_schedule']['status'] = value
@property
def result(self):
return self.job_doc['job_schedule'].get('result', '')
@result.setter
def result(self, value):
self.job_doc['job_schedule']['result'] = value
def can_be_removed(self):
return self.job_doc_status == Job.REMOVED_STATUS
@staticmethod
def save_action_to_file(action, f):
parser = configparser.ConfigParser()
parser.add_section('action')
for action_k, action_v in action.items():
parser.set('action', action_k, action_v)
parser.write(f)
f.seek(0)
@property
def schedule_date(self):
return self.job_doc['job_schedule'].get('schedule_date', '')
@property
def schedule_interval(self):
return self.job_doc['job_schedule'].get('schedule_interval', '')
@property
def schedule_start_date(self):
return self.job_doc['job_schedule'].get('schedule_start_date', '')
@property
def schedule_end_date(self):
return self.job_doc['job_schedule'].get('schedule_end_date', '')
@property
def schedule_cron_fields(self):
cron_fields = ['year', 'month', 'day', 'week', 'day_of_week',
'hour', 'minute', 'second']
cron_schedule = {}
for cron in self.job_doc['job_schedule'].keys():
if cron.startswith('schedule_'):
cron_key = cron.split('_', 1)[1]
cron_schedule.update({
cron_key: self.job_doc['job_schedule'][cron]})
return {key: value
for key, value in cron_schedule.items()
if key in cron_fields}
@property
def scheduled(self):
return self.scheduler.is_scheduled(self.id)
def get_schedule_args(self):
|
def process_event(self, job_doc):
with self.scheduler.lock:
next_event = job_doc['job_schedule'].get('event', '')
while next_event:
if next_event == Job.STOP_EVENT:
if isinstance(self.state(), StopState):
LOG.info('JOB {0} event: STOP'.format(self.id))
next_event = self.state.stop(self, job_doc)
elif next_event == Job.START_EVENT:
LOG.info('JOB {0} event: START'.format(self.id))
next_event = self.state.start(self, job_doc)
elif next_event == Job.ABORT_EVENT:
LOG.info('JOB {0} event: ABORT'.format(self.id))
next_event = self.state.abort(self, job_doc)
elif next_event == Job.ABORTED_RESULT:
LOG.info('JOB {0} aborted.'.format(self.id))
break
def upload_metadata(self, metadata_string):
try:
metadata = json.loads(metadata_string)
if metadata:
metadata['job_id'] = self.id
self.scheduler.upload_metadata(metadata)
LOG.info("Job {0}, freezer action metadata uploaded"
.format(self.id))
except Exception as e:
LOG.error('metrics upload error: {0}'.format(e))
def execute_job_action(self, job_action):
max_tries = (job_action.get('max_retries', 0) + 1)
tries = max_tries
freezer_action = job_action.get('freezer_action', {})
max_retries_interval = job_action.get('max_retries_interval', 60)
action_name = freezer_action.get('action', '')
while tries:
with tempfile.NamedTemporaryFile(delete=False) as config_file:
self.save_action_to_file(freezer_action, config_file)
config_file_name = config_file.name
freezer_command = '{0} --metadata-out - --config {1}'.\
format(self.executable, config_file.name)
self.process = subprocess.Popen(freezer_command.split(),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=os.environ.copy())
# store the pid for this process in the api
try:
self.job_doc['job_schedule']['current_pid'] = \
self.process.pid
self.scheduler.update_job(self.job_doc['job_id'],
self.job_doc)
except Exception as error:
LOG.error("Error saving the process id {}".format(error))
output, error = self.process.communicate()
# ensure the tempfile gets deleted
utils.delete_file(config_file_name)
if error:
LOG.error("Freezer client error: {0}".format(error))
elif output:
self.upload_metadata(output)
if self.process.returncode == -15:
# This means the job action was aborted by the scheduler
LOG.warning('Freezer-agent was killed by the scheduler. '
'Cleanup should be done manually: container, '
'mountpoint and lvm snapshots.')
return Job.ABORTED_RESULT
elif self.process.returncode:
# ERROR
tries -= 1
if tries:
LOG.warning('Job {0} failed {1} action,'
' retrying in {2} seconds'
.format(self.id, action_name,
max_retries_interval))
time.sleep(max_retries_interval)
else:
# SUCCESS
LOG.info('Job {0} action {1}'
' returned success exit code'.
format(self.id, action_name))
return Job.SUCCESS_RESULT
LOG.error('Job {0} action {1} failed after {2} tries'
.format(self.id, action_name, max_tries))
return Job.FAIL_RESULT
def contains_exec(self):
jobs = self.job_doc.get('job_actions')
for job in jobs:
freezer_action = job.get('freezer_action')
action = freezer_action.get('action')
if action == 'exec':
return True
return False
def update_job_schedule_doc(self, **kwargs):
"""
Updates the job_schedule section of the job doc with the
provided keyword args. No checks about accepted key/values
are being made here since they may vary in the future.
:param kwargs: keyword args to add
:return: None
"""
job_schedule = self.job_doc['job_schedule']
job_schedule.update(kwargs)
def execute(self):
result = Job.SUCCESS_RESULT
with self.scheduler.lock:
LOG.info('job {0} running'.format(self.id))
self.state = RunningState
self.update_job_schedule_doc(status=Job.RUNNING_STATUS,
result="",
time_started=int(time.time()),
time_ended=Job.TIME_NULL)
self.scheduler.update_job_schedule(
self.id,
self.job_doc['job_schedule'])
self.start_session()
# if the job contains exec action and the scheduler passes the
# parameter --disable-exec job execution should fail
if self.contains_exec() and CONF.disable_exec:
LOG.info("Job {0} failed because it contains exec action "
"and exec actions are disabled by scheduler"
.format(self.id))
self.result = Job.FAIL_RESULT
self.finish()
return
for job_action in self.job_doc.get('job_actions', []):
if job_action.get('mandatory', False) or\
(result == Job.SUCCESS_RESULT):
action_result = self.execute_job_action(job_action)
if action_result == Job.FAIL_RESULT:
result = Job.FAIL_RESULT
if action_result == Job.ABORTED_RESULT:
result = Job.ABORTED_RESULT
else:
freezer_action = job_action.get('freezer_action', {})
action_name = freezer_action.get('action', '')
LOG.warning("skipping {0} action".
format(action_name))
self.result = result
self.finish()
def finish(self):
self.update_job_schedule_doc(time_ended=int(time.time()))
self.end_session(self.result)
with self.scheduler.lock:
if self.event == Job.REMOVE_EVENT:
self.unschedule()
self.job_doc_status = Job.REMOVED_STATUS
return
if not self.scheduled:
self.job_doc_status = Job.COMPLETED_STATUS
self.state = StopState
self.scheduler.update_job(self.id, self.job_doc)
return
if self.event in [Job.STOP_EVENT, Job.ABORT_EVENT]:
self.unschedule()
self.job_doc_status = Job.COMPLETED_STATUS
self.scheduler.update_job(self.id, self.job_doc)
else:
self.job_doc_status = Job.SCHEDULED_STATUS
self.state = ScheduledState
self.scheduler.update_job_schedule(
self.id,
self.job_doc['job_schedule'])
def start_session(self):
if not self.session_id:
return
retry = 5
while retry:
try:
resp = self.scheduler.start_session(self.session_id,
self.id,
self.session_tag)
if resp['result'] == 'success':
self.session_tag = resp['session_tag']
return
except Exception as e:
LOG.error('Error while starting session {0}. {1}'.
format(self.session_id, e))
LOG.warning('Retrying to start session {0}'.
format(self.session_id))
retry -= 1
LOG.error('Unable to start session {0}'.format(self.session_id))
def end_session(self, result):
if not self.session_id:
return
retry = 5
while retry:
try:
resp = self.scheduler.end_session(self.session_id,
self.id,
self.session_tag,
result)
if resp['result'] == 'success':
return
except Exception as e:
LOG.error('Error while ending session {0}. {1}'.
format(self.session_id, e))
LOG.warning('Retrying to end session {0}'.
format(self.session_id))
retry -= 1
LOG.error('Unable to end session {0}'.format(self.session_id))
def schedule(self):
try:
kwargs = self.get_schedule_args()
self.scheduler.add_job(self.execute, id=self.id,
executor='threadpool',
misfire_grace_time=3600, **kwargs)
except Exception as e:
LOG.error("Unable to schedule job {0}: {1}".
format(self.id, e))
LOG.info('scheduler job with parameters {0}'.format(kwargs))
if self.scheduled:
self.job_doc_status = Job.SCHEDULED_STATUS
self.state = ScheduledState
else:
# job not scheduled or already started and waiting for lock
self.job_doc_status = Job.COMPLETED_STATUS
self.state = StopState
def unschedule(self):
try:
# already executing job are not present in the apscheduler list
self.scheduler.remove_job(job_id=self.id)
except Exception:
pass
self.event = Job.NO_EVENT
self.job_doc_status = Job.STOP_STATUS
self.state = StopState
def terminate(self):
if self.process:
self.process.terminate()
def kill(self):
if self.process:
self.process.kill()
| def get_start_date(date):
# start_date format "%Y-%m-%dT%H:%M:%S"
now = datetime.datetime.now()
start_date = now + datetime.timedelta(0, 2, 0)
if (utils.date_to_timestamp(date) >
utils.date_to_timestamp(now.isoformat().split('.')[0])):
start_date = datetime.datetime.strptime(
date, "%Y-%m-%dT%H:%M:%S")
return start_date
def get_end_date(start, end):
# start end format "%Y-%m-%dT%H:%M:%S"
end_date = datetime.datetime.strptime(end, "%Y-%m-%dT%H:%M:%S")
if (utils.date_to_timestamp(start) > utils.date_to_timestamp(end)):
end_date = None
return end_date
kwargs_date = {}
if self.schedule_start_date:
kwargs_date.update({
'start_date': get_start_date(self.schedule_start_date)
})
if self.schedule_end_date:
end_date = get_end_date(self.schedule_start_date,
self.schedule_end_date)
kwargs_date.update({
'end_date': end_date
})
if self.schedule_date:
return {'trigger': 'date',
'run_date': self.schedule_date}
elif self.schedule_interval:
kwargs = {'trigger': 'interval'}
kwargs.update(kwargs_date)
if self.schedule_interval == 'continuous':
kwargs.update({'seconds': 1})
else:
val, unit = self.schedule_interval.split(' ')
kwargs.update({unit: int(val)})
return kwargs
elif self.schedule_cron_fields:
kwargs = {'trigger': 'cron'}
kwargs.update(kwargs_date)
cron_fields = self.schedule_cron_fields
kwargs.update(cron_fields)
return kwargs
else:
# no scheduling information, schedule to start within a few seconds
return {'trigger': 'date',
'run_date': datetime.datetime.now() +
datetime.timedelta(0, 2, 0)} |
reaction.rs | use crate::{
channel::ReactionType,
guild::member::{Member, OptionalMemberDeserializer},
id::{ChannelId, GuildId, MessageId, UserId},
};
use serde::{
de::{Deserializer, Error as DeError, IgnoredAny, MapAccess, Visitor},
Deserialize, Serialize,
};
use std::fmt::{Formatter, Result as FmtResult};
#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize)]
pub struct Reaction {
pub channel_id: ChannelId,
pub emoji: ReactionType,
pub guild_id: Option<GuildId>,
pub member: Option<Member>,
pub message_id: MessageId,
pub user_id: UserId,
}
#[derive(Debug, Deserialize)]
#[serde(field_identifier, rename_all = "snake_case")]
enum | {
ChannelId,
Emoji,
GuildId,
Member,
MessageId,
UserId,
}
struct ReactionVisitor;
impl<'de> Visitor<'de> for ReactionVisitor {
type Value = Reaction;
fn expecting(&self, f: &mut Formatter<'_>) -> FmtResult {
f.write_str("struct Reaction")
}
fn visit_map<V: MapAccess<'de>>(self, mut map: V) -> Result<Self::Value, V::Error> {
let mut channel_id = None;
let mut emoji = None;
let mut guild_id = None;
let mut member = None;
let mut message_id = None;
let mut user_id = None;
loop {
let key = match map.next_key() {
Ok(Some(key)) => key,
Ok(None) => break,
Err(_) => {
// Encountered when we run into an unknown key.
map.next_value::<IgnoredAny>()?;
continue;
}
};
match key {
Field::ChannelId => {
if channel_id.is_some() {
return Err(DeError::duplicate_field("channel_id"));
}
channel_id = Some(map.next_value()?);
}
Field::Emoji => {
if emoji.is_some() {
return Err(DeError::duplicate_field("emoji"));
}
emoji = Some(map.next_value()?);
}
Field::GuildId => {
if guild_id.is_some() {
return Err(DeError::duplicate_field("guild_id"));
}
guild_id = map.next_value()?;
}
Field::Member => {
if member.is_some() {
return Err(DeError::duplicate_field("member"));
}
let deserializer = OptionalMemberDeserializer::new(GuildId(0));
member = map.next_value_seed(deserializer)?;
}
Field::MessageId => {
if message_id.is_some() {
return Err(DeError::duplicate_field("message_id"));
}
message_id = Some(map.next_value()?);
}
Field::UserId => {
if user_id.is_some() {
return Err(DeError::duplicate_field("user_id"));
}
user_id = Some(map.next_value()?);
}
}
}
let channel_id = channel_id.ok_or_else(|| DeError::missing_field("channel_id"))?;
let emoji = emoji.ok_or_else(|| DeError::missing_field("emoji"))?;
let message_id = message_id.ok_or_else(|| DeError::missing_field("message_id"))?;
let user_id = user_id.ok_or_else(|| DeError::missing_field("user_id"))?;
if let (Some(guild_id), Some(member)) = (guild_id, member.as_mut()) {
member.guild_id = guild_id;
}
Ok(Reaction {
channel_id,
emoji,
guild_id,
member,
message_id,
user_id,
})
}
}
impl<'de> Deserialize<'de> for Reaction {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
const FIELDS: &[&str] = &[
"channel_id",
"emoji",
"guild_id",
"member",
"message_id",
"user_id",
];
deserializer.deserialize_struct("Reaction", FIELDS, ReactionVisitor)
}
}
#[cfg(test)]
mod tests {
use super::super::{Reaction, ReactionType};
use crate::{
guild::Member,
id::{ChannelId, GuildId, MessageId, RoleId, UserId},
user::User,
};
use serde_test::Token;
#[test]
fn test_reaction_with_member() {
let expected = Reaction {
channel_id: ChannelId(2),
emoji: ReactionType::Unicode {
name: "🙂".to_owned(),
},
guild_id: Some(GuildId(1)),
member: Some(Member {
deaf: false,
guild_id: GuildId(1),
hoisted_role: Some(RoleId(5)),
joined_at: Some("2020-01-01T00:00:00.000000+00:00".to_owned()),
mute: false,
nick: Some("typing".to_owned()),
premium_since: None,
roles: vec![RoleId(5)],
user: User {
avatar: Some("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_owned()),
bot: false,
discriminator: "0001".to_owned(),
email: None,
flags: None,
id: UserId(4),
locale: None,
mfa_enabled: None,
name: "test".to_owned(),
premium_type: None,
public_flags: None,
system: None,
verified: None,
},
}),
message_id: MessageId(3),
user_id: UserId(4),
};
serde_test::assert_tokens(
&expected,
&[
Token::Struct {
name: "Reaction",
len: 6,
},
Token::Str("channel_id"),
Token::NewtypeStruct { name: "ChannelId" },
Token::Str("2"),
Token::Str("emoji"),
Token::Struct {
name: "ReactionType",
len: 1,
},
Token::Str("name"),
Token::Str("🙂"),
Token::StructEnd,
Token::Str("guild_id"),
Token::Some,
Token::NewtypeStruct { name: "GuildId" },
Token::Str("1"),
Token::Str("member"),
Token::Some,
Token::Struct {
name: "Member",
len: 9,
},
Token::Str("deaf"),
Token::Bool(false),
Token::Str("guild_id"),
Token::NewtypeStruct { name: "GuildId" },
Token::Str("1"),
Token::Str("hoisted_role"),
Token::Some,
Token::NewtypeStruct { name: "RoleId" },
Token::Str("5"),
Token::Str("joined_at"),
Token::Some,
Token::Str("2020-01-01T00:00:00.000000+00:00"),
Token::Str("mute"),
Token::Bool(false),
Token::Str("nick"),
Token::Some,
Token::Str("typing"),
Token::Str("premium_since"),
Token::None,
Token::Str("roles"),
Token::Seq { len: Some(1) },
Token::NewtypeStruct { name: "RoleId" },
Token::Str("5"),
Token::SeqEnd,
Token::Str("user"),
Token::Struct {
name: "User",
len: 13,
},
Token::Str("avatar"),
Token::Some,
Token::Str("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"),
Token::Str("bot"),
Token::Bool(false),
Token::Str("discriminator"),
Token::Str("0001"),
Token::Str("email"),
Token::None,
Token::Str("flags"),
Token::None,
Token::Str("id"),
Token::NewtypeStruct { name: "UserId" },
Token::Str("4"),
Token::Str("locale"),
Token::None,
Token::Str("mfa_enabled"),
Token::None,
Token::Str("username"),
Token::Str("test"),
Token::Str("premium_type"),
Token::None,
Token::Str("public_flags"),
Token::None,
Token::Str("system"),
Token::None,
Token::Str("verified"),
Token::None,
Token::StructEnd,
Token::StructEnd,
Token::Str("message_id"),
Token::NewtypeStruct { name: "MessageId" },
Token::Str("3"),
Token::Str("user_id"),
Token::NewtypeStruct { name: "UserId" },
Token::Str("4"),
Token::StructEnd,
],
);
}
#[test]
fn test_reaction_without_member() {
let expected = Reaction {
channel_id: ChannelId(2),
emoji: ReactionType::Unicode {
name: "🙂".to_owned(),
},
guild_id: None,
member: None,
message_id: MessageId(3),
user_id: UserId(4),
};
serde_test::assert_tokens(
&expected,
&[
Token::Struct {
name: "Reaction",
len: 6,
},
Token::Str("channel_id"),
Token::NewtypeStruct { name: "ChannelId" },
Token::Str("2"),
Token::Str("emoji"),
Token::Struct {
name: "ReactionType",
len: 1,
},
Token::Str("name"),
Token::Str("🙂"),
Token::StructEnd,
Token::Str("guild_id"),
Token::None,
Token::Str("member"),
Token::None,
Token::Str("message_id"),
Token::NewtypeStruct { name: "MessageId" },
Token::Str("3"),
Token::Str("user_id"),
Token::NewtypeStruct { name: "UserId" },
Token::Str("4"),
Token::StructEnd,
],
);
}
}
| Field |
v1DeploymentStatus.d.ts | /**
* Kubernetes
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: v1.13.9
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { V1DeploymentCondition } from './v1DeploymentCondition';
/** | * DeploymentStatus is the most recently observed status of the Deployment.
*/
export declare class V1DeploymentStatus {
/**
* Total number of available pods (ready for at least minReadySeconds) targeted by this deployment.
*/
'availableReplicas'?: number;
/**
* Count of hash collisions for the Deployment. The Deployment controller uses this field as a collision avoidance mechanism when it needs to create the name for the newest ReplicaSet.
*/
'collisionCount'?: number;
/**
* Represents the latest available observations of a deployment\'s current state.
*/
'conditions'?: Array<V1DeploymentCondition>;
/**
* The generation observed by the deployment controller.
*/
'observedGeneration'?: number;
/**
* Total number of ready pods targeted by this deployment.
*/
'readyReplicas'?: number;
/**
* Total number of non-terminated pods targeted by this deployment (their labels match the selector).
*/
'replicas'?: number;
/**
* Total number of unavailable pods targeted by this deployment. This is the total number of pods that are still required for the deployment to have 100% available capacity. They may either be pods that are running but not yet available or pods that still have not been created.
*/
'unavailableReplicas'?: number;
/**
* Total number of non-terminated pods targeted by this deployment that have the desired template spec.
*/
'updatedReplicas'?: number;
static discriminator: string | undefined;
static attributeTypeMap: Array<{
name: string;
baseName: string;
type: string;
}>;
static getAttributeTypeMap(): {
name: string;
baseName: string;
type: string;
}[];
} | |
extras_export_templates_list_responses.go | // Code generated by go-swagger; DO NOT EDIT.
// Copyright 2018 The go-netbox 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.
package extras
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"fmt"
"io"
"github.com/go-openapi/runtime"
strfmt "github.com/go-openapi/strfmt"
"github.com/digitalocean/go-netbox/netbox/models"
)
// ExtrasExportTemplatesListReader is a Reader for the ExtrasExportTemplatesList structure.
type ExtrasExportTemplatesListReader struct {
formats strfmt.Registry
}
// ReadResponse reads a server response into the received o.
func (o *ExtrasExportTemplatesListReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
switch response.Code() {
case 200:
result := NewExtrasExportTemplatesListOK()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return result, nil
default:
return nil, runtime.NewAPIError("unknown error", response, response.Code())
}
}
// NewExtrasExportTemplatesListOK creates a ExtrasExportTemplatesListOK with default headers values
func | () *ExtrasExportTemplatesListOK {
return &ExtrasExportTemplatesListOK{}
}
/*ExtrasExportTemplatesListOK handles this case with default header values.
ExtrasExportTemplatesListOK extras export templates list o k
*/
type ExtrasExportTemplatesListOK struct {
Payload *models.ExtrasExportTemplatesListOKBody
}
func (o *ExtrasExportTemplatesListOK) Error() string {
return fmt.Sprintf("[GET /extras/export-templates/][%d] extrasExportTemplatesListOK %+v", 200, o.Payload)
}
func (o *ExtrasExportTemplatesListOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
o.Payload = new(models.ExtrasExportTemplatesListOKBody)
// response payload
if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}
| NewExtrasExportTemplatesListOK |
index.tsx | import Taro from '@tarojs/taro'
import { useState, useEffect, useRef, useCallback } from 'react'
import { View, Navigator, ITouchEvent } from '@tarojs/components'
import * as utils from '../wxs/utils'
import { NoticeBarProps } from '../../../types/notice-bar'
import { getRect, requestAnimationFrame } from '../common/utils'
import VanIcon from '../icon/index'
import * as computed from './wxs'
let NOTICE_BAR_INDEX = 0
export default function Index(props: NoticeBarProps) {
const [state, setState] = useState({
ready: false,
show: true,
animationData: { actions: [] },
unitag: 0,
})
const params: any = {
animation: null,
resetAnimation: null,
timer: null,
wrapWidth: undefined,
contentWidth: undefined,
duration: undefined,
}
const ref = useRef(params)
const {
text = '',
mode = '',
url = '',
openType = 'navigate',
delay = 1,
speed = 60,
scrollable = null,
leftIcon = '',
color = '#ed6a0c',
backgroundColor = '#fffbe8',
background,
wrapable,
renderLeftIcon,
renderRightIcon,
onClick,
onClose,
style,
className,
children,
...others
} = props
useEffect(() => {
setState((state) => {
return {
...state,
unitag: NOTICE_BAR_INDEX++,
}
})
}, [])
Taro.useReady(() => {
ref.current.resetAnimation = Taro.createAnimation({
duration: 0,
timingFunction: 'linear',
})
setState((state) => {
return {
...state,
ready: true,
}
})
})
useEffect(() => { | init()
}
return () => {
/* eslint-disable-next-line */
ref.current.timer && clearTimeout(ref.current.timer)
}
/* eslint-disable-next-line */
}, [text, speed, state.ready])
const scroll = useCallback(() => {
ref.current.timer && clearTimeout(ref.current.timer)
ref.current.timer = null
setState((state) => {
return {
...state,
animationData: ref.current.resetAnimation
.translateX(ref.current.wrapWidth)
.step()
.export(),
}
})
setTimeout(() => {
requestAnimationFrame(() => {
setState((state) => {
return {
...state,
animationData: ref.current.animation
.translateX(-ref.current.contentWidth)
.step()
.export(),
}
})
})
}, 10)
ref.current.timer = setTimeout(() => {
scroll()
}, ref.current.duration)
}, [])
const init = useCallback(() => {
requestAnimationFrame(() => {
Promise.all([
getRect(null, `.van-notice-bar__content_${state.unitag}`),
getRect(null, `.van-notice-bar__wrap_${state.unitag}`),
]).then((rects) => {
const contentRect: any = rects[0]
const wrapRect: any = rects[1]
if (
contentRect == null ||
wrapRect == null ||
!contentRect.width ||
!wrapRect.width ||
scrollable === false
) {
return
}
Taro.nextTick(() => {
if (scrollable || wrapRect.width <= contentRect.width) {
ref.current.wrapWidth = wrapRect.width
ref.current.contentWidth = contentRect.width
ref.current.duration =
((wrapRect.width + contentRect.width) / speed) * 1000
ref.current.animation = Taro.createAnimation({
duration: ref.current.duration,
timingFunction: 'linear',
delay,
})
scroll()
}
})
})
})
}, [state.unitag, scrollable, speed, delay, scroll])
const onClickIcon = useCallback(
(event: ITouchEvent) => {
if (mode === 'closeable') {
ref.current.timer && clearTimeout(ref.current.timer)
ref.current.timer = null
setState((state) => {
return {
...state,
show: false,
}
})
onClose?.(event)
}
},
[mode, onClose],
)
return (
state.show && (
<View
className={
utils.bem('notice-bar', {
withicon: mode,
wrapable,
}) + ` ${className || ''}`
}
style={utils.style([
computed.rootStyle({
color,
backgroundColor,
background,
}),
style,
])}
{...others}
onClick={onClick}
>
{leftIcon ? (
<VanIcon
size={32}
name={leftIcon}
className="van-notice-bar__left-icon"
></VanIcon>
) : (
renderLeftIcon
)}
<View
className={`van-notice-bar__wrap van-notice-bar__wrap_${state.unitag}`}
>
<View
className={
`van-notice-bar__content van-notice-bar__content_${state.unitag} ` +
(scrollable === false && !wrapable ? 'van-ellipsis' : '')
}
animation={state.animationData}
>
{text}
{!text && children}
</View>
</View>
{mode === 'closeable' ? (
<VanIcon
className="van-notice-bar__right-icon"
name="cross"
onClick={onClickIcon}
/>
) : mode === 'link' ? (
<Navigator url={url} openType={openType}>
<VanIcon className="van-notice-bar__right-icon" name="arrow" />
</Navigator>
) : (
renderRightIcon
)}
</View>
)
)
} | if (text && state.ready) { |
public.controller.spec.ts | // import { Test, TestingModule } from '@nestjs/testing'
// import { AppService } from '../../app.service'
// import { PublicController } from './public.controller'
// import {
// Controller,
// Get,
// Request,
// Res,
// UseGuards
// // Param
// } from '@nestjs/common'
// import { Response } from 'express'
describe('AppController', () => {
// let publicController: PublicController
// beforeEach(async () => {
// const app: TestingModule = await Test.createTestingModule({
// controllers: [PublicController],
// providers: [AppService]
// }).compile()
// publicController = app.get<PublicController>(PublicController)
// })
describe('root', () => {
it('should return "Welcome!"', () => {
// const req = Request()
// const res = new Response()
// expect(publicController.getHome(req, res)).toBe('Hello World!')
expect(true).toBe(true)
})
}) | }) |
|
block.rs | use crate::THEME;
use tui::{
style::Style,
text::Span,
widgets::{Block, Borders},
};
pub fn new(title: &str) -> Block | {
Block::default()
.borders(Borders::ALL)
.border_style(Style::default().fg(THEME.border_color()))
.title_alignment(tui::layout::Alignment::Center)
.border_type(tui::widgets::BorderType::Rounded)
.title(Span::styled(
title,
Style::default().fg(THEME.text_secondary()),
))
} |
|
frame.rs | // Copyright (C) 2018-2019, Cloudflare, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * 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.
use crate::Error;
use crate::Result;
use crate::octets;
use crate::packet;
use crate::ranges;
use crate::stream;
pub const MAX_CRYPTO_OVERHEAD: usize = 8;
pub const MAX_STREAM_OVERHEAD: usize = 12;
pub const MAX_STREAM_SIZE: u64 = 1 << 62;
pub const MAX_DGRAM_OVERHEAD: usize = 8;
#[derive(Clone, PartialEq)]
pub enum Frame {
Padding {
len: usize,
},
Ping,
ACK {
ack_delay: u64,
ranges: ranges::RangeSet,
},
ResetStream {
stream_id: u64,
error_code: u64,
final_size: u64,
},
StopSending {
stream_id: u64,
error_code: u64,
},
Crypto {
data: stream::RangeBuf,
},
NewToken {
token: Vec<u8>,
},
Stream {
stream_id: u64,
data: stream::RangeBuf,
},
MaxData {
max: u64,
},
MaxStreamData {
stream_id: u64,
max: u64,
},
MaxStreamsBidi {
max: u64,
},
MaxStreamsUni {
max: u64,
},
DataBlocked {
limit: u64,
},
StreamDataBlocked {
stream_id: u64,
limit: u64,
},
StreamsBlockedBidi {
limit: u64,
},
StreamsBlockedUni {
limit: u64,
},
NewConnectionId {
seq_num: u64,
retire_prior_to: u64,
conn_id: Vec<u8>,
reset_token: Vec<u8>,
},
RetireConnectionId {
seq_num: u64,
},
PathChallenge {
data: Vec<u8>,
},
PathResponse {
data: Vec<u8>,
},
ConnectionClose {
error_code: u64,
frame_type: u64,
reason: Vec<u8>,
},
ApplicationClose {
error_code: u64,
reason: Vec<u8>,
},
HandshakeDone,
Datagram {
data: Vec<u8>,
},
}
impl Frame {
pub fn from_bytes(
b: &mut octets::Octets, pkt: packet::Type,
) -> Result<Frame> {
let frame_type = b.get_varint()?;
// println!("GOT FRAME {:x}", frame_type);
let frame = match frame_type {
0x00 => {
let mut len = 1;
while b.peek_u8() == Ok(0x00) {
b.get_u8()?;
len += 1;
}
Frame::Padding { len }
},
0x01 => Frame::Ping,
0x02 => parse_ack_frame(frame_type, b)?,
0x04 => Frame::ResetStream {
stream_id: b.get_varint()?,
error_code: b.get_varint()?,
final_size: b.get_varint()?,
},
0x05 => Frame::StopSending {
stream_id: b.get_varint()?,
error_code: b.get_varint()?,
},
0x06 => {
let offset = b.get_varint()?;
let data = b.get_bytes_with_varint_length()?;
let data = stream::RangeBuf::from(data.as_ref(), offset, false);
Frame::Crypto { data }
},
0x07 => Frame::NewToken {
token: b.get_bytes_with_varint_length()?.to_vec(),
},
0x08..=0x0f => parse_stream_frame(frame_type, b)?,
0x10 => Frame::MaxData {
max: b.get_varint()?,
},
0x11 => Frame::MaxStreamData {
stream_id: b.get_varint()?,
max: b.get_varint()?,
},
0x12 => Frame::MaxStreamsBidi {
max: b.get_varint()?,
},
0x13 => Frame::MaxStreamsUni {
max: b.get_varint()?,
},
0x14 => Frame::DataBlocked {
limit: b.get_varint()?,
},
0x15 => Frame::StreamDataBlocked {
stream_id: b.get_varint()?,
limit: b.get_varint()?,
},
0x16 => Frame::StreamsBlockedBidi {
limit: b.get_varint()?,
},
0x17 => Frame::StreamsBlockedUni {
limit: b.get_varint()?,
},
0x18 => Frame::NewConnectionId {
seq_num: b.get_varint()?,
retire_prior_to: b.get_varint()?,
conn_id: b.get_bytes_with_u8_length()?.to_vec(),
reset_token: b.get_bytes(16)?.to_vec(),
},
0x19 => Frame::RetireConnectionId {
seq_num: b.get_varint()?,
},
0x1a => Frame::PathChallenge {
data: b.get_bytes(8)?.to_vec(),
},
0x1b => Frame::PathResponse {
data: b.get_bytes(8)?.to_vec(),
},
0x1c => Frame::ConnectionClose {
error_code: b.get_varint()?,
frame_type: b.get_varint()?,
reason: b.get_bytes_with_varint_length()?.to_vec(),
},
0x1d => Frame::ApplicationClose {
error_code: b.get_varint()?,
reason: b.get_bytes_with_varint_length()?.to_vec(),
},
0x1e => Frame::HandshakeDone,
0x30 | 0x31 => parse_datagram_frame(frame_type, b)?,
_ => return Err(Error::InvalidFrame),
};
let allowed = match (pkt, &frame) {
// PADDING and PING are allowed on all packet types.
(_, Frame::Padding { .. }) | (_, Frame::Ping { .. }) => true,
// ACK, CRYPTO, HANDSHAKE_DONE, NEW_TOKEN, PATH_RESPONSE, and
// RETIRE_CONNECTION_ID can't be sent on 0-RTT packets.
(packet::Type::ZeroRTT, Frame::ACK { .. }) => false,
(packet::Type::ZeroRTT, Frame::Crypto { .. }) => false,
(packet::Type::ZeroRTT, Frame::HandshakeDone) => false,
(packet::Type::ZeroRTT, Frame::NewToken { .. }) => false,
(packet::Type::ZeroRTT, Frame::PathResponse { .. }) => false,
(packet::Type::ZeroRTT, Frame::RetireConnectionId { .. }) => false,
(packet::Type::ZeroRTT, Frame::ConnectionClose { .. }) => false,
// ACK, CRYPTO and CONNECTION_CLOSE can be sent on all other packet
// types.
(_, Frame::ACK { .. }) => true,
(_, Frame::Crypto { .. }) => true,
(_, Frame::ConnectionClose { .. }) => true,
// All frames are allowed on 0-RTT and 1-RTT packets.
(packet::Type::Short, _) => true,
(packet::Type::ZeroRTT, _) => true,
// All other cases are forbidden.
(..) => false,
};
if !allowed {
return Err(Error::InvalidPacket);
}
Ok(frame)
}
pub fn to_bytes(&self, b: &mut octets::OctetsMut) -> Result<usize> {
let before = b.cap();
match self {
Frame::Padding { len } => {
let mut left = *len;
while left > 0 {
b.put_varint(0x00)?;
left -= 1;
}
},
Frame::Ping => {
b.put_varint(0x01)?;
},
Frame::ACK { ack_delay, ranges } => {
b.put_varint(0x02)?;
let mut it = ranges.iter().rev();
let first = it.next().unwrap();
let ack_block = (first.end - 1) - first.start;
b.put_varint(first.end - 1)?;
b.put_varint(*ack_delay)?;
b.put_varint(it.len() as u64)?;
b.put_varint(ack_block)?;
let mut smallest_ack = first.start;
for block in it {
let gap = smallest_ack - block.end - 1;
let ack_block = (block.end - 1) - block.start;
b.put_varint(gap)?;
b.put_varint(ack_block)?;
smallest_ack = block.start;
}
},
Frame::ResetStream {
stream_id,
error_code,
final_size,
} => {
b.put_varint(0x04)?;
b.put_varint(*stream_id)?;
b.put_varint(*error_code)?;
b.put_varint(*final_size)?;
},
Frame::StopSending {
stream_id,
error_code,
} => {
b.put_varint(0x05)?;
b.put_varint(*stream_id)?;
b.put_varint(*error_code)?;
},
Frame::Crypto { data } => {
b.put_varint(0x06)?;
b.put_varint(data.off() as u64)?;
b.put_varint(data.len() as u64)?;
b.put_bytes(&data)?;
},
Frame::NewToken { token } => {
b.put_varint(0x07)?;
b.put_varint(token.len() as u64)?;
b.put_bytes(&token)?;
},
Frame::Stream { stream_id, data } => {
let mut ty: u8 = 0x08;
// Always encode offset
ty |= 0x04;
// Always encode length
ty |= 0x02;
if data.fin() {
ty |= 0x01;
}
b.put_varint(u64::from(ty))?;
b.put_varint(*stream_id)?;
b.put_varint(data.off() as u64)?;
b.put_varint(data.len() as u64)?;
b.put_bytes(data.as_ref())?;
},
Frame::MaxData { max } => {
b.put_varint(0x10)?;
b.put_varint(*max)?;
},
Frame::MaxStreamData { stream_id, max } => {
b.put_varint(0x11)?;
b.put_varint(*stream_id)?;
b.put_varint(*max)?;
},
Frame::MaxStreamsBidi { max } => {
b.put_varint(0x12)?;
b.put_varint(*max)?;
},
Frame::MaxStreamsUni { max } => {
b.put_varint(0x13)?;
b.put_varint(*max)?;
},
Frame::DataBlocked { limit } => {
b.put_varint(0x14)?;
b.put_varint(*limit)?;
},
Frame::StreamDataBlocked { stream_id, limit } => {
b.put_varint(0x15)?;
b.put_varint(*stream_id)?;
b.put_varint(*limit)?;
},
Frame::StreamsBlockedBidi { limit } => {
b.put_varint(0x16)?;
b.put_varint(*limit)?;
},
Frame::StreamsBlockedUni { limit } => {
b.put_varint(0x17)?;
b.put_varint(*limit)?;
},
Frame::NewConnectionId {
seq_num,
retire_prior_to,
conn_id,
reset_token,
} => {
b.put_varint(0x18)?;
b.put_varint(*seq_num)?;
b.put_varint(*retire_prior_to)?;
b.put_u8(conn_id.len() as u8)?;
b.put_bytes(conn_id.as_ref())?;
b.put_bytes(reset_token.as_ref())?;
},
Frame::RetireConnectionId { seq_num } => {
b.put_varint(0x19)?;
b.put_varint(*seq_num)?;
},
Frame::PathChallenge { data } => {
b.put_varint(0x1a)?;
b.put_bytes(data.as_ref())?;
},
Frame::PathResponse { data } => {
b.put_varint(0x1b)?;
b.put_bytes(data.as_ref())?;
},
Frame::ConnectionClose {
error_code,
frame_type,
reason,
} => {
b.put_varint(0x1c)?;
b.put_varint(*error_code)?;
b.put_varint(*frame_type)?;
b.put_varint(reason.len() as u64)?;
b.put_bytes(reason.as_ref())?;
},
Frame::ApplicationClose { error_code, reason } => {
b.put_varint(0x1d)?;
b.put_varint(*error_code)?;
b.put_varint(reason.len() as u64)?;
b.put_bytes(reason.as_ref())?;
},
Frame::HandshakeDone => {
b.put_varint(0x1e)?;
},
Frame::Datagram { data } => {
let mut ty: u8 = 0x30;
// Always encode length
ty |= 0x01;
b.put_varint(u64::from(ty))?;
b.put_varint(data.len() as u64)?;
b.put_bytes(data.as_ref())?;
},
}
Ok(before - b.cap())
}
pub fn wire_len(&self) -> usize {
match self {
Frame::Padding { len } => *len,
Frame::Ping => 1,
Frame::ACK { ack_delay, ranges } => {
let mut it = ranges.iter().rev();
let first = it.next().unwrap();
let ack_block = (first.end - 1) - first.start;
let mut len = 1 + // frame type
octets::varint_len(first.end - 1) + // largest_ack
octets::varint_len(*ack_delay) + // ack_delay
octets::varint_len(it.len() as u64) + // block_count
octets::varint_len(ack_block); // first_block
let mut smallest_ack = first.start;
for block in it {
let gap = smallest_ack - block.end - 1;
let ack_block = (block.end - 1) - block.start;
len += octets::varint_len(gap) + // gap
octets::varint_len(ack_block); // ack_block
smallest_ack = block.start;
}
len
},
Frame::ResetStream {
stream_id,
error_code,
final_size,
} => {
1 + // frame type
octets::varint_len(*stream_id) + // stream_id
octets::varint_len(*error_code) + // error_code
octets::varint_len(*final_size) // final_size
},
Frame::StopSending {
stream_id,
error_code,
} => {
1 + // frame type
octets::varint_len(*stream_id) + // stream_id
octets::varint_len(*error_code) // error_code
},
Frame::Crypto { data } => {
1 + // frame type
octets::varint_len(data.off() as u64) + // offset
octets::varint_len(data.len() as u64) + // length
data.len() // data
},
Frame::NewToken { token } => {
1 + // frame type
octets::varint_len(token.len() as u64) + // token length
token.len() // token
},
Frame::Stream { stream_id, data } => {
1 + // frame type
octets::varint_len(*stream_id) + // stream_id
octets::varint_len(data.off() as u64) + // offset
octets::varint_len(data.len() as u64) + // length
data.len() // data
},
Frame::MaxData { max } => {
1 + // frame type
octets::varint_len(*max) // max
},
Frame::MaxStreamData { stream_id, max } => {
1 + // frame type
octets::varint_len(*stream_id) + // stream_id
octets::varint_len(*max) // max | Frame::MaxStreamsBidi { max } => {
1 + // frame type
octets::varint_len(*max) // max
},
Frame::MaxStreamsUni { max } => {
1 + // frame type
octets::varint_len(*max) // max
},
Frame::DataBlocked { limit } => {
1 + // frame type
octets::varint_len(*limit) // limit
},
Frame::StreamDataBlocked { stream_id, limit } => {
1 + // frame type
octets::varint_len(*stream_id) + // stream_id
octets::varint_len(*limit) // limit
},
Frame::StreamsBlockedBidi { limit } => {
1 + // frame type
octets::varint_len(*limit) // limit
},
Frame::StreamsBlockedUni { limit } => {
1 + // frame type
octets::varint_len(*limit) // limit
},
Frame::NewConnectionId {
seq_num,
retire_prior_to,
conn_id,
reset_token,
} => {
1 + // frame type
octets::varint_len(*seq_num) + // seq_num
octets::varint_len(*retire_prior_to) + // retire_prior_to
1 + // conn_id length
conn_id.len() + // conn_id
reset_token.len() // reset_token
},
Frame::RetireConnectionId { seq_num } => {
1 + // frame type
octets::varint_len(*seq_num) // seq_num
},
Frame::PathChallenge { .. } => {
1 + // frame type
8 // data
},
Frame::PathResponse { .. } => {
1 + // frame type
8 // data
},
Frame::ConnectionClose {
frame_type,
error_code,
reason,
..
} => {
1 + // frame type
octets::varint_len(*error_code) + // error_code
octets::varint_len(*frame_type) + // frame_type
octets::varint_len(reason.len() as u64) + // reason_len
reason.len() // reason
},
Frame::ApplicationClose { reason, error_code } => {
1 + // frame type
octets::varint_len(*error_code) + // error_code
octets::varint_len(reason.len() as u64) + // reason_len
reason.len() // reason
},
Frame::HandshakeDone => {
1 // frame type
},
Frame::Datagram { data } => {
1 + // frame type
octets::varint_len(data.len() as u64) + // length
data.len() // data
},
}
}
pub fn ack_eliciting(&self) -> bool {
match self {
Frame::Padding { .. } |
Frame::ACK { .. } |
Frame::ApplicationClose { .. } |
Frame::ConnectionClose { .. } => false,
_ => true,
}
}
pub fn retransmittable(&self) -> bool {
match self {
Frame::Datagram { .. } => false,
_ => true,
}
}
#[cfg(feature = "qlog")]
pub fn to_qlog(&self) -> qlog::QuicFrame {
match self {
Frame::Padding { .. } => qlog::QuicFrame::padding(),
Frame::Ping { .. } => qlog::QuicFrame::ping(),
Frame::ACK { ack_delay, ranges } => {
let ack_ranges =
ranges.iter().map(|r| (r.start, r.end - 1)).collect();
qlog::QuicFrame::ack(
Some(ack_delay.to_string()),
Some(ack_ranges),
None,
None,
None,
)
},
Frame::ResetStream {
stream_id,
error_code,
final_size,
} => qlog::QuicFrame::reset_stream(
stream_id.to_string(),
*error_code,
final_size.to_string(),
),
Frame::StopSending {
stream_id,
error_code,
} =>
qlog::QuicFrame::stop_sending(stream_id.to_string(), *error_code),
Frame::Crypto { data } => qlog::QuicFrame::crypto(
data.off().to_string(),
data.len().to_string(),
),
Frame::NewToken { token } => qlog::QuicFrame::new_token(
token.len().to_string(),
"TODO: https://github.com/quiclog/internet-drafts/issues/36"
.to_string(),
),
Frame::Stream { stream_id, data } => qlog::QuicFrame::stream(
stream_id.to_string(),
data.off().to_string(),
data.len().to_string(),
data.fin(),
None,
),
Frame::MaxData { max } => qlog::QuicFrame::max_data(max.to_string()),
Frame::MaxStreamData { stream_id, max } =>
qlog::QuicFrame::max_stream_data(
stream_id.to_string(),
max.to_string(),
),
Frame::MaxStreamsBidi { max } => qlog::QuicFrame::max_streams(
qlog::StreamType::Bidirectional,
max.to_string(),
),
Frame::MaxStreamsUni { max } => qlog::QuicFrame::max_streams(
qlog::StreamType::Unidirectional,
max.to_string(),
),
Frame::DataBlocked { limit } =>
qlog::QuicFrame::data_blocked(limit.to_string()),
Frame::StreamDataBlocked { stream_id, limit } =>
qlog::QuicFrame::stream_data_blocked(
stream_id.to_string(),
limit.to_string(),
),
Frame::StreamsBlockedBidi { limit } =>
qlog::QuicFrame::streams_blocked(
qlog::StreamType::Bidirectional,
limit.to_string(),
),
Frame::StreamsBlockedUni { limit } =>
qlog::QuicFrame::streams_blocked(
qlog::StreamType::Unidirectional,
limit.to_string(),
),
Frame::NewConnectionId {
seq_num,
retire_prior_to,
conn_id,
..
} => qlog::QuicFrame::new_connection_id(
seq_num.to_string(),
retire_prior_to.to_string(),
conn_id.len() as u64,
"TODO: https://github.com/quiclog/internet-drafts/issues/36"
.to_string(),
"TODO: https://github.com/quiclog/internet-drafts/issues/36"
.to_string(),
),
Frame::RetireConnectionId { seq_num } =>
qlog::QuicFrame::retire_connection_id(seq_num.to_string()),
Frame::PathChallenge { .. } => qlog::QuicFrame::path_challenge(Some(
"TODO: https://github.com/quiclog/internet-drafts/issues/36"
.to_string(),
)),
Frame::PathResponse { .. } => qlog::QuicFrame::path_response(Some(
"TODO: https://github.com/quiclog/internet-drafts/issues/36"
.to_string(),
)),
Frame::ConnectionClose {
error_code, reason, ..
} => qlog::QuicFrame::connection_close(
qlog::ErrorSpace::TransportError,
*error_code,
*error_code,
String::from_utf8(reason.clone()).unwrap(),
Some(
"TODO: https://github.com/quiclog/internet-drafts/issues/36"
.to_string(),
),
),
Frame::ApplicationClose { error_code, reason } =>
qlog::QuicFrame::connection_close(
qlog::ErrorSpace::ApplicationError,
*error_code,
*error_code,
String::from_utf8(reason.clone()).unwrap(),
None, /* Application variant of the frame has no trigger
* frame type */
),
Frame::HandshakeDone => qlog::QuicFrame::handshake_done(),
Frame::Datagram { .. } => qlog::QuicFrame::unknown(0x30),
}
}
}
impl std::fmt::Debug for Frame {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Frame::Padding { len } => {
write!(f, "PADDING len={}", len)?;
},
Frame::Ping => {
write!(f, "PING")?;
},
Frame::ACK { ack_delay, ranges } => {
write!(f, "ACK delay={} blocks={:?}", ack_delay, ranges)?;
},
Frame::ResetStream {
stream_id,
error_code,
final_size,
} => {
write!(
f,
"RESET_STREAM stream={} err={:x} size={}",
stream_id, error_code, final_size
)?;
},
Frame::StopSending {
stream_id,
error_code,
} => {
write!(
f,
"STOP_SENDING stream={} err={:x}",
stream_id, error_code
)?;
},
Frame::Crypto { data } => {
write!(f, "CRYPTO off={} len={}", data.off(), data.len())?;
},
Frame::NewToken { .. } => {
write!(f, "NEW_TOKEN (TODO)")?;
},
Frame::Stream { stream_id, data } => {
write!(
f,
"STREAM id={} off={} len={} fin={}",
stream_id,
data.off(),
data.len(),
data.fin()
)?;
},
Frame::MaxData { max } => {
write!(f, "MAX_DATA max={}", max)?;
},
Frame::MaxStreamData { stream_id, max } => {
write!(f, "MAX_STREAM_DATA stream={} max={}", stream_id, max)?;
},
Frame::MaxStreamsBidi { max } => {
write!(f, "MAX_STREAMS type=bidi max={}", max)?;
},
Frame::MaxStreamsUni { max } => {
write!(f, "MAX_STREAMS type=uni max={}", max)?;
},
Frame::DataBlocked { limit } => {
write!(f, "DATA_BLOCKED limit={}", limit)?;
},
Frame::StreamDataBlocked { stream_id, limit } => {
write!(
f,
"STREAM_DATA_BLOCKED stream={} limit={}",
stream_id, limit
)?;
},
Frame::StreamsBlockedBidi { limit } => {
write!(f, "STREAMS_BLOCKED type=bidi limit={}", limit)?;
},
Frame::StreamsBlockedUni { limit } => {
write!(f, "STREAMS_BLOCKED type=uni limit={}", limit)?;
},
Frame::NewConnectionId { .. } => {
write!(f, "NEW_CONNECTION_ID (TODO)")?;
},
Frame::RetireConnectionId { .. } => {
write!(f, "RETIRE_CONNECTION_ID (TODO)")?;
},
Frame::PathChallenge { data } => {
write!(f, "PATH_CHALLENGE data={:02x?}", data)?;
},
Frame::PathResponse { data } => {
write!(f, "PATH_RESPONSE data={:02x?}", data)?;
},
Frame::ConnectionClose {
error_code,
frame_type,
reason,
} => {
write!(
f,
"CONNECTION_CLOSE err={:x} frame={:x} reason={:x?}",
error_code, frame_type, reason
)?;
},
Frame::ApplicationClose { error_code, reason } => {
write!(
f,
"APPLICATION_CLOSE err={:x} reason={:x?}",
error_code, reason
)?;
},
Frame::HandshakeDone => {
write!(f, "HANDSHAKE_DONE")?;
},
Frame::Datagram { data } => {
write!(f, "DATAGRAM len={}", data.len(),)?;
},
}
Ok(())
}
}
fn parse_ack_frame(_ty: u64, b: &mut octets::Octets) -> Result<Frame> {
let largest_ack = b.get_varint()?;
let ack_delay = b.get_varint()?;
let block_count = b.get_varint()?;
let ack_block = b.get_varint()?;
if largest_ack < ack_block {
return Err(Error::InvalidFrame);
}
let mut smallest_ack = largest_ack - ack_block;
let mut ranges = ranges::RangeSet::default();
#[allow(clippy::range_plus_one)]
ranges.insert(smallest_ack..largest_ack + 1);
for _i in 0..block_count {
let gap = b.get_varint()?;
if smallest_ack < 2 + gap {
return Err(Error::InvalidFrame);
}
let largest_ack = (smallest_ack - gap) - 2;
let ack_block = b.get_varint()?;
if largest_ack < ack_block {
return Err(Error::InvalidFrame);
}
smallest_ack = largest_ack - ack_block;
#[allow(clippy::range_plus_one)]
ranges.insert(smallest_ack..largest_ack + 1);
}
Ok(Frame::ACK { ack_delay, ranges })
}
fn parse_stream_frame(ty: u64, b: &mut octets::Octets) -> Result<Frame> {
let first = ty as u8;
let stream_id = b.get_varint()?;
let offset = if first & 0x04 != 0 {
b.get_varint()?
} else {
0
};
let len = if first & 0x02 != 0 {
b.get_varint()? as usize
} else {
b.cap()
};
if offset + len as u64 >= MAX_STREAM_SIZE {
return Err(Error::InvalidFrame);
}
let fin = first & 0x01 != 0;
let data = b.get_bytes(len)?;
let data = stream::RangeBuf::from(data.as_ref(), offset, fin);
Ok(Frame::Stream { stream_id, data })
}
fn parse_datagram_frame(ty: u64, b: &mut octets::Octets) -> Result<Frame> {
let first = ty as u8;
let len = if first & 0x01 != 0 {
b.get_varint()? as usize
} else {
b.cap()
};
let data = b.get_bytes(len)?;
Ok(Frame::Datagram {
data: Vec::from(data.buf()),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn padding() {
let mut d = [42; 128];
let frame = Frame::Padding { len: 128 };
let wire_len = {
let mut b = octets::OctetsMut::with_slice(&mut d);
frame.to_bytes(&mut b).unwrap()
};
assert_eq!(wire_len, 128);
let mut b = octets::Octets::with_slice(&d);
assert_eq!(Frame::from_bytes(&mut b, packet::Type::Short), Ok(frame));
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Initial).is_ok());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::ZeroRTT).is_ok());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Handshake).is_ok());
}
#[test]
fn ping() {
let mut d = [42; 128];
let frame = Frame::Ping;
let wire_len = {
let mut b = octets::OctetsMut::with_slice(&mut d);
frame.to_bytes(&mut b).unwrap()
};
assert_eq!(wire_len, 1);
assert_eq!(&d[..wire_len], [0x01 as u8]);
let mut b = octets::Octets::with_slice(&d);
assert_eq!(Frame::from_bytes(&mut b, packet::Type::Short), Ok(frame));
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::ZeroRTT).is_ok());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Initial).is_ok());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Handshake).is_ok());
}
#[test]
fn ack() {
let mut d = [42; 128];
let mut ranges = ranges::RangeSet::default();
ranges.insert(4..7);
ranges.insert(9..12);
ranges.insert(15..19);
ranges.insert(3000..5000);
let frame = Frame::ACK {
ack_delay: 874_656_534,
ranges,
};
let wire_len = {
let mut b = octets::OctetsMut::with_slice(&mut d);
frame.to_bytes(&mut b).unwrap()
};
assert_eq!(wire_len, 17);
let mut b = octets::Octets::with_slice(&d);
assert_eq!(Frame::from_bytes(&mut b, packet::Type::Short), Ok(frame));
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Initial).is_ok());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::ZeroRTT).is_err());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Handshake).is_ok());
}
#[test]
fn reset_stream() {
let mut d = [42; 128];
let frame = Frame::ResetStream {
stream_id: 123_213,
error_code: 21_123_767,
final_size: 21_123_767,
};
let wire_len = {
let mut b = octets::OctetsMut::with_slice(&mut d);
frame.to_bytes(&mut b).unwrap()
};
assert_eq!(wire_len, 13);
let mut b = octets::Octets::with_slice(&d);
assert_eq!(Frame::from_bytes(&mut b, packet::Type::Short), Ok(frame));
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::ZeroRTT).is_ok());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Initial).is_err());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Handshake).is_err());
}
#[test]
fn stop_sending() {
let mut d = [42; 128];
let frame = Frame::StopSending {
stream_id: 123_213,
error_code: 15_352,
};
let wire_len = {
let mut b = octets::OctetsMut::with_slice(&mut d);
frame.to_bytes(&mut b).unwrap()
};
assert_eq!(wire_len, 7);
let mut b = octets::Octets::with_slice(&d);
assert_eq!(Frame::from_bytes(&mut b, packet::Type::Short), Ok(frame));
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::ZeroRTT).is_ok());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Initial).is_err());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Handshake).is_err());
}
#[test]
fn crypto() {
let mut d = [42; 128];
let data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
let frame = Frame::Crypto {
data: stream::RangeBuf::from(&data, 1230976, false),
};
let wire_len = {
let mut b = octets::OctetsMut::with_slice(&mut d);
frame.to_bytes(&mut b).unwrap()
};
assert_eq!(wire_len, 18);
let mut b = octets::Octets::with_slice(&d);
assert_eq!(Frame::from_bytes(&mut b, packet::Type::Short), Ok(frame));
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Initial).is_ok());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::ZeroRTT).is_err());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Handshake).is_ok());
}
#[test]
fn new_token() {
let mut d = [42; 128];
let frame = Frame::NewToken {
token: Vec::from("this is a token"),
};
let wire_len = {
let mut b = octets::OctetsMut::with_slice(&mut d);
frame.to_bytes(&mut b).unwrap()
};
assert_eq!(wire_len, 17);
let mut b = octets::Octets::with_slice(&d);
assert_eq!(Frame::from_bytes(&mut b, packet::Type::Short), Ok(frame));
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Initial).is_err());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::ZeroRTT).is_err());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Handshake).is_err());
}
#[test]
fn stream() {
let mut d = [42; 128];
let data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
let frame = Frame::Stream {
stream_id: 32,
data: stream::RangeBuf::from(&data, 1230976, true),
};
let wire_len = {
let mut b = octets::OctetsMut::with_slice(&mut d);
frame.to_bytes(&mut b).unwrap()
};
assert_eq!(wire_len, 19);
let mut b = octets::Octets::with_slice(&d);
assert_eq!(Frame::from_bytes(&mut b, packet::Type::Short), Ok(frame));
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::ZeroRTT).is_ok());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Initial).is_err());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Handshake).is_err());
}
#[test]
fn stream_too_big() {
let mut d = [42; 128];
let data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
let frame = Frame::Stream {
stream_id: 32,
data: stream::RangeBuf::from(&data, MAX_STREAM_SIZE - 11, true),
};
let wire_len = {
let mut b = octets::OctetsMut::with_slice(&mut d);
frame.to_bytes(&mut b).unwrap()
};
assert_eq!(wire_len, 23);
let mut b = octets::Octets::with_slice(&d);
assert_eq!(
Frame::from_bytes(&mut b, packet::Type::Short),
Err(Error::InvalidFrame)
);
}
#[test]
fn max_data() {
let mut d = [42; 128];
let frame = Frame::MaxData { max: 128_318_273 };
let wire_len = {
let mut b = octets::OctetsMut::with_slice(&mut d);
frame.to_bytes(&mut b).unwrap()
};
assert_eq!(wire_len, 5);
let mut b = octets::Octets::with_slice(&d);
assert_eq!(Frame::from_bytes(&mut b, packet::Type::Short), Ok(frame));
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::ZeroRTT).is_ok());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Initial).is_err());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Handshake).is_err());
}
#[test]
fn max_stream_data() {
let mut d = [42; 128];
let frame = Frame::MaxStreamData {
stream_id: 12_321,
max: 128_318_273,
};
let wire_len = {
let mut b = octets::OctetsMut::with_slice(&mut d);
frame.to_bytes(&mut b).unwrap()
};
assert_eq!(wire_len, 7);
let mut b = octets::Octets::with_slice(&d);
assert_eq!(Frame::from_bytes(&mut b, packet::Type::Short), Ok(frame));
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::ZeroRTT).is_ok());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Initial).is_err());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Handshake).is_err());
}
#[test]
fn max_streams_bidi() {
let mut d = [42; 128];
let frame = Frame::MaxStreamsBidi { max: 128_318_273 };
let wire_len = {
let mut b = octets::OctetsMut::with_slice(&mut d);
frame.to_bytes(&mut b).unwrap()
};
assert_eq!(wire_len, 5);
let mut b = octets::Octets::with_slice(&d);
assert_eq!(Frame::from_bytes(&mut b, packet::Type::Short), Ok(frame));
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::ZeroRTT).is_ok());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Initial).is_err());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Handshake).is_err());
}
#[test]
fn max_streams_uni() {
let mut d = [42; 128];
let frame = Frame::MaxStreamsUni { max: 128_318_273 };
let wire_len = {
let mut b = octets::OctetsMut::with_slice(&mut d);
frame.to_bytes(&mut b).unwrap()
};
assert_eq!(wire_len, 5);
let mut b = octets::Octets::with_slice(&d);
assert_eq!(Frame::from_bytes(&mut b, packet::Type::Short), Ok(frame));
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::ZeroRTT).is_ok());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Initial).is_err());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Handshake).is_err());
}
#[test]
fn data_blocked() {
let mut d = [42; 128];
let frame = Frame::DataBlocked { limit: 128_318_273 };
let wire_len = {
let mut b = octets::OctetsMut::with_slice(&mut d);
frame.to_bytes(&mut b).unwrap()
};
assert_eq!(wire_len, 5);
let mut b = octets::Octets::with_slice(&d);
assert_eq!(Frame::from_bytes(&mut b, packet::Type::Short), Ok(frame));
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::ZeroRTT).is_ok());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Initial).is_err());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Handshake).is_err());
}
#[test]
fn stream_data_blocked() {
let mut d = [42; 128];
let frame = Frame::StreamDataBlocked {
stream_id: 12_321,
limit: 128_318_273,
};
let wire_len = {
let mut b = octets::OctetsMut::with_slice(&mut d);
frame.to_bytes(&mut b).unwrap()
};
assert_eq!(wire_len, 7);
let mut b = octets::Octets::with_slice(&d);
assert_eq!(Frame::from_bytes(&mut b, packet::Type::Short), Ok(frame));
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::ZeroRTT).is_ok());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Initial).is_err());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Handshake).is_err());
}
#[test]
fn streams_blocked_bidi() {
let mut d = [42; 128];
let frame = Frame::StreamsBlockedBidi { limit: 128_318_273 };
let wire_len = {
let mut b = octets::OctetsMut::with_slice(&mut d);
frame.to_bytes(&mut b).unwrap()
};
assert_eq!(wire_len, 5);
let mut b = octets::Octets::with_slice(&d);
assert_eq!(Frame::from_bytes(&mut b, packet::Type::Short), Ok(frame));
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::ZeroRTT).is_ok());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Initial).is_err());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Handshake).is_err());
}
#[test]
fn streams_blocked_uni() {
let mut d = [42; 128];
let frame = Frame::StreamsBlockedUni { limit: 128_318_273 };
let wire_len = {
let mut b = octets::OctetsMut::with_slice(&mut d);
frame.to_bytes(&mut b).unwrap()
};
assert_eq!(wire_len, 5);
let mut b = octets::Octets::with_slice(&d);
assert_eq!(Frame::from_bytes(&mut b, packet::Type::Short), Ok(frame));
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::ZeroRTT).is_ok());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Initial).is_err());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Handshake).is_err());
}
#[test]
fn new_connection_id() {
let mut d = [42; 128];
let frame = Frame::NewConnectionId {
seq_num: 123_213,
retire_prior_to: 122_211,
conn_id: vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
reset_token: vec![0x42; 16],
};
let wire_len = {
let mut b = octets::OctetsMut::with_slice(&mut d);
frame.to_bytes(&mut b).unwrap()
};
assert_eq!(wire_len, 41);
let mut b = octets::Octets::with_slice(&d);
assert_eq!(Frame::from_bytes(&mut b, packet::Type::Short), Ok(frame));
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::ZeroRTT).is_ok());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Initial).is_err());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Handshake).is_err());
}
#[test]
fn retire_connection_id() {
let mut d = [42; 128];
let frame = Frame::RetireConnectionId { seq_num: 123_213 };
let wire_len = {
let mut b = octets::OctetsMut::with_slice(&mut d);
frame.to_bytes(&mut b).unwrap()
};
assert_eq!(wire_len, 5);
let mut b = octets::Octets::with_slice(&d);
assert_eq!(Frame::from_bytes(&mut b, packet::Type::Short), Ok(frame));
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Initial).is_err());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::ZeroRTT).is_err());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Handshake).is_err());
}
#[test]
fn path_challenge() {
let mut d = [42; 128];
let frame = Frame::PathChallenge {
data: vec![1, 2, 3, 4, 5, 6, 7, 8],
};
let wire_len = {
let mut b = octets::OctetsMut::with_slice(&mut d);
frame.to_bytes(&mut b).unwrap()
};
assert_eq!(wire_len, 9);
let mut b = octets::Octets::with_slice(&d);
assert_eq!(Frame::from_bytes(&mut b, packet::Type::Short), Ok(frame));
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::ZeroRTT).is_ok());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Initial).is_err());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Handshake).is_err());
}
#[test]
fn path_response() {
let mut d = [42; 128];
let frame = Frame::PathResponse {
data: vec![1, 2, 3, 4, 5, 6, 7, 8],
};
let wire_len = {
let mut b = octets::OctetsMut::with_slice(&mut d);
frame.to_bytes(&mut b).unwrap()
};
assert_eq!(wire_len, 9);
let mut b = octets::Octets::with_slice(&d);
assert_eq!(Frame::from_bytes(&mut b, packet::Type::Short), Ok(frame));
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Initial).is_err());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::ZeroRTT).is_err());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Handshake).is_err());
}
#[test]
fn connection_close() {
let mut d = [42; 128];
let frame = Frame::ConnectionClose {
error_code: 0xbeef,
frame_type: 523_423,
reason: vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
};
let wire_len = {
let mut b = octets::OctetsMut::with_slice(&mut d);
frame.to_bytes(&mut b).unwrap()
};
assert_eq!(wire_len, 22);
let mut b = octets::Octets::with_slice(&d);
assert_eq!(Frame::from_bytes(&mut b, packet::Type::Short), Ok(frame));
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Initial).is_ok());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::ZeroRTT).is_err());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Handshake).is_ok());
}
#[test]
fn application_close() {
let mut d = [42; 128];
let frame = Frame::ApplicationClose {
error_code: 0xbeef,
reason: vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
};
let wire_len = {
let mut b = octets::OctetsMut::with_slice(&mut d);
frame.to_bytes(&mut b).unwrap()
};
assert_eq!(wire_len, 18);
let mut b = octets::Octets::with_slice(&d);
assert_eq!(Frame::from_bytes(&mut b, packet::Type::Short), Ok(frame));
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::ZeroRTT).is_ok());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Initial).is_err());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Handshake).is_err());
}
#[test]
fn handshake_done() {
let mut d = [42; 128];
let frame = Frame::HandshakeDone;
let wire_len = {
let mut b = octets::OctetsMut::with_slice(&mut d);
frame.to_bytes(&mut b).unwrap()
};
assert_eq!(wire_len, 1);
let mut b = octets::Octets::with_slice(&d);
assert_eq!(Frame::from_bytes(&mut b, packet::Type::Short), Ok(frame));
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Initial).is_err());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::ZeroRTT).is_err());
let mut b = octets::Octets::with_slice(&d);
assert!(Frame::from_bytes(&mut b, packet::Type::Handshake).is_err());
}
#[test]
fn datagram() {
let mut d = [42; 128];
let data = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
let frame = Frame::Datagram { data };
let wire_len = {
let mut b = octets::OctetsMut::with_slice(&mut d);
frame.to_bytes(&mut b).unwrap()
};
assert_eq!(wire_len, 14);
let mut b = octets::Octets::with_slice(&mut d);
assert_eq!(Frame::from_bytes(&mut b, packet::Type::Short), Ok(frame));
let mut b = octets::Octets::with_slice(&mut d);
assert!(Frame::from_bytes(&mut b, packet::Type::Initial).is_err());
let mut b = octets::Octets::with_slice(&mut d);
assert!(Frame::from_bytes(&mut b, packet::Type::ZeroRTT).is_ok());
let mut b = octets::Octets::with_slice(&mut d);
assert!(Frame::from_bytes(&mut b, packet::Type::Handshake).is_err());
}
} | },
|
global_alloc.rs | use core::alloc::{GlobalAlloc, Layout};
use core::ptr;
use linked_list_allocator::{self, LockedHeap};
pub enum Allocator {
Unavailable,
Available(LockedHeap),
}
impl Allocator {
pub unsafe fn allocate_from(start: u64, end: u64) {
match ALLOCATOR {
Allocator::Unavailable => {
ALLOCATOR = Allocator::Available(LockedHeap::new(
start as usize,
end as usize,
));
}
_ => panic!("Allocator has already been initialized"),
}
}
}
unsafe impl GlobalAlloc for Allocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
match self {
Allocator::Unavailable => ptr::null_mut(),
Allocator::Available(alloc) => alloc.alloc(layout),
}
}
unsafe fn | (&self, ptr: *mut u8, layout: Layout) {
match self {
Allocator::Unavailable => (),
Allocator::Available(alloc) => alloc.dealloc(ptr, layout),
}
}
}
// Tests use the std global allocator, but this symbol must still be defined
// for the library to compile, so define it here but do not set it as the
// global allocator.
#[cfg(test)]
static mut ALLOCATOR: Allocator = Allocator::Unavailable;
#[cfg(not(test))]
#[global_allocator]
static mut ALLOCATOR: Allocator = Allocator::Unavailable;
| dealloc |
infer_defaults.py | import numpy as np
from sklearn.preprocessing import LabelEncoder
from lightgbm import LGBMClassifier, LGBMRegressor
def | (df, features, y, n_jobs):
model_class = LGBMRegressor
if len(np.unique(y)) == 2:
y = LabelEncoder().fit_transform(y)
model_class = LGBMClassifier
categoricals = df[features].select_dtypes(exclude=[np.number]).columns.tolist()
for f in categoricals:
df[f] = LabelEncoder().fit_transform(df[f].apply(str))
min_child_samples = int(0.01*df.shape[0])
model = model_class(min_child_samples=min_child_samples, n_jobs=n_jobs)
return model, df, categoricals, y
| infer_model |
classification_test.py | from abc import abstractmethod
from typing import Any, Dict
import pandas as pd
from .metric_test import MetricTest
from overrides import overrides
from munch import Munch
from expanded_checklist.checklist.utils import \
DataShape, is_2d_list, ACCUMULATED_STR
pd.options.display.float_format = "{:,.2f}".format
class ClassificationMetric(MetricTest):
def __init__(
self,
name: str,
required_ds: DataShape,
only_accumulate: bool = False
) -> None:
"""
Arguments:
name: name of the test
For the remaining parameters see MetricTest
"""
super().__init__(
name, required_ds, only_accumulate, probability_based=False,
drop_none_labels=True)
@abstractmethod
def | (self, labels, preds, confs) -> Any:
"""
Get results for the binary classification.
"""
raise NotImplementedError
def get_results(self, labels, preds, confs, meta, **kwargs):
"""
Get one vs other results for each class.
If a metric/test supports direct calculation of multi-class results
then it should override this function or (even better) the get_results
function (which calls this function).
"""
# classes are ints, starting from 0
class_results = {}
if 'n_classes' in kwargs:
self.n_classes = kwargs['n_classes']
for cl in range(self.n_classes):
# turn the data into one vs other
if is_2d_list(labels):
labels_tmp = []
for x in labels:
labels_tmp.append([True if i == cl else False for i in x])
if not any(labels_tmp[-1]):
continue
else:
labels_tmp = [True if x == cl else False for x in labels]
if not any(labels_tmp):
continue
if not is_2d_list(preds):
pred_tmp = [True if x == cl else False for x in preds]
# get the conf score for a particular class
conf_tmp = [x[cl] for x in confs]
else:
pred_tmp = []
conf_tmp = []
for x in preds:
pred_tmp.append([True if i == cl else False for i in x])
# get the conf score for a particular class
for x in confs:
conf_tmp.append([i[cl] for i in x])
res = self.get_binary_class_results(labels_tmp, pred_tmp, conf_tmp)
class_results[cl] = res
accumulated = self.cross_class_accumulation(
class_results, labels, preds, confs)
if accumulated:
class_results[ACCUMULATED_STR] = accumulated
return class_results
def cross_class_accumulation(
self,
class_results: Dict, # class to results mapping
labels, preds, confs
) -> Any:
"""
Accumulate the results obtained for each class independently.
Return the result for all classes, to be assigned as a value for
ACCUMULATED_STR key.
"""
return {}
| get_binary_class_results |
tictactoe.js | /* global xxx */
'use strict';
{
let player = '';
let cpu = '';
let filled = [];
let free = [];
const createEvents = () => {
document.getElementById('X').addEventListener('click', start);
document.getElementById('O').addEventListener('click', start);
document.getElementById('continue').addEventListener('click', newGame);
let actions = document.getElementsByClassName('action');
actions = Array.from(actions);
actions.forEach(function (element) {
element.addEventListener('click', move);
});
};
const start = (e) => {
player = e.target.id;
cpu = (player === 'X' ? 'O' : 'X');
filled = ['', '', '', '', '', '', '', '', ''];
free = [0, 1, 2, 3, 4, 5, 6, 7, 8];
document.getElementById; | const gameEnds = (user) => {
for (let i = 0; i < free.length; i++) { // disable boxs on board
document.getElementById(free[i]).removeEventListener(
'click', move);
}
document.getElementById('result').style.display = 'block';
if (user === 'tie') {
document.getElementById('aftermath').innerText = 'TIE !';
}
if (user === cpu) {
document.getElementById('aftermath').innerText = 'You LOSE !';
}
if (user === player) {
document.getElementById('aftermath').innerText = 'You WIN !';
}
document.getElementById('continue').addEventListener('click', newGame);
};
const move = (e) => {
const option = e.target.id;
filled[option] = player;
document.getElementById(option).removeEventListener('click', move);
document.getElementById(option).innerText = player;
adjustBoards();
if (win(player)) {
gameEnds(player);
} else if (free.length === 0) {
gameEnds('tie');
} else {
cpuMoves();
if (win(cpu)) {
gameEnds(cpu);
}
}
};
const win = (user) => {
if (filled[0] === user) {
if (filled[1] === user) {
if (filled[2] === user) return true;
}
if (filled[3] === user) {
if (filled[6] === user) return true;
}
if (filled[4] === user) {
if (filled[8] === user) return true;
}
}
if (filled[1] === user && filled[4] === user && filled[7] === user) return true;
if (filled[2] === user) {
if (filled[4] === user) {
if (filled[6] === user) return true;
}
if (filled[5] === user) {
if (filled[8] === user) return true;
}
}
if (filled[3] === user && filled[4] === user && filled[5] === user) return true;
if (filled[6] === user && filled[7] === user && filled[8] === user) return true;
};
const cpuMoves = () => {
const cpuBox = free[Math.floor((Math.random() * free.length))];
filled[cpuBox] = cpu;
document.getElementById(cpuBox).removeEventListener('click', move);
document.getElementById(cpuBox).innerText = cpu;
adjustBoards();
};
const adjustBoards = () => {
let aux = [];
for (let i = 0; i < free.length; i++) {
if (filled[free[i]] === '') {
aux.push(free[i]);
}
}
free = aux.slice();
};
const newGame = () => {
location.reload();
};
window.addEventListener('load', createEvents);
} | document.getElementById('menu').style.display = 'none';
document.getElementById('board').style.display = 'block';
};
|
maxpacketsize.rs | #[doc = "Register `MAXPACKETSIZE` reader"]
pub struct R(crate::R<MAXPACKETSIZE_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<MAXPACKETSIZE_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
} | impl From<crate::R<MAXPACKETSIZE_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<MAXPACKETSIZE_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `MAXPACKETSIZE` writer"]
pub struct W(crate::W<MAXPACKETSIZE_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<MAXPACKETSIZE_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<MAXPACKETSIZE_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<MAXPACKETSIZE_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `MAXPACKETSIZE` reader - Length of keystream generated when MODE.LENGTH = Extended. This value must be greater or equal to the subsequent packet payload to be encrypted/decrypted."]
pub struct MAXPACKETSIZE_R(crate::FieldReader<u8, u8>);
impl MAXPACKETSIZE_R {
#[inline(always)]
pub(crate) fn new(bits: u8) -> Self {
MAXPACKETSIZE_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for MAXPACKETSIZE_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `MAXPACKETSIZE` writer - Length of keystream generated when MODE.LENGTH = Extended. This value must be greater or equal to the subsequent packet payload to be encrypted/decrypted."]
pub struct MAXPACKETSIZE_W<'a> {
w: &'a mut W,
}
impl<'a> MAXPACKETSIZE_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0xff) | (value as u32 & 0xff);
self.w
}
}
impl R {
#[doc = "Bits 0:7 - Length of keystream generated when MODE.LENGTH = Extended. This value must be greater or equal to the subsequent packet payload to be encrypted/decrypted."]
#[inline(always)]
pub fn maxpacketsize(&self) -> MAXPACKETSIZE_R {
MAXPACKETSIZE_R::new((self.bits & 0xff) as u8)
}
}
impl W {
#[doc = "Bits 0:7 - Length of keystream generated when MODE.LENGTH = Extended. This value must be greater or equal to the subsequent packet payload to be encrypted/decrypted."]
#[inline(always)]
pub fn maxpacketsize(&mut self) -> MAXPACKETSIZE_W {
MAXPACKETSIZE_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "Length of keystream generated when MODE.LENGTH = Extended.\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [maxpacketsize](index.html) module"]
pub struct MAXPACKETSIZE_SPEC;
impl crate::RegisterSpec for MAXPACKETSIZE_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [maxpacketsize::R](R) reader structure"]
impl crate::Readable for MAXPACKETSIZE_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [maxpacketsize::W](W) writer structure"]
impl crate::Writable for MAXPACKETSIZE_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets MAXPACKETSIZE to value 0xfb"]
impl crate::Resettable for MAXPACKETSIZE_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0xfb
}
} | } |
oldnew_test.go | // Protocol Buffers for Go with Gadgets
//
// Copyright (c) 2013, The GoGo Authors. All rights reserved.
// http://github.com/gogo/protobuf
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * 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
// OWNER 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.
package unrecognizedgroup
import (
math_rand "math/rand"
"testing"
time "time"
"github.com/gogo/protobuf/proto"
)
func TestNewOld(t *testing.T) {
popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano()))
newer := NewPopulatedNewNoGroup(popr, true)
data1, err := proto.Marshal(newer)
if err != nil {
panic(err)
}
older := &OldWithGroup{}
if err = proto.Unmarshal(data1, older); err != nil {
panic(err)
}
data2, err := proto.Marshal(older)
if err != nil {
panic(err)
}
bluer := &NewNoGroup{}
if err := proto.Unmarshal(data2, bluer); err != nil {
panic(err)
}
if err := newer.VerboseEqual(bluer); err != nil {
t.Fatalf("%#v !VerboseProto %#v, since %v", newer, bluer, err)
}
}
func | (t *testing.T) {
popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano()))
older := NewPopulatedOldWithGroup(popr, true)
data1, err := proto.Marshal(older)
if err != nil {
panic(err)
}
newer := &NewNoGroup{}
if err = proto.Unmarshal(data1, newer); err != nil {
panic(err)
}
data2, err := proto.Marshal(newer)
if err != nil {
panic(err)
}
bluer := &OldWithGroup{}
if err := proto.Unmarshal(data2, bluer); err != nil {
panic(err)
}
if err := older.VerboseEqual(bluer); err != nil {
t.Fatalf("%#v !VerboseProto %#v, since %v", older, bluer, err)
}
}
func TestOldNewOldNew(t *testing.T) {
popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano()))
older := NewPopulatedOldWithGroup(popr, true)
data1, err := proto.Marshal(older)
if err != nil {
panic(err)
}
newer := &NewNoGroup{}
if err = proto.Unmarshal(data1, newer); err != nil {
panic(err)
}
data2, err := proto.Marshal(newer)
if err != nil {
panic(err)
}
bluer := &OldWithGroup{}
if err = proto.Unmarshal(data2, bluer); err != nil {
panic(err)
}
if err = older.VerboseEqual(bluer); err != nil {
t.Fatalf("%#v !VerboseProto %#v, since %v", older, bluer, err)
}
data3, err := proto.Marshal(bluer)
if err != nil {
panic(err)
}
purple := &NewNoGroup{}
if err = proto.Unmarshal(data3, purple); err != nil {
panic(err)
}
data4, err := proto.Marshal(purple)
if err != nil {
panic(err)
}
magenta := &OldWithGroup{}
if err := proto.Unmarshal(data4, magenta); err != nil {
panic(err)
}
if err := older.VerboseEqual(magenta); err != nil {
t.Fatalf("%#v !VerboseProto %#v, since %v", older, magenta, err)
}
}
| TestOldNew |
registry_list_reader.go | /*
Copyright (c) 2019 Red Hat, 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.
*/
// IMPORTANT: This file has been generated automatically, refrain from modifying it manually as all
// your changes will be lost when the file is generated again.
package v1 // github.com/openshift-online/ocm-sdk-go/accountsmgmt/v1
import (
"fmt"
"github.com/openshift-online/ocm-sdk-go/helpers"
)
// registryListData is type used internally to marshal and unmarshal lists of objects
// of type 'registry'.
type registryListData []*registryData
// UnmarshalRegistryList reads a list of values of the 'registry'
// from the given source, which can be a slice of bytes, a string, an io.Reader or a
// json.Decoder.
func UnmarshalRegistryList(source interface{}) (list *RegistryList, err error) |
// wrap is the method used internally to convert a list of values of the
// 'registry' value to a JSON document.
func (l *RegistryList) wrap() (data registryListData, err error) {
if l == nil {
return
}
data = make(registryListData, len(l.items))
for i, item := range l.items {
data[i], err = item.wrap()
if err != nil {
return
}
}
return
}
// unwrap is the function used internally to convert the JSON unmarshalled data to a
// list of values of the 'registry' type.
func (d registryListData) unwrap() (list *RegistryList, err error) {
if d == nil {
return
}
items := make([]*Registry, len(d))
for i, item := range d {
items[i], err = item.unwrap()
if err != nil {
return
}
}
list = new(RegistryList)
list.items = items
return
}
// registryListLinkData is type used internally to marshal and unmarshal links
// to lists of objects of type 'registry'.
type registryListLinkData struct {
Kind *string "json:\"kind,omitempty\""
HREF *string "json:\"href,omitempty\""
Items []*registryData "json:\"items,omitempty\""
}
// wrapLink is the method used internally to convert a list of values of the
// 'registry' value to a link.
func (l *RegistryList) wrapLink() (data *registryListLinkData, err error) {
if l == nil {
return
}
items := make([]*registryData, len(l.items))
for i, item := range l.items {
items[i], err = item.wrap()
if err != nil {
return
}
}
data = new(registryListLinkData)
data.Items = items
data.HREF = l.href
data.Kind = new(string)
if l.link {
*data.Kind = RegistryListLinkKind
} else {
*data.Kind = RegistryListKind
}
return
}
// unwrapLink is the function used internally to convert a JSON link to a list
// of values of the 'registry' type to a list.
func (d *registryListLinkData) unwrapLink() (list *RegistryList, err error) {
if d == nil {
return
}
items := make([]*Registry, len(d.Items))
for i, item := range d.Items {
items[i], err = item.unwrap()
if err != nil {
return
}
}
list = new(RegistryList)
list.items = items
list.href = d.HREF
if d.Kind != nil {
switch *d.Kind {
case RegistryListKind:
list.link = false
case RegistryListLinkKind:
list.link = true
default:
err = fmt.Errorf(
"expected kind '%s' or '%s' but got '%s'",
RegistryListKind,
RegistryListLinkKind,
*d.Kind,
)
return
}
}
return
}
| {
decoder, err := helpers.NewDecoder(source)
if err != nil {
return
}
var data registryListData
err = decoder.Decode(&data)
if err != nil {
return
}
list, err = data.unwrap()
return
} |
prince_region0_iv_body10.rs | #[doc = "Reader of register PRINCE_REGION0_IV_BODY10"]
pub type R = crate::R<u32, super::PRINCE_REGION0_IV_BODY10>;
#[doc = "Writer for register PRINCE_REGION0_IV_BODY10"]
pub type W = crate::W<u32, super::PRINCE_REGION0_IV_BODY10>;
#[doc = "Register PRINCE_REGION0_IV_BODY10 `reset()`'s with value 0"]
impl crate::ResetValue for super::PRINCE_REGION0_IV_BODY10 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `FIELD`"]
pub type FIELD_R = crate::R<u32, u32>;
#[doc = "Write proxy for field `FIELD`"]
pub struct FIELD_W<'a> {
w: &'a mut W,
}
impl<'a> FIELD_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn | (self, value: u32) -> &'a mut W {
self.w.bits = (self.w.bits & !0xffff_ffff) | ((value as u32) & 0xffff_ffff);
self.w
}
}
impl R {
#[doc = "Bits 0:31 - ."]
#[inline(always)]
pub fn field(&self) -> FIELD_R {
FIELD_R::new((self.bits & 0xffff_ffff) as u32)
}
}
impl W {
#[doc = "Bits 0:31 - ."]
#[inline(always)]
pub fn field(&mut self) -> FIELD_W {
FIELD_W { w: self }
}
}
| bits |
xps_export_options.go | /*
* --------------------------------------------------------------------------------------------------------------------
* <copyright company="Aspose">
* Copyright (c) 2018 Aspose.Slides for Cloud
* </copyright>
* <summary>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* </summary>
* --------------------------------------------------------------------------------------------------------------------
*/
package asposeslidescloud
import (
"encoding/json"
)
// Provides options that control how a presentation is saved in XPS format.
type IXpsExportOptions interface {
// Default regular font for rendering the presentation.
getDefaultRegularFont() string
setDefaultRegularFont(newValue string)
// Export format.
getFormat() string
setFormat(newValue string)
// Specifies whether the generated document should include hidden slides or not. Default is false.
getShowHiddenSlides() bool
setShowHiddenSlides(newValue bool)
// True to convert all metafiles used in a presentation to the PNG images.
getSaveMetafilesAsPng() bool
setSaveMetafilesAsPng(newValue bool)
// True to draw black frame around each slide.
getDrawSlidesFrame() bool
setDrawSlidesFrame(newValue bool)
}
type XpsExportOptions struct {
// Default regular font for rendering the presentation.
DefaultRegularFont string `json:"DefaultRegularFont,omitempty"`
// Export format.
Format string `json:"Format,omitempty"`
// Specifies whether the generated document should include hidden slides or not. Default is false.
ShowHiddenSlides bool `json:"ShowHiddenSlides"`
// True to convert all metafiles used in a presentation to the PNG images.
SaveMetafilesAsPng bool `json:"SaveMetafilesAsPng"`
// True to draw black frame around each slide.
DrawSlidesFrame bool `json:"DrawSlidesFrame"`
}
func NewXpsExportOptions() *XpsExportOptions {
instance := new(XpsExportOptions)
return instance
}
func (this *XpsExportOptions) getDefaultRegularFont() string {
return this.DefaultRegularFont
}
func (this *XpsExportOptions) setDefaultRegularFont(newValue string) {
this.DefaultRegularFont = newValue
}
func (this *XpsExportOptions) getFormat() string {
return this.Format
}
func (this *XpsExportOptions) setFormat(newValue string) {
this.Format = newValue
}
func (this *XpsExportOptions) getShowHiddenSlides() bool {
return this.ShowHiddenSlides
}
func (this *XpsExportOptions) setShowHiddenSlides(newValue bool) {
this.ShowHiddenSlides = newValue
}
func (this *XpsExportOptions) getSaveMetafilesAsPng() bool {
return this.SaveMetafilesAsPng
}
func (this *XpsExportOptions) setSaveMetafilesAsPng(newValue bool) {
this.SaveMetafilesAsPng = newValue
}
func (this *XpsExportOptions) getDrawSlidesFrame() bool {
return this.DrawSlidesFrame
}
func (this *XpsExportOptions) setDrawSlidesFrame(newValue bool) {
this.DrawSlidesFrame = newValue
}
func (this *XpsExportOptions) UnmarshalJSON(b []byte) error {
var objMap map[string]*json.RawMessage
err := json.Unmarshal(b, &objMap)
if err != nil {
return err
}
if valDefaultRegularFont, ok := objMap["defaultRegularFont"]; ok |
if valDefaultRegularFontCap, ok := objMap["DefaultRegularFont"]; ok {
if valDefaultRegularFontCap != nil {
var valueForDefaultRegularFont string
err = json.Unmarshal(*valDefaultRegularFontCap, &valueForDefaultRegularFont)
if err != nil {
return err
}
this.DefaultRegularFont = valueForDefaultRegularFont
}
}
if valFormat, ok := objMap["format"]; ok {
if valFormat != nil {
var valueForFormat string
err = json.Unmarshal(*valFormat, &valueForFormat)
if err != nil {
return err
}
this.Format = valueForFormat
}
}
if valFormatCap, ok := objMap["Format"]; ok {
if valFormatCap != nil {
var valueForFormat string
err = json.Unmarshal(*valFormatCap, &valueForFormat)
if err != nil {
return err
}
this.Format = valueForFormat
}
}
if valShowHiddenSlides, ok := objMap["showHiddenSlides"]; ok {
if valShowHiddenSlides != nil {
var valueForShowHiddenSlides bool
err = json.Unmarshal(*valShowHiddenSlides, &valueForShowHiddenSlides)
if err != nil {
return err
}
this.ShowHiddenSlides = valueForShowHiddenSlides
}
}
if valShowHiddenSlidesCap, ok := objMap["ShowHiddenSlides"]; ok {
if valShowHiddenSlidesCap != nil {
var valueForShowHiddenSlides bool
err = json.Unmarshal(*valShowHiddenSlidesCap, &valueForShowHiddenSlides)
if err != nil {
return err
}
this.ShowHiddenSlides = valueForShowHiddenSlides
}
}
if valSaveMetafilesAsPng, ok := objMap["saveMetafilesAsPng"]; ok {
if valSaveMetafilesAsPng != nil {
var valueForSaveMetafilesAsPng bool
err = json.Unmarshal(*valSaveMetafilesAsPng, &valueForSaveMetafilesAsPng)
if err != nil {
return err
}
this.SaveMetafilesAsPng = valueForSaveMetafilesAsPng
}
}
if valSaveMetafilesAsPngCap, ok := objMap["SaveMetafilesAsPng"]; ok {
if valSaveMetafilesAsPngCap != nil {
var valueForSaveMetafilesAsPng bool
err = json.Unmarshal(*valSaveMetafilesAsPngCap, &valueForSaveMetafilesAsPng)
if err != nil {
return err
}
this.SaveMetafilesAsPng = valueForSaveMetafilesAsPng
}
}
if valDrawSlidesFrame, ok := objMap["drawSlidesFrame"]; ok {
if valDrawSlidesFrame != nil {
var valueForDrawSlidesFrame bool
err = json.Unmarshal(*valDrawSlidesFrame, &valueForDrawSlidesFrame)
if err != nil {
return err
}
this.DrawSlidesFrame = valueForDrawSlidesFrame
}
}
if valDrawSlidesFrameCap, ok := objMap["DrawSlidesFrame"]; ok {
if valDrawSlidesFrameCap != nil {
var valueForDrawSlidesFrame bool
err = json.Unmarshal(*valDrawSlidesFrameCap, &valueForDrawSlidesFrame)
if err != nil {
return err
}
this.DrawSlidesFrame = valueForDrawSlidesFrame
}
}
return nil
}
| {
if valDefaultRegularFont != nil {
var valueForDefaultRegularFont string
err = json.Unmarshal(*valDefaultRegularFont, &valueForDefaultRegularFont)
if err != nil {
return err
}
this.DefaultRegularFont = valueForDefaultRegularFont
}
} |
styles.js | (window["webpackJsonp"] = window["webpackJsonp"] || []).push([["styles"],{
/***/ "./node_modules/raw-loader/index.js!./node_modules/postcss-loader/lib/index.js??embedded!./src/styles.css":
/*!**********************************************************************************************!*\
!*** ./node_modules/raw-loader!./node_modules/postcss-loader/lib??embedded!./src/styles.css ***!
\**********************************************************************************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = "/* You can add global styles to this file, and also import other style files */\n"
/***/ }),
/***/ "./node_modules/style-loader/lib/addStyles.js":
/*!****************************************************!*\
!*** ./node_modules/style-loader/lib/addStyles.js ***!
\****************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var stylesInDom = {};
var memoize = function (fn) {
var memo;
return function () {
if (typeof memo === "undefined") memo = fn.apply(this, arguments);
return memo;
};
};
var isOldIE = memoize(function () {
// Test for IE <= 9 as proposed by Browserhacks
// @see http://browserhacks.com/#hack-e71d8692f65334173fee715c222cb805
// Tests for existence of standard globals is to allow style-loader
// to operate correctly into non-standard environments
// @see https://github.com/webpack-contrib/style-loader/issues/177
return window && document && document.all && !window.atob;
});
var getTarget = function (target) {
return document.querySelector(target);
};
var getElement = (function (fn) {
var memo = {};
return function(target) {
// If passing function in options, then use it for resolve "head" element.
// Useful for Shadow Root style i.e
// {
// insertInto: function () { return document.querySelector("#foo").shadowRoot }
// }
if (typeof target === 'function') {
return target();
}
if (typeof memo[target] === "undefined") {
var styleTarget = getTarget.call(this, target);
// Special case to return head of iframe instead of iframe itself
if (window.HTMLIFrameElement && styleTarget instanceof window.HTMLIFrameElement) {
try {
// This will throw an exception if access to iframe is blocked
// due to cross-origin restrictions
styleTarget = styleTarget.contentDocument.head;
} catch(e) {
styleTarget = null;
}
}
memo[target] = styleTarget;
}
return memo[target]
};
})();
var singleton = null;
var singletonCounter = 0;
var stylesInsertedAtTop = [];
var fixUrls = __webpack_require__(/*! ./urls */ "./node_modules/style-loader/lib/urls.js");
module.exports = function(list, options) {
if (typeof DEBUG !== "undefined" && DEBUG) {
if (typeof document !== "object") throw new Error("The style-loader cannot be used in a non-browser environment");
}
options = options || {};
options.attrs = typeof options.attrs === "object" ? options.attrs : {};
// Force single-tag solution on IE6-9, which has a hard limit on the # of <style>
// tags it will allow on a page
if (!options.singleton && typeof options.singleton !== "boolean") options.singleton = isOldIE();
// By default, add <style> tags to the <head> element
if (!options.insertInto) options.insertInto = "head";
// By default, add <style> tags to the bottom of the target
if (!options.insertAt) options.insertAt = "bottom";
var styles = listToStyles(list, options);
addStylesToDom(styles, options);
return function update (newList) {
var mayRemove = [];
for (var i = 0; i < styles.length; i++) {
var item = styles[i];
var domStyle = stylesInDom[item.id];
domStyle.refs--;
mayRemove.push(domStyle);
}
if(newList) {
var newStyles = listToStyles(newList, options);
addStylesToDom(newStyles, options);
}
for (var i = 0; i < mayRemove.length; i++) {
var domStyle = mayRemove[i];
if(domStyle.refs === 0) {
for (var j = 0; j < domStyle.parts.length; j++) domStyle.parts[j]();
delete stylesInDom[domStyle.id];
}
}
};
};
function addStylesToDom (styles, options) {
for (var i = 0; i < styles.length; i++) {
var item = styles[i];
var domStyle = stylesInDom[item.id];
if(domStyle) {
domStyle.refs++;
for(var j = 0; j < domStyle.parts.length; j++) {
domStyle.parts[j](item.parts[j]);
}
for(; j < item.parts.length; j++) {
domStyle.parts.push(addStyle(item.parts[j], options));
}
} else {
var parts = [];
for(var j = 0; j < item.parts.length; j++) {
parts.push(addStyle(item.parts[j], options));
}
stylesInDom[item.id] = {id: item.id, refs: 1, parts: parts};
}
}
}
function listToStyles (list, options) {
var styles = [];
var newStyles = {};
for (var i = 0; i < list.length; i++) {
var item = list[i];
var id = options.base ? item[0] + options.base : item[0];
var css = item[1];
var media = item[2];
var sourceMap = item[3];
var part = {css: css, media: media, sourceMap: sourceMap};
if(!newStyles[id]) styles.push(newStyles[id] = {id: id, parts: [part]});
else newStyles[id].parts.push(part);
}
return styles;
}
function insertStyleElement (options, style) {
var target = getElement(options.insertInto)
if (!target) {
throw new Error("Couldn't find a style target. This probably means that the value for the 'insertInto' parameter is invalid.");
}
var lastStyleElementInsertedAtTop = stylesInsertedAtTop[stylesInsertedAtTop.length - 1];
if (options.insertAt === "top") {
if (!lastStyleElementInsertedAtTop) {
target.insertBefore(style, target.firstChild);
} else if (lastStyleElementInsertedAtTop.nextSibling) {
target.insertBefore(style, lastStyleElementInsertedAtTop.nextSibling);
} else {
target.appendChild(style);
}
stylesInsertedAtTop.push(style);
} else if (options.insertAt === "bottom") {
target.appendChild(style);
} else if (typeof options.insertAt === "object" && options.insertAt.before) {
var nextSibling = getElement(options.insertInto + " " + options.insertAt.before);
target.insertBefore(style, nextSibling);
} else {
throw new Error("[Style Loader]\n\n Invalid value for parameter 'insertAt' ('options.insertAt') found.\n Must be 'top', 'bottom', or Object.\n (https://github.com/webpack-contrib/style-loader#insertat)\n");
}
}
function removeStyleElement (style) {
if (style.parentNode === null) return false;
style.parentNode.removeChild(style);
var idx = stylesInsertedAtTop.indexOf(style);
if(idx >= 0) {
stylesInsertedAtTop.splice(idx, 1);
}
}
function createStyleElement (options) {
var style = document.createElement("style");
if(options.attrs.type === undefined) {
options.attrs.type = "text/css";
}
addAttrs(style, options.attrs);
insertStyleElement(options, style);
return style;
}
function createLinkElement (options) {
var link = document.createElement("link");
if(options.attrs.type === undefined) {
options.attrs.type = "text/css";
}
options.attrs.rel = "stylesheet";
addAttrs(link, options.attrs);
insertStyleElement(options, link);
return link;
}
function addAttrs (el, attrs) {
Object.keys(attrs).forEach(function (key) {
el.setAttribute(key, attrs[key]);
});
}
function | (obj, options) {
var style, update, remove, result;
// If a transform function was defined, run it on the css
if (options.transform && obj.css) {
result = options.transform(obj.css);
if (result) {
// If transform returns a value, use that instead of the original css.
// This allows running runtime transformations on the css.
obj.css = result;
} else {
// If the transform function returns a falsy value, don't add this css.
// This allows conditional loading of css
return function() {
// noop
};
}
}
if (options.singleton) {
var styleIndex = singletonCounter++;
style = singleton || (singleton = createStyleElement(options));
update = applyToSingletonTag.bind(null, style, styleIndex, false);
remove = applyToSingletonTag.bind(null, style, styleIndex, true);
} else if (
obj.sourceMap &&
typeof URL === "function" &&
typeof URL.createObjectURL === "function" &&
typeof URL.revokeObjectURL === "function" &&
typeof Blob === "function" &&
typeof btoa === "function"
) {
style = createLinkElement(options);
update = updateLink.bind(null, style, options);
remove = function () {
removeStyleElement(style);
if(style.href) URL.revokeObjectURL(style.href);
};
} else {
style = createStyleElement(options);
update = applyToTag.bind(null, style);
remove = function () {
removeStyleElement(style);
};
}
update(obj);
return function updateStyle (newObj) {
if (newObj) {
if (
newObj.css === obj.css &&
newObj.media === obj.media &&
newObj.sourceMap === obj.sourceMap
) {
return;
}
update(obj = newObj);
} else {
remove();
}
};
}
var replaceText = (function () {
var textStore = [];
return function (index, replacement) {
textStore[index] = replacement;
return textStore.filter(Boolean).join('\n');
};
})();
function applyToSingletonTag (style, index, remove, obj) {
var css = remove ? "" : obj.css;
if (style.styleSheet) {
style.styleSheet.cssText = replaceText(index, css);
} else {
var cssNode = document.createTextNode(css);
var childNodes = style.childNodes;
if (childNodes[index]) style.removeChild(childNodes[index]);
if (childNodes.length) {
style.insertBefore(cssNode, childNodes[index]);
} else {
style.appendChild(cssNode);
}
}
}
function applyToTag (style, obj) {
var css = obj.css;
var media = obj.media;
if(media) {
style.setAttribute("media", media)
}
if(style.styleSheet) {
style.styleSheet.cssText = css;
} else {
while(style.firstChild) {
style.removeChild(style.firstChild);
}
style.appendChild(document.createTextNode(css));
}
}
function updateLink (link, options, obj) {
var css = obj.css;
var sourceMap = obj.sourceMap;
/*
If convertToAbsoluteUrls isn't defined, but sourcemaps are enabled
and there is no publicPath defined then lets turn convertToAbsoluteUrls
on by default. Otherwise default to the convertToAbsoluteUrls option
directly
*/
var autoFixUrls = options.convertToAbsoluteUrls === undefined && sourceMap;
if (options.convertToAbsoluteUrls || autoFixUrls) {
css = fixUrls(css);
}
if (sourceMap) {
// http://stackoverflow.com/a/26603875
css += "\n/*# sourceMappingURL=data:application/json;base64," + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + " */";
}
var blob = new Blob([css], { type: "text/css" });
var oldSrc = link.href;
link.href = URL.createObjectURL(blob);
if(oldSrc) URL.revokeObjectURL(oldSrc);
}
/***/ }),
/***/ "./node_modules/style-loader/lib/urls.js":
/*!***********************************************!*\
!*** ./node_modules/style-loader/lib/urls.js ***!
\***********************************************/
/*! no static exports found */
/***/ (function(module, exports) {
/**
* When source maps are enabled, `style-loader` uses a link element with a data-uri to
* embed the css on the page. This breaks all relative urls because now they are relative to a
* bundle instead of the current page.
*
* One solution is to only use full urls, but that may be impossible.
*
* Instead, this function "fixes" the relative urls to be absolute according to the current page location.
*
* A rudimentary test suite is located at `test/fixUrls.js` and can be run via the `npm test` command.
*
*/
module.exports = function (css) {
// get current location
var location = typeof window !== "undefined" && window.location;
if (!location) {
throw new Error("fixUrls requires window.location");
}
// blank or null?
if (!css || typeof css !== "string") {
return css;
}
var baseUrl = location.protocol + "//" + location.host;
var currentDir = baseUrl + location.pathname.replace(/\/[^\/]*$/, "/");
// convert each url(...)
/*
This regular expression is just a way to recursively match brackets within
a string.
/url\s*\( = Match on the word "url" with any whitespace after it and then a parens
( = Start a capturing group
(?: = Start a non-capturing group
[^)(] = Match anything that isn't a parentheses
| = OR
\( = Match a start parentheses
(?: = Start another non-capturing groups
[^)(]+ = Match anything that isn't a parentheses
| = OR
\( = Match a start parentheses
[^)(]* = Match anything that isn't a parentheses
\) = Match a end parentheses
) = End Group
*\) = Match anything and then a close parens
) = Close non-capturing group
* = Match anything
) = Close capturing group
\) = Match a close parens
/gi = Get all matches, not the first. Be case insensitive.
*/
var fixedCss = css.replace(/url\s*\(((?:[^)(]|\((?:[^)(]+|\([^)(]*\))*\))*)\)/gi, function(fullMatch, origUrl) {
// strip quotes (if they exist)
var unquotedOrigUrl = origUrl
.trim()
.replace(/^"(.*)"$/, function(o, $1){ return $1; })
.replace(/^'(.*)'$/, function(o, $1){ return $1; });
// already a full url? no change
if (/^(#|data:|http:\/\/|https:\/\/|file:\/\/\/|\s*$)/i.test(unquotedOrigUrl)) {
return fullMatch;
}
// convert the url to a full url
var newUrl;
if (unquotedOrigUrl.indexOf("//") === 0) {
//TODO: should we add protocol?
newUrl = unquotedOrigUrl;
} else if (unquotedOrigUrl.indexOf("/") === 0) {
// path should be relative to the base url
newUrl = baseUrl + unquotedOrigUrl; // already starts with '/'
} else {
// path should be relative to current directory
newUrl = currentDir + unquotedOrigUrl.replace(/^\.\//, ""); // Strip leading './'
}
// send back the fixed url(...)
return "url(" + JSON.stringify(newUrl) + ")";
});
// send back the fixed css
return fixedCss;
};
/***/ }),
/***/ "./src/styles.css":
/*!************************!*\
!*** ./src/styles.css ***!
\************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
var content = __webpack_require__(/*! !../node_modules/raw-loader!../node_modules/postcss-loader/lib??embedded!./styles.css */ "./node_modules/raw-loader/index.js!./node_modules/postcss-loader/lib/index.js??embedded!./src/styles.css");
if(typeof content === 'string') content = [[module.i, content, '']];
var transform;
var insertInto;
var options = {"hmr":true}
options.transform = transform
options.insertInto = undefined;
var update = __webpack_require__(/*! ../node_modules/style-loader/lib/addStyles.js */ "./node_modules/style-loader/lib/addStyles.js")(content, options);
if(content.locals) module.exports = content.locals;
if(false) {}
/***/ }),
/***/ 2:
/*!******************************!*\
!*** multi ./src/styles.css ***!
\******************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(/*! C:\wsad\code\cluhighscores2\clubhighscores\src\styles.css */"./src/styles.css");
/***/ })
},[[2,"runtime"]]]);
//# sourceMappingURL=styles.js.map | addStyle |
Calorie.js | import React, { useState } from "react";
function Calorie({ resultCalorie, setResultCalorie }) {
const [state, setState] = useState({
age: "",
height: "",
weight: "",
select: "",
checkedFemale: false,
checkedMale: false,
});
const [error, setError] = useState(false);
const handleInput = (e) => {
const { name, value } = e.target;
setState((prev) => ({
...prev,
[name]: value,
}));
};
const handleForm = (e) => {
e.preventDefault();
if (
state.age === "" ||
state.height === "" ||
state.weight === "" ||
state.select === "" ||
(state.checkedFemale === false && state.checkedMale === false)
) {
setError(true);
return;
} else {
let result = 0;
if (state.checkedFemale) {
result =
665.1 +
9.563 * state.weight +
1.85 * state.height -
4.676 * state.age;
} else if (state.checkedMale) {
result =
66.47 +
13.75 * state.weight +
5.003 * state.height -
6.755 * state.age;
}
setResultCalorie((result * state.select).toFixed(1));
}
setState({
age: "",
height: "",
weight: "",
select: "choose",
checkedFemale: false,
checkedMale: false,
});
setError(false);
};
const handleClear = () => {
setState({
age: "",
height: "",
weight: "",
checkedFemale: false,
checkedMale: false,
});
setResultCalorie("");
setError(false);
};
let mildLossPerentage = resultCalorie * 0.1;
let normalLossPercentage = resultCalorie * 0.19;
let highLossPercentage = resultCalorie * 0.41;
return (
<div className="calorie">
<h3 className="calorie__title">Calculate calories</h3>
<form onSubmit={handleForm}>
<span>Gender: </span>
<input
type="radio"
value="female"
id="female"
name="gender"
checked={state.checkedFemale}
onChange={() =>
setState((prev) => ({
...prev,
checkedFemale: true,
checkedMale: false,
}))
}
/>
<label htmlFor="female" className="calorie__gender">
Female
</label>
<input
type="radio"
value="male"
id="male"
name="gender"
checked={state.checkedMale}
onChange={() =>
setState((prev) => ({
...prev,
checkedFemale: false,
checkedMale: true,
}))
}
/>
<label htmlFor="male" className="calorie__gender">
Male
</label>
<label className="calorie__label">
<div>Age</div>
<input
type="number"
name="age"
value={state.age}
onChange={handleInput}
/>
<span></span>
</label>
<label className="calorie__label">
<div>Height [cm]</div>
<input
type="number"
name="height"
value={state.height}
onChange={handleInput}
/>
<span></span>
</label>
<label className="calorie__label">
<div>Weight [kg]</div>
<input
type="number"
name="weight"
value={state.weight}
onChange={handleInput}
/>
<span></span>
</label>
<label className="calorie__label__select">
<span>Activity: </span>
<select
className="calorie__select"
onChange={handleInput}
value={state.select}
name="select"
>
<option value="choose">Choose your activity</option>
<option value="1.1">Sedentary: little or no exercise</option>
<option value="1.2">Light: exercise 1-3 times/week</option>
<option value="1.375">Moderate: exercise 4-5 times/week</option>
<option value="1.55"> | </option>
<option value="1.725">
Very Active: intense exercise 6-7 times/week
</option>
<option value="1.9">
Extra Active: very intense exercise daily, or physical job
</option>
</select>
</label>
<div className="calorie__button">
<button type="submit">Calculate</button>
<button type="button" onClick={handleClear}>
Clear
</button>
</div>
</form>
<div className="calorie__result">
<p>
Maintain weight: <span>{resultCalorie * 1} [kcal] </span>
</p>
<p>
Mild weight loss:
<span>{(resultCalorie - mildLossPerentage).toFixed(1)} [kcal]</span>
</p>
<p>
Weight loss:
<span>
{(resultCalorie - normalLossPercentage).toFixed(1)} [kcal]
</span>
</p>
<p>
Extreme weight loss:
<span> {(resultCalorie - highLossPercentage).toFixed(1)} [kcal]</span>
</p>
</div>
{error && (
<p
style={{
color: "rgb(255, 73, 92)",
fontWeight: "600",
textAlign: "center",
paddingTop: "10px",
}}
>
Error: complete the blank
</p>
)}
</div>
);
}
export default Calorie; | Active: daily exercise or intense exercise 3-4 times/week |
lazy_iterator.ts | /**
* @license
* Copyright 2018 Google LLC. 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 * as tf from '@tensorflow/tfjs-core';
import {getTensorsInContainer, isTensorInList} from '@tensorflow/tfjs-core/dist/tensor_util';
import * as seedrandom from 'seedrandom';
import {DataElement, IteratorContainer} from '../types';
import {deepMapAndAwaitAll, DeepMapAsyncResult, DeepMapResult, deepZip, zipToList} from '../util/deep_map';
import {GrowingRingBuffer} from '../util/growing_ring_buffer';
import {RingBuffer} from '../util/ring_buffer';
// Here we implement a simple asynchronous iterator.
// This lets us avoid using either third-party stream libraries or
// recent TypeScript language support requiring polyfills.
/**
* Create a `LazyIterator` from an array of items.
*/
export function iteratorFromItems<T>(items: T[]): LazyIterator<T> {
return new ArrayIterator(items);
}
/**
* Create a `LazyIterator` of incrementing integers.
*/
export function iteratorFromIncrementing(start: number): LazyIterator<number> {
let i = start;
return iteratorFromFunction(() => ({value: i++, done: false}));
}
/**
* Create a `LazyIterator` from a function.
*
* ```js
* let i = -1;
* const func = () =>
* ++i < 5 ? {value: i, done: false} : {value: null, done: true};
* const iter = tf.data.iteratorFromFunction(func);
* await iter.forEach(e => console.log(e));
* ```
*
* @param func A function that produces data on each call.
*/
export function | <T>(
func: () =>
IteratorResult<T>| Promise<IteratorResult<T>>): LazyIterator<T> {
return new FunctionCallIterator(func);
}
/**
* Create a `LazyIterator` by concatenating underlying streams, which are
* themselves provided as a stream.
*
* This can also be thought of as a "stream flatten" operation.
*
* @param baseIterators A stream of streams to be concatenated.
* @param baseErrorHandler An optional function that can intercept `Error`s
* raised during a `next()` call on the base stream. This function can decide
* whether the error should be propagated, whether the error should be
* ignored, or whether the base stream should be terminated.
*/
export function iteratorFromConcatenated<T>(
baseIterators: LazyIterator<LazyIterator<T>>,
baseErrorHandler?: (e: Error) => boolean): LazyIterator<T> {
return new ChainedIterator(baseIterators, baseErrorHandler);
}
/**
* Create a `LazyIterator` by concatenating streams produced by calling a
* stream-generating function a given number of times.
*
* Since a `LazyIterator` is read-once, it cannot be repeated, but this
* function can be used to achieve a similar effect:
*
* LazyIterator.ofConcatenatedFunction(() => new MyIterator(), 6);
*
* @param iteratorFunc: A function that produces a new stream on each call.
* @param count: The number of times to call the function.
* @param baseErrorHandler An optional function that can intercept `Error`s
* raised during a `next()` call on the base stream. This function can decide
* whether the error should be propagated, whether the error should be
* ignored, or whether the base stream should be terminated.
*/
export function iteratorFromConcatenatedFunction<T>(
iteratorFunc: () => IteratorResult<LazyIterator<T>>, count: number,
baseErrorHandler?: (e: Error) => boolean): LazyIterator<T> {
return iteratorFromConcatenated(
iteratorFromFunction(iteratorFunc).take(count), baseErrorHandler);
}
/**
* Create a `LazyIterator` by zipping together an array, dict, or nested
* structure of `LazyIterator`s (and perhaps additional constants).
*
* The underlying streams must provide elements in a consistent order such
* that they correspond.
*
* Typically, the underlying streams should have the same number of
* elements. If they do not, the behavior is determined by the
* `mismatchMode` argument.
*
* The nested structure of the `iterators` argument determines the
* structure of elements in the resulting iterator.
*
* @param iterators: An array or object containing LazyIterators at the
* leaves.
* @param mismatchMode: Determines what to do when one underlying iterator
* is exhausted before the others. `ZipMismatchMode.FAIL` (the default)
* causes an error to be thrown in this case. `ZipMismatchMode.SHORTEST`
* causes the zipped iterator to terminate with the furst underlying
* streams, so elements remaining on the longer streams are ignored.
* `ZipMismatchMode.LONGEST` causes the zipped stream to continue, filling
* in nulls for the exhausted streams, until all streams are exhausted.
*/
export function iteratorFromZipped<O extends DataElement>(
iterators: IteratorContainer,
mismatchMode: ZipMismatchMode = ZipMismatchMode.FAIL): LazyIterator<O> {
return new ZipIterator<O>(iterators, mismatchMode);
}
/**
* An asynchronous iterator, providing lazy access to a potentially
* unbounded stream of elements.
*
* Iterator can be obtained from a dataset:
* `const iter = await dataset.iterator();`
*/
export abstract class LazyIterator<T> {
// This class implements AsyncIterator<T>, but we have not yet set the
// TypeScript --downlevelIteration flag to enable that.
abstract summary(): string;
/**
* Returns a `Promise` for the next element in the stream.
*
* When an item can be provided successfully, the return value is
* `{value:T, done:false}`.
*
* Calling next() on a closed stream returns `{value:null, done:true}`.
*/
abstract async next(): Promise<IteratorResult<T>>;
/**
* Collect all remaining elements of a bounded stream into an array.
* Obviously this will succeed only for small streams that fit in memory.
* Useful for testing.
*
* @param maxItems the maximum number of items to return. If the stream
* terminates, fewer items will be returned. (default 1000)
* @param prefetch the size of the prefetch buffer to use when collecting
* items. Some amount of prefetch is important to test parallel streams,
* i.e. with multiple Promises outstanding. Without prefetch, this method
* makes purely serial next() calls.
*
* @returns A Promise for an array of stream elements, which will resolve
* when the stream is exhausted.
*/
async collect(maxItems = 1000, prefetch = 100): Promise<T[]> {
const stream = prefetch > 0 ? this.prefetch(prefetch) : this;
const result: T[] = [];
let count = 0;
let x = await stream.next();
while (!x.done) {
result.push(x.value);
count++;
if (count >= maxItems) {
return result;
}
x = await stream.next();
}
return result;
}
/**
* Draw items from the stream until it is exhausted.
*
* This can be useful when the stream has side effects but no output. In
* that case, calling this function guarantees that the stream will be
* fully processed.
*/
async resolveFully(): Promise<void> {
let x = await this.next();
while (!x.done) {
x = await this.next();
}
}
/**
* Draw items from the stream until it is exhausted, or a predicate fails.
*
* This can be useful when the stream has side effects but no output. In
* that case, calling this function guarantees that the stream will be
* fully processed.
*/
async resolveWhile(predicate: (r: T) => boolean): Promise<void> {
let x = await this.next();
let shouldContinue = predicate(x.value);
while ((!x.done) && shouldContinue) {
x = await this.next();
shouldContinue = predicate(x.value);
}
}
/**
* Handles errors thrown on this stream using a provided handler function.
*
* @param handler A function that handles any `Error` thrown during a `next()`
* call and returns true if the stream should continue (dropping the failed
* call) or false if the stream should quietly terminate. If the handler
* itself throws (or rethrows) an `Error`, that will be propagated.
*
* @returns A `LazyIterator` of elements passed through from upstream,
* possibly filtering or terminating on upstream `next()` calls that
* throw an `Error`.
*/
handleErrors(handler: (error: Error) => boolean): LazyIterator<T> {
return new ErrorHandlingLazyIterator(this, handler);
}
// TODO(soergel): Implement reduce() etc.
/**
* Filters this stream according to `predicate`.
*
* @param predicate A function mapping a stream element to a boolean or a
* `Promise` for one.
*
* @returns A `LazyIterator` of elements for which the predicate was true.
*/
filter(predicate: (value: T) => boolean): LazyIterator<T> {
return new FilterIterator(this, predicate);
}
/**
* Maps this stream through a 1-to-1 transform.
*
* @param transform A function mapping a stream element to a transformed
* element.
*
* @returns A `LazyIterator` of transformed elements.
*/
map<O>(transform: (value: T) => O): LazyIterator<O> {
return new MapIterator(this, transform);
}
/**
* Maps this stream through an async 1-to-1 transform.
*
* @param transform A function mapping a stream element to a `Promise` for a
* transformed stream element.
*
* @returns A `LazyIterator` of transformed elements.
*/
mapAsync<O>(transform: (value: T) => Promise<O>): LazyIterator<O> {
return new AsyncMapIterator(this, transform);
}
/**
* Maps this stream through a 1-to-1 transform, forcing serial execution.
*
* @param transform A function mapping a stream element to a transformed
* element.
*
* @returns A `LazyIterator` of transformed elements.
*/
serialMapAsync<O>(transform: (value: T) => Promise<O>): LazyIterator<O> {
return new AsyncMapIterator(this, transform).serial();
}
/**
* Maps this stream through a 1-to-many transform.
*
* @param transform A function mapping a stream element to an array of
* transformed elements.
*
* @returns A `DataStream` of transformed elements.
*/
flatmap<O>(transform: (value: T) => O[]): LazyIterator<O> {
return new FlatmapIterator(this, transform);
}
/**
* Apply a function to every element of the stream.
*
* @param f A function to apply to each stream element.
*/
async forEach(f: (value: T) => void): Promise<void> {
return this.map(f).resolveFully();
}
/**
* Apply a function to every element of the stream, forcing serial execution.
*
* @param f A function to apply to each stream element. Should return 'true'
* to indicate that the stream should continue, or 'false' to cause it to
* terminate.
*/
async serialForEach(f: (value: T) => Promise<boolean>): Promise<void> {
return this.serialMapAsync(f).resolveWhile(x => (x === true));
}
/**
* Groups elements into batches, represented as arrays of elements.
*
* We can think of the elements of this iterator as 'rows' (even if they are
* nested structures). By the same token, consecutive values for a given
* key within the elements form a 'column'. This matches the usual sense of
* 'row' and 'column' when processing tabular data (e.g., parsing a CSV).
*
* Thus, "Row-major" means that the resulting batch is simply a collection of
* rows: `[row1, row2, row3, ...]`. This is contrast to the column-major
* form, which is needed for vectorized computation.
*
* @param batchSize The number of elements desired per batch.
* @param smallLastBatch Whether to emit the final batch when it has fewer
* than batchSize elements. Default true.
* @returns A `LazyIterator` of batches of elements, represented as arrays
* of the original element type.
*/
rowMajorBatch(batchSize: number, smallLastBatch = true): LazyIterator<T[]> {
return new RowMajorBatchIterator(this, batchSize, smallLastBatch);
}
/**
* Groups elements into batches, represented in column-major form.
*
* We can think of the elements of this iterator as 'rows' (even if they are
* nested structures). By the same token, consecutive values for a given
* key within the elements form a 'column'. This matches the usual sense of
* 'row' and 'column' when processing tabular data (e.g., parsing a CSV).
*
* Thus, "column-major" means that the resulting batch is a (potentially
* nested) structure representing the columns. Each column entry, then,
* contains a collection of the values found in that column for a range of
* input elements. This representation allows for vectorized computation, in
* contrast to the row-major form.
*
* The inputs should all have the same nested structure (i.e., of arrays and
* dicts). The result is a single object with the same nested structure,
* where the leaves are arrays collecting the values of the inputs at that
* location (or, optionally, the result of a custom function applied to those
* arrays).
*
* @param batchSize The number of elements desired per batch.
* @param smallLastBatch Whether to emit the final batch when it has fewer
* than batchSize elements. Default true.
* @param zipFn: (optional) A function that expects an array of elements at a
* single node of the object tree, and returns a `DeepMapResult`. The
* `DeepMapResult` either provides a result value for that node (i.e.,
* representing the subtree), or indicates that the node should be processed
* recursively. The default zipFn recurses as far as possible and places
* arrays at the leaves.
* @returns A `LazyIterator` of batches of elements, represented as an object
* with collections at the leaves.
*/
columnMajorBatch(
batchSize: number, smallLastBatch = true,
// tslint:disable-next-line:no-any
zipFn: (xs: any[]) => DeepMapResult = zipToList):
LazyIterator<DataElement> {
// First collect the desired number of input elements as a row-major batch.
const rowBatches = this.rowMajorBatch(batchSize, smallLastBatch);
// Now 'rotate' or 'pivot' the data, collecting all values from each column
// in the batch (i.e., for each key within the elements) into an array.
return rowBatches.map(x => deepZip(x, zipFn));
}
/**
* Concatenate this `LazyIterator` with another.
*
* @param iterator A `LazyIterator` to be concatenated onto this one.
* @param baseErrorHandler An optional function that can intercept `Error`s
* raised during a `next()` call on the base stream. This function can
* decide whether the error should be propagated, whether the error should
* be ignored, or whether the base stream should be terminated.
* @returns A `LazyIterator`.
*/
concatenate(
iterator: LazyIterator<T>,
baseErrorHandler?: (e: Error) => boolean): LazyIterator<T> {
return new ChainedIterator(
iteratorFromItems([this, iterator]), baseErrorHandler);
}
/**
* Limits this stream to return at most `count` items.
*
* @param count The maximum number of items to provide from the stream. If
* a negative or undefined value is given, the entire stream is returned
* unaltered.
*/
take(count: number): LazyIterator<T> {
if (count < 0 || count == null) {
return this;
}
return new TakeIterator(this, count);
}
/**
* Skips the first `count` items in this stream.
*
* @param count The number of items to skip. If a negative or undefined
* value is given, the entire stream is returned unaltered.
*/
skip(count: number): LazyIterator<T> {
if (count < 0 || count == null) {
return this;
}
return new SkipIterator(this, count);
}
/**
* Prefetch the first `bufferSize` items in this stream.
*
* Note this prefetches Promises, but makes no guarantees about when those
* Promises resolve.
*
* @param bufferSize: An integer specifying the number of elements to be
* prefetched.
*/
prefetch(bufferSize: number): LazyIterator<T> {
return new PrefetchIterator(this, bufferSize);
}
// TODO(soergel): deep sharded shuffle, where supported
/**
* Randomly shuffles the elements of this stream.
*
* @param bufferSize: An integer specifying the number of elements from
* this stream from which the new stream will sample.
* @param seed: (Optional.) An integer specifying the random seed that
* will be used to create the distribution.
*/
shuffle(windowSize: number, seed?: string): LazyIterator<T> {
return new ShuffleIterator(this, windowSize, seed);
}
/**
* Force an iterator to execute serially: each next() call will await the
* prior one, so that they cannot execute concurrently.
*/
serial(): LazyIterator<T> {
return new SerialIterator(this);
}
}
// ============================================================================
// The following private classes serve to implement the chainable methods
// on LazyIterator. Unfortunately they can't be placed in separate files,
// due to resulting trouble with circular imports.
// ============================================================================
// Iterators that just extend LazyIterator directly
// ============================================================================
class ArrayIterator<T> extends LazyIterator<T> {
private trav = 0;
constructor(protected items: T[]) {
super();
}
summary() {
return `Array of ${this.items.length} items`;
}
async next(): Promise<IteratorResult<T>> {
if (this.trav >= this.items.length) {
return {value: null, done: true};
}
const item = this.items[this.trav];
let result;
if (item instanceof tf.Tensor) {
result = tf.clone(item);
} else {
result = item;
}
this.trav++;
return {value: result, done: false};
}
}
class FunctionCallIterator<T> extends LazyIterator<T> {
constructor(
protected nextFn: () => IteratorResult<T>| Promise<IteratorResult<T>>) {
super();
}
summary() {
return `Function call`;
}
async next(): Promise<IteratorResult<T>> {
try {
return this.nextFn();
} catch (e) {
// Modify the error message but leave the stack trace intact
e.message =
`Error thrown while iterating through a dataset: ${e.message}`;
throw e;
}
}
}
class SerialIterator<T> extends LazyIterator<T> {
// Strict Promise execution order:
// a next() call may not even begin until the previous one completes.
private lastRead: Promise<IteratorResult<T>>;
constructor(protected upstream: LazyIterator<T>) {
super();
this.lastRead = Promise.resolve({value: null, done: false});
}
summary() {
return `${this.upstream.summary()} -> Serial`;
}
async next(): Promise<IteratorResult<T>> {
// This sets this.lastRead to a new Promise right away, as opposed to
// saying `await this.lastRead; this.lastRead = this.serialNext();` which
// would not work because this.nextRead would be updated only after the
// promise resolves.
this.lastRead = this.lastRead.then(() => this.serialNext());
return this.lastRead;
}
private async serialNext(): Promise<IteratorResult<T>> {
return this.upstream.next();
}
}
class SkipIterator<T> extends LazyIterator<T> {
// Strict Promise execution order:
// a next() call may not even begin until the previous one completes.
private lastRead: Promise<IteratorResult<T>>;
// Local state that should not be clobbered by out-of-order execution.
count = 0;
constructor(protected upstream: LazyIterator<T>, protected maxCount: number) {
super();
this.lastRead = Promise.resolve({value: null, done: false});
}
summary() {
return `${this.upstream.summary()} -> Skip`;
}
async next(): Promise<IteratorResult<T>> {
// This sets this.lastRead to a new Promise right away, as opposed to
// saying `await this.lastRead; this.lastRead = this.serialNext();` which
// would not work because this.nextRead would be updated only after the
// promise resolves.
this.lastRead = this.lastRead.then(() => this.serialNext());
return this.lastRead;
}
private async serialNext(): Promise<IteratorResult<T>> {
// TODO(soergel): consider tradeoffs of reading in parallel, eg.
// collecting next() promises in an Array and then waiting for
// Promise.all() of those. Benefit: pseudo-parallel execution. Drawback:
// maybe delayed GC.
while (this.count++ < this.maxCount) {
const skipped = await this.upstream.next();
// short-circuit if upstream is already empty
if (skipped.done) {
return skipped;
}
tf.dispose(skipped.value as {});
}
return this.upstream.next();
}
}
class TakeIterator<T> extends LazyIterator<T> {
count = 0;
constructor(protected upstream: LazyIterator<T>, protected maxCount: number) {
super();
}
summary() {
return `${this.upstream.summary()} -> Take`;
}
async next(): Promise<IteratorResult<T>> {
if (this.count++ >= this.maxCount) {
return {value: null, done: true};
}
return this.upstream.next();
}
}
// Note this batch just groups items into row-wise element arrays.
// Rotating these to a column-wise representation happens only at the dataset
// level.
class RowMajorBatchIterator<T> extends LazyIterator<T[]> {
// Strict Promise execution order:
// a next() call may not even begin until the previous one completes.
private lastRead: Promise<IteratorResult<T[]>>;
constructor(
protected upstream: LazyIterator<T>, protected batchSize: number,
protected enableSmallLastBatch = true) {
super();
this.lastRead = Promise.resolve({value: null, done: false});
}
summary() {
return `${this.upstream.summary()} -> RowMajorBatch`;
}
async next(): Promise<IteratorResult<T[]>> {
// This sets this.lastRead to a new Promise right away, as opposed to
// saying `await this.lastRead; this.lastRead = this.serialNext();` which
// would not work because this.nextRead would be updated only after the
// promise resolves.
this.lastRead = this.lastRead.then(() => this.serialNext());
return this.lastRead;
}
private async serialNext(): Promise<IteratorResult<T[]>> {
const batch: T[] = [];
while (batch.length < this.batchSize) {
const item = await this.upstream.next();
if (item.done) {
if (this.enableSmallLastBatch && batch.length > 0) {
return {value: batch, done: false};
}
return {value: null, done: true};
}
batch.push(item.value);
}
return {value: batch, done: false};
}
}
class FilterIterator<T> extends LazyIterator<T> {
// Strict Promise execution order:
// a next() call may not even begin until the previous one completes.
private lastRead: Promise<IteratorResult<T>>;
constructor(
protected upstream: LazyIterator<T>,
protected predicate: (value: T) => boolean) {
super();
this.lastRead = Promise.resolve({value: null, done: false});
}
summary() {
return `${this.upstream.summary()} -> Filter`;
}
async next(): Promise<IteratorResult<T>> {
// This sets this.lastRead to a new Promise right away, as opposed to
// saying `await this.lastRead; this.lastRead = this.serialNext();` which
// would not work because this.nextRead would be updated only after the
// promise resolves.
this.lastRead = this.lastRead.then(() => this.serialNext());
return this.lastRead;
}
private async serialNext(): Promise<IteratorResult<T>> {
while (true) {
const item = await this.upstream.next();
if (item.done || this.predicate(item.value)) {
return item;
}
tf.dispose(item.value as {});
}
}
}
class MapIterator<I, O> extends LazyIterator<O> {
constructor(
protected upstream: LazyIterator<I>,
protected transform: (value: I) => O) {
super();
}
summary() {
return `${this.upstream.summary()} -> Map`;
}
async next(): Promise<IteratorResult<O>> {
const item = await this.upstream.next();
if (item.done) {
return {value: null, done: true};
}
const inputTensors = getTensorsInContainer(item.value as {});
// Careful: the transform may mutate the item in place.
// That's why we have to remember the input Tensors above, and then
// below dispose only those that were not passed through to the output.
// Note too that the transform function is responsible for tidying
// any intermediate Tensors. Here we are concerned only about the
// inputs.
const mapped = this.transform(item.value);
const outputTensors = getTensorsInContainer(mapped as {});
// TODO(soergel) faster intersection
// TODO(soergel) move to tf.disposeExcept(in, out)?
for (const t of inputTensors) {
if (!isTensorInList(t, outputTensors)) {
t.dispose();
}
}
return {value: mapped, done: false};
}
}
class ErrorHandlingLazyIterator<T> extends LazyIterator<T> {
count = 0;
constructor(
protected upstream: LazyIterator<T>,
protected handler: (error: Error) => boolean) {
super();
this.lastRead = Promise.resolve({value: null, done: false});
}
summary() {
return `${this.upstream.summary()} -> handleErrors`;
}
// Strict Promise execution order:
// a next() call may not even begin until the previous one completes.
private lastRead: Promise<IteratorResult<T>>;
async next(): Promise<IteratorResult<T>> {
// This sets this.lastRead to a new Promise right away, as opposed to
// saying `await this.lastRead; this.lastRead = this.serialNext();` which
// would not work because this.nextRead would be updated only after the
// promise resolves.
this.lastRead = this.lastRead.then(() => this.serialNext());
return this.lastRead;
}
async serialNext(): Promise<IteratorResult<T>> {
while (true) {
try {
return await this.upstream.next();
} catch (e) {
if (!this.handler(e)) {
return {value: null, done: true};
}
// If the handler returns true, loop and fetch the next upstream item.
// If the upstream iterator throws an endless stream of errors, and if
// the handler says to ignore them, then we loop forever here. That is
// the correct behavior-- it's up to the handler to decide when to stop.
}
}
}
}
class AsyncMapIterator<I, O> extends LazyIterator<O> {
constructor(
protected upstream: LazyIterator<I>,
protected transform: (value: I) => Promise<O>) {
super();
}
summary() {
return `${this.upstream.summary()} -> AsyncMap`;
}
async next(): Promise<IteratorResult<O>> {
const item = await this.upstream.next();
if (item.done) {
return {value: null, done: true};
}
const inputTensors = getTensorsInContainer(item.value as {});
// Careful: the transform may mutate the item in place.
// That's why we have to remember the input Tensors above, and then
// below dispose only those that were not passed through to the output.
// Note too that the transform function is responsible for tidying
// any intermediate Tensors. Here we are concerned only about the
// inputs.
const mapped = await this.transform(item.value);
const outputTensors = getTensorsInContainer(mapped as {});
// TODO(soergel) faster intersection
// TODO(soergel) move to tf.disposeExcept(in, out)?
for (const t of inputTensors) {
if (!isTensorInList(t, outputTensors)) {
t.dispose();
}
}
return {value: mapped, done: false};
}
}
// Iterators that maintain a queue of pending items
// ============================================================================
/**
* A base class for transforming streams that operate by maintaining an
* output queue of elements that are ready to return via next(). This is
* commonly required when the transformation is 1-to-many: A call to next()
* may trigger a call to the underlying stream, which will produce many
* mapped elements of this stream-- of which we need to return only one, so
* we have to queue the rest.
*/
export abstract class OneToManyIterator<T> extends LazyIterator<T> {
// Strict Promise execution order:
// a next() call may not even begin until the previous one completes.
private lastRead: Promise<IteratorResult<T>>;
// Local state that should not be clobbered by out-of-order execution.
protected outputQueue: RingBuffer<T>;
constructor() {
super();
this.outputQueue = new GrowingRingBuffer<T>();
this.lastRead = Promise.resolve({value: null, done: false});
}
async next(): Promise<IteratorResult<T>> {
// This sets this.lastRead to a new Promise right away, as opposed to
// saying `await this.lastRead; this.lastRead = this.serialNext();` which
// would not work because this.nextRead would be updated only after the
// promise resolves.
this.lastRead = this.lastRead.then(() => this.serialNext());
return this.lastRead;
}
/**
* Read one or more chunks from upstream and process them, possibly
* reading or writing a carryover, and adding processed items to the
* output queue. Note it's possible that no items are added to the queue
* on a given pump() call, even if the upstream stream is not closed
* (e.g., because items are filtered).
*
* @return `true` if any action was taken, i.e. fetching items from the
* upstream source OR adding items to the output queue. `false` if the
* upstream source is exhausted AND nothing was added to the queue
* (i.e., any remaining carryover).
*/
protected abstract async pump(): Promise<boolean>;
async serialNext(): Promise<IteratorResult<T>> {
// Fetch so that the queue contains at least one item if possible.
// If the upstream source is exhausted, AND there are no items left in
// the output queue, then this stream is also exhausted.
while (this.outputQueue.length() === 0) {
// TODO(soergel): consider parallel reads.
if (!await this.pump()) {
return {value: null, done: true};
}
}
return {value: this.outputQueue.shift(), done: false};
}
}
class FlatmapIterator<I, O> extends OneToManyIterator<O> {
constructor(
protected upstream: LazyIterator<I>,
protected transform: (value: I) => O[]) {
super();
}
summary() {
return `${this.upstream.summary()} -> Flatmap`;
}
async pump(): Promise<boolean> {
const item = await this.upstream.next();
if (item.done) {
return false;
}
const inputTensors = getTensorsInContainer(item.value as {});
// Careful: the transform may mutate the item in place.
// that's why we have to remember the input Tensors above, and then
// below dispose only those that were not passed through to the output.
// Note too that the transform function is responsible for tidying any
// intermediate Tensors. Here we are concerned only about the inputs.
const mappedArray = this.transform(item.value);
const outputTensors = getTensorsInContainer(mappedArray as {});
this.outputQueue.pushAll(mappedArray);
// TODO(soergel) faster intersection, and deduplicate outputTensors
// TODO(soergel) move to tf.disposeExcept(in, out)?
for (const t of inputTensors) {
if (!isTensorInList(t, outputTensors)) {
t.dispose();
}
}
return true;
}
}
/**
* Provides a `LazyIterator` that concatenates a stream of underlying
* streams.
*
* Doing this in a concurrency-safe way requires some trickery. In
* particular, we want this stream to return the elements from the
* underlying streams in the correct order according to when next() was
* called, even if the resulting Promises resolve in a different order.
*/
export class ChainedIterator<T> extends LazyIterator<T> {
// Strict Promise execution order:
// a next() call may not even begin until the previous one completes.
private lastRead: Promise<IteratorResult<T>> = null;
// Local state that should not be clobbered by out-of-order execution.
private iterator: LazyIterator<T> = null;
private moreIterators: LazyIterator<LazyIterator<T>>;
constructor(
iterators: LazyIterator<LazyIterator<T>>,
private readonly baseErrorHandler?: (e: Error) => boolean) {
super();
this.moreIterators = iterators;
}
summary() {
const upstreamSummaries = 'TODO: fill in upstream of chained summaries';
return `${upstreamSummaries} -> Chained`;
}
async next(): Promise<IteratorResult<T>> {
this.lastRead = this.readFromChain(this.lastRead);
return this.lastRead;
}
private async readFromChain(lastRead: Promise<IteratorResult<T>>):
Promise<IteratorResult<T>> {
// Must await on the previous read since the previous read may have advanced
// the stream of streams, from which we need to read.
// This is unfortunate since we can't parallelize reads. Which means
// prefetching of chained streams is a no-op.
// One solution is to prefetch immediately upstream of this.
await lastRead;
if (this.iterator == null) {
const iteratorResult = await this.moreIterators.next();
if (iteratorResult.done) {
// No more streams to stream from.
return {value: null, done: true};
}
this.iterator = iteratorResult.value;
if (this.baseErrorHandler != null) {
this.iterator = this.iterator.handleErrors(this.baseErrorHandler);
}
}
const itemResult = await this.iterator.next();
if (itemResult.done) {
this.iterator = null;
return this.readFromChain(lastRead);
}
return itemResult;
}
}
export enum ZipMismatchMode {
FAIL, // require zipped streams to have the same length
SHORTEST, // terminate zip when the first stream is exhausted
LONGEST // use nulls for exhausted streams; use up the longest stream.
}
/**
* Provides a `LazyIterator` that zips together an array, dict, or nested
* structure of `LazyIterator`s (and perhaps additional constants).
*
* The underlying streams must provide elements in a consistent order such
* that they correspond.
*
* Typically, the underlying streams should have the same number of
* elements. If they do not, the behavior is determined by the
* `mismatchMode` argument.
*
* The nested structure of the `iterators` argument determines the
* structure of elements in the resulting iterator.
*
* Doing this in a concurrency-safe way requires some trickery. In
* particular, we want this stream to return the elements from the
* underlying streams in the correct order according to when next() was
* called, even if the resulting Promises resolve in a different order.
*
* @param iterators: An array or object containing LazyIterators at the
* leaves.
* @param mismatchMode: Determines what to do when one underlying iterator
* is exhausted before the others. `ZipMismatchMode.FAIL` (the default)
* causes an error to be thrown in this case. `ZipMismatchMode.SHORTEST`
* causes the zipped iterator to terminate with the furst underlying
* streams, so elements remaining on the longer streams are ignored.
* `ZipMismatchMode.LONGEST` causes the zipped stream to continue, filling
* in nulls for the exhausted streams, until all streams are exhausted.
*/
class ZipIterator<O extends DataElement> extends LazyIterator<O> {
private count = 0;
private currentPromise: Promise<IteratorResult<O>> = null;
constructor(
protected readonly iterators: IteratorContainer,
protected readonly mismatchMode: ZipMismatchMode = ZipMismatchMode.FAIL) {
super();
}
summary() {
const upstreamSummaries = 'TODO: fill in upstream of zip summaries';
return `{${upstreamSummaries}} -> Zip`;
}
private async nextState(afterState: Promise<IteratorResult<O>>):
Promise<IteratorResult<O>> {
// This chaining ensures that the underlying next() are not even called
// before the previous ones have resolved.
await afterState;
// Collect underlying iterator "done" signals as a side effect in
// getNext()
let numIterators = 0;
let iteratorsDone = 0;
function getNext(container: IteratorContainer): DeepMapAsyncResult {
if (container instanceof LazyIterator) {
const result = container.next();
return {
value: result.then(x => {
numIterators++;
if (x.done) {
iteratorsDone++;
}
return x.value;
}),
recurse: false
};
} else {
return {value: null, recurse: true};
}
}
const mapped: O = await deepMapAndAwaitAll(this.iterators, getNext);
if (numIterators === iteratorsDone) {
// The streams have all ended.
return {value: null, done: true};
}
if (iteratorsDone > 0) {
switch (this.mismatchMode) {
case ZipMismatchMode.FAIL:
throw new Error(
'Zipped streams should have the same length. ' +
`Mismatched at element ${this.count}.`);
case ZipMismatchMode.SHORTEST:
return {value: null, done: true};
case ZipMismatchMode.LONGEST:
default:
// Continue. The exhausted streams already produced value: null.
}
}
this.count++;
return {value: mapped, done: false};
}
async next(): Promise<IteratorResult<O>> {
this.currentPromise = this.nextState(this.currentPromise);
return (await this.currentPromise);
}
}
// Iterators that maintain a ring buffer of pending promises
// ============================================================================
/**
* A stream that prefetches a given number of items from an upstream source,
* returning them in FIFO order.
*
* Note this prefetches Promises, but makes no guarantees about when those
* Promises resolve.
*/
export class PrefetchIterator<T> extends LazyIterator<T> {
protected buffer: RingBuffer<Promise<IteratorResult<T>>>;
constructor(
protected upstream: LazyIterator<T>, protected bufferSize: number) {
super();
this.buffer = new RingBuffer<Promise<IteratorResult<T>>>(bufferSize);
}
summary() {
return `${this.upstream.summary()} -> Prefetch`;
}
/**
* Refill the prefetch buffer. Returns only after the buffer is full, or
* the upstream source is exhausted.
*/
protected refill() {
while (!this.buffer.isFull()) {
const v = this.upstream.next();
this.buffer.push(v);
}
}
next(): Promise<IteratorResult<T>> {
this.refill();
// This shift will never throw an error because the buffer is always
// full after a refill. If the stream is exhausted, the buffer will be
// full of Promises that will resolve to the end-of-stream signal.
return this.buffer.shift();
}
}
/**
* A stream that performs a sliding-window random shuffle on an upstream
* source. This is like a `PrefetchIterator` except that the items are
* returned in randomized order. Mixing naturally improves as the buffer
* size increases.
*/
export class ShuffleIterator<T> extends PrefetchIterator<T> {
private readonly random: seedrandom.prng;
// Strict Promise execution order:
// a next() call may not even begin until the previous one completes.
private lastRead: Promise<IteratorResult<T>>;
// Local state that should not be clobbered by out-of-order execution.
private upstreamExhausted = false;
constructor(
protected upstream: LazyIterator<T>, protected windowSize: number,
seed?: string) {
super(upstream, windowSize);
this.random = seedrandom.alea(seed || tf.util.now().toString());
this.lastRead = Promise.resolve({value: null, done: false});
}
async next(): Promise<IteratorResult<T>> {
// This sets this.lastRead to a new Promise right away, as opposed to
// saying `await this.lastRead; this.lastRead = this.serialNext();` which
// would not work because this.nextRead would be updated only after the
// promise resolves.
this.lastRead = this.lastRead.then(() => this.serialNext());
return this.lastRead;
}
private randomInt(max: number) {
return Math.floor(this.random() * max);
}
protected chooseIndex(): number {
return this.randomInt(this.buffer.length());
}
async serialNext(): Promise<IteratorResult<T>> {
// TODO(soergel): consider performance
if (!this.upstreamExhausted) {
this.refill();
}
while (!this.buffer.isEmpty()) {
const chosenIndex = this.chooseIndex();
const result = await this.buffer.shuffleExcise(chosenIndex);
if (result.done) {
this.upstreamExhausted = true;
} else {
this.refill();
return result;
}
}
return {value: null, done: true};
}
}
| iteratorFromFunction |
gen_spirv_dialect.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 The MLIR 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.
# Script for updating SPIR-V dialect by scraping information from SPIR-V
# HTML and JSON specs from the Internet.
#
# For example, to define the enum attribute for SPIR-V memory model:
#
# ./gen_spirv_dialect.py --base_td_path /path/to/SPIRVBase.td \
# --new-enum MemoryModel
#
# The 'operand_kinds' dict of spirv.core.grammar.json contains all supported
# SPIR-V enum classes.
import re
import requests
import textwrap
SPIRV_HTML_SPEC_URL = 'https://www.khronos.org/registry/spir-v/specs/unified1/SPIRV.html'
SPIRV_JSON_SPEC_URL = 'https://raw.githubusercontent.com/KhronosGroup/SPIRV-Headers/master/include/spirv/unified1/spirv.core.grammar.json'
AUTOGEN_OP_DEF_SEPARATOR = '\n// -----\n\n'
AUTOGEN_ENUM_SECTION_MARKER = 'enum section. Generated from SPIR-V spec; DO NOT MODIFY!'
AUTOGEN_OPCODE_SECTION_MARKER = (
'opcode section. Generated from SPIR-V spec; DO NOT MODIFY!')
def get_spirv_doc_from_html_spec():
"""Extracts instruction documentation from SPIR-V HTML spec.
Returns:
- A dict mapping from instruction opcode to documentation.
"""
response = requests.get(SPIRV_HTML_SPEC_URL)
spec = response.content
from bs4 import BeautifulSoup
spirv = BeautifulSoup(spec, 'html.parser')
section_anchor = spirv.find('h3', {'id': '_a_id_instructions_a_instructions'})
doc = {}
for section in section_anchor.parent.find_all('div', {'class': 'sect3'}):
for table in section.find_all('table'):
inst_html = table.tbody.tr.td.p
opname = inst_html.a['id']
# Ignore the first line, which is just the opname.
doc[opname] = inst_html.text.split('\n', 1)[1].strip()
return doc
def get_spirv_grammar_from_json_spec():
"""Extracts operand kind and instruction grammar from SPIR-V JSON spec.
Returns:
- A list containing all operand kinds' grammar
- A list containing all instructions' grammar
"""
response = requests.get(SPIRV_JSON_SPEC_URL)
spec = response.content
import json
spirv = json.loads(spec)
return spirv['operand_kinds'], spirv['instructions']
def split_list_into_sublists(items, offset):
"""Split the list of items into multiple sublists.
This is to make sure the string composed from each sublist won't exceed
80 characters.
Arguments:
- items: a list of strings
- offset: the offset in calculating each sublist's length
"""
chuncks = []
chunk = []
chunk_len = 0
for item in items:
chunk_len += len(item) + 2
if chunk_len > 80:
chuncks.append(chunk)
chunk = []
chunk_len = len(item) + 2
chunk.append(item)
if len(chunk) != 0:
chuncks.append(chunk)
return chuncks
def uniquify(lst, equality_fn):
"""Returns a list after pruning duplicate elements.
Arguments:
- lst: List whose elements are to be uniqued.
- equality_fn: Function used to compare equality between elements of the
list.
Returns:
- A list with all duplicated removed. The order of elements is same as the
original list, with only the first occurence of duplicates retained.
"""
keys = set()
unique_lst = []
for elem in lst:
key = equality_fn(elem)
if equality_fn(key) not in keys:
unique_lst.append(elem)
keys.add(key)
return unique_lst
def gen_operand_kind_enum_attr(operand_kind):
"""Generates the TableGen I32EnumAttr definition for the given operand kind.
Returns:
- The operand kind's name
- A string containing the TableGen I32EnumAttr definition
"""
if 'enumerants' not in operand_kind:
return '', ''
kind_name = operand_kind['kind']
kind_acronym = ''.join([c for c in kind_name if c >= 'A' and c <= 'Z'])
kind_cases = [(case['enumerant'], case['value'])
for case in operand_kind['enumerants']]
kind_cases = uniquify(kind_cases, lambda x: x[1])
max_len = max([len(symbol) for (symbol, _) in kind_cases])
# Generate the definition for each enum case
fmt_str = 'def SPV_{acronym}_{symbol} {colon:>{offset}} '\
'I32EnumAttrCase<"{symbol}", {value}>;'
case_defs = [
fmt_str.format(
acronym=kind_acronym,
symbol=case[0],
value=case[1],
colon=':',
offset=(max_len + 1 - len(case[0]))) for case in kind_cases
]
case_defs = '\n'.join(case_defs)
# Generate the list of enum case names
fmt_str = 'SPV_{acronym}_{symbol}';
case_names = [fmt_str.format(acronym=kind_acronym,symbol=case[0])
for case in kind_cases]
# Split them into sublists and concatenate into multiple lines
case_names = split_list_into_sublists(case_names, 6)
case_names = ['{:6}'.format('') + ', '.join(sublist)
for sublist in case_names]
case_names = ',\n'.join(case_names)
# Generate the enum attribute definition
enum_attr = 'def SPV_{name}Attr :\n '\
'I32EnumAttr<"{name}", "valid SPIR-V {name}", [\n{cases}\n ]> {{\n'\
' let returnType = "::mlir::spirv::{name}";\n'\
' let convertFromStorage = '\
'"static_cast<::mlir::spirv::{name}>($_self.getInt())";\n'\
' let cppNamespace = "::mlir::spirv";\n}}'.format(
name=kind_name, cases=case_names)
return kind_name, case_defs + '\n\n' + enum_attr
def gen_opcode(instructions):
""" Generates the TableGen definition to map opname to opcode
Returns:
- A string containing the TableGen SPV_OpCode definition
"""
max_len = max([len(inst['opname']) for inst in instructions])
def_fmt_str = 'def SPV_OC_{name} {colon:>{offset}} '\
'I32EnumAttrCase<"{name}", {value}>;'
opcode_defs = [
def_fmt_str.format(
name=inst['opname'],
value=inst['opcode'],
colon=':',
offset=(max_len + 1 - len(inst['opname']))) for inst in instructions
]
opcode_str = '\n'.join(opcode_defs)
decl_fmt_str = 'SPV_OC_{name}'
opcode_list = [
decl_fmt_str.format(name=inst['opname']) for inst in instructions
]
opcode_list = split_list_into_sublists(opcode_list, 6)
opcode_list = [
'{:6}'.format('') + ', '.join(sublist) for sublist in opcode_list
]
opcode_list = ',\n'.join(opcode_list)
enum_attr = 'def SPV_OpcodeAttr :\n'\
' I32EnumAttr<"{name}", "valid SPIR-V instructions", [\n'\
'{lst}\n'\
' ]> {{\n'\
' let returnType = "::mlir::spirv::{name}";\n'\
' let convertFromStorage = '\
'"static_cast<::mlir::spirv::{name}>($_self.getInt())";\n'\
' let cppNamespace = "::mlir::spirv";\n}}'.format(
name='Opcode', lst=opcode_list)
return opcode_str + '\n\n' + enum_attr
def update_td_opcodes(path, instructions, filter_list):
"""Updates SPIRBase.td with new generated opcode cases.
Arguments:
- path: the path to SPIRBase.td
- instructions: a list containing all SPIR-V instructions' grammar
- filter_list: a list containing new opnames to add
"""
with open(path, 'r') as f:
content = f.read()
content = content.split(AUTOGEN_OPCODE_SECTION_MARKER)
assert len(content) == 3
# Extend opcode list with existing list
existing_opcodes = [k[11:] for k in re.findall('def SPV_OC_\w+', content[1])]
filter_list.extend(existing_opcodes)
filter_list = list(set(filter_list))
# Generate the opcode for all instructions in SPIR-V
filter_instrs = list(
filter(lambda inst: (inst['opname'] in filter_list), instructions))
# Sort instruction based on opcode
filter_instrs.sort(key=lambda inst: inst['opcode'])
opcode = gen_opcode(filter_instrs)
# Substitute the opcode
content = content[0] + AUTOGEN_OPCODE_SECTION_MARKER + '\n\n' + \
opcode + '\n\n// End ' + AUTOGEN_OPCODE_SECTION_MARKER \
+ content[2]
with open(path, 'w') as f:
f.write(content)
def update_td_enum_attrs(path, operand_kinds, filter_list):
"""Updates SPIRBase.td with new generated enum definitions.
Arguments:
- path: the path to SPIRBase.td
- operand_kinds: a list containing all operand kinds' grammar
- filter_list: a list containing new enums to add
"""
with open(path, 'r') as f:
content = f.read()
content = content.split(AUTOGEN_ENUM_SECTION_MARKER)
assert len(content) == 3
# Extend filter list with existing enum definitions
existing_kinds = [
k[8:-4] for k in re.findall('def SPV_\w+Attr', content[1])]
filter_list.extend(existing_kinds)
# Generate definitions for all enums in filter list
defs = [gen_operand_kind_enum_attr(kind)
for kind in operand_kinds if kind['kind'] in filter_list]
# Sort alphabetically according to enum name
defs.sort(key=lambda enum : enum[0])
# Only keep the definitions from now on
defs = [enum[1] for enum in defs]
# Substitute the old section
content = content[0] + AUTOGEN_ENUM_SECTION_MARKER + '\n\n' + \
'\n\n'.join(defs) + "\n\n// End " + AUTOGEN_ENUM_SECTION_MARKER \
+ content[2];
with open(path, 'w') as f:
f.write(content)
def snake_casify(name):
"""Turns the given name to follow snake_case convension."""
name = re.sub('\W+', '', name).split()
name = [s.lower() for s in name]
return '_'.join(name)
def map_spec_operand_to_ods_argument(operand):
"""Maps a operand in SPIR-V JSON spec to an op argument in ODS.
Arguments:
- A dict containing the operand's kind, quantifier, and name
Returns:
- A string containing both the type and name for the argument
"""
kind = operand['kind']
quantifier = operand.get('quantifier', '')
# These instruction "operands" are for encoding the results; they should
# not be handled here.
assert kind != 'IdResultType', 'unexpected to handle "IdResultType" kind'
assert kind != 'IdResult', 'unexpected to handle "IdResult" kind'
if kind == 'IdRef':
if quantifier == '':
arg_type = 'SPV_Type'
elif quantifier == '?':
arg_type = 'SPV_Optional<SPV_Type>'
else:
arg_type = 'Variadic<SPV_Type>'
elif kind == 'IdMemorySemantics' or kind == 'IdScope':
# TODO(antiagainst): Need to further constrain 'IdMemorySemantics'
# and 'IdScope' given that they should be gernated from OpConstant.
assert quantifier == '', ('unexpected to have optional/variadic memory '
'semantics or scope <id>')
arg_type = 'I32'
elif kind == 'LiteralInteger':
if quantifier == '':
arg_type = 'I32Attr'
elif quantifier == '?':
arg_type = 'OptionalAttr<I32Attr>'
else:
arg_type = 'OptionalAttr<I32ArrayAttr>'
elif kind == 'LiteralString' or \
kind == 'LiteralContextDependentNumber' or \
kind == 'LiteralExtInstInteger' or \
kind == 'LiteralSpecConstantOpInteger' or \
kind == 'PairLiteralIntegerIdRef' or \
kind == 'PairIdRefLiteralInteger' or \
kind == 'PairIdRefIdRef':
assert False, '"{}" kind unimplemented'.format(kind)
else:
# The rest are all enum operands that we represent with op attributes.
assert quantifier != '*', 'unexpected to have variadic enum attribute'
arg_type = 'SPV_{}Attr'.format(kind)
if quantifier == '?':
arg_type = 'OptionalAttr<{}>'.format(arg_type)
name = operand.get('name', '')
name = snake_casify(name) if name else kind.lower()
return '{}:${}'.format(arg_type, name)
def get_op_definition(instruction, doc, existing_info):
"""Generates the TableGen op definition for the given SPIR-V instruction.
Arguments:
- instruction: the instruction's SPIR-V JSON grammar
- doc: the instruction's SPIR-V HTML doc
- existing_info: a dict containing potential manually specified sections for
this instruction
Returns:
- A string containing the TableGen op definition
"""
fmt_str = 'def SPV_{opname}Op : SPV_Op<"{opname}", [{traits}]> {{\n'\
' let summary = {summary};\n\n'\
' let description = [{{\n'\
'{description}\n\n'\
' ### Custom assembly form\n'\
'{assembly}'\
'}}];\n\n'\
' let arguments = (ins{args});\n\n'\
' let results = (outs{results});\n'\
'{extras}'\
'}}\n'
opname = instruction['opname'][2:]
summary, description = doc.split('\n', 1)
wrapper = textwrap.TextWrapper(
width=76, initial_indent=' ', subsequent_indent=' ')
# Format summary. If the summary can fit in the same line, we print it out
# as a "-quoted string; otherwise, wrap the lines using "[{...}]".
summary = summary.strip();
if len(summary) + len(' let summary = "";') <= 80:
summary = '"{}"'.format(summary)
else:
summary = '[{{\n{}\n }}]'.format(wrapper.fill(summary))
# Wrap description
| description = [wrapper.fill(line) for line in description if line]
description = '\n\n'.join(description)
operands = instruction.get('operands', [])
# Set op's result
results = ''
if len(operands) > 0 and operands[0]['kind'] == 'IdResultType':
results = '\n SPV_Type:$result\n '
operands = operands[1:]
if 'results' in existing_info:
results = existing_info['results']
# Ignore the operand standing for the result <id>
if len(operands) > 0 and operands[0]['kind'] == 'IdResult':
operands = operands[1:]
# Set op' argument
arguments = existing_info.get('arguments', None)
if arguments is None:
arguments = [map_spec_operand_to_ods_argument(o) for o in operands]
arguments = '\n '.join(arguments)
if arguments:
# Prepend and append whitespace for formatting
arguments = '\n {}\n '.format(arguments)
assembly = existing_info.get('assembly', None)
if assembly is None:
assembly = ' ``` {.ebnf}\n'\
' [TODO]\n'\
' ```\n\n'\
' For example:\n\n'\
' ```\n'\
' [TODO]\n'\
' ```\n '
return fmt_str.format(
opname=opname,
traits=existing_info.get('traits', ''),
summary=summary,
description=description,
assembly=assembly,
args=arguments,
results=results,
extras=existing_info.get('extras', ''))
def extract_td_op_info(op_def):
"""Extracts potentially manually specified sections in op's definition.
Arguments: - A string containing the op's TableGen definition
- doc: the instruction's SPIR-V HTML doc
Returns:
- A dict containing potential manually specified sections
"""
# Get opname
opname = [o[8:-2] for o in re.findall('def SPV_\w+Op', op_def)]
assert len(opname) == 1, 'more than one ops in the same section!'
opname = opname[0]
# Get traits
op_tmpl_params = op_def.split('<', 1)[1].split('>', 1)[0].split(', ', 1)
if len(op_tmpl_params) == 1:
traits = ''
else:
traits = op_tmpl_params[1].strip('[]')
# Get custom assembly form
rest = op_def.split('### Custom assembly form\n')
assert len(rest) == 2, \
'{}: cannot find "### Custom assembly form"'.format(opname)
rest = rest[1].split(' let arguments = (ins')
assert len(rest) == 2, '{}: cannot find arguments'.format(opname)
assembly = rest[0].rstrip('}];\n')
# Get arguments
rest = rest[1].split(' let results = (outs')
assert len(rest) == 2, '{}: cannot find results'.format(opname)
args = rest[0].rstrip(');\n')
# Get results
rest = rest[1].split(');', 1)
assert len(rest) == 2, \
'{}: cannot find ");" ending results'.format(opname)
results = rest[0]
extras = rest[1].strip(' }\n')
if extras:
extras = '\n {}\n'.format(extras)
return {
# Prefix with 'Op' to make it consistent with SPIR-V spec
'opname': 'Op{}'.format(opname),
'traits': traits,
'assembly': assembly,
'arguments': args,
'results': results,
'extras': extras
}
def update_td_op_definitions(path, instructions, docs, filter_list):
"""Updates SPIRVOps.td with newly generated op definition.
Arguments:
- path: path to SPIRVOps.td
- instructions: SPIR-V JSON grammar for all instructions
- docs: SPIR-V HTML doc for all instructions
- filter_list: a list containing new opnames to include
Returns:
- A string containing all the TableGen op definitions
"""
with open(path, 'r') as f:
content = f.read()
# Split the file into chuncks, each containing one op.
ops = content.split(AUTOGEN_OP_DEF_SEPARATOR)
header = ops[0]
footer = ops[-1]
ops = ops[1:-1]
# For each existing op, extract the manually-written sections out to retain
# them when re-generating the ops. Also append the existing ops to filter
# list.
op_info_dict = {}
for op in ops:
info_dict = extract_td_op_info(op)
opname = info_dict['opname']
op_info_dict[opname] = info_dict
filter_list.append(opname)
filter_list = sorted(list(set(filter_list)))
op_defs = []
for opname in filter_list:
# Find the grammar spec for this op
instruction = next(
inst for inst in instructions if inst['opname'] == opname)
op_defs.append(
get_op_definition(instruction, docs[opname],
op_info_dict.get(opname, {})))
# Substitute the old op definitions
op_defs = [header] + op_defs + [footer]
content = AUTOGEN_OP_DEF_SEPARATOR.join(op_defs)
with open(path, 'w') as f:
f.write(content)
if __name__ == '__main__':
import argparse
cli_parser = argparse.ArgumentParser(
description='Update SPIR-V dialect definitions using SPIR-V spec')
cli_parser.add_argument(
'--base-td-path',
dest='base_td_path',
type=str,
default=None,
help='Path to SPIRVBase.td')
cli_parser.add_argument(
'--op-td-path',
dest='op_td_path',
type=str,
default=None,
help='Path to SPIRVOps.td')
cli_parser.add_argument(
'--new-enum',
dest='new_enum',
type=str,
default=None,
help='SPIR-V enum to be added to SPIRVBase.td')
cli_parser.add_argument(
'--new-opcodes',
dest='new_opcodes',
type=str,
default=None,
nargs='*',
help='update SPIR-V opcodes in SPIRVBase.td')
cli_parser.add_argument(
'--new-inst',
dest='new_inst',
type=str,
default=None,
help='SPIR-V instruction to be added to SPIRVOps.td')
args = cli_parser.parse_args()
operand_kinds, instructions = get_spirv_grammar_from_json_spec()
# Define new enum attr
if args.new_enum is not None:
assert args.base_td_path is not None
filter_list = [args.new_enum] if args.new_enum else []
update_td_enum_attrs(args.base_td_path, operand_kinds, filter_list)
# Define new opcode
if args.new_opcodes is not None:
assert args.base_td_path is not None
update_td_opcodes(args.base_td_path, instructions, args.new_opcodes)
# Define new op
if args.new_inst is not None:
assert args.op_td_path is not None
filter_list = [args.new_inst] if args.new_inst else []
docs = get_spirv_doc_from_html_spec()
update_td_op_definitions(args.op_td_path, instructions, docs, filter_list)
print('Done. Note that this script just generates a template; ', end='')
print('please read the spec and update traits, arguments, and ', end='')
print('results accordingly.') | description = description.split('\n')
|
debug.py | from audio_util import *
from dataloader import *
noise_path = '/home/smg/haoyuli/SiibGAN/database/Train/Noise/'
clean_path = '/home/smg/haoyuli/SiibGAN/database/Train/Clean/'
gen_file_list = get_filepaths('/home/smg/haoyuli/SiibGAN/database/Train/Clean/')
genloader = create_dataloader(gen_file_list,noise_path)
x = iter(genloader) |
enh_file_list = ['0.2228,/home/smg/haoyuli/SiibGAN/database/Train/Enhance/Train_32.wav']
disloader = create_dataloader(enh_file_list,noise_path,clean_path,'D')
x = iter(disloader)
a,b,c = x.next() |
bandClean,bandNoise,clean_mag,clean_phase,noise_mag,noise_phase, target = x.next() |
v1beta1_self_subject_access_review_spec.py | # coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.11.3
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class V1beta1SelfSubjectAccessReviewSpec(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'non_resource_attributes': 'V1beta1NonResourceAttributes',
'resource_attributes': 'V1beta1ResourceAttributes'
}
attribute_map = {
'non_resource_attributes': 'nonResourceAttributes',
'resource_attributes': 'resourceAttributes'
}
def __init__(self, non_resource_attributes=None, resource_attributes=None):
"""
V1beta1SelfSubjectAccessReviewSpec - a model defined in Swagger
"""
self._non_resource_attributes = None
self._resource_attributes = None
self.discriminator = None
if non_resource_attributes is not None:
self.non_resource_attributes = non_resource_attributes
if resource_attributes is not None:
self.resource_attributes = resource_attributes
@property
def non_resource_attributes(self):
"""
Gets the non_resource_attributes of this V1beta1SelfSubjectAccessReviewSpec.
NonResourceAttributes describes information for a non-resource access request
:return: The non_resource_attributes of this V1beta1SelfSubjectAccessReviewSpec.
:rtype: V1beta1NonResourceAttributes
"""
return self._non_resource_attributes
@non_resource_attributes.setter
def non_resource_attributes(self, non_resource_attributes):
"""
Sets the non_resource_attributes of this V1beta1SelfSubjectAccessReviewSpec.
NonResourceAttributes describes information for a non-resource access request
:param non_resource_attributes: The non_resource_attributes of this V1beta1SelfSubjectAccessReviewSpec.
:type: V1beta1NonResourceAttributes
"""
self._non_resource_attributes = non_resource_attributes
@property
def resource_attributes(self):
"""
Gets the resource_attributes of this V1beta1SelfSubjectAccessReviewSpec.
ResourceAuthorizationAttributes describes information for a resource access request
:return: The resource_attributes of this V1beta1SelfSubjectAccessReviewSpec.
:rtype: V1beta1ResourceAttributes
"""
return self._resource_attributes
@resource_attributes.setter
def resource_attributes(self, resource_attributes):
"""
Sets the resource_attributes of this V1beta1SelfSubjectAccessReviewSpec.
ResourceAuthorizationAttributes describes information for a resource access request
:param resource_attributes: The resource_attributes of this V1beta1SelfSubjectAccessReviewSpec.
:type: V1beta1ResourceAttributes
"""
self._resource_attributes = resource_attributes
def | (self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return pformat(self.to_dict())
def __repr__(self):
"""
For `print` and `pprint`
"""
return self.to_str()
def __eq__(self, other):
"""
Returns true if both objects are equal
"""
if not isinstance(other, V1beta1SelfSubjectAccessReviewSpec):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
| to_dict |
calendar.py | from display.handlers.base import BaseHandler
| def get(self):
title = 'CalendarHandler'
self.render('calendar/calendar.html', title = title, **self.render_dict) | class CalendarHandler(BaseHandler): |
reportsControllers.js | const { Report } = require('../models');
const fs = require('fs');
const GETallReports = async (req, res) => {
try {
const reports = await Report.findAll({ order: [ ['createdAt', 'DESC'] ] });
return res
.status(200)
.render('reports/allReports', {
reports,
title: 'All reports',
error: ""
});
} catch(err) {
console.log(err);
return res
.status(500)
.render('reports/allReports', { | error: 'Something went wrong.',
title: 'Error'
});
}
}
const GETallByUser = async (req, res) => {
try {
const user = req.params.user;
const reports = await Report.findAll({ order: [ ['createdAt', 'DESC'] ], where: { user } });
if (reports.length === 0) {
return res
.status(200)
.render('reports/allReports', {
reports,
title: `No reports by ${user}`,
error: `There are no reports from ${user}`
});
} else {
return res
.status(400)
.render('reports/allReports', {
reports,
title: `All reports by ${user}`,
error: ""
});
}
} catch(err) {
console.log(err);
return res
.status(500)
.render('reports/allReports', {
error: 'Something went wrong.',
title: 'Error'
});
}
}
const GETinsertReport = (req, res) => {
res.render('reports/insertReport', {
title: 'Insert a new report',
error: ''
});
};
const POSTsingleReport = async (req, res) => {
try {
const { place, pollution, description, user } = req.body;
if(req.fileValidationError) {
return res
.render('reports/insertReport', {
title: 'Error',
error: req.fileValidationError
});
} else if (!req.file) {
await Report.create({ place, pollution, description, user });
return res
.status(300)
.redirect('allReports');
} else if (req.file) {
const image = req.file.filename;
await Report.create({ place, pollution, description, user, image });
return res
.status(300)
.redirect('allReports');
}
} catch(error) {
console.log(error);
return res
.status(500)
.render('reports/insertReport', {
title: 'Error',
error
});
}
};
const GETsingleReport = async (req, res) => {
try {
const id = req.params.id;
const report = await Report.findByPk(id);
return res
.status(200)
.render('reports/singleReport', {
report,
title: `Report by ${report.user}`
});
} catch(error) {
console.log(error);
return res
.status(404)
.render('404', { title: "Report not found" });
}
};
const deleteImage = async (id) => {
try {
const report = await Report.findByPk(id);
const image = report.image;
if (image) {
const imgDir = `./public/reportImages/${image}`;
const esxistsImg = fs.existsSync(imgDir)
console.log(esxistsImg);
if (esxistsImg) {
fs.unlinkSync(imgDir);
return "Deleted";
} else {
return "File doesn't extists";
}
}
} catch (error) {
return error
}
}
const DELETEsingleReport = async (req, res) => {
try {
const id = req.params.id;
await deleteImage(id);
await Report.destroy({ where: { id } });
return res
.status(300)
.json({ redirect: '/reports/allReports' });
} catch(error) {
return res
.status(404)
.render('404', { title: "Something went wrong" });
}
};
module.exports = {
GETallReports,
GETallByUser,
GETinsertReport,
POSTsingleReport,
GETsingleReport,
DELETEsingleReport
} | |
narrow_phase.rs | #[cfg(feature = "parallel")]
use rayon::prelude::*;
use crate::data::{BundleSet, Coarena, ComponentSet, ComponentSetMut, ComponentSetOption};
use crate::dynamics::CoefficientCombineRule;
use crate::dynamics::{
IslandManager, RigidBodyActivation, RigidBodyDominance, RigidBodyIds, RigidBodyType,
};
use crate::geometry::{
BroadPhasePairEvent, ColliderChanges, ColliderGraphIndex, ColliderHandle, ColliderMaterial,
ColliderPair, ColliderParent, ColliderPosition, ColliderShape, ColliderType, ContactData,
ContactEvent, ContactManifold, ContactManifoldData, ContactPair, InteractionGraph,
IntersectionEvent, SolverContact, SolverFlags,
};
use crate::math::{Real, Vector};
use crate::pipeline::{
ActiveEvents, ActiveHooks, ContactModificationContext, EventHandler, PairFilterContext,
PhysicsHooks,
};
use crate::prelude::ColliderFlags;
use parry::query::{DefaultQueryDispatcher, PersistentQueryDispatcher};
use parry::utils::IsometryOpt;
use std::collections::HashMap;
use std::sync::Arc;
#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
struct ColliderGraphIndices {
contact_graph_index: ColliderGraphIndex,
intersection_graph_index: ColliderGraphIndex,
}
impl ColliderGraphIndices {
fn invalid() -> Self {
Self {
contact_graph_index: InteractionGraph::<(), ()>::invalid_graph_index(),
intersection_graph_index: InteractionGraph::<(), ()>::invalid_graph_index(),
}
}
}
#[derive(Copy, Clone, PartialEq, Eq)]
enum PairRemovalMode {
FromContactGraph,
FromIntersectionGraph,
Auto,
}
/// The narrow-phase responsible for computing precise contact information between colliders.
#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
#[derive(Clone)]
pub struct NarrowPhase {
#[cfg_attr(
feature = "serde-serialize",
serde(skip, default = "crate::geometry::default_persistent_query_dispatcher")
)]
query_dispatcher: Arc<dyn PersistentQueryDispatcher<ContactManifoldData, ContactData>>,
contact_graph: InteractionGraph<ColliderHandle, ContactPair>,
intersection_graph: InteractionGraph<ColliderHandle, bool>,
graph_indices: Coarena<ColliderGraphIndices>,
}
pub(crate) type ContactManifoldIndex = usize;
impl NarrowPhase {
/// Creates a new empty narrow-phase.
pub fn new() -> Self {
Self::with_query_dispatcher(DefaultQueryDispatcher)
}
/// Creates a new empty narrow-phase with a custom query dispatcher.
pub fn with_query_dispatcher<D>(d: D) -> Self
where
D: 'static + PersistentQueryDispatcher<ContactManifoldData, ContactData>,
{
Self {
query_dispatcher: Arc::new(d),
contact_graph: InteractionGraph::new(),
intersection_graph: InteractionGraph::new(),
graph_indices: Coarena::new(),
}
}
/// The query dispatcher used by this narrow-phase to select the right collision-detection
/// algorithms depending of the shape types.
pub fn query_dispatcher(
&self,
) -> &dyn PersistentQueryDispatcher<ContactManifoldData, ContactData> {
&*self.query_dispatcher
}
/// The contact graph containing all contact pairs and their contact information.
pub fn contact_graph(&self) -> &InteractionGraph<ColliderHandle, ContactPair> {
&self.contact_graph
}
/// The intersection graph containing all intersection pairs and their intersection information.
pub fn intersection_graph(&self) -> &InteractionGraph<ColliderHandle, bool> {
&self.intersection_graph
}
/// All the contacts involving the given collider.
///
/// It is strongly recommended to use the [`NarrowPhase::contacts_with`] method instead. This
/// method can be used if the generation number of the collider handle isn't known.
pub fn contacts_with_unknown_gen(&self, collider: u32) -> impl Iterator<Item = &ContactPair> {
self.graph_indices
.get_unknown_gen(collider)
.map(|id| id.contact_graph_index)
.into_iter()
.flat_map(move |id| self.contact_graph.interactions_with(id))
.map(|pair| pair.2)
}
/// All the contacts involving the given collider.
pub fn contacts_with<'a>(
&self,
collider: ColliderHandle,
) -> impl Iterator<Item = &ContactPair> {
self.graph_indices
.get(collider.0)
.map(|id| id.contact_graph_index)
.into_iter()
.flat_map(move |id| self.contact_graph.interactions_with(id))
.map(|pair| pair.2)
}
/// All the intersections involving the given collider.
///
/// It is strongly recommended to use the [`NarrowPhase::intersections_with`] method instead.
/// This method can be used if the generation number of the collider handle isn't known.
pub fn intersections_with_unknown_gen(
&self,
collider: u32,
) -> impl Iterator<Item = (ColliderHandle, ColliderHandle, bool)> + '_ {
self.graph_indices
.get_unknown_gen(collider)
.map(|id| id.intersection_graph_index)
.into_iter()
.flat_map(move |id| {
self.intersection_graph
.interactions_with(id)
.map(|e| (e.0, e.1, *e.2))
})
}
/// All the intersections involving the given collider.
pub fn intersections_with(
&self,
collider: ColliderHandle,
) -> impl Iterator<Item = (ColliderHandle, ColliderHandle, bool)> + '_ {
self.graph_indices
.get(collider.0)
.map(|id| id.intersection_graph_index)
.into_iter()
.flat_map(move |id| {
self.intersection_graph
.interactions_with(id)
.map(|e| (e.0, e.1, *e.2))
})
}
/// The contact pair involving two specific colliders.
///
/// It is strongly recommended to use the [`NarrowPhase::contact_pair`] method instead. This
/// method can be used if the generation number of the collider handle isn't known.
///
/// If this returns `None`, there is no contact between the two colliders.
/// If this returns `Some`, then there may be a contact between the two colliders. Check the
/// result [`ContactPair::has_any_active_collider`] method to see if there is an actual contact.
pub fn contact_pair_unknown_gen(&self, collider1: u32, collider2: u32) -> Option<&ContactPair> {
let id1 = self.graph_indices.get_unknown_gen(collider1)?;
let id2 = self.graph_indices.get_unknown_gen(collider2)?;
self.contact_graph
.interaction_pair(id1.contact_graph_index, id2.contact_graph_index)
.map(|c| c.2)
}
/// The contact pair involving two specific colliders.
///
/// If this returns `None`, there is no contact between the two colliders.
/// If this returns `Some`, then there may be a contact between the two colliders. Check the
/// result [`ContactPair::has_any_active_collider`] method to see if there is an actual contact.
pub fn contact_pair(
&self,
collider1: ColliderHandle,
collider2: ColliderHandle,
) -> Option<&ContactPair> {
let id1 = self.graph_indices.get(collider1.0)?;
let id2 = self.graph_indices.get(collider2.0)?;
self.contact_graph
.interaction_pair(id1.contact_graph_index, id2.contact_graph_index)
.map(|c| c.2)
}
/// The intersection pair involving two specific colliders.
///
/// It is strongly recommended to use the [`NarrowPhase::intersection_pair`] method instead. This
/// method can be used if the generation number of the collider handle isn't known.
///
/// If this returns `None` or `Some(false)`, then there is no intersection between the two colliders.
/// If this returns `Some(true)`, then there may be an intersection between the two colliders.
pub fn intersection_pair_unknown_gen(&self, collider1: u32, collider2: u32) -> Option<bool> {
let id1 = self.graph_indices.get_unknown_gen(collider1)?;
let id2 = self.graph_indices.get_unknown_gen(collider2)?;
self.intersection_graph
.interaction_pair(id1.intersection_graph_index, id2.intersection_graph_index)
.map(|c| *c.2)
}
/// The intersection pair involving two specific colliders.
///
/// If this returns `None` or `Some(false)`, then there is no intersection between the two colliders.
/// If this returns `Some(true)`, then there may be an intersection between the two colliders.
pub fn intersection_pair(
&self,
collider1: ColliderHandle,
collider2: ColliderHandle,
) -> Option<bool> {
let id1 = self.graph_indices.get(collider1.0)?;
let id2 = self.graph_indices.get(collider2.0)?;
self.intersection_graph
.interaction_pair(id1.intersection_graph_index, id2.intersection_graph_index)
.map(|c| *c.2)
}
/// All the contact pairs maintained by this narrow-phase.
pub fn contact_pairs(&self) -> impl Iterator<Item = &ContactPair> {
self.contact_graph.interactions()
}
/// All the intersection pairs maintained by this narrow-phase.
pub fn intersection_pairs(
&self,
) -> impl Iterator<Item = (ColliderHandle, ColliderHandle, bool)> + '_ {
self.intersection_graph
.interactions_with_endpoints()
.map(|e| (e.0, e.1, *e.2))
}
// #[cfg(feature = "parallel")]
// pub(crate) fn contact_pairs_vec_mut(&mut self) -> &mut Vec<ContactPair> {
// &mut self.contact_graph.interactions
// }
/// Maintain the narrow-phase internal state by taking collider removal into account.
pub fn handle_user_changes<Bodies, Colliders>(
&mut self,
mut islands: Option<&mut IslandManager>,
modified_colliders: &[ColliderHandle],
removed_colliders: &[ColliderHandle],
colliders: &mut Colliders,
bodies: &mut Bodies,
events: &mut dyn EventHandler,
) where
Bodies: ComponentSetMut<RigidBodyActivation>
+ ComponentSet<RigidBodyType>
+ ComponentSetMut<RigidBodyIds>,
Colliders: ComponentSet<ColliderChanges>
+ ComponentSet<ColliderType>
+ ComponentSet<ColliderFlags>
+ ComponentSetOption<ColliderParent>,
{
// TODO: avoid these hash-maps.
// They are necessary to handle the swap-remove done internally
// by the contact/intersection graphs when a node is removed.
let mut prox_id_remap = HashMap::new();
let mut contact_id_remap = HashMap::new();
for collider in removed_colliders {
// NOTE: if the collider does not have any graph indices currently, there is nothing
// to remove in the narrow-phase for this collider.
if let Some(graph_idx) = self
.graph_indices
.remove(collider.0, ColliderGraphIndices::invalid())
{
let intersection_graph_id = prox_id_remap
.get(collider)
.copied()
.unwrap_or(graph_idx.intersection_graph_index);
let contact_graph_id = contact_id_remap
.get(collider)
.copied()
.unwrap_or(graph_idx.contact_graph_index);
self.remove_collider(
intersection_graph_id,
contact_graph_id,
islands.as_deref_mut(),
colliders,
bodies,
&mut prox_id_remap,
&mut contact_id_remap,
);
}
}
self.handle_modified_colliders(islands, modified_colliders, colliders, bodies, events);
}
pub(crate) fn remove_collider<Bodies, Colliders>(
&mut self,
intersection_graph_id: ColliderGraphIndex,
contact_graph_id: ColliderGraphIndex,
islands: Option<&mut IslandManager>,
colliders: &mut Colliders,
bodies: &mut Bodies,
prox_id_remap: &mut HashMap<ColliderHandle, ColliderGraphIndex>,
contact_id_remap: &mut HashMap<ColliderHandle, ColliderGraphIndex>,
) where
Bodies: ComponentSetMut<RigidBodyActivation>
+ ComponentSet<RigidBodyType>
+ ComponentSetMut<RigidBodyIds>,
Colliders: ComponentSetOption<ColliderParent>,
{
// Wake up every body in contact with the deleted collider.
if let Some(islands) = islands {
for (a, b, _) in self.contact_graph.interactions_with(contact_graph_id) {
if let Some(parent) = colliders.get(a.0).map(|c| c.handle) {
islands.wake_up(bodies, parent, true)
}
if let Some(parent) = colliders.get(b.0).map(|c| c.handle) {
islands.wake_up(bodies, parent, true)
}
}
}
// We have to manage the fact that one other collider will
// have its graph index changed because of the node's swap-remove.
if let Some(replacement) = self.intersection_graph.remove_node(intersection_graph_id) {
if let Some(replacement) = self.graph_indices.get_mut(replacement.0) {
replacement.intersection_graph_index = intersection_graph_id;
} else {
prox_id_remap.insert(replacement, intersection_graph_id);
// I feel like this should never happen now that the narrow-phase is the one owning
// the graph_indices. Let's put an unreachable in there and see if anybody still manages
// to reach it. If nobody does, we will remove this.
unreachable!();
}
}
if let Some(replacement) = self.contact_graph.remove_node(contact_graph_id) {
if let Some(replacement) = self.graph_indices.get_mut(replacement.0) {
replacement.contact_graph_index = contact_graph_id;
} else {
contact_id_remap.insert(replacement, contact_graph_id);
// I feel like this should never happen now that the narrow-phase is the one owning
// the graph_indices. Let's put an unreachable in there and see if anybody still manages
// to reach it. If nobody does, we will remove this.
unreachable!();
}
}
}
pub(crate) fn handle_modified_colliders<Bodies, Colliders>(
&mut self,
mut islands: Option<&mut IslandManager>,
modified_colliders: &[ColliderHandle],
colliders: &Colliders,
bodies: &mut Bodies,
events: &mut dyn EventHandler,
) where
Bodies: ComponentSetMut<RigidBodyActivation>
+ ComponentSet<RigidBodyType>
+ ComponentSetMut<RigidBodyIds>,
Colliders: ComponentSet<ColliderChanges>
+ ComponentSet<ColliderType>
+ ComponentSet<ColliderFlags>
+ ComponentSetOption<ColliderParent>,
{
let mut pairs_to_remove = vec![];
for handle in modified_colliders {
// NOTE: we use `get` because the collider may no longer
// exist if it has been removed.
let co_changes: Option<&ColliderChanges> = colliders.get(handle.0);
if let Some(co_changes) = co_changes {
if co_changes.needs_narrow_phase_update() {
// No flag relevant to the narrow-phase is enabled for this collider.
return;
}
if let Some(gid) = self.graph_indices.get(handle.0) {
// For each modified colliders, we need to wake-up the bodies it is in contact with
// so that the narrow-phase properly takes into account the change in, e.g.,
// collision groups. Waking up the modified collider's parent isn't enough because
// it could be a static or kinematic body which don't propagate the wake-up state.
let co_parent: Option<&ColliderParent> = colliders.get(handle.0);
let (co_changes, co_type): (&ColliderChanges, &ColliderType) =
colliders.index_bundle(handle.0);
if let Some(islands) = islands.as_deref_mut() {
if let Some(co_parent) = co_parent {
islands.wake_up(bodies, co_parent.handle, true);
}
for inter in self
.contact_graph
.interactions_with(gid.contact_graph_index)
{
let other_handle = if *handle == inter.0 { inter.1 } else { inter.0 };
let other_parent: Option<&ColliderParent> =
colliders.get(other_handle.0);
if let Some(other_parent) = other_parent {
islands.wake_up(bodies, other_parent.handle, true);
}
}
}
// For each collider which had their sensor status modified, we need
// to transfer their contact/intersection graph edges to the intersection/contact graph.
// To achieve this we will remove the relevant contact/intersection pairs form the
// contact/intersection graphs, and then add them into the other graph.
if co_changes.contains(ColliderChanges::TYPE) {
if co_type.is_sensor() {
// Find the contact pairs for this collider and
// push them to `pairs_to_remove`.
for inter in self
.contact_graph
.interactions_with(gid.contact_graph_index)
{
pairs_to_remove.push((
ColliderPair::new(inter.0, inter.1),
PairRemovalMode::FromContactGraph,
));
}
} else {
// Find the contact pairs for this collider and
// push them to `pairs_to_remove` if both involved
// colliders are not sensors.
for inter in self
.intersection_graph
.interactions_with(gid.intersection_graph_index)
.filter(|(h1, h2, _)| {
let co_type1: &ColliderType = colliders.index(h1.0);
let co_type2: &ColliderType = colliders.index(h2.0);
!co_type1.is_sensor() && !co_type2.is_sensor()
})
{
pairs_to_remove.push((
ColliderPair::new(inter.0, inter.1),
PairRemovalMode::FromIntersectionGraph,
));
}
}
}
}
}
}
// Remove the pair from the relevant graph.
for pair in &pairs_to_remove {
self.remove_pair(
islands.as_deref_mut(),
colliders,
bodies,
&pair.0,
events,
pair.1,
);
}
// Add the paid removed pair to the relevant graph.
for pair in pairs_to_remove {
self.add_pair(colliders, &pair.0);
}
}
fn remove_pair<Bodies, Colliders>(
&mut self,
islands: Option<&mut IslandManager>,
colliders: &Colliders,
bodies: &mut Bodies,
pair: &ColliderPair,
events: &mut dyn EventHandler,
mode: PairRemovalMode,
) where
Bodies: ComponentSetMut<RigidBodyActivation>
+ ComponentSet<RigidBodyType>
+ ComponentSetMut<RigidBodyIds>,
Colliders: ComponentSet<ColliderType>
+ ComponentSet<ColliderFlags>
+ ComponentSetOption<ColliderParent>,
{
let co_type1: Option<&ColliderType> = colliders.get(pair.collider1.0);
let co_type2: Option<&ColliderType> = colliders.get(pair.collider2.0);
if let (Some(co_type1), Some(co_type2)) = (co_type1, co_type2) {
// TODO: could we just unwrap here?
// Don't we have the guarantee that we will get a `AddPair` before a `DeletePair`?
if let (Some(gid1), Some(gid2)) = (
self.graph_indices.get(pair.collider1.0),
self.graph_indices.get(pair.collider2.0),
) {
if mode == PairRemovalMode::FromIntersectionGraph
|| (mode == PairRemovalMode::Auto
&& (co_type1.is_sensor() || co_type2.is_sensor()))
{
let was_intersecting = self
.intersection_graph
.remove_edge(gid1.intersection_graph_index, gid2.intersection_graph_index);
// Emit an intersection lost event if we had an intersection before removing the edge.
if Some(true) == was_intersecting {
let co_flag1: &ColliderFlags = colliders.index(pair.collider1.0);
let co_flag2: &ColliderFlags = colliders.index(pair.collider2.0);
if (co_flag1.active_events | co_flag2.active_events)
.contains(ActiveEvents::INTERSECTION_EVENTS)
{
let prox_event =
IntersectionEvent::new(pair.collider1, pair.collider2, false);
events.handle_intersection_event(prox_event)
}
}
} else {
let contact_pair = self
.contact_graph
.remove_edge(gid1.contact_graph_index, gid2.contact_graph_index);
// Emit a contact stopped event if we had a contact before removing the edge.
// Also wake up the dynamic bodies that were in contact.
if let Some(ctct) = contact_pair {
if ctct.has_any_active_contact {
let co_parent1: Option<&ColliderParent> =
colliders.get(pair.collider1.0);
let co_parent2: Option<&ColliderParent> =
colliders.get(pair.collider2.0);
if let Some(islands) = islands {
if let Some(co_parent1) = co_parent1 {
islands.wake_up(bodies, co_parent1.handle, true);
}
if let Some(co_parent2) = co_parent2 {
islands.wake_up(bodies, co_parent2.handle, true);
}
}
let co_flag1: &ColliderFlags = colliders.index(pair.collider1.0);
let co_flag2: &ColliderFlags = colliders.index(pair.collider2.0);
if (co_flag1.active_events | co_flag2.active_events)
.contains(ActiveEvents::CONTACT_EVENTS)
{
events.handle_contact_event(
ContactEvent::Stopped(pair.collider1, pair.collider2),
&ctct,
)
}
}
}
}
}
}
}
fn add_pair<Colliders>(&mut self, colliders: &Colliders, pair: &ColliderPair)
where
Colliders: ComponentSet<ColliderType> + ComponentSetOption<ColliderParent>,
{
let co_type1: Option<&ColliderType> = colliders.get(pair.collider1.0);
let co_type2: Option<&ColliderType> = colliders.get(pair.collider2.0);
if let (Some(co_type1), Some(co_type2)) = (co_type1, co_type2) {
let co_parent1: Option<&ColliderParent> = colliders.get(pair.collider1.0);
let co_parent2: Option<&ColliderParent> = colliders.get(pair.collider2.0);
if co_parent1.map(|p| p.handle) == co_parent2.map(|p| p.handle) {
// Same parents. Ignore collisions.
return;
}
let (gid1, gid2) = self.graph_indices.ensure_pair_exists(
pair.collider1.0,
pair.collider2.0,
ColliderGraphIndices::invalid(),
);
if co_type1.is_sensor() || co_type2.is_sensor() {
// NOTE: the collider won't have a graph index as long
// as it does not interact with anything.
if !InteractionGraph::<(), ()>::is_graph_index_valid(gid1.intersection_graph_index)
{
gid1.intersection_graph_index =
self.intersection_graph.graph.add_node(pair.collider1);
}
if !InteractionGraph::<(), ()>::is_graph_index_valid(gid2.intersection_graph_index)
{
gid2.intersection_graph_index =
self.intersection_graph.graph.add_node(pair.collider2);
}
if self
.intersection_graph
.graph
.find_edge(gid1.intersection_graph_index, gid2.intersection_graph_index)
.is_none()
{
let _ = self.intersection_graph.add_edge(
gid1.intersection_graph_index,
gid2.intersection_graph_index,
false,
);
}
} else {
// NOTE: same code as above, but for the contact graph.
// TODO: refactor both pieces of code somehow?
// NOTE: the collider won't have a graph index as long
// as it does not interact with anything.
if !InteractionGraph::<(), ()>::is_graph_index_valid(gid1.contact_graph_index) {
gid1.contact_graph_index = self.contact_graph.graph.add_node(pair.collider1);
}
if !InteractionGraph::<(), ()>::is_graph_index_valid(gid2.contact_graph_index) {
gid2.contact_graph_index = self.contact_graph.graph.add_node(pair.collider2);
}
if self
.contact_graph
.graph
.find_edge(gid1.contact_graph_index, gid2.contact_graph_index)
.is_none()
{
let interaction = ContactPair::new(pair.collider1, pair.collider2);
let _ = self.contact_graph.add_edge(
gid1.contact_graph_index,
gid2.contact_graph_index,
interaction,
);
}
}
}
}
pub(crate) fn register_pairs<Bodies, Colliders>(
&mut self,
mut islands: Option<&mut IslandManager>,
colliders: &Colliders,
bodies: &mut Bodies,
broad_phase_events: &[BroadPhasePairEvent],
events: &mut dyn EventHandler,
) where
Bodies: ComponentSetMut<RigidBodyActivation>
+ ComponentSetMut<RigidBodyIds>
+ ComponentSet<RigidBodyType>,
Colliders: ComponentSet<ColliderType>
+ ComponentSet<ColliderFlags>
+ ComponentSetOption<ColliderParent>,
{
for event in broad_phase_events {
match event {
BroadPhasePairEvent::AddPair(pair) => {
self.add_pair(colliders, pair);
}
BroadPhasePairEvent::DeletePair(pair) => {
self.remove_pair(
islands.as_deref_mut(),
colliders,
bodies,
pair,
events,
PairRemovalMode::Auto,
);
}
}
}
}
pub(crate) fn compute_intersections<Bodies, Colliders>(
&mut self,
bodies: &Bodies,
colliders: &Colliders,
modified_colliders: &[ColliderHandle],
hooks: &dyn PhysicsHooks<Bodies, Colliders>,
events: &mut dyn EventHandler,
) where
Bodies: ComponentSet<RigidBodyActivation>
+ ComponentSet<RigidBodyType>
+ ComponentSet<RigidBodyDominance>,
Colliders: ComponentSet<ColliderChanges>
+ ComponentSetOption<ColliderParent>
+ ComponentSet<ColliderShape>
+ ComponentSet<ColliderPosition>
+ ComponentSet<ColliderMaterial>
+ ComponentSet<ColliderFlags>,
{
if modified_colliders.is_empty() {
return;
}
let nodes = &self.intersection_graph.graph.nodes;
let query_dispatcher = &*self.query_dispatcher;
// TODO: don't iterate on all the edges.
par_iter_mut!(&mut self.intersection_graph.graph.edges).for_each(|edge| {
let handle1 = nodes[edge.source().index()].weight;
let handle2 = nodes[edge.target().index()].weight;
let co_parent1: Option<&ColliderParent> = colliders.get(handle1.0);
let (co_changes1, co_shape1, co_pos1, co_flags1): (
&ColliderChanges,
&ColliderShape,
&ColliderPosition,
&ColliderFlags,
) = colliders.index_bundle(handle1.0);
let co_parent2: Option<&ColliderParent> = colliders.get(handle2.0);
let (co_changes2, co_shape2, co_pos2, co_flags2): (
&ColliderChanges,
&ColliderShape,
&ColliderPosition,
&ColliderFlags,
) = colliders.index_bundle(handle2.0);
if !co_changes1.needs_narrow_phase_update() && !co_changes2.needs_narrow_phase_update()
{
// No update needed for these colliders.
return;
}
// TODO: avoid lookup into bodies.
let mut rb_type1 = RigidBodyType::Static;
let mut rb_type2 = RigidBodyType::Static;
if let Some(co_parent1) = co_parent1 {
rb_type1 = *bodies.index(co_parent1.handle.0);
}
if let Some(co_parent2) = co_parent2 {
rb_type2 = *bodies.index(co_parent2.handle.0);
}
| return;
}
// Filter based on collision groups.
if !co_flags1.collision_groups.test(co_flags2.collision_groups) {
return;
}
let active_hooks = co_flags1.active_hooks | co_flags2.active_hooks;
let active_events = co_flags1.active_events | co_flags2.active_events;
// Filter based on rigid-body types.
if !co_flags1.active_collision_types.test(rb_type1, rb_type2)
&& !co_flags2.active_collision_types.test(rb_type1, rb_type2)
{
return;
}
if active_hooks.contains(ActiveHooks::FILTER_INTERSECTION_PAIR) {
let context = PairFilterContext {
bodies,
colliders,
rigid_body1: co_parent1.map(|p| p.handle),
rigid_body2: co_parent2.map(|p| p.handle),
collider1: handle1,
collider2: handle2,
};
if !hooks.filter_intersection_pair(&context) {
// No intersection allowed.
return;
}
}
let pos12 = co_pos1.inv_mul(co_pos2);
if let Ok(intersection) =
query_dispatcher.intersection_test(&pos12, &**co_shape1, &**co_shape2)
{
if active_events.contains(ActiveEvents::INTERSECTION_EVENTS)
&& intersection != edge.weight
{
edge.weight = intersection;
events.handle_intersection_event(IntersectionEvent::new(
handle1,
handle2,
intersection,
));
}
}
});
}
pub(crate) fn compute_contacts<Bodies, Colliders>(
&mut self,
prediction_distance: Real,
bodies: &Bodies,
colliders: &Colliders,
modified_colliders: &[ColliderHandle],
hooks: &dyn PhysicsHooks<Bodies, Colliders>,
events: &mut dyn EventHandler,
) where
Bodies: ComponentSet<RigidBodyActivation>
+ ComponentSet<RigidBodyType>
+ ComponentSet<RigidBodyDominance>,
Colliders: ComponentSet<ColliderChanges>
+ ComponentSetOption<ColliderParent>
+ ComponentSet<ColliderShape>
+ ComponentSet<ColliderPosition>
+ ComponentSet<ColliderMaterial>
+ ComponentSet<ColliderFlags>,
{
if modified_colliders.is_empty() {
return;
}
let query_dispatcher = &*self.query_dispatcher;
// TODO: don't iterate on all the edges.
par_iter_mut!(&mut self.contact_graph.graph.edges).for_each(|edge| {
let pair = &mut edge.weight;
let co_parent1: Option<&ColliderParent> = colliders.get(pair.collider1.0);
let (co_changes1, co_shape1, co_pos1, co_material1, co_flags1): (
&ColliderChanges,
&ColliderShape,
&ColliderPosition,
&ColliderMaterial,
&ColliderFlags,
) = colliders.index_bundle(pair.collider1.0);
let co_parent2: Option<&ColliderParent> = colliders.get(pair.collider2.0);
let (co_changes2, co_shape2, co_pos2, co_material2, co_flags2): (
&ColliderChanges,
&ColliderShape,
&ColliderPosition,
&ColliderMaterial,
&ColliderFlags,
) = colliders.index_bundle(pair.collider2.0);
if !co_changes1.needs_narrow_phase_update() && !co_changes2.needs_narrow_phase_update()
{
// No update needed for these colliders.
return;
}
// TODO: avoid lookup into bodies.
let mut rb_type1 = RigidBodyType::Static;
let mut rb_type2 = RigidBodyType::Static;
if let Some(co_parent1) = co_parent1 {
rb_type1 = *bodies.index(co_parent1.handle.0);
}
if let Some(co_parent2) = co_parent2 {
rb_type2 = *bodies.index(co_parent2.handle.0);
}
// Filter based on the rigid-body types.
if !co_flags1.active_collision_types.test(rb_type1, rb_type2)
&& !co_flags2.active_collision_types.test(rb_type1, rb_type2)
{
return;
}
// Filter based on collision groups.
if !co_flags1.collision_groups.test(co_flags2.collision_groups) {
return;
}
let active_hooks = co_flags1.active_hooks | co_flags2.active_hooks;
let active_events = co_flags1.active_events | co_flags2.active_events;
let mut solver_flags = if active_hooks.contains(ActiveHooks::FILTER_CONTACT_PAIRS) {
let context = PairFilterContext {
bodies,
colliders,
rigid_body1: co_parent1.map(|p| p.handle),
rigid_body2: co_parent2.map(|p| p.handle),
collider1: pair.collider1,
collider2: pair.collider2,
};
if let Some(solver_flags) = hooks.filter_contact_pair(&context) {
solver_flags
} else {
// No contact allowed.
return;
}
} else {
SolverFlags::default()
};
if !co_flags1.solver_groups.test(co_flags2.solver_groups) {
solver_flags.remove(SolverFlags::COMPUTE_IMPULSES);
}
if co_changes1.contains(ColliderChanges::SHAPE)
|| co_changes2.contains(ColliderChanges::SHAPE)
{
// The shape changed so the workspace is no longer valid.
pair.workspace = None;
}
let pos12 = co_pos1.inv_mul(co_pos2);
let _ = query_dispatcher.contact_manifolds(
&pos12,
&**co_shape1,
&**co_shape2,
prediction_distance,
&mut pair.manifolds,
&mut pair.workspace,
);
let mut has_any_active_contact = false;
let friction = CoefficientCombineRule::combine(
co_material1.friction,
co_material2.friction,
co_material1.friction_combine_rule as u8,
co_material2.friction_combine_rule as u8,
);
let restitution = CoefficientCombineRule::combine(
co_material1.restitution,
co_material2.restitution,
co_material1.restitution_combine_rule as u8,
co_material2.restitution_combine_rule as u8,
);
let zero = RigidBodyDominance(0); // The value doesn't matter, it will be MAX because of the effective groups.
let dominance1 = co_parent1
.map(|p1| *bodies.index(p1.handle.0))
.unwrap_or(zero);
let dominance2 = co_parent2
.map(|p2| *bodies.index(p2.handle.0))
.unwrap_or(zero);
for manifold in &mut pair.manifolds {
let world_pos1 = manifold.subshape_pos1.prepend_to(co_pos1);
manifold.data.solver_contacts.clear();
manifold.data.rigid_body1 = co_parent1.map(|p| p.handle);
manifold.data.rigid_body2 = co_parent2.map(|p| p.handle);
manifold.data.solver_flags = solver_flags;
manifold.data.relative_dominance =
dominance1.effective_group(&rb_type1) - dominance2.effective_group(&rb_type2);
manifold.data.normal = world_pos1 * manifold.local_n1;
// Generate solver contacts.
for (contact_id, contact) in manifold.points.iter().enumerate() {
assert!(
contact_id <= u8::MAX as usize,
"A contact manifold cannot contain more than 255 contacts currently."
);
if contact.dist < prediction_distance {
// Generate the solver contact.
let solver_contact = SolverContact {
contact_id: contact_id as u8,
point: world_pos1 * contact.local_p1
+ manifold.data.normal * contact.dist / 2.0,
dist: contact.dist,
friction,
restitution,
tangent_velocity: Vector::zeros(),
warmstart_impulse: contact.data.impulse,
warmstart_tangent_impulse: contact.data.tangent_impulse,
prev_rhs: contact.data.rhs,
};
manifold.data.solver_contacts.push(solver_contact);
has_any_active_contact = true;
}
}
// Apply the user-defined contact modification.
if active_hooks.contains(ActiveHooks::MODIFY_SOLVER_CONTACTS) {
let mut modifiable_solver_contacts =
std::mem::replace(&mut manifold.data.solver_contacts, Vec::new());
let mut modifiable_user_data = manifold.data.user_data;
let mut modifiable_normal = manifold.data.normal;
let mut context = ContactModificationContext {
bodies,
colliders,
rigid_body1: co_parent1.map(|p| p.handle),
rigid_body2: co_parent2.map(|p| p.handle),
collider1: pair.collider1,
collider2: pair.collider2,
manifold,
solver_contacts: &mut modifiable_solver_contacts,
normal: &mut modifiable_normal,
user_data: &mut modifiable_user_data,
};
hooks.modify_solver_contacts(&mut context);
manifold.data.solver_contacts = modifiable_solver_contacts;
manifold.data.normal = modifiable_normal;
manifold.data.user_data = modifiable_user_data;
}
}
if has_any_active_contact != pair.has_any_active_contact {
if active_events.contains(ActiveEvents::CONTACT_EVENTS) {
if has_any_active_contact {
events.handle_contact_event(
ContactEvent::Started(pair.collider1, pair.collider2),
pair,
);
} else {
events.handle_contact_event(
ContactEvent::Stopped(pair.collider1, pair.collider2),
pair,
);
}
}
pair.has_any_active_contact = has_any_active_contact;
}
});
}
/// Retrieve all the interactions with at least one contact point, happening between two active bodies.
// NOTE: this is very similar to the code from JointSet::select_active_interactions.
pub(crate) fn select_active_contacts<'a, Bodies>(
&'a mut self,
islands: &IslandManager,
bodies: &Bodies,
out_manifolds: &mut Vec<&'a mut ContactManifold>,
out: &mut Vec<Vec<ContactManifoldIndex>>,
) where
Bodies: ComponentSet<RigidBodyIds>
+ ComponentSet<RigidBodyType>
+ ComponentSet<RigidBodyActivation>,
{
for out_island in &mut out[..islands.num_islands()] {
out_island.clear();
}
// TODO: don't iterate through all the interactions.
for inter in self.contact_graph.graph.edges.iter_mut() {
for manifold in &mut inter.weight.manifolds {
if manifold
.data
.solver_flags
.contains(SolverFlags::COMPUTE_IMPULSES)
&& manifold.data.num_active_contacts() != 0
{
let (active_island_id1, rb_type1, sleeping1) =
if let Some(handle1) = manifold.data.rigid_body1 {
let data: (&RigidBodyIds, &RigidBodyType, &RigidBodyActivation) =
bodies.index_bundle(handle1.0);
(data.0.active_island_id, *data.1, data.2.sleeping)
} else {
(0, RigidBodyType::Static, true)
};
let (active_island_id2, rb_type2, sleeping2) =
if let Some(handle2) = manifold.data.rigid_body2 {
let data: (&RigidBodyIds, &RigidBodyType, &RigidBodyActivation) =
bodies.index_bundle(handle2.0);
(data.0.active_island_id, *data.1, data.2.sleeping)
} else {
(0, RigidBodyType::Static, true)
};
if (rb_type1.is_dynamic() || rb_type2.is_dynamic())
&& (!rb_type1.is_dynamic() || !sleeping1)
&& (!rb_type2.is_dynamic() || !sleeping2)
{
let island_index = if !rb_type1.is_dynamic() {
active_island_id2
} else {
active_island_id1
};
out[island_index].push(out_manifolds.len());
out_manifolds.push(manifold);
}
}
}
}
}
} | // Filter based on the rigid-body types.
if !co_flags1.active_collision_types.test(rb_type1, rb_type2)
&& !co_flags2.active_collision_types.test(rb_type1, rb_type2)
{ |
main.py | # PYTHON_ARGCOMPLETE_OK
"""The command line interface to pipx"""
import argparse
import logging
import logging.config
import os
import re
import shlex
import sys
import textwrap
import time
import urllib.parse
from pathlib import Path
from typing import Any, Callable, Dict, List
import argcomplete # type: ignore
from packaging.requirements import InvalidRequirement, Requirement
from packaging.utils import canonicalize_name
import pipx.constants
from pipx import commands, constants
from pipx.animate import hide_cursor, show_cursor
from pipx.colors import bold, green
from pipx.constants import ExitCode
from pipx.emojis import hazard
from pipx.interpreter import DEFAULT_PYTHON
from pipx.util import PipxError, mkdir, pipx_wrap, rmdir
from pipx.venv import VenvContainer
from pipx.version import __version__
logger = logging.getLogger(__name__)
VenvCompleter = Callable[[str], List[str]]
def print_version() -> None:
print(__version__)
SPEC_HELP = textwrap.dedent(
"""\
The package name or specific installation source passed to pip.
Runs `pip install -U SPEC`.
For example `--spec mypackage==2.0.0` or `--spec git+https://github.com/user/repo.git@branch`
"""
)
PIPX_DESCRIPTION = textwrap.dedent(
f"""
Install and execute apps from Python packages.
Binaries can either be installed globally into isolated Virtual Environments
or run directly in a temporary Virtual Environment.
Virtual Environment location is {str(constants.PIPX_LOCAL_VENVS)}.
Symlinks to apps are placed in {str(constants.LOCAL_BIN_DIR)}.
"""
)
PIPX_DESCRIPTION += pipx_wrap(
"""
optional environment variables:
PIPX_HOME Overrides default pipx location. Virtual Environments will be installed to $PIPX_HOME/venvs.
PIPX_BIN_DIR Overrides location of app installations. Apps are symlinked or copied here.
USE_EMOJI Overrides emoji behavior. Default value varies based on platform.
PIPX_DEFAULT_PYTHON Overrides default python used for commands.
""",
subsequent_indent=" " * 24, # match the indent of argparse options
keep_newlines=True,
)
DOC_DEFAULT_PYTHON = os.getenv("PIPX__DOC_DEFAULT_PYTHON", DEFAULT_PYTHON)
INSTALL_DESCRIPTION = textwrap.dedent(
f"""
The install command is the preferred way to globally install apps
from python packages on your system. It creates an isolated virtual
environment for the package, then ensures the package's apps are
accessible on your $PATH.
The result: apps you can run from anywhere, located in packages
you can cleanly upgrade or uninstall. Guaranteed to not have
dependency version conflicts or interfere with your OS's python
packages. 'sudo' is not required to do this.
pipx install PACKAGE_NAME
pipx install --python PYTHON PACKAGE_NAME
pipx install VCS_URL
pipx install ./LOCAL_PATH
pipx install ZIP_FILE
pipx install TAR_GZ_FILE
The PACKAGE_SPEC argument is passed directly to `pip install`.
The default virtual environment location is {constants.DEFAULT_PIPX_HOME}
and can be overridden by setting the environment variable `PIPX_HOME`
(Virtual Environments will be installed to `$PIPX_HOME/venvs`).
The default app location is {constants.DEFAULT_PIPX_BIN_DIR} and can be
overridden by setting the environment variable `PIPX_BIN_DIR`.
The default python executable used to install a package is
{DOC_DEFAULT_PYTHON} and can be overridden
by setting the environment variable `PIPX_DEFAULT_PYTHON`.
"""
)
class LineWrapRawTextHelpFormatter(argparse.RawDescriptionHelpFormatter):
def _split_lines(self, text: str, width: int) -> List[str]:
text = self._whitespace_matcher.sub(" ", text).strip()
return textwrap.wrap(text, width)
class InstalledVenvsCompleter:
def __init__(self, venv_container: VenvContainer) -> None:
self.packages = [str(p.name) for p in sorted(venv_container.iter_venv_dirs())]
def use(self, prefix: str, **kwargs: Any) -> List[str]:
return [
f"{prefix}{x[len(prefix):]}"
for x in self.packages
if x.startswith(canonicalize_name(prefix))
]
def get_pip_args(parsed_args: Dict[str, str]) -> List[str]:
pip_args: List[str] = []
if parsed_args.get("index_url"):
pip_args += ["--index-url", parsed_args["index_url"]]
if parsed_args.get("pip_args"):
pip_args += shlex.split(parsed_args.get("pip_args", ""))
# make sure --editable is last because it needs to be right before
# package specification
if parsed_args.get("editable"):
pip_args += ["--editable"]
return pip_args
def get_venv_args(parsed_args: Dict[str, str]) -> List[str]:
venv_args: List[str] = []
if parsed_args.get("system_site_packages"):
venv_args += ["--system-site-packages"]
return venv_args
def run_pipx_command(args: argparse.Namespace) -> ExitCode: # noqa: C901
verbose = args.verbose if "verbose" in args else False
pip_args = get_pip_args(vars(args))
venv_args = get_venv_args(vars(args))
venv_container = VenvContainer(constants.PIPX_LOCAL_VENVS)
if "package" in args:
package = args.package
if urllib.parse.urlparse(package).scheme:
raise PipxError("Package cannot be a url")
if "spec" in args and args.spec is not None:
if urllib.parse.urlparse(args.spec).scheme:
if "#egg=" not in args.spec:
args.spec = args.spec + f"#egg={package}"
venv_dir = venv_container.get_venv_dir(package)
logger.info(f"Virtual Environment location is {venv_dir}")
if "skip" in args:
skip_list = [canonicalize_name(x) for x in args.skip]
if args.command == "run":
package_or_url = (
args.spec
if ("spec" in args and args.spec is not None)
else args.app_with_args[0]
)
# For any package, we need to just use the name
try:
package_name = Requirement(args.app_with_args[0]).name
except InvalidRequirement:
# Raw URLs to scripts are supported, too, so continue if
# we can't parse this as a package
package_name = args.app_with_args[0]
use_cache = not args.no_cache
commands.run(
package_name,
package_or_url,
args.app_with_args[1:],
args.python,
pip_args,
venv_args,
args.pypackages,
verbose,
use_cache,
)
# We should never reach here because run() is NoReturn.
return ExitCode(1)
elif args.command == "install":
return commands.install(
None,
None,
args.package_spec,
constants.LOCAL_BIN_DIR,
args.python,
pip_args,
venv_args,
verbose,
force=args.force,
include_dependencies=args.include_deps,
suffix=args.suffix,
)
elif args.command == "inject":
return commands.inject(
venv_dir,
None,
args.dependencies,
pip_args,
verbose=verbose,
include_apps=args.include_apps,
include_dependencies=args.include_deps,
force=args.force,
)
elif args.command == "upgrade":
return commands.upgrade(
venv_dir,
pip_args,
verbose,
include_injected=args.include_injected,
force=args.force,
)
elif args.command == "upgrade-all":
return commands.upgrade_all(
venv_container,
verbose,
include_injected=args.include_injected,
skip=skip_list,
force=args.force,
)
elif args.command == "list":
return commands.list_packages(venv_container, args.include_injected, args.json)
elif args.command == "uninstall":
return commands.uninstall(venv_dir, constants.LOCAL_BIN_DIR, verbose)
elif args.command == "uninstall-all":
return commands.uninstall_all(venv_container, constants.LOCAL_BIN_DIR, verbose)
elif args.command == "reinstall":
return commands.reinstall(
venv_dir=venv_dir,
local_bin_dir=constants.LOCAL_BIN_DIR,
python=args.python,
verbose=verbose,
)
elif args.command == "reinstall-all":
return commands.reinstall_all(
venv_container,
constants.LOCAL_BIN_DIR,
args.python,
verbose,
skip=skip_list,
)
elif args.command == "runpip":
if not venv_dir:
raise PipxError("Developer error: venv_dir is not defined.")
return commands.run_pip(package, venv_dir, args.pipargs, args.verbose)
elif args.command == "ensurepath":
try:
return commands.ensure_pipx_paths(force=args.force)
except Exception as e:
logger.debug("Uncaught Exception:", exc_info=True)
raise PipxError(str(e), wrap_message=False)
elif args.command == "completions":
print(constants.completion_instructions)
return ExitCode(0)
else:
raise PipxError(f"Unknown command {args.command}")
def add_pip_venv_args(parser: argparse.ArgumentParser) -> None:
parser.add_argument(
"--system-site-packages",
action="store_true",
help="Give the virtual environment access to the system site-packages dir.",
)
parser.add_argument("--index-url", "-i", help="Base URL of Python Package Index")
parser.add_argument(
"--editable",
"-e",
help="Install a project in editable mode",
action="store_true",
)
parser.add_argument(
"--pip-args",
help="Arbitrary pip arguments to pass directly to pip install/upgrade commands",
)
def add_include_dependencies(parser: argparse.ArgumentParser) -> None:
parser.add_argument(
"--include-deps", help="Include apps of dependent packages", action="store_true"
)
def _add_install(subparsers: argparse._SubParsersAction) -> None:
p = subparsers.add_parser(
"install",
help="Install a package",
formatter_class=LineWrapRawTextHelpFormatter,
description=INSTALL_DESCRIPTION,
)
p.add_argument("package_spec", help="package name or pip installation spec")
add_include_dependencies(p)
p.add_argument("--verbose", action="store_true")
p.add_argument(
"--force",
"-f",
action="store_true",
help="Modify existing virtual environment and files in PIPX_BIN_DIR",
)
p.add_argument(
"--suffix",
default="",
help=(
"Optional suffix for virtual environment and executable names. "
"NOTE: The suffix feature is experimental and subject to change."
),
)
p.add_argument(
"--python",
default=DEFAULT_PYTHON,
help=(
"The Python executable used to create the Virtual Environment and run the "
"associated app/apps. Must be v3.6+."
),
)
add_pip_venv_args(p)
def _add_inject(subparsers, venv_completer: VenvCompleter) -> None:
p = subparsers.add_parser(
"inject",
help="Install packages into an existing Virtual Environment",
description="Installs packages to an existing pipx-managed virtual environment.",
)
p.add_argument(
"package",
help="Name of the existing pipx-managed Virtual Environment to inject into",
).completer = venv_completer
p.add_argument(
"dependencies",
nargs="+",
help="the packages to inject into the Virtual Environment--either package name or pip package spec",
)
p.add_argument(
"--include-apps",
action="store_true",
help="Add apps from the injected packages onto your PATH",
)
add_include_dependencies(p)
add_pip_venv_args(p)
p.add_argument(
"--force",
"-f",
action="store_true",
help="Modify existing virtual environment and files in PIPX_BIN_DIR",
)
p.add_argument("--verbose", action="store_true")
def _add_upgrade(subparsers, venv_completer: VenvCompleter) -> None:
p = subparsers.add_parser(
"upgrade",
help="Upgrade a package",
description="Upgrade a package in a pipx-managed Virtual Environment by running 'pip install --upgrade PACKAGE'",
)
p.add_argument("package").completer = venv_completer
p.add_argument(
"--include-injected",
action="store_true",
help="Also upgrade packages injected into the main app's environment",
)
p.add_argument(
"--force",
"-f",
action="store_true",
help="Modify existing virtual environment and files in PIPX_BIN_DIR",
)
add_pip_venv_args(p)
p.add_argument("--verbose", action="store_true")
def _add_upgrade_all(subparsers: argparse._SubParsersAction) -> None:
p = subparsers.add_parser(
"upgrade-all",
help="Upgrade all packages. Runs `pip install -U <pkgname>` for each package.",
description="Upgrades all packages within their virtual environments by running 'pip install --upgrade PACKAGE'",
)
p.add_argument(
"--include-injected",
action="store_true",
help="Also upgrade packages injected into the main app's environment",
)
p.add_argument("--skip", nargs="+", default=[], help="skip these packages")
p.add_argument(
"--force",
"-f",
action="store_true",
help="Modify existing virtual environment and files in PIPX_BIN_DIR",
)
p.add_argument("--verbose", action="store_true")
def _add_uninstall(subparsers, venv_completer: VenvCompleter) -> None:
p = subparsers.add_parser(
"uninstall",
help="Uninstall a package",
description="Uninstalls a pipx-managed Virtual Environment by deleting it and any files that point to its apps.",
)
p.add_argument("package").completer = venv_completer
p.add_argument("--verbose", action="store_true")
def _add_uninstall_all(subparsers: argparse._SubParsersAction) -> None:
p = subparsers.add_parser(
"uninstall-all",
help="Uninstall all packages",
description="Uninstall all pipx-managed packages",
)
p.add_argument("--verbose", action="store_true")
def _add_reinstall(subparsers, venv_completer: VenvCompleter) -> None:
p = subparsers.add_parser(
"reinstall",
formatter_class=LineWrapRawTextHelpFormatter,
help="Reinstall a package",
description=textwrap.dedent(
"""
Reinstalls a package.
Package is uninstalled, then installed with pipx install PACKAGE
with the same options used in the original install of PACKAGE.
"""
),
)
p.add_argument("package").completer = venv_completer
p.add_argument(
"--python",
default=DEFAULT_PYTHON,
help=(
"The Python executable used to recreate the Virtual Environment "
"and run the associated app/apps. Must be v3.6+."
),
)
p.add_argument("--verbose", action="store_true")
def _add_reinstall_all(subparsers: argparse._SubParsersAction) -> None:
p = subparsers.add_parser(
"reinstall-all",
formatter_class=LineWrapRawTextHelpFormatter,
help="Reinstall all packages",
description=textwrap.dedent(
"""
Reinstalls all packages.
Packages are uninstalled, then installed with pipx install PACKAGE
with the same options used in the original install of PACKAGE.
This is useful if you upgraded to a new version of Python and want
all your packages to use the latest as well.
"""
),
)
p.add_argument(
"--python",
default=DEFAULT_PYTHON,
help=(
"The Python executable used to recreate the Virtual Environment "
"and run the associated app/apps. Must be v3.6+."
),
)
p.add_argument("--skip", nargs="+", default=[], help="skip these packages")
p.add_argument("--verbose", action="store_true")
def _add_list(subparsers: argparse._SubParsersAction) -> None:
p = subparsers.add_parser(
"list",
help="List installed packages",
description="List packages and apps installed with pipx",
)
p.add_argument(
"--include-injected",
action="store_true",
help="Show packages injected into the main app's environment",
)
p.add_argument(
"--json", action="store_true", help="Output rich data in json format."
)
p.add_argument("--verbose", action="store_true")
def _add_run(subparsers: argparse._SubParsersAction) -> None:
p = subparsers.add_parser(
"run",
formatter_class=LineWrapRawTextHelpFormatter,
help=(
"Download the latest version of a package to a temporary virtual environment, "
"then run an app from it. Also compatible with local `__pypackages__` "
"directory (experimental)."
),
description=textwrap.dedent(
f"""
Download the latest version of a package to a temporary virtual environment,
then run an app from it. The environment will be cached
and re-used for up to {constants.TEMP_VENV_EXPIRATION_THRESHOLD_DAYS} days. This
means subsequent calls to 'run' for the same package will be faster
since they can re-use the cached Virtual Environment.
In support of PEP 582 'run' will use apps found in a local __pypackages__
directory, if present. Please note that this behavior is experimental,
and acts as a companion tool to pythonloc. It may be modified or
removed in the future. See https://github.com/cs01/pythonloc.
"""
),
)
p.add_argument(
"--no-cache",
action="store_true",
help="Do not re-use cached virtual environment if it exists",
)
p.add_argument(
"app_with_args",
metavar="app ...",
nargs=argparse.REMAINDER,
help="app/package name and any arguments to be passed to it",
default=[],
)
p.add_argument(
"--pypackages",
action="store_true",
help="Require app to be run from local __pypackages__ directory",
)
p.add_argument("--spec", help=SPEC_HELP)
p.add_argument("--verbose", action="store_true")
p.add_argument(
"--python",
default=DEFAULT_PYTHON,
help="The Python version to run package's CLI app with. Must be v3.6+.",
)
add_pip_venv_args(p)
p.set_defaults(subparser=p)
# modify usage text to show required app argument
p.usage = re.sub(r"^usage: ", "", p.format_usage())
# add a double-dash to usage text to show requirement before app
p.usage = re.sub(r"\.\.\.", "app ...", p.usage)
def _add_runpip(subparsers, venv_completer: VenvCompleter) -> None:
p = subparsers.add_parser(
"runpip",
help="Run pip in an existing pipx-managed Virtual Environment",
description="Run pip in an existing pipx-managed Virtual Environment",
)
p.add_argument(
"package",
help="Name of the existing pipx-managed Virtual Environment to run pip in",
).completer = venv_completer
p.add_argument(
"pipargs",
nargs=argparse.REMAINDER,
default=[],
help="Arguments to forward to pip command",
)
p.add_argument("--verbose", action="store_true")
def _add_ensurepath(subparsers: argparse._SubParsersAction) -> None:
p = subparsers.add_parser(
"ensurepath",
help=(
"Ensure directories necessary for pipx operation are in your "
"PATH environment variable."
),
description=(
"Ensure directory where pipx stores apps is in your "
"PATH environment variable. Also if pipx was installed via "
"`pip install --user`, ensure pipx itself is in your PATH. "
"Note that running this may modify "
"your shell's configuration file(s) such as '~/.bashrc'."
),
)
p.add_argument(
"--force",
"-f",
action="store_true",
help=(
"Add text to your shell's config file even if it looks like your "
"PATH already contains paths to pipx and pipx-install apps."
),
)
def get_command_parser() -> argparse.ArgumentParser:
venv_container = VenvContainer(constants.PIPX_LOCAL_VENVS)
completer_venvs = InstalledVenvsCompleter(venv_container)
parser = argparse.ArgumentParser(
prog="pipx",
formatter_class=LineWrapRawTextHelpFormatter,
description=PIPX_DESCRIPTION,
)
parser.man_short_description = PIPX_DESCRIPTION.splitlines()[1] # type: ignore
subparsers = parser.add_subparsers(
dest="command", description="Get help for commands with pipx COMMAND --help"
)
_add_install(subparsers)
_add_inject(subparsers, completer_venvs.use)
_add_upgrade(subparsers, completer_venvs.use)
_add_upgrade_all(subparsers)
_add_uninstall(subparsers, completer_venvs.use)
_add_uninstall_all(subparsers)
_add_reinstall(subparsers, completer_venvs.use)
_add_reinstall_all(subparsers)
_add_list(subparsers)
_add_run(subparsers)
_add_runpip(subparsers, completer_venvs.use)
_add_ensurepath(subparsers)
parser.add_argument("--version", action="store_true", help="Print version and exit")
subparsers.add_parser(
"completions",
help="Print instructions on enabling shell completions for pipx",
description="Print instructions on enabling shell completions for pipx",
)
return parser
def delete_oldest_logs(file_list: List[Path], keep_number: int) -> None:
file_list = sorted(file_list)
if len(file_list) > keep_number:
for existing_file in file_list[:-keep_number]:
try:
existing_file.unlink()
except FileNotFoundError:
pass
def setup_log_file() -> Path:
max_logs = 10
# don't use utils.mkdir, to prevent emission of log message
constants.PIPX_LOG_DIR.mkdir(parents=True, exist_ok=True)
delete_oldest_logs(list(constants.PIPX_LOG_DIR.glob("cmd_*[0-9].log")), max_logs)
delete_oldest_logs(
list(constants.PIPX_LOG_DIR.glob("cmd_*_pip_errors.log")), max_logs
)
datetime_str = time.strftime("%Y-%m-%d_%H.%M.%S")
log_file = constants.PIPX_LOG_DIR / f"cmd_{datetime_str}.log"
counter = 1
while log_file.exists() and counter < 10:
log_file = constants.PIPX_LOG_DIR / f"cmd_{datetime_str}_{counter}.log"
counter += 1
return log_file
def setup_logging(verbose: bool) -> None:
pipx_str = bold(green("pipx >")) if sys.stdout.isatty() else "pipx >"
pipx.constants.pipx_log_file = setup_log_file()
# "incremental" is False so previous pytest tests don't accumulate handlers
logging_config = {
"version": 1,
"formatters": {
"stream_nonverbose": {
"class": "logging.Formatter",
"format": "{message}",
"style": "{",
},
"stream_verbose": {
"class": "logging.Formatter",
"format": pipx_str + "({funcName}:{lineno}): {message}",
"style": "{",
},
"file": {
"class": "logging.Formatter",
"format": "{relativeCreated: >8.1f}ms ({funcName}:{lineno}): {message}",
"style": "{",
},
},
"handlers": {
"stream": {
"class": "logging.StreamHandler",
"formatter": "stream_verbose" if verbose else "stream_nonverbose",
"level": "INFO" if verbose else "WARNING",
},
"file": {
"class": "logging.FileHandler",
"formatter": "file",
"filename": str(pipx.constants.pipx_log_file),
"encoding": "utf-8",
"level": "DEBUG",
},
},
"loggers": {"pipx": {"handlers": ["stream", "file"], "level": "DEBUG"}},
"incremental": False,
}
logging.config.dictConfig(logging_config)
def setup(args: argparse.Namespace) -> None:
if "version" in args and args.version:
print_version()
sys.exit(0)
setup_logging("verbose" in args and args.verbose)
logger.debug(f"{time.strftime('%Y-%m-%d %H:%M:%S')}")
logger.debug(f"{' '.join(sys.argv)}")
logger.info(f"pipx version is {__version__}")
logger.info(f"Default python interpreter is {repr(DEFAULT_PYTHON)}")
mkdir(constants.PIPX_LOCAL_VENVS)
mkdir(constants.LOCAL_BIN_DIR)
mkdir(constants.PIPX_VENV_CACHEDIR)
rmdir(constants.PIPX_TRASH_DIR, False)
old_pipx_venv_location = constants.PIPX_LOCAL_VENVS / "pipx-app"
if old_pipx_venv_location.exists():
logger.warning(
pipx_wrap(
f"""
{hazard} A virtual environment for pipx was detected at
{str(old_pipx_venv_location)}. The 'pipx-app' package has been
renamed back to 'pipx'
(https://github.com/pypa/pipx/issues/82).
""",
subsequent_indent=" " * 4,
)
)
def | (parsed_pipx_args: argparse.Namespace) -> None:
if parsed_pipx_args.command == "run":
# we manually discard a first -- because using nargs=argparse.REMAINDER
# will not do it automatically
if parsed_pipx_args.app_with_args and parsed_pipx_args.app_with_args[0] == "--":
parsed_pipx_args.app_with_args.pop(0)
# since we would like app to be required but not in a separate argparse
# add_argument, we implement our own missing required arg error
if not parsed_pipx_args.app_with_args:
parsed_pipx_args.subparser.error(
"the following arguments are required: app"
)
def cli() -> ExitCode:
"""Entry point from command line"""
try:
hide_cursor()
parser = get_command_parser()
argcomplete.autocomplete(parser)
parsed_pipx_args = parser.parse_args()
setup(parsed_pipx_args)
check_args(parsed_pipx_args)
if not parsed_pipx_args.command:
parser.print_help()
return ExitCode(1)
return run_pipx_command(parsed_pipx_args)
except PipxError as e:
print(str(e), file=sys.stderr)
logger.debug(f"PipxError: {e}", exc_info=True)
return ExitCode(1)
except KeyboardInterrupt:
return ExitCode(1)
except Exception:
logger.debug("Uncaught Exception:", exc_info=True)
raise
finally:
logger.debug("pipx finished.")
show_cursor()
if __name__ == "__main__":
sys.exit(cli())
| check_args |
my_db.py | # Copyright (c) [2021] [Andrii Kuts, Oleksandr Tsepkov]
import sqlite3 as sq
import csv
with sq.connect("data/server.db") as con:
cur = con.cursor()
def create_table_teams():
cur.execute("""CREATE TABLE IF NOT EXISTS teams (
team_id INTEGER PRIMARY KEY,
team_name TEXT
)""")
con.commit()
def create_table_users():
cur.execute("""CREATE TABLE IF NOT EXISTS users (
user_id INTEGER PRIMARY KEY,
nickname TEXT,
team_id INTEGER,
CONSTRAINT FK_team FOREIGN KEY (team_id) REFERENCES teams(team_id)
)""")
con.commit()
def create_table_restaurants():
cur.execute("""CREATE TABLE IF NOT EXISTS restaurants (
restaurant_id INTEGER PRIMARY KEY,
restaurant_name TEXT,
city TEXT
)""")
con.commit()
def create_table_dishes():
cur.execute("""CREATE TABLE IF NOT EXISTS dishes (
dish_id INTEGER PRIMARY KEY,
dish_name TEXT,
category TEXT,
restaurant_id INTEGER,
CONSTRAINT FK_rest FOREIGN KEY (restaurant_id) REFERENCES restaurants(restaurant_id)
)""")
con.commit()
def create_table_orders():
cur.execute("""CREATE TABLE IF NOT EXISTS orders (
order_id INTEGER PRIMARY KEY,
user_id INTEGER,
dish_id INTEGER,
order_date DATE,
CONSTRAINT FK_users FOREIGN KEY (user_id) REFERENCES users(user_id),
CONSTRAINT FK_dish FOREIGN KEY (dish_id) REFERENCES dishes(dish_id)
)""")
con.commit()
def create_table_chefs():
cur.execute("""CREATE TABLE IF NOT EXISTS chefs (
user_id INTEGER,
team_id INTEGER,
CONSTRAINT FK_teams FOREIGN KEY (team_id) REFERENCES teams(team_id),
CONSTRAINT FK_user FOREIGN KEY (user_id) REFERENCES users(user_id)
)""")
con.commit()
def add_team(team_name):
cur.execute(f"INSERT INTO teams(team_name) VALUES('{team_name}')")
con.commit()
#updated
def add_chef(user_id,team_id):
cur.execute(f"DELETE FROM chefs WHERE team_id={team_id}")
cur.execute(f"INSERT INTO chefs(user_id,team_id) VALUES({user_id},{team_id})")
con.commit()
def get_chef(team_id):
cur.execute(f"SELECT u.nickname FROM users u INNER JOIN chefs s ON u.team_id=s.team_id WHERE s.team_id={team_id}")
return cur.fetchone()[0]
def get_users_team_id(user_id):
cur.execute(f"SELECT team_id FROM users WHERE user_id = ('{user_id}')")
return cur.fetchone()[0]
def leave_team(user_id):
cur.execute(f"DELETE FROM users WHERE user_id = ({user_id})")
con.commit()
def add_user(user_id, nickname, team_id):
cur.execute("INSERT INTO users VALUES(?, ?, ?)", (user_id, nickname, team_id))
con.commit()
def add_order(user_id, dish_id, order_date):
if not user_exists(user_id):
return "You are not on any team. A great chance to create a new one!\nUse the following command:\n`$create <TEAM_NAME>`\n"
if not dish_exists(dish_id):
return "Dish with id `{}` does not exist".format(dish_id)
cur.execute("INSERT INTO orders(user_id, dish_id, order_date) VALUES(?, ?, ?)", (user_id, dish_id, order_date))
con.commit()
def | (team_id):
cur.execute(f"SELECT team_name FROM teams WHERE team_id={team_id}")
return cur.fetchone()[0]
def delete_order(user_id, order_id):
cur.execute(f"DELETE FROM orders WHERE order_id={order_id} AND user_id={user_id}")
def user_exists(user_id):
cur.execute(f"SELECT EXISTS(SELECT * FROM users WHERE user_id={user_id} LIMIT 1)")
return cur.fetchone()[0]
def dish_exists(dish_id):
cur.execute(f"SELECT EXISTS(SELECT * FROM dishes WHERE dish_id={dish_id} LIMIT 1)")
return cur.fetchone()[0]
def restaurant_exists(restaurant_id):
cur.execute(f"SELECT EXISTS(SELECT * FROM restaurants WHERE restaurant_id={restaurant_id} LIMIT 1)")
return cur.fetchone()[0]
def get_restaurant_name(restaurant_id):
cur.execute(f"SELECT restaurant_name FROM restaurants WHERE restaurant_id={restaurant_id}")
return cur.fetchone()[0]
def order_exists(order_id, user_id):
cur.execute(f"SELECT EXISTS(SELECT * FROM orders WHERE order_id={order_id} AND user_id={user_id} LIMIT 1)")
return cur.fetchone()[0]
def team_exists(team_id):
cur.execute(f"SELECT EXISTS(SELECT * FROM teams WHERE team_id={team_id} LIMIT 1)")
return cur.fetchone()[0]
def get_users_team_info(user_id):
cur.execute(f"SELECT t.team_id, t.team_name FROM teams t WHERE t.team_id=(SELECT u.team_id FROM users u WHERE u.user_id={user_id} LIMIT 1)")
get = cur.fetchone()
if get is None:
return "You are not on any team. A great chance to create a new one!\nUse the following command:\n`$create <TEAM_NAME>`\n"
else:
return "Your team name is: `{}`\nTeam_id: `{}`\nTeam members:\n{}".format(get[1], get[0], get_team_members(user_id))
def get_order_info(user_id):
cur.execute("SELECT DATE()")
current_date = cur.fetchone()
cur.execute(f"SELECT o.order_id, d.dish_id, d.dish_name, o.order_date FROM dishes d INNER JOIN orders o ON o.dish_id=d.dish_id WHERE o.user_id={user_id} AND o.order_date='{current_date[0]}'")
info = ""
var = cur.fetchone()
if var is None:
return "You don't make any order yet!\nUse the following command:\n`$order <YOUR_ORDER>`\n"
while var is not None:
info += ('\n' + "order_id: " + '`' + str(var[0]) + '`' + '\tdish_id: ' + '`' + str(var[1]) + '`\t`' + var[2] + '`\t`' + var[3] + '`')
var = cur.fetchone()
return "Your order is: {}".format(info)
def get_team_members(user_id):
cur.execute(f"SELECT nickname FROM users WHERE team_id=(SELECT team_id FROM users WHERE user_id={user_id})")
return str(cur.fetchall()).replace('[', '').replace('(', '').replace(',', '').replace(')', '').replace(']', '').replace("'", '`')
def get_restaurants():
cur.execute("SELECT * FROM restaurants")
l = cur.fetchall()
info = ""
for i in l:
info += ('\n' + "restaurant id: " + '`' + str(i[0]) + '`' + '\t' + '`' + i[1] + '`' + '\t' + '`' + i[2] + '`')
return info
def get_menu(restaurant_id):
cur.execute(f"SELECT * FROM dishes WHERE restaurant_id={restaurant_id}")
l = cur.fetchall()
info = ""
for i in l:
info += ('\n' + "dish id: " + '\t' + '`' + str(i[0]) + '`' + '\t' + '`' + i[1] + '`' + '\t' + '`' + i[2] + '`' )
return info
def insert_into_restaurants():
with open("data/restaurants.csv", "r") as file:
rows = csv.reader(file)
cur.executemany("INSERT INTO restaurants VALUES (?,?,?)", rows)
con.commit()
# cur.execute("SELECT * FROM restaurants")
# print(cur.fetchall())
def insert_into_dishes():
with open("data/dishes.csv", "r") as file:
rows = csv.reader(file)
cur.executemany("INSERT INTO dishes VALUES (?,?,?,?)", rows)
con.commit()
# cur.execute("SELECT * FROM dishes")
# print(cur.fetchall())
def get_my_favorite_list(user_id):
cur.execute(f"SELECT o.dish_id, r.restaurant_name, d.dish_name, COUNT(*) FROM orders o INNER JOIN dishes d ON d.dish_id=o.dish_id INNER JOIN restaurants r ON d.restaurant_id=r.restaurant_id WHERE o.user_id={user_id} GROUP BY d.dish_id ORDER BY COUNT(*) DESC LIMIT 5")
info = ""
get = cur.fetchone();
if get is None:
return "You need to make some orders first\n"
while get is not None:
info += "dish_id: " + '`' + str(get[0]) + '` ' + '`' + get[1] + '` ' + '`' + get[2] + '`''\n'
get = cur.fetchone()
return info
def get_my_team_orders(user_id):
team_id = get_users_team_id(user_id)
cur.execute("SELECT DATE()")
current_date = cur.fetchone()
cur.execute(f"SELECT u.nickname, r.restaurant_name, d.dish_name FROM orders o INNER JOIN users u ON u.user_id=o.user_id INNER JOIN dishes d ON d.dish_id=o.dish_id INNER JOIN restaurants r ON d.restaurant_id=r.restaurant_id WHERE o.order_date='{current_date[0]}' AND u.team_id={team_id}")
info = "Orders from your teammates:\n"
get = cur.fetchone()
while get is not None:
info += '`' + get[0] + '` `' + get[1] + '` `' + get[2] + '`' + '\n'
get = cur.fetchone()
return info
def drop_all():
cur.execute("PRAGMA foreign_keys = OFF")
cur.execute("DROP TABLE IF EXISTS users")
cur.execute("DROP TABLE IF EXISTS teams")
cur.execute("DROP TABLE IF EXISTS orders")
cur.execute("DROP TABLE IF EXISTS dishes")
cur.execute("DROP TABLE IF EXISTS restaurants")
cur.execute("DROP TABLE IF EXISTS chefs")
cur.execute("PRAGMA foreign_keys = ON")
con.commit() | get_team_name |
angular-route.min.js | /*
AngularJS v1.5.7-local+sha.f3377da
(c) 2010-2016 Google, Inc. http://angularjs.org
License: MIT
*/
(function(D,c){'use strict';function w(s,h,g){return{restrict:"ECA",terminal:!0,priority:400,transclude:"element",link:function(a,e,b,f,y){function k(){n&&(g.cancel(n),n=null);l&&(l.$destroy(),l=null);m&&(n=g.leave(m),n.then(function(){n=null}),m=null)}function z(){var b=s.current&&s.current.locals;if(c.isDefined(b&&b.$template)){var b=a.$new(),f=s.current;m=y(b,function(b){g.enter(b,null,m||e).then(function(){!c.isDefined(u)||u&&!a.$eval(u)||h()});k()});l=f.scope=b;l.$emit("$viewContentLoaded");
l.$eval(r)}else k()}var l,m,n,u=b.autoscroll,r=b.onload||"";a.$on("$routeChangeSuccess",z);z()}}}function v(c,h,g){return{restrict:"ECA",priority:-400,link:function(a,e){var b=g.current,f=b.locals;e.html(f.$template);var y=c(e.contents());if(b.controller){f.$scope=a;var k=h(b.controller,f);b.controllerAs&&(a[b.controllerAs]=k);e.data("$ngControllerController",k);e.children().data("$ngControllerController",k)}a[b.resolveAs||"$resolve"]=f;y(a)}}}var r=c.module("ngRoute",["ng"]).provider("$route",function(){function s(a,
e){return c.extend(Object.create(a),e)}function h(a,c){var b=c.caseInsensitiveMatch,f={originalPath:a,regexp:a},g=f.keys=[];a=a.replace(/([().])/g,"\\$1").replace(/(\/)?:(\w+)(\*\?|[\?\*])?/g,function(a,c,b,e){a="?"===e||"*?"===e?"?":null;e="*"===e||"*?"===e?"*":null;g.push({name:b,optional:!!a});c=c||"";return""+(a?"":c)+"(?:"+(a?c:"")+(e&&"(.+?)"||"([^/]+)")+(a||"")+")"+(a||"")}).replace(/([\/$\*])/g,"\\$1");f.regexp=new RegExp("^"+a+"$",b?"i":"");return f}var g={};this.when=function(a,e){var b= | "$sce",function(a,e,b,f,h,k,r){function l(q){var d=t.current;(A=(p=w())&&d&&p.$$route===d.$$route&&c.equals(p.pathParams,d.pathParams)&&!p.reloadOnSearch&&!x)||!d&&!p||a.$broadcast("$routeChangeStart",p,d).defaultPrevented&&q&&q.preventDefault()}function m(){var q=t.current,d=p;if(A)q.params=d.params,c.copy(q.params,b),a.$broadcast("$routeUpdate",q);else if(d||q){x=!1;if((t.current=d)&&d.redirectTo){var B=e.url(),g;c.isString(d.redirectTo)?(e.path(v(d.redirectTo,d.params)).search(d.params).replace(),
g=e.url()):(g=d.redirectTo(d.pathParams,e.path(),e.search()),e.url(g).replace());if(c.isDefined(g)&&B!==g)return}f.when(d).then(n).then(function(e){d===t.current&&(d&&(d.locals=e,c.copy(d.params,b)),a.$broadcast("$routeChangeSuccess",d,q))},function(c){d===t.current&&a.$broadcast("$routeChangeError",d,q,c)})}}function n(a){if(a){var d=c.extend({},a.resolve);c.forEach(d,function(a,b){d[b]=c.isString(a)?h.get(a):h.invoke(a,null,null,b)});a=u(a);c.isDefined(a)&&(d.$template=a);return f.all(d)}}function u(a){var d,
b;c.isDefined(d=a.template)?c.isFunction(d)&&(d=d(a.params)):c.isDefined(b=a.templateUrl)&&(c.isFunction(b)&&(b=b(a.params)),c.isDefined(b)&&(a.loadedTemplateUrl=r.valueOf(b),d=k(b)));return d}function w(){var a,d;c.forEach(g,function(b,g){var f;if(f=!d){var h=e.path();f=b.keys;var l={};if(b.regexp)if(h=b.regexp.exec(h)){for(var k=1,n=h.length;k<n;++k){var m=f[k-1],p=h[k];m&&p&&(l[m.name]=p)}f=l}else f=null;else f=null;f=a=f}f&&(d=s(b,{params:c.extend({},e.search(),a),pathParams:a}),d.$$route=b)});
return d||g[null]&&s(g[null],{params:{},pathParams:{}})}function v(a,b){var e=[];c.forEach((a||"").split(":"),function(a,c){if(0===c)e.push(a);else{var f=a.match(/(\w+)(?:[?*])?(.*)/),g=f[1];e.push(b[g]);e.push(f[2]||"");delete b[g]}});return e.join("")}var x=!1,p,A,t={routes:g,reload:function(){x=!0;var b={defaultPrevented:!1,preventDefault:function(){this.defaultPrevented=!0;x=!1}};a.$evalAsync(function(){l(b);b.defaultPrevented||m()})},updateParams:function(a){if(this.current&&this.current.$$route)a=
c.extend({},this.current.params,a),e.path(v(this.current.$$route.originalPath,a)),e.search(a);else throw C("norout");}};a.$on("$locationChangeStart",l);a.$on("$locationChangeSuccess",m);return t}]}),C=c.$$minErr("ngRoute");r.provider("$routeParams",function(){this.$get=function(){return{}}});r.directive("ngView",w);r.directive("ngView",v);w.$inject=["$route","$anchorScroll","$animate"];v.$inject=["$compile","$controller","$route"]})(window,window.angular);
//# sourceMappingURL=angular-route.min.js.map | c.copy(e);c.isUndefined(b.reloadOnSearch)&&(b.reloadOnSearch=!0);c.isUndefined(b.caseInsensitiveMatch)&&(b.caseInsensitiveMatch=this.caseInsensitiveMatch);g[a]=c.extend(b,a&&h(a,b));if(a){var f="/"===a[a.length-1]?a.substr(0,a.length-1):a+"/";g[f]=c.extend({redirectTo:a},h(f,b))}return this};this.caseInsensitiveMatch=!1;this.otherwise=function(a){"string"===typeof a&&(a={redirectTo:a});this.when(null,a);return this};this.$get=["$rootScope","$location","$routeParams","$q","$injector","$templateRequest", |
FHIR_AdverseEvent_SuspectEntity.py | from typing import Any, List, Literal, TypedDict
|
# Actual or potential/avoided event causing unintended physical injury resulting from or contributed to by medical care, a research study or other healthcare setting factors that requires additional monitoring, treatment, or hospitalization, or that results in death.
FHIR_AdverseEvent_SuspectEntity = TypedDict(
"FHIR_AdverseEvent_SuspectEntity",
{
# Unique id for the element within a resource (for internal references). This may be any string value that does not contain spaces.
"id": FHIR_string,
# May be used to represent additional information that is not part of the basic definition of the element. To make the use of extensions safe and manageable, there is a strict set of governance applied to the definition and use of extensions. Though any implementer can define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension.
"extension": List[Any],
# May be used to represent additional information that is not part of the basic definition of the element and that modifies the understanding of the element in which it is contained and/or the understanding of the containing element's descendants. Usually modifier elements provide negation or qualification. To make the use of extensions safe and manageable, there is a strict set of governance applied to the definition and use of extensions. Though any implementer can define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension. Applications processing a resource are required to check for modifier extensions.Modifier extensions SHALL NOT change the meaning of any elements on Resource or DomainResource (including cannot change the meaning of modifierExtension itself).
"modifierExtension": List[Any],
# Identifies the actual instance of what caused the adverse event. May be a substance, medication, medication administration, medication statement or a device.
"instance": FHIR_Reference,
# Information on the possible cause of the event.
"causality": List[FHIR_AdverseEvent_Causality],
},
total=False,
) | from .FHIR_AdverseEvent_Causality import FHIR_AdverseEvent_Causality
from .FHIR_Reference import FHIR_Reference
from .FHIR_string import FHIR_string |
mod.rs | use crate::Num;
use proc_macro2::{Ident, Span, TokenStream};
use quote::{quote, ToTokens};
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
pub(crate) mod deku_read;
pub(crate) mod deku_write;
#[cfg(feature = "proc-macro-crate")]
fn get_crate_name() -> Ident {
let found_crate =
proc_macro_crate::crate_name("deku").unwrap_or(proc_macro_crate::FoundCrate::Itself);
let crate_name = match found_crate {
proc_macro_crate::FoundCrate::Itself => "deku".to_string(),
proc_macro_crate::FoundCrate::Name(name) => name,
};
Ident::new(&crate_name, Span::call_site())
}
// proc-macro-crate depends on std, for no_std, use default name. Sorry.
#[cfg(not(feature = "proc-macro-crate"))]
fn | () -> Ident {
Ident::new("deku", Span::call_site())
}
/// Generate enum initialization TokenStream
/// Cases:
/// - No fields: `MyEnum`
/// - Named: `MyEnum { field_idents }`
/// - Unnamed: `MyEnum ( field_idents )`
fn gen_enum_init<V: ToTokens, I: ToTokens>(
is_named: bool,
enum_variant: V,
field_idents: Vec<I>,
) -> TokenStream {
if field_idents.is_empty() {
return quote! { #enum_variant };
}
if is_named {
quote! {
#enum_variant {
#(#field_idents),*
}
}
} else {
quote! {
#enum_variant (
#(#field_idents),*
)
}
}
}
/// Generate struct initialization TokenStream
/// Cases:
/// - No fields: `Self {}`
/// - Named: `Self { field_idents }`
/// - Unnamed: `Self ( field_idents )`
fn gen_struct_init<I: ToTokens>(is_named: bool, field_idents: Vec<I>) -> TokenStream {
if field_idents.is_empty() {
return quote! { Self {} };
}
if is_named {
quote! {
Self {
#(#field_idents),*
}
}
} else {
quote! {
Self (
#(#field_idents),*
)
}
}
}
/// Generate struct destruction
///
/// - Named: `#ident { ref fields }`
/// - Unnamed: `#ident ( ref fields )`
fn gen_struct_destruction<I: ToTokens, F: ToTokens>(
named: bool,
ident: I,
field_idents: &[F],
) -> TokenStream {
if named {
quote! {
#ident {
#(ref #field_idents),*
}
}
} else {
quote! {
#ident (
#(ref #field_idents),*
)
}
}
}
/// Convert a field ident to internal ident:
/// `a` -> `__deku_a`
fn gen_internal_field_ident(ident: &TokenStream) -> TokenStream {
// Concat token: https://github.com/rust-lang/rust/issues/29599
let span = ident.span();
let s = ident.to_string();
let mut name = "__deku_".to_owned();
// If its a raw identifier, we must remove 'r#'
name.push_str(s.strip_prefix("r#").unwrap_or(&s));
syn::Ident::new(&name, span).to_token_stream()
}
/// Map all field indents to internal idents
///
/// - Named: `{ a: __deku_a }`
/// - Unnamed: `( __deku_a )`
fn gen_internal_field_idents(named: bool, idents: Vec<&TokenStream>) -> Vec<TokenStream> {
if named {
idents
.into_iter()
.map(|i| (i.clone(), gen_internal_field_ident(i)))
.map(|(i, h)| quote! {#i: #h})
.collect()
} else {
idents.into_iter().map(gen_internal_field_ident).collect()
}
}
fn split_ctx_to_pats_and_types(
ctx: &Punctuated<syn::FnArg, syn::token::Comma>,
) -> syn::Result<Vec<(&syn::Pat, &syn::Type)>> {
// `()` or `(u8, u32)`
ctx.iter()
.map(|arg| {
match arg {
syn::FnArg::Typed(pat_type) => Ok((pat_type.pat.as_ref(), pat_type.ty.as_ref())),
// a self is unacceptable
syn::FnArg::Receiver(r) => Err(syn::Error::new(r.span(), "Unacceptable context")),
}
})
.collect::<Result<Vec<_>, _>>()
}
/// Generate ctx types and argument
///
/// - Empty: arg: `(): ()`, type: `()`
/// - One: arg: `a: usize`, type: `usize`
/// - Other: arg: `(a, b, ...): (u8, u8, ...)`, type: `(u8, u8, ...)`
fn gen_ctx_types_and_arg(
ctx: Option<&Punctuated<syn::FnArg, syn::token::Comma>>,
) -> syn::Result<(TokenStream, TokenStream)> {
if let Some(ctx) = ctx {
let pats_types = split_ctx_to_pats_and_types(ctx)?;
if pats_types.len() == 1 {
// remove parens for single item
let (pat, ty) = pats_types[0];
Ok((quote! {#ty}, quote! {#pat:#ty}))
} else {
let pats = pats_types.iter().map(|(pat, _)| pat);
let types = pats_types.iter().map(|(_, ty)| ty);
// "a: u8, b: usize" -> (u8, usize)
let types_cpy = types.clone();
let ctx_types = quote! {(#(#types_cpy),*)};
// "a: u8, b: usize" -> (a, b): (u8, usize)
let ctx_arg = quote! {(#(#pats),*): (#(#types),*)};
Ok((ctx_types, ctx_arg))
}
} else {
Ok((quote! {()}, quote! {_: ()}))
}
}
/// Generate type from matching ident from `id` in `ctx`
///
/// Given #[deku(ctx = "test: u16, my_id: u8", id = "my_id")], will return `u8`
fn gen_type_from_ctx_id(
ctx: &Punctuated<syn::FnArg, syn::token::Comma>,
id: &crate::Id,
) -> Option<TokenStream> {
let id = syn::Ident::new(&id.to_string(), id.span());
ctx.iter().find_map(|arg| {
if let syn::FnArg::Typed(pat_type) = arg {
if let syn::Pat::Ident(ident) = &*pat_type.pat {
if id == ident.ident {
let t = &pat_type.ty;
return Some(quote! {#t});
}
}
}
None
})
}
/// Generate argument for `id`:
/// `#deku(endian = "big", bits = "1")` -> `Endian::Big, Size::Bits(1)`
pub(crate) fn gen_id_args(
endian: Option<&syn::LitStr>,
bits: Option<&Num>,
bytes: Option<&Num>,
) -> syn::Result<TokenStream> {
let crate_ = get_crate_name();
let endian = endian.map(gen_endian_from_str).transpose()?;
let bits = bits.map(|n| quote! {::#crate_::ctx::Size::Bits(#n)});
let bytes = bytes.map(|n| quote! {::#crate_::ctx::Size::Bytes(#n)});
// FIXME: Should be `into_iter` here, see https://github.com/rust-lang/rust/issues/66145.
let id_args = [endian.as_ref(), bits.as_ref(), bytes.as_ref()]
.iter()
.filter_map(|i| *i)
.collect::<Vec<_>>();
match &id_args[..] {
[arg] => Ok(quote! {#arg}),
args => Ok(quote! {#(#args),*}),
}
}
/// Generate argument for fields:
///
/// `#deku(endian = "big", bits = "1", ctx = "a")` -> `Endian::Big, Size::Bits(1), a`
fn gen_field_args(
endian: Option<&syn::LitStr>,
bits: Option<&Num>,
bytes: Option<&Num>,
ctx: Option<&Punctuated<syn::Expr, syn::token::Comma>>,
) -> syn::Result<TokenStream> {
let crate_ = get_crate_name();
let endian = endian.map(gen_endian_from_str).transpose()?;
let bits = bits.map(|n| quote! {::#crate_::ctx::Size::Bits(#n)});
let bytes = bytes.map(|n| quote! {::#crate_::ctx::Size::Bytes(#n)});
let ctx = ctx.map(|c| quote! {#c});
// FIXME: Should be `into_iter` here, see https://github.com/rust-lang/rust/issues/66145.
let field_args = [endian.as_ref(), bits.as_ref(), bytes.as_ref(), ctx.as_ref()]
.iter()
.filter_map(|i| *i)
.collect::<Vec<_>>();
// Because `impl DekuRead<'_, (T1, T2)>` but `impl DekuRead<'_, T1>`(not tuple)
match &field_args[..] {
[arg] => Ok(quote! {#arg}),
args => Ok(quote! {#(#args),*}),
}
}
/// Generate endian tokens from string: `big` -> `Endian::Big`.
fn gen_endian_from_str(s: &syn::LitStr) -> syn::Result<TokenStream> {
let crate_ = get_crate_name();
match s.value().as_str() {
"little" => Ok(quote! {::#crate_::ctx::Endian::Little}),
"big" => Ok(quote! {::#crate_::ctx::Endian::Big}),
_ => {
// treat as variable, possibly from `ctx`
let v: TokenStream = s.value().parse()?;
Ok(quote! {#v})
}
}
}
/// Wraps a TokenStream with a closure providing access to `ctx` variables when
/// `ctx_default` is provided
fn wrap_default_ctx(
body: TokenStream,
ctx: &Option<syn::punctuated::Punctuated<syn::FnArg, syn::token::Comma>>,
ctx_default: &Option<Punctuated<syn::Expr, syn::token::Comma>>,
) -> TokenStream {
if let (Some(ctx), Some(ctx_default)) = (ctx, ctx_default) {
// wrap in a function to make `ctx` variables in scope
quote! {
|#ctx| -> Result<_, _> {
#body
}(#ctx_default)
}
} else {
body
}
}
/// Returns true if the literal substring `s` is in the token
fn token_contains_string(tok: &Option<TokenStream>, s: &str) -> bool {
tok.as_ref()
.map(|v| {
let v = v.to_string();
v.contains(s)
})
.unwrap_or(false)
}
fn pad_bits(
bits: Option<&TokenStream>,
bytes: Option<&TokenStream>,
emit_padding: fn(&TokenStream) -> TokenStream,
) -> TokenStream {
match (bits, bytes) {
(Some(pad_bits), Some(pad_bytes)) => {
emit_padding("e! { (#pad_bits) + ((#pad_bytes) * 8) })
}
(Some(pad_bits), None) => emit_padding(pad_bits),
(None, Some(pad_bytes)) => emit_padding("e! {((#pad_bytes) * 8)}),
(None, None) => quote!(),
}
}
| get_crate_name |
store_test.go | package scheduler
import (
"testing"
"github.com/sapiens-sapide/scheduler/storage"
"github.com/sapiens-sapide/scheduler/task"
)
func TestStore(t *testing.T) {
mock := task.CallbackMock{}
funcRegistry := task.NewFuncRegistry()
store := getStoreBridge(funcRegistry, nil)
task := newTask(funcRegistry, mock.CallNoArgs)
task.IsRecurring = true
err := store.Add(task)
if err != nil {
t.Error("Failed to store task")
}
}
func TestStoreTaskWithMultipleParams(t *testing.T) {
mock := task.CallbackMock{}
funcRegistry := task.NewFuncRegistry()
store := getStoreBridge(funcRegistry, nil)
task := newTask(funcRegistry, mock.CallWithArgs, "Hello", "World")
err := store.Add(task)
if err != nil {
t.Error("Failed to store task with multiple params")
}
}
func TestStoreThatFails(t *testing.T) {
mock := task.CallbackMock{}
funcRegistry := task.NewFuncRegistry()
store := getStoreBridge(funcRegistry, nil)
task := newTask(funcRegistry, mock.CallWithChan, make(chan bool))
err := store.Add(task)
if err == nil {
t.Error("Wrong storage of a task with a channel arg took place")
}
}
func | (t *testing.T) {
mock := task.CallbackMock{}
funcRegistry := task.NewFuncRegistry()
store := getStoreBridge(funcRegistry, nil)
task := newTask(funcRegistry, mock.CallWithArgs, "Hello", "World")
_ = store.Add(task)
err := store.Remove(task)
if err != nil {
t.Error("Failed to remove task")
}
}
func TestRemoveThatFails(t *testing.T) {
mock := task.CallbackMock{}
funcRegistry := task.NewFuncRegistry()
store := getStoreBridge(funcRegistry, nil)
task := newTask(funcRegistry, mock.CallWithChan, make(chan bool))
err := store.Remove(task)
if err == nil {
t.Error("Wrong call to remove a task with a channel arg took place")
}
}
func TestFetch(t *testing.T) {
mock := task.CallbackMock{}
funcRegistry := task.NewFuncRegistry()
store := getStoreBridge(funcRegistry, nil)
task := newTask(funcRegistry, mock.CallNoArgs)
err := store.Add(task)
if err != nil {
t.Error("Failed to store task")
}
tasks, err := store.Fetch()
if err != nil {
t.Error("Could not read tasks from store")
}
if len(tasks) != 1 {
t.Error("Found wrong task count")
}
}
func TestFetchWithParams(t *testing.T) {
mock := task.CallbackMock{}
funcRegistry := task.NewFuncRegistry()
store := getStoreBridge(funcRegistry, nil)
task := newTask(funcRegistry, mock.CallWithArgs, "Test", true)
err := store.Add(task)
if err != nil {
t.Error("Failed to store task")
}
tasks, err := store.Fetch()
if err != nil {
t.Error("Could not read tasks from store")
}
if len(tasks) != 1 {
t.Error("Found wrong task count")
}
}
func TestFetchWrongRunTimes(t *testing.T) {
funcRegistry := task.NewFuncRegistry()
storeMock := newStoreMockWithMode(fail)
store := getStoreBridge(funcRegistry, storeMock)
_, err := store.Fetch()
if err == nil {
t.Error("Should fail when fetching")
}
storeMock.Mode = failOnLastRun
_, err = store.Fetch()
if err == nil {
t.Error("Should fail when parsing lastRun")
}
storeMock.Mode = failOnNextRun
_, err = store.Fetch()
if err == nil {
t.Error("Should fail when parsing nextRun")
}
storeMock.Mode = failOnDuration
_, err = store.Fetch()
if err == nil {
t.Error("Should fail when parsing duration")
}
storeMock.Mode = failOnIsRecurring
_, err = store.Fetch()
if err == nil {
t.Error("Should fail when parsing isRecurring")
}
funcRegistry.Add(mockFunction)
storeMock.Mode = failOnFuncMeta
_, err = store.Fetch()
if err == nil {
t.Error("Should fail when trying to find function")
}
storeMock.Mode = failOnEmptyParams
params, err := store.Fetch()
if err != nil && len(params) != 0 {
t.Error("Should fail when trying to parse empty string params")
}
storeMock.Mode = failOnEmptyListParams
_, err = store.Fetch()
if err == nil {
t.Error("Should fail when trying to parse empty string params")
}
}
func newTask(funcRegistry *task.FuncRegistry, function task.Function, params ...task.Param) *task.Task {
funcMeta, err := funcRegistry.Add(function)
if err != nil {
return nil
}
task := task.New(funcMeta, params)
_, _ = funcRegistry.Add(task.Func)
return task
}
func getStoreBridge(funcRegistry *task.FuncRegistry, store storage.TaskStore) storeBridge {
if store == nil {
store = storage.NewMemoryStorage()
}
storeBridge := storeBridge{
store: store,
funcRegistry: funcRegistry,
}
return storeBridge
}
| TestRemoveTask |
main.go | package main
import (
"context"
"fmt"
"log"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/networth-app/networth/lib"
)
var (
plaidClientID = nwlib.GetEnv("PLAID_CLIENT_ID")
plaidSecret = nwlib.GetEnv("PLAID_SECRET")
plaidPublicKey = nwlib.GetEnv("PLAID_PUBLIC_KEY")
plaidEnv = nwlib.GetEnv("PLAID_ENV")
plaidClient = nwlib.NewPlaidClient(plaidClientID, plaidSecret, plaidPublicKey, plaidEnv)
kms = nwlib.NewKMSClient()
db = nwlib.NewDynamoDBClient()
snsARN = nwlib.GetEnv("SNS_TOPIC_ARN")
)
func handleScheduledEvent(ctx context.Context, e events.CloudWatchEvent) |
func main() {
lambda.Start(handleScheduledEvent)
}
| {
users, err := db.GetAllUsers()
processedUsers := make(map[string]string)
if err != nil {
log.Printf("Problem getting all users: %+v", err)
return
}
for _, user := range users {
// ignore processed users:
if _, existed := processedUsers[user.Username]; existed {
log.Printf("Skipping sync for processed username: %s", user.Username)
continue
}
log.Printf("Sync started for username: %s\n", user.Username)
tokens, err := db.GetTokens(kms, user.Username)
if err != nil {
log.Printf("Problem getting tokens: %+v", err)
}
for _, token := range tokens {
// ignore token with known error:
if token.Error != "" {
log.Printf("Skipping sync for token with error: %s", token.Error)
continue
}
if err := nwlib.SyncAccounts(plaidClient, db, &token); err != nil {
errMsg := fmt.Sprintf("Problem syncing accounts for username: %s, item id: %s\n %+v", user.Username, token.ItemID, err)
log.Println(errMsg)
nwlib.PublishSNS(snsARN, errMsg)
panic(err)
}
}
if err := nwlib.SyncNetworth(db, user.Username); err != nil {
log.Printf("Problem syncing networth: %+v", err)
}
processedUsers[user.Username] = user.Username
}
log.Println("Sync done.")
} |
main.py | import pathgraph
import robotsearch
import unittest
class TestGraphMethods(unittest.TestCase):
|
def main():
unittest.main()
if __name__ == "__main__":
main() | def test_create_undirected_graph(self):
self.assertTrue(isinstance(pathgraph.graph_by_type("undirected"), pathgraph.UndirectedGraph))
def test_create_directed_graph(self):
self.assertTrue(isinstance(pathgraph.graph_by_type("directed"), pathgraph.DirectedGraph))
def test_add_duplicate_edge_undirected(self):
graph = pathgraph.graph_by_type("undirected")
destination = pathgraph.DestinationNode("B", 1)
self.assertTrue(graph.add_edge(fromKey="A", destination=destination))
self.assertFalse(graph.add_edge(fromKey="A", destination=destination))
def test_add_duplicate_edge_directed(self):
graph=pathgraph.graph_by_type("directed")
destination = pathgraph.DestinationNode("B", 1)
self.assertTrue(graph.add_edge(fromKey="A", destination=destination))
self.assertFalse(graph.add_edge(fromKey="A", destination=destination)) |
tagged_test.go | package uploader
import (
"fmt"
"net/url"
"strconv"
"strings"
"testing"
"github.com/lomik/carbon-clickhouse/helper/RowBinary"
"github.com/lomik/carbon-clickhouse/helper/escape"
"github.com/lomik/zapwriter"
"github.com/stretchr/testify/assert"
)
func TestUrlParse(t *testing.T) {
assert := assert.New(t)
// make metric name as receiver
metric := escape.Path("instance:cpu_utilization:ratio_avg") +
"?" + escape.Query("dc") + "=" + escape.Query("qwe") +
"&" + escape.Query("fqdn") + "=" + escape.Query("asd") +
"&" + escape.Query("instance") + "=" + escape.Query("10.33.10.10:9100") +
"&" + escape.Query("job") + "=" + escape.Query("node")
assert.Equal("instance:cpu_utilization:ratio_avg?dc=qwe&fqdn=asd&instance=10.33.10.10%3A9100&job=node", metric)
// original url.Parse
m, err := url.Parse(metric)
assert.NotNil(m)
assert.NoError(err)
assert.Equal("", m.Path)
// from tagged uploader
m, err = urlParse(metric)
assert.NotNil(m)
assert.NoError(err)
assert.Equal("instance:cpu_utilization:ratio_avg", m.Path)
}
func BenchmarkKeySprintf(b *testing.B) {
path := "test.path"
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = fmt.Sprintf("%d:%s", 1285, path)
}
}
func BenchmarkKeyConcat(b *testing.B) {
path := "test.path"
var unum uint16 = 1245
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = strconv.Itoa(int(unum)) + ":" + path
}
}
func TestTagged_parseName_Overflow(t *testing.T) {
var tag1 []string
wb := RowBinary.GetWriteBuffer() | defer tagsBuf.Release()
logger := zapwriter.Logger("upload")
base := &Base{
queue: make(chan string, 1024),
inQueue: make(map[string]bool),
logger: logger,
config: &Config{TableName: "test"},
}
var sb strings.Builder
sb.WriteString("very_long_name_field1.very_long_name_field2.very_long_name_field3.very_long_name_field4?")
for i := 0; i < 100; i++ {
if i > 0 {
sb.WriteString("&")
}
sb.WriteString(fmt.Sprintf("very_long_tag%d=very_long_value%d", i, i))
}
u := NewTagged(base)
err := u.parseName(sb.String(), 10, tag1, wb, tagsBuf)
assert.Equal(t, errBufOverflow, err)
} | tagsBuf := RowBinary.GetWriteBuffer()
defer wb.Release() |
f7181b87434e6a3a078b7f233f6a61d24e5fe9ccbase.py | from __future__ import absolute_import
import os
import sys
from django.core.management.base import BaseCommand
import celery
import djcelery
DB_SHARED_THREAD = """\
DatabaseWrapper objects created in a thread can only \
be used in that same thread. The object with alias '%s' \
was created in thread id %s and this is thread id %s.\
"""
def patch_thread_ident():
# monkey patch django.
# This patch make sure that we use real threads to get the ident which
# is going to happen if we are using gevent or eventlet.
# -- patch taken from gunicorn
if getattr(patch_thread_ident, 'called', False):
return
try:
from django.db.backends import BaseDatabaseWrapper, DatabaseError
if 'validate_thread_sharing' in BaseDatabaseWrapper.__dict__:
import thread
_get_ident = thread.get_ident
__old__init__ = BaseDatabaseWrapper.__init__
def _init(self, *args, **kwargs):
__old__init__(self, *args, **kwargs)
self._thread_ident = _get_ident()
def _validate_thread_sharing(self):
if (not self.allow_thread_sharing
and self._thread_ident != _get_ident()):
|
BaseDatabaseWrapper.__init__ = _init
BaseDatabaseWrapper.validate_thread_sharing = \
_validate_thread_sharing
patch_thread_ident.called = True
except ImportError:
pass
patch_thread_ident()
class CeleryCommand(BaseCommand):
options = BaseCommand.option_list
skip_opts = ['--app', '--loader', '--config']
keep_base_opts = False
def get_version(self):
return 'celery %s\ndjango-celery %s' % (celery.__version__,
djcelery.__version__)
def execute(self, *args, **options):
broker = options.get('broker')
if broker:
self.set_broker(broker)
super(CeleryCommand, self).execute(*args, **options)
def set_broker(self, broker):
os.environ['CELERY_BROKER_URL'] = broker
def run_from_argv(self, argv):
self.handle_default_options(argv[2:])
return super(CeleryCommand, self).run_from_argv(argv)
def handle_default_options(self, argv):
acc = []
broker = None
for i, arg in enumerate(argv):
if '--settings=' in arg:
_, settings_module = arg.split('=')
os.environ['DJANGO_SETTINGS_MODULE'] = settings_module
elif '--pythonpath=' in arg:
_, pythonpath = arg.split('=')
sys.path.insert(0, pythonpath)
elif '--broker=' in arg:
_, broker = arg.split('=')
elif arg == '-b':
broker = argv[i + 1]
else:
acc.append(arg)
if broker:
self.set_broker(broker)
return argv if self.keep_base_opts else acc
def die(self, msg):
sys.stderr.write(msg)
sys.stderr.write('\n')
sys.exit()
@property
def option_list(self):
return [x for x in self.options
if x._long_opts[0] not in self.skip_opts]
| raise DatabaseError(
DB_SHARED_THREAD % (
self.alias, self._thread_ident, _get_ident()),
) |
managers.go | package storsimple
// 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.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"net/http"
)
// ManagersClient is the client for the Managers methods of the Storsimple service.
type ManagersClient struct {
BaseClient
}
// NewManagersClient creates an instance of the ManagersClient client.
func NewManagersClient(subscriptionID string) ManagersClient {
return NewManagersClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewManagersClientWithBaseURI creates an instance of the ManagersClient client.
func NewManagersClientWithBaseURI(baseURI string, subscriptionID string) ManagersClient {
return ManagersClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// CreateExtendedInfo creates the extended info of the manager.
//
// parameters is the manager extended information. resourceGroupName is the resource group name managerName is the
// manager name
func (client ManagersClient) CreateExtendedInfo(ctx context.Context, parameters ManagerExtendedInfo, resourceGroupName string, managerName string) (result ManagerExtendedInfo, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: parameters,
Constraints: []validation.Constraint{{Target: "parameters.ManagerExtendedInfoProperties", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "parameters.ManagerExtendedInfoProperties.IntegrityKey", Name: validation.Null, Rule: true, Chain: nil},
{Target: "parameters.ManagerExtendedInfoProperties.Algorithm", Name: validation.Null, Rule: true, Chain: nil},
}}}},
{TargetValue: managerName,
Constraints: []validation.Constraint{{Target: "managerName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "managerName", Name: validation.MinLength, Rule: 2, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "storsimple.ManagersClient", "CreateExtendedInfo")
}
req, err := client.CreateExtendedInfoPreparer(ctx, parameters, resourceGroupName, managerName)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "CreateExtendedInfo", nil, "Failure preparing request")
return
}
resp, err := client.CreateExtendedInfoSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "CreateExtendedInfo", resp, "Failure sending request")
return
}
result, err = client.CreateExtendedInfoResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "CreateExtendedInfo", resp, "Failure responding to request")
}
return
}
// CreateExtendedInfoPreparer prepares the CreateExtendedInfo request.
func (client ManagersClient) CreateExtendedInfoPreparer(ctx context.Context, parameters ManagerExtendedInfo, resourceGroupName string, managerName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"managerName": managerName,
"resourceGroupName": resourceGroupName,
"subscriptionId": client.SubscriptionID,
}
const APIVersion = "2017-06-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPut(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/extendedInformation/vaultExtendedInfo", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CreateExtendedInfoSender sends the CreateExtendedInfo request. The method will close the
// http.Response Body if it receives an error.
func (client ManagersClient) CreateExtendedInfoSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// CreateExtendedInfoResponder handles the response to the CreateExtendedInfo request. The method always
// closes the http.Response Body.
func (client ManagersClient) CreateExtendedInfoResponder(resp *http.Response) (result ManagerExtendedInfo, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// CreateOrUpdate creates or updates the manager.
//
// parameters is the manager. resourceGroupName is the resource group name managerName is the manager name
func (client ManagersClient) CreateOrUpdate(ctx context.Context, parameters Manager, resourceGroupName string, managerName string) (result Manager, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: parameters,
Constraints: []validation.Constraint{{Target: "parameters.ManagerProperties", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "parameters.ManagerProperties.Sku", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "parameters.ManagerProperties.Sku.Name", Name: validation.Null, Rule: true, Chain: nil}}},
}}}},
{TargetValue: managerName,
Constraints: []validation.Constraint{{Target: "managerName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "managerName", Name: validation.MinLength, Rule: 2, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "storsimple.ManagersClient", "CreateOrUpdate")
}
req, err := client.CreateOrUpdatePreparer(ctx, parameters, resourceGroupName, managerName)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "CreateOrUpdate", nil, "Failure preparing request")
return
}
resp, err := client.CreateOrUpdateSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "CreateOrUpdate", resp, "Failure sending request")
return
}
result, err = client.CreateOrUpdateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "CreateOrUpdate", resp, "Failure responding to request")
}
return
}
// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
func (client ManagersClient) CreateOrUpdatePreparer(ctx context.Context, parameters Manager, resourceGroupName string, managerName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"managerName": managerName,
"resourceGroupName": resourceGroupName,
"subscriptionId": client.SubscriptionID,
}
const APIVersion = "2017-06-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPut(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the
// http.Response Body if it receives an error.
func (client ManagersClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always
// closes the http.Response Body.
func (client ManagersClient) CreateOrUpdateResponder(resp *http.Response) (result Manager, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Delete deletes the manager.
//
// resourceGroupName is the resource group name managerName is the manager name
func (client ManagersClient) Delete(ctx context.Context, resourceGroupName string, managerName string) (result autorest.Response, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: managerName,
Constraints: []validation.Constraint{{Target: "managerName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "managerName", Name: validation.MinLength, Rule: 2, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "storsimple.ManagersClient", "Delete")
}
req, err := client.DeletePreparer(ctx, resourceGroupName, managerName)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "Delete", nil, "Failure preparing request")
return
}
resp, err := client.DeleteSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "Delete", resp, "Failure sending request")
return
}
result, err = client.DeleteResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "Delete", resp, "Failure responding to request")
}
return
}
// DeletePreparer prepares the Delete request.
func (client ManagersClient) DeletePreparer(ctx context.Context, resourceGroupName string, managerName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"managerName": managerName,
"resourceGroupName": resourceGroupName,
"subscriptionId": client.SubscriptionID,
}
const APIVersion = "2017-06-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client ManagersClient) DeleteSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client ManagersClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),
autorest.ByClosing())
result.Response = resp
return
}
// DeleteExtendedInfo deletes the extended info of the manager.
//
// resourceGroupName is the resource group name managerName is the manager name
func (client ManagersClient) DeleteExtendedInfo(ctx context.Context, resourceGroupName string, managerName string) (result autorest.Response, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: managerName,
Constraints: []validation.Constraint{{Target: "managerName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "managerName", Name: validation.MinLength, Rule: 2, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "storsimple.ManagersClient", "DeleteExtendedInfo")
}
req, err := client.DeleteExtendedInfoPreparer(ctx, resourceGroupName, managerName)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "DeleteExtendedInfo", nil, "Failure preparing request")
return
}
resp, err := client.DeleteExtendedInfoSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "DeleteExtendedInfo", resp, "Failure sending request")
return
}
result, err = client.DeleteExtendedInfoResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "DeleteExtendedInfo", resp, "Failure responding to request")
}
return
}
// DeleteExtendedInfoPreparer prepares the DeleteExtendedInfo request.
func (client ManagersClient) DeleteExtendedInfoPreparer(ctx context.Context, resourceGroupName string, managerName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"managerName": managerName,
"resourceGroupName": resourceGroupName,
"subscriptionId": client.SubscriptionID,
}
const APIVersion = "2017-06-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/extendedInformation/vaultExtendedInfo", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteExtendedInfoSender sends the DeleteExtendedInfo request. The method will close the
// http.Response Body if it receives an error.
func (client ManagersClient) DeleteExtendedInfoSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// DeleteExtendedInfoResponder handles the response to the DeleteExtendedInfo request. The method always
// closes the http.Response Body.
func (client ManagersClient) DeleteExtendedInfoResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),
autorest.ByClosing())
result.Response = resp
return
}
// Get returns the properties of the specified manager name.
//
// resourceGroupName is the resource group name managerName is the manager name
func (client ManagersClient) Get(ctx context.Context, resourceGroupName string, managerName string) (result Manager, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: managerName,
Constraints: []validation.Constraint{{Target: "managerName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "managerName", Name: validation.MinLength, Rule: 2, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "storsimple.ManagersClient", "Get")
}
req, err := client.GetPreparer(ctx, resourceGroupName, managerName)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "Get", resp, "Failure responding to request")
}
return
}
// GetPreparer prepares the Get request.
func (client ManagersClient) GetPreparer(ctx context.Context, resourceGroupName string, managerName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"managerName": managerName,
"resourceGroupName": resourceGroupName,
"subscriptionId": client.SubscriptionID,
}
const APIVersion = "2017-06-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client ManagersClient) GetSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client ManagersClient) GetResponder(resp *http.Response) (result Manager, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// GetActivationKey returns the activation key of the manager.
//
// resourceGroupName is the resource group name managerName is the manager name
func (client ManagersClient) GetActivationKey(ctx context.Context, resourceGroupName string, managerName string) (result Key, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: managerName,
Constraints: []validation.Constraint{{Target: "managerName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "managerName", Name: validation.MinLength, Rule: 2, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "storsimple.ManagersClient", "GetActivationKey")
}
req, err := client.GetActivationKeyPreparer(ctx, resourceGroupName, managerName)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "GetActivationKey", nil, "Failure preparing request")
return
}
resp, err := client.GetActivationKeySender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "GetActivationKey", resp, "Failure sending request")
return
}
result, err = client.GetActivationKeyResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "GetActivationKey", resp, "Failure responding to request")
}
return
}
// GetActivationKeyPreparer prepares the GetActivationKey request.
func (client ManagersClient) GetActivationKeyPreparer(ctx context.Context, resourceGroupName string, managerName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"managerName": managerName,
"resourceGroupName": resourceGroupName,
"subscriptionId": client.SubscriptionID,
}
const APIVersion = "2017-06-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsPost(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/listActivationKey", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetActivationKeySender sends the GetActivationKey request. The method will close the
// http.Response Body if it receives an error.
func (client ManagersClient) GetActivationKeySender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// GetActivationKeyResponder handles the response to the GetActivationKey request. The method always
// closes the http.Response Body.
func (client ManagersClient) GetActivationKeyResponder(resp *http.Response) (result Key, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// GetDevicePublicEncryptionKey returns the public encryption key of the device.
//
// deviceName is the device name resourceGroupName is the resource group name managerName is the manager name
func (client ManagersClient) GetDevicePublicEncryptionKey(ctx context.Context, deviceName string, resourceGroupName string, managerName string) (result PublicKey, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: managerName,
Constraints: []validation.Constraint{{Target: "managerName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "managerName", Name: validation.MinLength, Rule: 2, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "storsimple.ManagersClient", "GetDevicePublicEncryptionKey")
}
req, err := client.GetDevicePublicEncryptionKeyPreparer(ctx, deviceName, resourceGroupName, managerName)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "GetDevicePublicEncryptionKey", nil, "Failure preparing request")
return
}
resp, err := client.GetDevicePublicEncryptionKeySender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "GetDevicePublicEncryptionKey", resp, "Failure sending request")
return
}
result, err = client.GetDevicePublicEncryptionKeyResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "GetDevicePublicEncryptionKey", resp, "Failure responding to request")
}
return
}
// GetDevicePublicEncryptionKeyPreparer prepares the GetDevicePublicEncryptionKey request.
func (client ManagersClient) GetDevicePublicEncryptionKeyPreparer(ctx context.Context, deviceName string, resourceGroupName string, managerName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"deviceName": deviceName,
"managerName": managerName,
"resourceGroupName": resourceGroupName,
"subscriptionId": client.SubscriptionID,
}
const APIVersion = "2017-06-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsPost(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/publicEncryptionKey", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetDevicePublicEncryptionKeySender sends the GetDevicePublicEncryptionKey request. The method will close the
// http.Response Body if it receives an error.
func (client ManagersClient) GetDevicePublicEncryptionKeySender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// GetDevicePublicEncryptionKeyResponder handles the response to the GetDevicePublicEncryptionKey request. The method always
// closes the http.Response Body.
func (client ManagersClient) GetDevicePublicEncryptionKeyResponder(resp *http.Response) (result PublicKey, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// GetEncryptionSettings returns the encryption settings of the manager.
//
// resourceGroupName is the resource group name managerName is the manager name
func (client ManagersClient) GetEncryptionSettings(ctx context.Context, resourceGroupName string, managerName string) (result EncryptionSettings, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: managerName,
Constraints: []validation.Constraint{{Target: "managerName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "managerName", Name: validation.MinLength, Rule: 2, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "storsimple.ManagersClient", "GetEncryptionSettings")
}
req, err := client.GetEncryptionSettingsPreparer(ctx, resourceGroupName, managerName)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "GetEncryptionSettings", nil, "Failure preparing request")
return
}
resp, err := client.GetEncryptionSettingsSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "GetEncryptionSettings", resp, "Failure sending request")
return
}
result, err = client.GetEncryptionSettingsResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "GetEncryptionSettings", resp, "Failure responding to request")
}
return
}
// GetEncryptionSettingsPreparer prepares the GetEncryptionSettings request.
func (client ManagersClient) GetEncryptionSettingsPreparer(ctx context.Context, resourceGroupName string, managerName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"managerName": managerName,
"resourceGroupName": resourceGroupName,
"subscriptionId": client.SubscriptionID,
}
const APIVersion = "2017-06-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/encryptionSettings/default", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetEncryptionSettingsSender sends the GetEncryptionSettings request. The method will close the
// http.Response Body if it receives an error.
func (client ManagersClient) GetEncryptionSettingsSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// GetEncryptionSettingsResponder handles the response to the GetEncryptionSettings request. The method always
// closes the http.Response Body.
func (client ManagersClient) GetEncryptionSettingsResponder(resp *http.Response) (result EncryptionSettings, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// GetExtendedInfo returns the extended information of the specified manager name.
//
// resourceGroupName is the resource group name managerName is the manager name
func (client ManagersClient) GetExtendedInfo(ctx context.Context, resourceGroupName string, managerName string) (result ManagerExtendedInfo, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: managerName,
Constraints: []validation.Constraint{{Target: "managerName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "managerName", Name: validation.MinLength, Rule: 2, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "storsimple.ManagersClient", "GetExtendedInfo")
}
req, err := client.GetExtendedInfoPreparer(ctx, resourceGroupName, managerName)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "GetExtendedInfo", nil, "Failure preparing request")
return
}
resp, err := client.GetExtendedInfoSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "GetExtendedInfo", resp, "Failure sending request")
return
}
result, err = client.GetExtendedInfoResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "GetExtendedInfo", resp, "Failure responding to request")
}
return
}
// GetExtendedInfoPreparer prepares the GetExtendedInfo request.
func (client ManagersClient) GetExtendedInfoPreparer(ctx context.Context, resourceGroupName string, managerName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"managerName": managerName,
"resourceGroupName": resourceGroupName,
"subscriptionId": client.SubscriptionID,
}
const APIVersion = "2017-06-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/extendedInformation/vaultExtendedInfo", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetExtendedInfoSender sends the GetExtendedInfo request. The method will close the
// http.Response Body if it receives an error.
func (client ManagersClient) GetExtendedInfoSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// GetExtendedInfoResponder handles the response to the GetExtendedInfo request. The method always
// closes the http.Response Body.
func (client ManagersClient) GetExtendedInfoResponder(resp *http.Response) (result ManagerExtendedInfo, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// GetPublicEncryptionKey returns the symmetric encrypted public encryption key of the manager.
//
// resourceGroupName is the resource group name managerName is the manager name
func (client ManagersClient) GetPublicEncryptionKey(ctx context.Context, resourceGroupName string, managerName string) (result SymmetricEncryptedSecret, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: managerName,
Constraints: []validation.Constraint{{Target: "managerName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "managerName", Name: validation.MinLength, Rule: 2, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "storsimple.ManagersClient", "GetPublicEncryptionKey")
}
req, err := client.GetPublicEncryptionKeyPreparer(ctx, resourceGroupName, managerName)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "GetPublicEncryptionKey", nil, "Failure preparing request")
return
}
resp, err := client.GetPublicEncryptionKeySender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "GetPublicEncryptionKey", resp, "Failure sending request")
return
}
result, err = client.GetPublicEncryptionKeyResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "GetPublicEncryptionKey", resp, "Failure responding to request")
}
return
}
// GetPublicEncryptionKeyPreparer prepares the GetPublicEncryptionKey request.
func (client ManagersClient) GetPublicEncryptionKeyPreparer(ctx context.Context, resourceGroupName string, managerName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"managerName": managerName,
"resourceGroupName": resourceGroupName,
"subscriptionId": client.SubscriptionID,
}
const APIVersion = "2017-06-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsPost(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/listPublicEncryptionKey", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetPublicEncryptionKeySender sends the GetPublicEncryptionKey request. The method will close the
// http.Response Body if it receives an error.
func (client ManagersClient) GetPublicEncryptionKeySender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// GetPublicEncryptionKeyResponder handles the response to the GetPublicEncryptionKey request. The method always
// closes the http.Response Body.
func (client ManagersClient) GetPublicEncryptionKeyResponder(resp *http.Response) (result SymmetricEncryptedSecret, 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 retrieves all the managers in a subscription.
func (client ManagersClient) List(ctx context.Context) (result ManagerList, err error) {
req, err := client.ListPreparer(ctx)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "List", nil, "Failure preparing request")
return
}
resp, err := client.ListSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "List", resp, "Failure sending request")
return
}
result, err = client.ListResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "List", resp, "Failure responding to request")
}
return
}
// ListPreparer prepares the List request.
func (client ManagersClient) ListPreparer(ctx context.Context) (*http.Request, error) {
pathParameters := map[string]interface{}{
"subscriptionId": client.SubscriptionID,
}
const APIVersion = "2017-06-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.StorSimple/managers", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListSender sends the List request. The method will close the
// http.Response Body if it receives an error.
func (client ManagersClient) ListSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListResponder handles the response to the List request. The method always
// closes the http.Response Body.
func (client ManagersClient) ListResponder(resp *http.Response) (result ManagerList, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListByResourceGroup retrieves all the managers in a resource group.
//
// resourceGroupName is the resource group name
func (client ManagersClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result ManagerList, err error) {
req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "ListByResourceGroup", nil, "Failure preparing request")
return
}
resp, err := client.ListByResourceGroupSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "ListByResourceGroup", resp, "Failure sending request")
return
}
result, err = client.ListByResourceGroupResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "ListByResourceGroup", resp, "Failure responding to request")
}
return
}
// ListByResourceGroupPreparer prepares the ListByResourceGroup request.
func (client ManagersClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": resourceGroupName,
"subscriptionId": client.SubscriptionID,
}
const APIVersion = "2017-06-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the
// http.Response Body if it receives an error.
func (client ManagersClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always
// closes the http.Response Body.
func (client ManagersClient) ListByResourceGroupResponder(resp *http.Response) (result ManagerList, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListFeatureSupportStatus lists the features and their support status
//
// resourceGroupName is the resource group name managerName is the manager name filter is oData Filter options
func (client ManagersClient) ListFeatureSupportStatus(ctx context.Context, resourceGroupName string, managerName string, filter string) (result FeatureList, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: managerName,
Constraints: []validation.Constraint{{Target: "managerName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "managerName", Name: validation.MinLength, Rule: 2, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "storsimple.ManagersClient", "ListFeatureSupportStatus")
}
req, err := client.ListFeatureSupportStatusPreparer(ctx, resourceGroupName, managerName, filter)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "ListFeatureSupportStatus", nil, "Failure preparing request")
return
}
resp, err := client.ListFeatureSupportStatusSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "ListFeatureSupportStatus", resp, "Failure sending request")
return
}
result, err = client.ListFeatureSupportStatusResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "ListFeatureSupportStatus", resp, "Failure responding to request")
}
return
}
// ListFeatureSupportStatusPreparer prepares the ListFeatureSupportStatus request.
func (client ManagersClient) ListFeatureSupportStatusPreparer(ctx context.Context, resourceGroupName string, managerName string, filter string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"managerName": managerName,
"resourceGroupName": resourceGroupName,
"subscriptionId": client.SubscriptionID,
}
const APIVersion = "2017-06-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
if len(filter) > 0 {
queryParameters["$filter"] = autorest.Encode("query", filter)
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/features", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListFeatureSupportStatusSender sends the ListFeatureSupportStatus request. The method will close the
// http.Response Body if it receives an error.
func (client ManagersClient) ListFeatureSupportStatusSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListFeatureSupportStatusResponder handles the response to the ListFeatureSupportStatus request. The method always
// closes the http.Response Body.
func (client ManagersClient) ListFeatureSupportStatusResponder(resp *http.Response) (result FeatureList, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListMetricDefinition gets the metric definitions for the specified manager.
//
// resourceGroupName is the resource group name managerName is the manager name
func (client ManagersClient) ListMetricDefinition(ctx context.Context, resourceGroupName string, managerName string) (result MetricDefinitionList, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: managerName,
Constraints: []validation.Constraint{{Target: "managerName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "managerName", Name: validation.MinLength, Rule: 2, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "storsimple.ManagersClient", "ListMetricDefinition")
}
req, err := client.ListMetricDefinitionPreparer(ctx, resourceGroupName, managerName)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "ListMetricDefinition", nil, "Failure preparing request")
return
}
resp, err := client.ListMetricDefinitionSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "ListMetricDefinition", resp, "Failure sending request")
return
}
result, err = client.ListMetricDefinitionResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "ListMetricDefinition", resp, "Failure responding to request")
}
return
}
// ListMetricDefinitionPreparer prepares the ListMetricDefinition request.
func (client ManagersClient) ListMetricDefinitionPreparer(ctx context.Context, resourceGroupName string, managerName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"managerName": managerName,
"resourceGroupName": resourceGroupName,
"subscriptionId": client.SubscriptionID,
}
const APIVersion = "2017-06-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/metricsDefinitions", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListMetricDefinitionSender sends the ListMetricDefinition request. The method will close the
// http.Response Body if it receives an error.
func (client ManagersClient) ListMetricDefinitionSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListMetricDefinitionResponder handles the response to the ListMetricDefinition request. The method always
// closes the http.Response Body.
func (client ManagersClient) ListMetricDefinitionResponder(resp *http.Response) (result MetricDefinitionList, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListMetrics gets the metrics for the specified manager.
//
// resourceGroupName is the resource group name managerName is the manager name filter is oData Filter options
func (client ManagersClient) ListMetrics(ctx context.Context, resourceGroupName string, managerName string, filter string) (result MetricList, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: managerName,
Constraints: []validation.Constraint{{Target: "managerName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "managerName", Name: validation.MinLength, Rule: 2, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "storsimple.ManagersClient", "ListMetrics")
}
req, err := client.ListMetricsPreparer(ctx, resourceGroupName, managerName, filter)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "ListMetrics", nil, "Failure preparing request")
return
}
resp, err := client.ListMetricsSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "ListMetrics", resp, "Failure sending request")
return
}
result, err = client.ListMetricsResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "ListMetrics", resp, "Failure responding to request")
}
return
}
// ListMetricsPreparer prepares the ListMetrics request.
func (client ManagersClient) ListMetricsPreparer(ctx context.Context, resourceGroupName string, managerName string, filter string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"managerName": managerName,
"resourceGroupName": resourceGroupName,
"subscriptionId": client.SubscriptionID,
}
const APIVersion = "2017-06-01"
queryParameters := map[string]interface{}{
"$filter": autorest.Encode("query", filter),
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/metrics", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListMetricsSender sends the ListMetrics request. The method will close the
// http.Response Body if it receives an error.
func (client ManagersClient) ListMetricsSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListMetricsResponder handles the response to the ListMetrics request. The method always
// closes the http.Response Body.
func (client ManagersClient) ListMetricsResponder(resp *http.Response) (result MetricList, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// RegenerateActivationKey re-generates and returns the activation key of the manager.
//
// resourceGroupName is the resource group name managerName is the manager name
func (client ManagersClient) RegenerateActivationKey(ctx context.Context, resourceGroupName string, managerName string) (result Key, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: managerName,
Constraints: []validation.Constraint{{Target: "managerName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "managerName", Name: validation.MinLength, Rule: 2, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "storsimple.ManagersClient", "RegenerateActivationKey")
}
req, err := client.RegenerateActivationKeyPreparer(ctx, resourceGroupName, managerName)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "RegenerateActivationKey", nil, "Failure preparing request")
return
}
resp, err := client.RegenerateActivationKeySender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "RegenerateActivationKey", resp, "Failure sending request")
return
}
result, err = client.RegenerateActivationKeyResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "RegenerateActivationKey", resp, "Failure responding to request")
}
return
}
// RegenerateActivationKeyPreparer prepares the RegenerateActivationKey request.
func (client ManagersClient) RegenerateActivationKeyPreparer(ctx context.Context, resourceGroupName string, managerName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"managerName": managerName,
"resourceGroupName": resourceGroupName,
"subscriptionId": client.SubscriptionID,
}
const APIVersion = "2017-06-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsPost(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/regenerateActivationKey", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// RegenerateActivationKeySender sends the RegenerateActivationKey request. The method will close the
// http.Response Body if it receives an error.
func (client ManagersClient) RegenerateActivationKeySender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// RegenerateActivationKeyResponder handles the response to the RegenerateActivationKey request. The method always
// closes the http.Response Body.
func (client ManagersClient) RegenerateActivationKeyResponder(resp *http.Response) (result Key, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Update updates the StorSimple Manager.
//
// parameters is the manager update parameters. resourceGroupName is the resource group name managerName is the manager
// name
func (client ManagersClient) Update(ctx context.Context, parameters ManagerPatch, resourceGroupName string, managerName string) (result Manager, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: managerName,
Constraints: []validation.Constraint{{Target: "managerName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "managerName", Name: validation.MinLength, Rule: 2, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "storsimple.ManagersClient", "Update")
}
req, err := client.UpdatePreparer(ctx, parameters, resourceGroupName, managerName)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "Update", nil, "Failure preparing request")
return
}
resp, err := client.UpdateSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "Update", resp, "Failure sending request")
return
}
result, err = client.UpdateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "Update", resp, "Failure responding to request")
}
return
}
// UpdatePreparer prepares the Update request.
func (client ManagersClient) UpdatePreparer(ctx context.Context, parameters ManagerPatch, resourceGroupName string, managerName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"managerName": managerName,
"resourceGroupName": resourceGroupName,
"subscriptionId": client.SubscriptionID,
}
const APIVersion = "2017-06-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPatch(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}", pathParameters), | }
// UpdateSender sends the Update request. The method will close the
// http.Response Body if it receives an error.
func (client ManagersClient) UpdateSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// UpdateResponder handles the response to the Update request. The method always
// closes the http.Response Body.
func (client ManagersClient) UpdateResponder(resp *http.Response) (result Manager, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// UpdateExtendedInfo updates the extended info of the manager.
//
// parameters is the manager extended information. resourceGroupName is the resource group name managerName is the
// manager name ifMatch is pass the ETag of ExtendedInfo fetched from GET call
func (client ManagersClient) UpdateExtendedInfo(ctx context.Context, parameters ManagerExtendedInfo, resourceGroupName string, managerName string, ifMatch string) (result ManagerExtendedInfo, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: managerName,
Constraints: []validation.Constraint{{Target: "managerName", Name: validation.MaxLength, Rule: 50, Chain: nil},
{Target: "managerName", Name: validation.MinLength, Rule: 2, Chain: nil}}}}); err != nil {
return result, validation.NewErrorWithValidationError(err, "storsimple.ManagersClient", "UpdateExtendedInfo")
}
req, err := client.UpdateExtendedInfoPreparer(ctx, parameters, resourceGroupName, managerName, ifMatch)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "UpdateExtendedInfo", nil, "Failure preparing request")
return
}
resp, err := client.UpdateExtendedInfoSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "UpdateExtendedInfo", resp, "Failure sending request")
return
}
result, err = client.UpdateExtendedInfoResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "storsimple.ManagersClient", "UpdateExtendedInfo", resp, "Failure responding to request")
}
return
}
// UpdateExtendedInfoPreparer prepares the UpdateExtendedInfo request.
func (client ManagersClient) UpdateExtendedInfoPreparer(ctx context.Context, parameters ManagerExtendedInfo, resourceGroupName string, managerName string, ifMatch string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"managerName": managerName,
"resourceGroupName": resourceGroupName,
"subscriptionId": client.SubscriptionID,
}
const APIVersion = "2017-06-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsJSON(),
autorest.AsPatch(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/extendedInformation/vaultExtendedInfo", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters),
autorest.WithHeader("If-Match", autorest.String(ifMatch)))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// UpdateExtendedInfoSender sends the UpdateExtendedInfo request. The method will close the
// http.Response Body if it receives an error.
func (client ManagersClient) UpdateExtendedInfoSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// UpdateExtendedInfoResponder handles the response to the UpdateExtendedInfo request. The method always
// closes the http.Response Body.
func (client ManagersClient) UpdateExtendedInfoResponder(resp *http.Response) (result ManagerExtendedInfo, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
} | autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx)) |
domainHelper_test.go | package helpers
import (
"fmt"
"testing"
configuration "github.com/GolosTools/golos-vote-bot/config"
)
func TestGetDomainRegexp(t *testing.T) | {
var config configuration.Config
err := configuration.LoadConfiguration("../config.json", &config)
if err != nil {
t.Error(err)
}
regexp, err := GetDomainRegexp(config.Domains)
texts := []string{
"https://mapala.net/ru/liora137/diekabr-skii-nizhnii-riedkiie-luchiki-solntsa/",
"https://goldvoice.club/@golos.loto/5x36-golos-lottery-1273-7757/",
"https://golos.io/ru--art/@amalinavia/otkrytka-k-novomu-godu-pryanichnyi-domik",
}
for _, text := range texts {
if !regexp.MatchString(text) {
t.Error("Не подошла ссылка " + text)
}
}
matched := regexp.FindStringSubmatch(texts[0])
author, permalink := matched[1], matched[2]
if author != "liora137" || permalink != "diekabr-skii-nizhnii-riedkiie-luchiki-solntsa" {
t.Error(fmt.Sprintf("Неожиданный автор %s и ссылка %s", author, permalink))
}
matched = regexp.FindStringSubmatch(texts[1])
author, permalink = matched[1], matched[2]
if author != "golos.loto" || permalink != "5x36-golos-lottery-1273-7757" {
t.Error(fmt.Sprintf("Неожиданный автор %s и ссылка %s", author, permalink))
}
matched = regexp.FindStringSubmatch(texts[2])
author, permalink = matched[1], matched[2]
if author != "amalinavia" || permalink != "otkrytka-k-novomu-godu-pryanichnyi-domik" {
t.Error(fmt.Sprintf("Неожиданный автор %s и ссылка %s", author, permalink))
}
}
|
|
endpoints.py | """
API MAPPING
"""
mapping_table = {
# Rest API: Organizations
'list_organizations': {
'path': '/organizations.json',
'method': 'GET',
'status': 200,
},
'show_organization': {
'path': '/organizations/{{organization_id}}.json',
'method': 'GET',
'status': 200,
},
'create_organization': {
'path': '/organizations.json',
'method': 'POST',
'status': 201,
},
'update_organization': {
'path': '/organizations/{{organization_id}}.json',
'method': 'PUT',
'status': 200,
},
'delete_organization': {
'path': '/organizations/{{organization_id}}.json',
'method': 'DELETE',
'status': 200,
},
# Rest API: Groups
'list_groups': {
'path': '/groups.json',
'method': 'GET',
'status': 200,
},
'show_group': {
'path': '/groups/{{group_id}}.json',
'method': 'GET',
'status': 200,
},
'create_group': {
'path': '/groups.json',
'method': 'POST',
'status': 201,
},
'update_group': {
'path': '/groups/{{group_id}}.json',
'method': 'PUT',
'status': 200,
},
'delete_group': {
'path': '/groups/{{group_id}}.json',
'method': 'DELETE',
'status': 200,
},
# Rest API: Tickets
'list_tickets': {
'path': '/rules/{{view_id}}.json',
'valid_params': ('page', ),
'method': 'GET',
'status': 200,
},
'show_ticket': {
'path': '/tickets/{{ticket_id}}.json',
'method': 'GET',
'status': 200,
},
'create_ticket': {
'path': '/tickets.json',
'method': 'POST',
'status': 201,
},
'update_ticket': {
'path': '/tickets/{{ticket_id}}.json',
'method': 'PUT',
'status': 200,
},
'comment_ticket': {
'path': '/tickets/{{ticket_id}}.json',
'method': 'PUT',
'status': 200,
},
'delete_ticket': {
'path': '/tickets/{{ticket_id}}.json',
'method': 'DELETE',
'status': 200,
},
# Rest API: Attachment
'create_attachment': {
'path': '/uploads.json',
'valid_params': ('filename', 'token'),
'method': 'POST',
'status': 201,
},
# Rest API: Users
'list_users': {
'path': '/users.json',
'valid_params': ('page', ),
'method': 'GET',
'status': 200,
},
'search_users': {
'path': '/users.json',
'valid_params': ('query', 'role', 'page'),
'method': 'GET',
'status': 200,
},
'show_user': {
'path': '/users/{{user_id}}.json',
'method': 'GET',
'status': 200,
},
'create_user': {
'path': '/users.json',
'method': 'POST',
'status': 201,
},
'update_user': {
'path': '/users/{{user_id}}.json',
'method': 'PUT',
'status': 200,
},
'delete_user': {
'path': '/users/{{user_id}}.json',
'method': 'DELETE',
'status': 200,
},
'list_user_identities': {
'path': '/users/{{user_id}}/user_identities.json',
'method': 'GET',
'status': 200,
},
'add_user_email': {
'path': '/users/{{user_id}}/user_identities.json',
'method': 'POST',
'status': 201,
},
'add_twitter_handle': {
'path': '/users/{{user_id}}/user_identities.json',
'method': 'POST',
'status': 201,
},
'make_identity_primary': {
'path': '/users/{{user_id}}/user_identities/{{identity_id}}/make_primary',
'method': 'POST',
'status': 200,
},
'delete_identity': {
'path': '/users/{{user_id}}/user_identities/{{identity_id}}',
'method': 'DELETE',
'status': 200,
},
# Rest API: Tags
'list_tags': {
'path': '/tags.json',
'method': 'GET',
'status': 200,
},
'list_assets': {
'path': '/tags/{{tag_id}}.json',
'valid_params': ('asset_type', 'page'),
'method': 'GET',
'status': 200,
},
# Rest API: Ticket Fields
'list_ticket_fields': {
'path': '/ticket_fields.json',
'method': 'GET',
'status': 200,
},
# Rest API: Macros
'list_macros': {
'path': '/macros.json',
'method': 'GET', | 'evaluate_macro': {
'path': '/macros/{{macro_id}}/apply.json',
'valid_params': ('ticket_id', ),
'method': 'POST',
'status': 201,
},
# Rest API: Search
'search': {
'path': '/search.json',
'valid_params': ('query', 'page'),
'method': 'GET',
'status': 200,
},
} | 'status': 200,
}, |
patch.py | # -*- coding: utf-8 -*-
#
import matplotlib as mpl
from . import path as mypath
def draw_patch(data, obj):
"""Return the PGFPlots code for patches.
"""
# Gather the draw options.
data, draw_options = mypath.get_draw_options(
data, obj.get_edgecolor(), obj.get_facecolor()
)
if isinstance(obj, mpl.patches.Rectangle):
# rectangle specialization
return _draw_rectangle(data, obj, draw_options)
elif isinstance(obj, mpl.patches.Ellipse):
# ellipse specialization
return _draw_ellipse(data, obj, draw_options)
# regular patch
return mypath.draw_path(data, obj.get_path(), draw_options=draw_options)
def | (data, obj):
"""Returns PGFPlots code for a number of patch objects.
"""
content = []
# Gather the draw options.
try:
edge_color = obj.get_edgecolor()[0]
except IndexError:
edge_color = None
try:
face_color = obj.get_facecolor()[0]
except IndexError:
face_color = None
data, draw_options = mypath.get_draw_options(data, edge_color, face_color)
for path in obj.get_paths():
data, cont = mypath.draw_path(data, path, draw_options=draw_options)
content.append(cont)
return data, content
def _draw_rectangle(data, obj, draw_options):
"""Return the PGFPlots code for rectangles.
"""
# Objects with labels are plot objects (from bar charts, etc).
# Even those without labels explicitly set have a label of
# "_nolegend_". Everything else should be skipped because
# they likely correspong to axis/legend objects which are
# handled by PGFPlots
label = obj.get_label()
if label == "":
return data, []
# get real label, bar charts by default only give rectangles
# labels of "_nolegend_"
# See
# <http://stackoverflow.com/questions/35881290/how-to-get-the-label-on-bar-plot-stacked-bar-plot-in-matplotlib>
handles, labels = obj.axes.get_legend_handles_labels()
labelsFound = [
label for h, label in zip(handles, labels) if obj in h.get_children()
]
if len(labelsFound) == 1:
label = labelsFound[0]
legend = ""
if label != "_nolegend_" and label not in data["rectangle_legends"]:
data["rectangle_legends"].add(label)
legend = ("\\addlegendimage{ybar,ybar legend,%s};\n") % (",".join(draw_options))
left_lower_x = obj.get_x()
left_lower_y = obj.get_y()
cont = (
"%s\\draw[%s] (axis cs:%.15g,%.15g) " "rectangle (axis cs:%.15g,%.15g);\n"
) % (
legend,
",".join(draw_options),
left_lower_x,
left_lower_y,
left_lower_x + obj.get_width(),
left_lower_y + obj.get_height(),
)
return data, cont
def _draw_ellipse(data, obj, draw_options):
"""Return the PGFPlots code for ellipses.
"""
if isinstance(obj, mpl.patches.Circle):
# circle specialization
return _draw_circle(data, obj, draw_options)
x, y = obj.center
cont = (
"\\draw[%s, rotate around={%.15g:(%.15g,%.15g)}] (axis cs:%.15g,%.15g) ellipse (%.15g and %.15g);\n"
% (
",".join(draw_options),
obj.angle,
x,
y,
x,
y,
0.5 * obj.width,
0.5 * obj.height,
)
)
return data, cont
def _draw_circle(data, obj, draw_options):
"""Return the PGFPlots code for circles.
"""
x, y = obj.center
cont = "\\draw[%s] (axis cs:%.15g,%.15g) circle (%.15g);\n" % (
",".join(draw_options),
x,
y,
obj.get_radius(),
)
return data, cont
| draw_patchcollection |
route.go | // Copyright 2021 Google LLC. 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.
package beta
import (
"context"
"crypto/sha256"
"encoding/json"
"fmt"
"time"
"google.golang.org/api/googleapi"
"github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl"
)
type Route struct {
Id *int64 `json:"id"`
Name *string `json:"name"`
Description *string `json:"description"`
Network *string `json:"network"`
Tag []string `json:"tag"`
DestRange *string `json:"destRange"`
Priority *int64 `json:"priority"`
NextHopInstance *string `json:"nextHopInstance"`
NextHopIP *string `json:"nextHopIP"`
NextHopNetwork *string `json:"nextHopNetwork"`
NextHopGateway *string `json:"nextHopGateway"`
NextHopPeering *string `json:"nextHopPeering"`
NextHopIlb *string `json:"nextHopIlb"`
Warning []RouteWarning `json:"warning"`
NextHopVpnTunnel *string `json:"nextHopVpnTunnel"`
SelfLink *string `json:"selfLink"`
Project *string `json:"project"`
}
func (r *Route) String() string {
return dcl.SprintResource(r)
}
// The enum RouteWarningCodeEnum.
type RouteWarningCodeEnum string
// RouteWarningCodeEnumRef returns a *RouteWarningCodeEnum with the value of string s
// If the empty string is provided, nil is returned.
func RouteWarningCodeEnumRef(s string) *RouteWarningCodeEnum |
func (v RouteWarningCodeEnum) Validate() error {
if string(v) == "" {
// Empty enum is okay.
return nil
}
for _, s := range []string{"BAD_REQUEST", "FORBIDDEN", "NOT_FOUND", "CONFLICT", "GONE", "PRECONDITION_FAILED", "INTERNAL_ERROR", "SERVICE_UNAVAILABLE"} {
if string(v) == s {
return nil
}
}
return &dcl.EnumInvalidError{
Enum: "RouteWarningCodeEnum",
Value: string(v),
Valid: []string{},
}
}
type RouteWarning struct {
empty bool `json:"-"`
Code *RouteWarningCodeEnum `json:"code"`
Message *string `json:"message"`
Data map[string]string `json:"data"`
}
type jsonRouteWarning RouteWarning
func (r *RouteWarning) UnmarshalJSON(data []byte) error {
var res jsonRouteWarning
if err := json.Unmarshal(data, &res); err != nil {
return err
}
var m map[string]interface{}
json.Unmarshal(data, &m)
if len(m) == 0 {
*r = *EmptyRouteWarning
} else {
r.Code = res.Code
r.Message = res.Message
r.Data = res.Data
}
return nil
}
// This object is used to assert a desired state where this RouteWarning is
// empty. Go lacks global const objects, but this object should be treated
// as one. Modifying this object will have undesirable results.
var EmptyRouteWarning *RouteWarning = &RouteWarning{empty: true}
func (r *RouteWarning) Empty() bool {
return r.empty
}
func (r *RouteWarning) String() string {
return dcl.SprintResource(r)
}
func (r *RouteWarning) HashCode() string {
// Placeholder for a more complex hash method that handles ordering, etc
// Hash resource body for easy comparison later
hash := sha256.New().Sum([]byte(r.String()))
return fmt.Sprintf("%x", hash)
}
// Describe returns a simple description of this resource to ensure that automated tools
// can identify it.
func (r *Route) Describe() dcl.ServiceTypeVersion {
return dcl.ServiceTypeVersion{
Service: "compute",
Type: "Route",
Version: "beta",
}
}
func (r *Route) ID() (string, error) {
if err := extractRouteFields(r); err != nil {
return "", err
}
nr := r.urlNormalized()
params := map[string]interface{}{
"id": dcl.ValueOrEmptyString(nr.Id),
"name": dcl.ValueOrEmptyString(nr.Name),
"description": dcl.ValueOrEmptyString(nr.Description),
"network": dcl.ValueOrEmptyString(nr.Network),
"tag": dcl.ValueOrEmptyString(nr.Tag),
"destRange": dcl.ValueOrEmptyString(nr.DestRange),
"priority": dcl.ValueOrEmptyString(nr.Priority),
"nextHopInstance": dcl.ValueOrEmptyString(nr.NextHopInstance),
"nextHopIP": dcl.ValueOrEmptyString(nr.NextHopIP),
"nextHopNetwork": dcl.ValueOrEmptyString(nr.NextHopNetwork),
"nextHopGateway": dcl.ValueOrEmptyString(nr.NextHopGateway),
"nextHopPeering": dcl.ValueOrEmptyString(nr.NextHopPeering),
"nextHopIlb": dcl.ValueOrEmptyString(nr.NextHopIlb),
"warning": dcl.ValueOrEmptyString(nr.Warning),
"nextHopVpnTunnel": dcl.ValueOrEmptyString(nr.NextHopVpnTunnel),
"selfLink": dcl.ValueOrEmptyString(nr.SelfLink),
"project": dcl.ValueOrEmptyString(nr.Project),
}
return dcl.Nprintf("projects/{{project}}/global/routes/{{name}}", params), nil
}
const RouteMaxPage = -1
type RouteList struct {
Items []*Route
nextToken string
pageSize int32
resource *Route
}
func (l *RouteList) HasNext() bool {
return l.nextToken != ""
}
func (l *RouteList) Next(ctx context.Context, c *Client) error {
ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second))
defer cancel()
if !l.HasNext() {
return fmt.Errorf("no next page")
}
items, token, err := c.listRoute(ctx, l.resource, l.nextToken, l.pageSize)
if err != nil {
return err
}
l.Items = items
l.nextToken = token
return err
}
func (c *Client) ListRoute(ctx context.Context, project string) (*RouteList, error) {
ctx = dcl.ContextWithRequestID(ctx)
ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second))
defer cancel()
return c.ListRouteWithMaxResults(ctx, project, RouteMaxPage)
}
func (c *Client) ListRouteWithMaxResults(ctx context.Context, project string, pageSize int32) (*RouteList, error) {
ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second))
defer cancel()
// Create a resource object so that we can use proper url normalization methods.
r := &Route{
Project: &project,
}
items, token, err := c.listRoute(ctx, r, "", pageSize)
if err != nil {
return nil, err
}
return &RouteList{
Items: items,
nextToken: token,
pageSize: pageSize,
resource: r,
}, nil
}
func (c *Client) GetRoute(ctx context.Context, r *Route) (*Route, error) {
ctx = dcl.ContextWithRequestID(ctx)
ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second))
defer cancel()
// This is *purposefully* supressing errors.
// This function is used with url-normalized values + not URL normalized values.
// URL Normalized values will throw unintentional errors, since those values are not of the proper parent form.
extractRouteFields(r)
b, err := c.getRouteRaw(ctx, r)
if err != nil {
if dcl.IsNotFound(err) {
return nil, &googleapi.Error{
Code: 404,
Message: err.Error(),
}
}
return nil, err
}
result, err := unmarshalRoute(b, c)
if err != nil {
return nil, err
}
result.Project = r.Project
result.Name = r.Name
if dcl.IsZeroValue(result.Priority) {
result.Priority = dcl.Int64(1000)
}
c.Config.Logger.InfoWithContextf(ctx, "Retrieved raw result state: %v", result)
c.Config.Logger.InfoWithContextf(ctx, "Canonicalizing with specified state: %v", r)
result, err = canonicalizeRouteNewState(c, result, r)
if err != nil {
return nil, err
}
if err := postReadExtractRouteFields(result); err != nil {
return result, err
}
c.Config.Logger.InfoWithContextf(ctx, "Created result state: %v", result)
return result, nil
}
func (c *Client) DeleteRoute(ctx context.Context, r *Route) error {
ctx = dcl.ContextWithRequestID(ctx)
ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second))
defer cancel()
if r == nil {
return fmt.Errorf("Route resource is nil")
}
c.Config.Logger.InfoWithContext(ctx, "Deleting Route...")
deleteOp := deleteRouteOperation{}
return deleteOp.do(ctx, r, c)
}
// DeleteAllRoute deletes all resources that the filter functions returns true on.
func (c *Client) DeleteAllRoute(ctx context.Context, project string, filter func(*Route) bool) error {
listObj, err := c.ListRoute(ctx, project)
if err != nil {
return err
}
err = c.deleteAllRoute(ctx, filter, listObj.Items)
if err != nil {
return err
}
for listObj.HasNext() {
err = listObj.Next(ctx, c)
if err != nil {
return nil
}
err = c.deleteAllRoute(ctx, filter, listObj.Items)
if err != nil {
return err
}
}
return nil
}
func (c *Client) ApplyRoute(ctx context.Context, rawDesired *Route, opts ...dcl.ApplyOption) (*Route, error) {
ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second))
defer cancel()
ctx = dcl.ContextWithRequestID(ctx)
var resultNewState *Route
err := dcl.Do(ctx, func(ctx context.Context) (*dcl.RetryDetails, error) {
newState, err := applyRouteHelper(c, ctx, rawDesired, opts...)
resultNewState = newState
if err != nil {
// If the error is 409, there is conflict in resource update.
// Here we want to apply changes based on latest state.
if dcl.IsConflictError(err) {
return &dcl.RetryDetails{}, dcl.OperationNotDone{Err: err}
}
return nil, err
}
return nil, nil
}, c.Config.RetryProvider)
return resultNewState, err
}
func applyRouteHelper(c *Client, ctx context.Context, rawDesired *Route, opts ...dcl.ApplyOption) (*Route, error) {
c.Config.Logger.InfoWithContext(ctx, "Beginning ApplyRoute...")
c.Config.Logger.InfoWithContextf(ctx, "User specified desired state: %v", rawDesired)
// 1.1: Validation of user-specified fields in desired state.
if err := rawDesired.validate(); err != nil {
return nil, err
}
if err := extractRouteFields(rawDesired); err != nil {
return nil, err
}
initial, desired, fieldDiffs, err := c.routeDiffsForRawDesired(ctx, rawDesired, opts...)
if err != nil {
return nil, fmt.Errorf("failed to create a diff: %w", err)
}
diffs, err := convertFieldDiffsToRouteDiffs(c.Config, fieldDiffs, opts)
if err != nil {
return nil, err
}
// TODO(magic-modules-eng): 2.2 Feasibility check (all updates are feasible so far).
// 2.3: Lifecycle Directive Check
var create bool
lp := dcl.FetchLifecycleParams(opts)
if initial == nil {
if dcl.HasLifecycleParam(lp, dcl.BlockCreation) {
return nil, dcl.ApplyInfeasibleError{Message: fmt.Sprintf("Creation blocked by lifecycle params: %#v.", desired)}
}
create = true
} else if dcl.HasLifecycleParam(lp, dcl.BlockAcquire) {
return nil, dcl.ApplyInfeasibleError{
Message: fmt.Sprintf("Resource already exists - apply blocked by lifecycle params: %#v.", initial),
}
} else {
for _, d := range diffs {
if d.RequiresRecreate {
return nil, dcl.ApplyInfeasibleError{
Message: fmt.Sprintf("infeasible update: (%v) would require recreation", d),
}
}
if dcl.HasLifecycleParam(lp, dcl.BlockModification) {
return nil, dcl.ApplyInfeasibleError{Message: fmt.Sprintf("Modification blocked, diff (%v) unresolvable.", d)}
}
}
}
// 2.4 Imperative Request Planning
var ops []routeApiOperation
if create {
ops = append(ops, &createRouteOperation{})
} else {
for _, d := range diffs {
ops = append(ops, d.UpdateOp)
}
}
c.Config.Logger.InfoWithContextf(ctx, "Created plan: %#v", ops)
// 2.5 Request Actuation
for _, op := range ops {
c.Config.Logger.InfoWithContextf(ctx, "Performing operation %T %+v", op, op)
if err := op.do(ctx, desired, c); err != nil {
c.Config.Logger.InfoWithContextf(ctx, "Failed operation %T %+v: %v", op, op, err)
return nil, err
}
c.Config.Logger.InfoWithContextf(ctx, "Finished operation %T %+v", op, op)
}
return applyRouteDiff(c, ctx, desired, rawDesired, ops, opts...)
}
func applyRouteDiff(c *Client, ctx context.Context, desired *Route, rawDesired *Route, ops []routeApiOperation, opts ...dcl.ApplyOption) (*Route, error) {
// 3.1, 3.2a Retrieval of raw new state & canonicalization with desired state
c.Config.Logger.InfoWithContext(ctx, "Retrieving raw new state...")
rawNew, err := c.GetRoute(ctx, desired.urlNormalized())
if err != nil {
return nil, err
}
// Get additional values from the first response.
// These values should be merged into the newState above.
if len(ops) > 0 {
lastOp := ops[len(ops)-1]
if o, ok := lastOp.(*createRouteOperation); ok {
if r, hasR := o.FirstResponse(); hasR {
c.Config.Logger.InfoWithContext(ctx, "Retrieving raw new state from operation...")
fullResp, err := unmarshalMapRoute(r, c)
if err != nil {
return nil, err
}
rawNew, err = canonicalizeRouteNewState(c, rawNew, fullResp)
if err != nil {
return nil, err
}
}
}
}
c.Config.Logger.InfoWithContextf(ctx, "Canonicalizing with raw desired state: %v", rawDesired)
// 3.2b Canonicalization of raw new state using raw desired state
newState, err := canonicalizeRouteNewState(c, rawNew, rawDesired)
if err != nil {
return rawNew, err
}
c.Config.Logger.InfoWithContextf(ctx, "Created canonical new state: %v", newState)
// 3.3 Comparison of the new state and raw desired state.
// TODO(magic-modules-eng): EVENTUALLY_CONSISTENT_UPDATE
newDesired, err := canonicalizeRouteDesiredState(rawDesired, newState)
if err != nil {
return newState, err
}
if err := postReadExtractRouteFields(newState); err != nil {
return newState, err
}
// Need to ensure any transformations made here match acceptably in differ.
if err := postReadExtractRouteFields(newDesired); err != nil {
return newState, err
}
c.Config.Logger.InfoWithContextf(ctx, "Diffing using canonicalized desired state: %v", newDesired)
newDiffs, err := diffRoute(c, newDesired, newState)
if err != nil {
return newState, err
}
if len(newDiffs) == 0 {
c.Config.Logger.InfoWithContext(ctx, "No diffs found. Apply was successful.")
} else {
c.Config.Logger.InfoWithContextf(ctx, "Found diffs: %v", newDiffs)
diffMessages := make([]string, len(newDiffs))
for i, d := range newDiffs {
diffMessages[i] = fmt.Sprintf("%v", d)
}
return newState, dcl.DiffAfterApplyError{Diffs: diffMessages}
}
c.Config.Logger.InfoWithContext(ctx, "Done Apply.")
return newState, nil
}
| {
v := RouteWarningCodeEnum(s)
return &v
} |
middleware.go | package http
import (
"net/http"
"path"
"strings"
"time"
"github.com/influxdata/influxdb" | "github.com/prometheus/client_golang/prometheus"
)
// Middleware constructor.
type Middleware func(http.Handler) http.Handler
func SetCORS(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
if origin := r.Header.Get("Origin"); origin != "" {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, Authorization, User-Agent")
}
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
func Metrics(name string, reqMetric *prometheus.CounterVec, durMetric *prometheus.HistogramVec) Middleware {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
statusW := NewStatusResponseWriter(w)
defer func(start time.Time) {
label := prometheus.Labels{
"handler": name,
"method": r.Method,
"path": normalizePath(r.URL.Path),
"status": statusW.StatusCodeClass(),
"user_agent": UserAgent(r),
}
durMetric.With(label).Observe(time.Since(start).Seconds())
reqMetric.With(label).Inc()
}(time.Now())
next.ServeHTTP(statusW, r)
}
return http.HandlerFunc(fn)
}
}
func SkipOptions(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
// Preflight CORS requests from the browser will send an options request,
// so we need to make sure we satisfy them
if origin := r.Header.Get("Origin"); origin == "" && r.Method == http.MethodOptions {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
func Trace(name string) Middleware {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
span, r := tracing.ExtractFromHTTPRequest(r, name)
defer span.Finish()
span.LogKV("user_agent", UserAgent(r))
for k, v := range r.Header {
if len(v) == 0 {
continue
}
if k == "Authorization" || k == "User-Agent" {
continue
}
// If header has multiple values, only the first value will be logged on the trace.
span.LogKV(k, v[0])
}
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
}
func UserAgent(r *http.Request) string {
header := r.Header.Get("User-Agent")
if header == "" {
return "unknown"
}
return ua.Parse(header).Name
}
func normalizePath(p string) string {
var parts []string
for head, tail := shiftPath(p); ; head, tail = shiftPath(tail) {
piece := head
if len(piece) == influxdb.IDLength {
if _, err := influxdb.IDFromString(head); err == nil {
piece = ":id"
}
}
parts = append(parts, piece)
if tail == "/" {
break
}
}
return "/" + path.Join(parts...)
}
func shiftPath(p string) (head, tail string) {
p = path.Clean("/" + p)
i := strings.Index(p[1:], "/") + 1
if i <= 0 {
return p[1:], "/"
}
return p[1:i], p[i:]
} | "github.com/influxdata/influxdb/kit/tracing"
ua "github.com/mileusna/useragent" |
wechat_member_model.go | package models
import (
"github.com/xiusin/pinecms/src/application/models/tables"
"github.com/xiusin/pinecms/src/common/helper"
"xorm.io/xorm"
)
type WechatMemberModel struct {
orm *xorm.Engine
}
func NewWechatMemberModel() *WechatMemberModel |
func (w *WechatMemberModel) GetList(page, limit int64) (list []tables.WechatMember, total int64) {
offset := (page - 1) * limit
total, _ = w.orm.Limit(int(limit), int(offset)).FindAndCount(&list)
if list == nil {
list = []tables.WechatMember{}
}
return list, total
}
func (w *WechatMemberModel) GetInfo(id int64) tables.WechatMember {
var member tables.WechatMember
w.orm.Where("id = ?", id).Get(&member)
return member
}
| {
return &WechatMemberModel{orm: helper.GetORM()}
} |
script.js | //All code will be ready run when the page is rendered
$(document).ready(function() {
//eventListner for the search button
//will find the search value in the search value id
$("#search-button").on("click", function() {
var searchValue = $("#search-value").val();
// clear input box
//sets the search value back to an empty stringt
$("#search-value").val("");
//makes a querry for the weather
searchWeather(searchValue);
});
//Searches the weather for the city searched by the user
$(".history").on("click", "li", function() {
//Store the text
searchWeather($(this).text());
});
//Creates the city search history tab on the left side of the page
function | (text) {
var li = $("<li>").addClass("list-group-item list-group-item-action").text(text);
//appends it to the page
$(".history").append(li);
}
//main search function that searches and grabs info from the API
function searchWeather(searchValue) {
$.ajax({
type: "GET",
//The API url and the API key to get the weather map information
url: "https://api.openweathermap.org/data/2.5/weather?q=" + searchValue + "&appid=08bce3851a2504c6cadfe41faa8bc8ac&units=imperial",
//returns the data in JSON
dataType: "json",
//if the query is successful in finding the specified weather data for the city.
success: function(data) {
// create history link for this search
if (history.indexOf(searchValue) === -1) {
history.push(searchValue);
window.localStorage.setItem("history", JSON.stringify(history));
//appending and creating the content and links for the history section above
makeRow(searchValue);
}
// clear any old content
$("#today").empty();
// create html content for current weather
//Referencing the various return data that the API brings back and setting it equal to a variable
//City Title
var title = $("<h3>").addClass("card-title").text(data.name + " (" + new Date().toLocaleDateString() + ")");
//Card the data cits in
var card = $("<div>").addClass("card");
//Wind Speed
var wind = $("<p>").addClass("card-text").text("Wind Speed: " + data.wind.speed + " MPH");
//Humidity
var humid = $("<p>").addClass("card-text").text("Humidity: " + data.main.humidity + "%");
//Temperature
var temp = $("<p>").addClass("card-text").text("Temperature: " + data.main.temp + " °F");
//Body copy
var cardBody = $("<div>").addClass("card-body");
//IMG
var img = $("<img>").attr("src", "http://openweathermap.org/img/w/" + data.weather[0].icon + ".png");
// merge and add to page
//Adds the title above the card div
title.append(img);
//appends tbe main content into the cardBody div
cardBody.append(title, temp, humid, wind);
//appends the card body to the page
card.append(cardBody);
//appends todays date
$("#today").append(card);
// call follow-up api endpoints
getForecast(searchValue);
getUVIndex(data.coord.lat, data.coord.lon);
getHourlyForecast(data.coord.lat, data.coord.lon);
}
});
}
function getForecast(searchValue) {
$.ajax({
type: "GET",
url: "https://api.openweathermap.org/data/2.5/forecast?q=" + searchValue + "&appid=08bce3851a2504c6cadfe41faa8bc8ac&units=imperial",
dataType: "json",
success: function(data) {
// overwrite any existing content with title and empty row
$("#forecast").html("<h4 class=\"mt-3\">5-Day Forecast:</h4>").append("<div class=\"row\">");
// loop over all forecasts (by 3-hour increments)
for (var i = 0; i < data.list.length; i++) {
// only look at forecasts around 3:00pm
if (data.list[i].dt_txt.indexOf("15:00:00") !== -1) {
// create html elements for a bootstrap card
var col = $("<div>").addClass("col-md-2");
var card = $("<div>").addClass("card bg-primary text-white");
var body = $("<div>").addClass("card-body p-2");
var title = $("<h5>").addClass("card-title").text(new Date(data.list[i].dt_txt).toLocaleDateString());
var img = $("<img>").attr("src", "http://openweathermap.org/img/w/" + data.list[i].weather[0].icon + ".png");
var p1 = $("<p>").addClass("card-text").text("Temp: " + data.list[i].main.temp_max + " °F");
var p2 = $("<p>").addClass("card-text").text("Humidity: " + data.list[i].main.humidity + "%");
// merge together and put on page
col.append(card.append(body.append(title, img, p1, p2)));
$("#forecast .row").append(col);
}
}
}
});
}
function getUVIndex(lat, lon) {
$.ajax({
type: "GET",
url: "https://api.openweathermap.org/data/2.5/uvi?appid=08bce3851a2504c6cadfe41faa8bc8ac&lat=" + lat + "&lon=" + lon,
dataType: "json",
success: function(data) {
var uv = $("<p>").text("UV Index: ");
var btn = $("<span>").addClass("btn btn-sm").text(data.value);
// change color depending on uv value
if (data.value < 3) {
btn.addClass("btn-success");
}
else if (data.value < 7) {
btn.addClass("btn-warning");
}
else {
btn.addClass("btn-danger");
}
$("#today .card-body").append(uv.append(btn));
}
});
}
// get current history, if any
var history = JSON.parse(window.localStorage.getItem("history")) || [];
if (history.length > 0) {
searchWeather(history[history.length-1]);
}
for (var i = 0; i < history.length; i++) {
makeRow(history[i]);
}
// function getHourlyForecast(lat, lon) {
// $.ajax({
// type: "GET",
// url: "https://api.openweathermap.org/data/2.5/onecall?lat=" + lat + "&lon=" + lon + "&appid=08bce3851a2504c6cadfe41faa8bc8ac",
// dataType: "json",
// success: function (data) {
// console.log(data);
// // for (var i = 0; i< 5; i++) {
// // }
// }
// })
// }
});
function getHourlyForecast(lat, lon) {
$.ajax({
type: "GET",
url: "https://api.openweathermap.org/data/2.5/onecall?lat=" + lat + "&lon=" + lon + "&appid=08bce3851a2504c6cadfe41faa8bc8ac&units=imperial",
dataType: "json",
success: function (data) {
console.log(data);
$('#hourlyForecast').html("<h4 class=\"mt-3\">5-Hour Forecast:</h4>").append("<div class=\"row\">");
var hour = moment().startOf("hour");
console.log(hour);
//gives us all 5 temps
for (let i = 0; i < 5; i++) {
var currentHourTemp = data.hourly[i].temp;
console.log(hour)
console.log(currentHourTemp);
//Creates a row and columns for our values
var col = $('<div>').addClass('col-md-2');
var card = $('<div>').addClass("card bg-primary text-white");
var body = $("<div>").addClass("card-body p-2");
var title = $("<h5>").addClass("card-title").text(hour.add(1, 'h').format("h a"));
console.log(title);
var img = $("<img>").attr("src", "http://openweathermap.org/img/w/" + data.hourly[i].weather[0].icon + ".png");
var p1 = $("<p>").addClass("card-text").text("Temp: " + currentHourTemp + " °F");
col.append(card.append(body.append(title, img, p1,)));
$("#hourlyForecast .row").append(col);
}
}
})};
//WHAT TO DISPLAY IN OUR 5 HOUR FORECAST
//1. Temp
//2. The weather img
// create html elements for a bootstrap card
// var col = $("<div>").addClass("col-md-2");
// var card = $("<div>").addClass("card bg-primary text-white");
// var body = $("<div>").addClass("card-body p-2");
// var title = $("<h5>").addClass("card-title").text(new Date(data.list[i].dt_txt).toLocaleDateString());
// var img = $("<img>").attr("src", "http://openweathermap.org/img/w/" + data.list[i].weather[0].icon + ".png");
// var p1 = $("<p>").addClass("card-text").text("Temp: " + data.list[i].main.temp_max + " °F");
// var p2 = $("<p>").addClass("card-text").text("Humidity: " + data.list[i].main.humidity + "%");
// // merge together and put on page
// col.append(card.append(body.append(title, img, p1, p2)));
// $("#forecast .row").append(col); | makeRow |
index.js | const readPkg = require('read-pkg');
const { compose } = require('ramda');
const withOnlyPackageCommits = require('./only-package-commits'); | const logPluginVersion = require('./log-plugin-version');
const { wrapStep } = require('semantic-release-plugin-decorators');
const {
mapNextReleaseVersion,
withOptionsTransforms,
} = require('./options-transforms');
const analyzeCommits = wrapStep(
'analyzeCommits',
compose(logPluginVersion('analyzeCommits'), withOnlyPackageCommits),
{
wrapperName: 'semantic-release-monorepo',
}
);
const generateNotes = wrapStep(
'generateNotes',
compose(
logPluginVersion('generateNotes'),
withOnlyPackageCommits,
withOptionsTransforms([mapNextReleaseVersion(versionToGitTag)])
),
{
wrapperName: 'semantic-release-monorepo',
}
);
module.exports = {
analyzeCommits,
generateNotes,
tagFormat: `${readPkg.sync().name}@\${version}`,
}; | const versionToGitTag = require('./version-to-git-tag'); |
startPyquil969.py | # qubit number=5
# total number=43
import pyquil
from pyquil.api import local_forest_runtime, QVMConnection
from pyquil import Program, get_qc
from pyquil.gates import *
import numpy as np
conn = QVMConnection()
def make_circuit()-> Program:
prog = Program() # circuit begin
prog += H(0) # number=3
prog += H(1) # number=4
prog += H(2) # number=5
prog += H(3) # number=6
prog += H(4) # number=21
prog += H(0) # number=1
prog += H(1) # number=2
prog += H(2) # number=7
prog += H(3) # number=8
prog += H(0) # number=33
prog += CZ(1,0) # number=34
prog += H(0) # number=35
prog += RX(-0.7822565707438585,2) # number=31
prog += X(0) # number=29
prog += CNOT(1,0) # number=30
prog += CNOT(0,1) # number=25
prog += CNOT(0,1) # number=40
prog += X(1) # number=41
prog += CNOT(0,1) # number=42
prog += CNOT(0,1) # number=27
prog += CNOT(0,2) # number=22
prog += X(2) # number=23
prog += CNOT(0,2) # number=24
prog += X(3) # number=12
prog += X(0) # number=13
prog += X(1) # number=14
prog += X(2) # number=15
prog += X(3) # number=16
prog += H(0) # number=17
prog += H(3) # number=37
prog += CZ(2,3) # number=38
prog += H(3) # number=39
prog += H(1) # number=18
prog += H(2) # number=19
prog += RX(2.5761059759436304,3) # number=32
prog += H(3) # number=20
# circuit end
return prog
def | (bitstrings) -> dict:
d = {}
for l in bitstrings:
if d.get(l) is None:
d[l] = 1
else:
d[l] = d[l] + 1
return d
if __name__ == '__main__':
prog = make_circuit()
qvm = get_qc('5q-qvm')
results = qvm.run_and_measure(prog,1024)
bitstrings = np.vstack([results[i] for i in qvm.qubits()]).T
bitstrings = [''.join(map(str, l)) for l in bitstrings]
writefile = open("../data/startPyquil969.csv","w")
print(summrise_results(bitstrings),file=writefile)
writefile.close()
| summrise_results |
rcgcpwm.rs | #[doc = "Reader of register RCGCPWM"]
pub type R = crate::R<u32, super::RCGCPWM>;
#[doc = "Writer for register RCGCPWM"]
pub type W = crate::W<u32, super::RCGCPWM>;
#[doc = "Register RCGCPWM `reset()`'s with value 0"]
impl crate::ResetValue for super::RCGCPWM {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `R0`"]
pub type R0_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `R0`"]
pub struct R0_W<'a> {
w: &'a mut W,
}
impl<'a> R0_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn | (self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Reader of field `R1`"]
pub type R1_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `R1`"]
pub struct R1_W<'a> {
w: &'a mut W,
}
impl<'a> R1_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
impl R {
#[doc = "Bit 0 - PWM Module 0 Run Mode Clock Gating Control"]
#[inline(always)]
pub fn r0(&self) -> R0_R {
R0_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - PWM Module 1 Run Mode Clock Gating Control"]
#[inline(always)]
pub fn r1(&self) -> R1_R {
R1_R::new(((self.bits >> 1) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - PWM Module 0 Run Mode Clock Gating Control"]
#[inline(always)]
pub fn r0(&mut self) -> R0_W {
R0_W { w: self }
}
#[doc = "Bit 1 - PWM Module 1 Run Mode Clock Gating Control"]
#[inline(always)]
pub fn r1(&mut self) -> R1_W {
R1_W { w: self }
}
}
| bit |
hr_history.js | const axios = require("axios");
const mysql = require("mysql");
const util = require("util");
//Function for getting historical data
exports.history_hour = (requestNumber, unixTime, looping, tableName, currency_op, coin) => {
var requestLimit = requestNumber; //Max 2000
var table = tableName;
var loopRepeat = looping;
let timestamp = unixTime;
var check = 0;
var basic_timestamp = unixTime;
var currency = currency_op;
var connection = mysql.createConnection({
host: "kyjdb.cdzelssaqpcy.ap-northeast-2.rds.amazonaws.com",
user: "kyjyeon",
password: "",
database: "coin",
port: 3400
})
//Connect to DB
let connect = () => {
connection.connect((err) => {
if (err) throw err;
console.log(`Connected to mysql...`);
})
}
//Connect to DB and bind the connections into one
const query = util.promisify(connection.query).bind(connection);
//Request API
function getRequest(loop) {
timestamp = basic_timestamp + ((requestLimit+1) * 3600 * loop);
return new Promise(resolve => {
axios.get(`https://min-api.cryptocompare.com/data/histohour?fsym=${coin}&tsym=${currency}&limit=${requestLimit}&aggregate=1&toTs=${timestamp}&api_key=`)
.then((res) => {
//Filter result
dataInput = (i) => {
var val1 = res.data.Data[i].time;
var val2 = res.data.Data[i].close;
var val3 = res.data.Data[i].high;
var val4 = res.data.Data[i].low;
var val5 = res.data.Data[i].open;
var val6 = res.data.Data[i].volumefrom;
var val7 = res.data.Data[i].volumeto;
//Insert value into DB table
try{
query("INSERT INTO " + table + "(_TIME,_CLOSE,_HIGH,_LOW,_OPEN,_VOLUMEFROM,_VOLUMETO)" + " VALUES(" + val1 + "," + val2 + "," + val3 + "," + val4 + "," + val5 + "," + val6 + "," + val7 + ")", (err) => {
if(err){
console.log("error");
}
else {
console.log(`${table} ${val1} : ${i} inserted correctly..`);
if (i == requestLimit - 1) {
console.log("Current Timestamp: " + timestamp + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
}
}
})
}catch(err){
if(err instanceof Errors.ER_DUP_ENTRY){
console.log("Duplicate entry");
connection.end(()=>{
console.log("connection ended...........");
});
}
if(err instanceof ER_DUP_ENTRY){
console.log("ER_DUP_ENTRY");
connection.end(()=>{
console.log("connection ended...........");
});
}
console.log(err);
}
}
async function | () {
for (let i = 0; i < requestLimit; i++) {
await dataInput(i);
}
}
inputData();
resolve();
});
})
}
//Synchronize execution using 'async'
async function insertData() {
for (var i = 0; i < loopRepeat; ++i) {
await getRequest(i, timestamp);
};
}
insertData();
}
| inputData |
jest.config.js | module.exports = {
preset: "ts-jest" | } |
|
core.py | import os
import lmctl.files as files
import yaml
import lmctl.utils.descriptors as descriptor_utils
import lmctl.project.source.config as project_configs
import lmctl.project.journal as project_journal
import lmctl.project.processes.validation as validation_exec
import lmctl.project.processes.staging as stage_exec
import lmctl.project.processes.compile as compile_exec
import lmctl.project.processes.pull as pull_exec
import lmctl.project.processes.package as package_exec
import lmctl.project.processes.listelement as list_exec
import lmctl.project.handlers.interface as handlers_api
import lmctl.project.handlers.manager as handler_manager
import lmctl.project.package.core as pkgs
########################
# Exceptions
########################
class ProjectError(Exception):
pass
class InvalidProjectError(ProjectError):
pass
class ValidateError(ProjectError):
pass
class BuildError(ProjectError):
pass
class BuildValidationError(BuildError):
def __init__(self, validation_result):
super().__init__('Build failed with validation errors')
self.validation_result = validation_result
class PullError(ProjectError):
pass
class ListError(ProjectError):
pass
########################
# Options
########################
class Options:
def __init__(self):
self.journal_consumer = None
class ValidateOptions(Options):
def __init__(self):
super().__init__()
self.allow_autocorrect = False
class BuildOptions(ValidateOptions):
def __init__(self):
super().__init__()
class PullOptions(Options):
def __init__(self):
super().__init__()
########################
# Results
########################
class BuildResult:
def | (self, pkg, validation_result):
self.pkg = pkg
self.validation_result = validation_result
########################
# Projects
########################
class ProjectBase():
def __init__(self, tree, config):
if tree is None:
raise ValueError('tree must be provided')
self.tree = tree
if config is None:
raise ValueError('config must be provided')
self.config = config
self.source_handler = handler_manager.source_handler_for(self.config)(self.tree.root_path, self.config)
self.subprojects = self.__init_subprojects()
def __init_subprojects(self):
subprojects = []
subprojects_config = self.config.subprojects
for subproject_config in subprojects_config:
child_project_path = self.tree.gen_child_project_path(subproject_config.directory)
child_project = Subproject(child_project_path, subproject_config, self)
subprojects.append(child_project)
return subprojects
class Subproject(ProjectBase):
def __init__(self, root_path, config, parent_project):
if root_path is None:
raise ValueError('root_path must be provided for a Subproject')
if config is None:
raise ValueError('config must be provided for a Subproject')
if parent_project is None:
raise ValueError('parent_project must be provided for a Subproject')
self.parent_project = parent_project
tree = SubprojectTree(root_path)
super().__init__(tree, config)
class Project(ProjectBase):
def __init__(self, root_path):
if root_path is None:
raise ValueError('root_path must be provided for a Project')
tree = ProjectTree(root_path)
config = self.__read_project_file(tree)
super().__init__(tree, config)
def __read_project_file(self, tree):
project_file_path = tree.project_file_path
if not os.path.exists(project_file_path):
raise InvalidProjectError('Could not find project file at path: {0}'.format(project_file_path))
with open(project_file_path, 'rt') as f:
config_dict = yaml.safe_load(f.read())
if not config_dict:
config_dict = {}
if 'schema' not in config_dict or config_dict['schema'] == project_configs.SCHEMA_1_0:
version = self.__attempt_to_determine_version()
config_dict = project_configs.ProjectConfigRewriter(project_file_path, config_dict, version).rewrite()
try:
return project_configs.ProjectConfigParser.from_dict(config_dict)
except project_configs.ProjectConfigError as e:
raise InvalidProjectError(str(e)) from e
def __attempt_to_determine_version(self):
try:
potential_descriptor = os.path.join(self.root_path, 'Descriptor', 'assembly.yml')
if os.path.exists(potential_descriptor):
descriptor = descriptor_utils.DescriptorParser().read_from_file(potential_descriptor)
return descriptor.get_version()
except Exception as e:
return None
def __init_journal(self, journal_consumer=None):
return project_journal.ProjectJournal(journal_consumer)
def validate(self, options):
journal = self.__init_journal(options.journal_consumer)
return self.__do_validate(options, journal)
def __do_validate(self, options, journal):
try:
return validation_exec.ValidationProcess(self, options, journal).execute()
except validation_exec.ValidationProcessError as e:
raise ValidateError(str(e)) from e
def build(self, options):
journal = self.__init_journal(options.journal_consumer)
return self.__do_build(options, journal)
def __do_build(self, options, journal):
validate_result = self.__do_validate(options, journal)
if validate_result.has_errors():
raise BuildValidationError(validate_result)
try:
staging_tree = stage_exec.StageProcess(self, options, journal).execute()
content_tree = compile_exec.CompileProcess(self, options, staging_tree, journal).execute()
final_pkg = package_exec.PkgProcess(self, options, content_tree, journal).execute()
except (stage_exec.StageProcessError, compile_exec.CompileProcessError, package_exec.PkgProcessError) as e:
raise BuildError(str(e)) from e
return BuildResult(final_pkg, validate_result)
def pull(self, env_sessions, options):
journal = self.__init_journal(options.journal_consumer)
return self.__do_pull(env_sessions, options, journal)
def __do_pull(self, env_sessions, options, journal):
try:
pull_exec.PullProcess(self, options, journal, env_sessions).execute()
except pull_exec.PullProcessError as e:
raise PullError(str(e)) from e
def list_elements(self, element_type):
journal = self.__init_journal()
try:
return list_exec.ListElementProcess(self, journal, element_type).execute()
except list_exec.ListElementProcessError as e:
raise ListError(str(e)) from e
########################
# Trees
########################
class ProjectBaseTree(files.Tree):
CONTAINS_DIR = 'Contains'
VNFCS_DIR = 'VNFCs'
TOSCA_METADATA_DIR = 'TOSCA-Metadata'
TOSCA_META_FILE = 'TOSCA.meta'
def __relative_child_projects_path(self):
return self.relative_path(ProjectBaseTree.CONTAINS_DIR)
def __vnfcs_or_contains(self):
vnfcs_path = self.vnfcs_path
contains_path = self.contains_path
if os.path.exists(vnfcs_path):
if os.path.exists(contains_path):
raise InvalidProjectError('Project has both a {0} directory and a {1} directory when there should only be one'.format(ProjectBaseTree.VNFCS_DIR, ProjectBaseTree.CONTAINS_DIR))
return vnfcs_path
else:
return contains_path
@property
def tosca_metadata_path(self):
return self.resolve_relative_path(ProjectBaseTree.TOSCA_METADATA_DIR)
@property
def tosca_meta_file_path(self):
return self.resolve_relative_path(ProjectBaseTree.TOSCA_META_FILE)
@property
def vnfcs_path(self):
return self.resolve_relative_path(ProjectBaseTree.VNFCS_DIR)
@property
def contains_path(self):
return self.resolve_relative_path(ProjectBaseTree.CONTAINS_DIR)
@property
def child_projects_path(self):
child_projects_path = self.__vnfcs_or_contains()
return child_projects_path
def gen_child_project_path(self, child_project_dir_name):
child_projects_path = self.__vnfcs_or_contains()
return os.path.join(child_projects_path, child_project_dir_name)
def gen_child_project_tree(self, child_project_dir_name):
return SubprojectTree(self.gen_child_project_path(child_project_dir_name))
class ProjectTree(ProjectBaseTree):
PROJECT_FILE_YML = 'lmproject.yml'
PROJECT_FILE_YAML = 'lmproject.yaml'
def __init__(self, root_path=None):
super().__init__(root_path)
@property
def project_file_name(self):
full_path = self.project_file_path
return os.path.basename(full_path)
@property
def project_file_path(self):
yml_path = self.resolve_relative_path(ProjectTree.PROJECT_FILE_YML)
yaml_path = self.resolve_relative_path(ProjectTree.PROJECT_FILE_YAML)
if os.path.exists(yaml_path):
if os.path.exists(yml_path):
raise InvalidProjectError('Project has both a {0} file and a {1} file when there should only be one'.format(ProjectTree.PROJECT_FILE_YML, ProjectTree.PROJECT_FILE_YAML))
return yaml_path
else:
return yml_path
class SubprojectTree(ProjectBaseTree):
def __init__(self, root_path):
super().__init__(root_path)
| __init__ |
main.rs | use clap::Clap;
use gre::*;
use noise::*;
use std::f64::consts::PI;
use svg::node::element::path::Data;
use svg::node::element::*;
fn | (opts: Opts) -> Vec<Group> {
let height = 210f64;
let width = 297f64;
let perlin = Perlin::new();
let size = 80.;
let f2 = (2., 4.);
let f1 = (14., 22.);
let amp1 = 0.8;
let amp2 = 0.4;
let samples = 200000;
let spins = 120.0;
let splits = 3.0;
let split_threshold = 1.0;
let pow = 2.0;
let noise_angle_freq = 2.0;
let noise_angle_displacement_freq = 0.02;
let noise_angle_displacement = 0.1;
let parametric = |p: f64| {
let p1 = (splits * p).floor();
let p2 = splits * p - p1;
let t = (p1 + split_threshold * p2) / splits;
let t2 =
(p1 + split_threshold * p2.powf(pow)) / splits;
let scale = 1.0 - t2;
let s = spins;
let mut p = (
scale
* amp1
* ((s * 2. * PI * t).cos()
+ amp2
* mix(
(s * f1.0 * PI * t).cos(),
(s * f2.0 * PI * t).cos(),
t,
)),
scale
* amp1
* ((s * 2. * PI * t).sin()
+ amp2
* mix(
(s * f1.1 * PI * t).sin(),
(s * f2.1 * PI * t).sin(),
t,
)),
);
let noise_angle = 2.
* PI
* perlin.get([
noise_angle_freq * p.0,
noise_angle_freq * p.1,
100.0 + opts.seed,
]);
let noise_amp = noise_angle_displacement
* perlin
.get([
noise_angle_displacement_freq * p.0,
noise_angle_displacement_freq * p.1,
opts.seed,
])
.max(0.0);
p.0 *= 1.4;
p.0 += noise_amp * noise_angle.cos();
p.1 += noise_amp * noise_angle.sin();
p
};
let mut routes = Vec::new();
let mut route = Vec::new();
let mut last = (-1000.0, -1000.0);
for i in 0..(samples + 1) {
let sp = i as f64 / (samples as f64);
let o = parametric(sp);
let p = (
width * 0.5 + size * o.0,
height * 0.5 + size * o.1,
);
if euclidian_dist(p, last) > 2.0 {
routes.push(route);
route = Vec::new();
}
route.push(p);
last = p;
}
routes.push(route);
let color = "darkblue";
let data =
routes.iter().fold(Data::new(), |data, route| {
render_route(data, route.clone())
});
let mut l = layer(color);
l = l.add(base_path(color, 0.5, data));
l = l.add(signature(1.5, (200.0, 180.0), color));
vec![l]
}
#[derive(Clap)]
#[clap()]
struct Opts {
#[clap(short, long, default_value = "0.0")]
seed: f64,
}
fn main() {
let opts: Opts = Opts::parse();
let groups = art(opts);
let mut document = base_a4_landscape("white");
for g in groups {
document = document.add(g);
}
svg::save("image.svg", &document).unwrap();
}
| art |
init.ts | import {
chain,
externalSchematic,
noop,
Rule,
schematic,
Tree,
} from '@angular-devkit/schematics';
import {
addDepsToPackageJson,
formatFiles,
readJsonInTree,
setDefaultCollection,
updateJsonInTree,
updateWorkspace,
Linter,
} from '@nrwl/workspace';
import {
angularDevkitVersion,
angularVersion,
jestPresetAngularVersion,
rxjsVersion,
} from '../../utils/versions';
import { Schema } from './schema';
import { E2eTestRunner, UnitTestRunner } from '../../utils/test-runners';
const updateDependencies = (options: Pick<Schema, 'linter'>): Rule =>
addDepsToPackageJson(
{
'@angular/animations': angularVersion,
'@angular/common': angularVersion,
'@angular/compiler': angularVersion,
'@angular/core': angularVersion,
'@angular/forms': angularVersion,
'@angular/platform-browser': angularVersion,
'@angular/platform-browser-dynamic': angularVersion,
'@angular/router': angularVersion,
rxjs: rxjsVersion,
tslib: '^2.0.0',
'zone.js': '^0.10.2',
},
{
'@angular/compiler-cli': angularVersion,
'@angular/language-service': angularVersion,
'@angular-devkit/build-angular': angularDevkitVersion,
codelyzer: options.linter === Linter.TsLint ? '^6.0.0' : undefined,
}
);
export function addUnitTestRunner(
options: Pick<Schema, 'unitTestRunner'>
): Rule {
switch (options.unitTestRunner) {
case UnitTestRunner.Karma:
return schematic('karma', {});
case UnitTestRunner.Jest:
return chain([
addDepsToPackageJson(
{},
{
'jest-preset-angular': jestPresetAngularVersion,
}
),
(host: Tree) => {
const packageJson = readJsonInTree(host, 'package.json');
if (packageJson.devDependencies['@nrwl/jest']) {
return noop();
}
return externalSchematic(
'@nrwl/jest',
'init',
{},
{
interactive: false,
}
);
},
]);
default:
return noop();
}
}
export function | (options: Pick<Schema, 'e2eTestRunner'>): Rule {
switch (options.e2eTestRunner) {
case E2eTestRunner.Protractor:
return (host: Tree) => {
const packageJson = readJsonInTree(host, 'package.json');
if (packageJson.devDependencies['protractor']) {
return noop();
}
return addDepsToPackageJson(
{},
{
protractor: '~7.0.0',
'jasmine-core': '~3.6.0',
'jasmine-spec-reporter': '~5.0.0',
'@types/jasmine': '~3.6.0',
'@types/jasminewd2': '~2.0.3',
}
);
};
case E2eTestRunner.Cypress:
return (host: Tree) => {
const packageJson = readJsonInTree(host, 'package.json');
if (packageJson.devDependencies['@nrwl/cypress']) {
return noop();
}
return externalSchematic(
'@nrwl/cypress',
'ng-add',
{},
{
interactive: false,
}
);
};
default:
return noop();
}
}
export function setDefaults(options: Schema): Rule {
const updateAngularWorkspace = updateWorkspace((workspace) => {
workspace.extensions.schematics = workspace.extensions.schematics || {};
workspace.extensions.schematics['@nrwl/angular:application'] = {
style: options.style,
linter: options.linter,
unitTestRunner: options.unitTestRunner,
e2eTestRunner: options.e2eTestRunner,
...(workspace.extensions.schematics['@nrwl/angular:application'] || {}),
};
workspace.extensions.schematics['@nrwl/angular:library'] = {
style: options.style,
linter: options.linter,
unitTestRunner: options.unitTestRunner,
...(workspace.extensions.schematics['@nrwl/angular:library'] || {}),
};
workspace.extensions.schematics['@nrwl/angular:component'] = {
style: options.style,
...(workspace.extensions.schematics['@nrwl/angular:component'] || {}),
};
});
return chain([setDefaultCollection('@nrwl/angular'), updateAngularWorkspace]);
}
function addPostinstall(): Rule {
return updateJsonInTree('package.json', (json, context) => {
json.scripts = json.scripts || {};
const command =
'ngcc --properties es2015 browser module main --first-only --create-ivy-entry-points';
if (!json.scripts.postinstall) {
json.scripts.postinstall = command;
} else if (!json.scripts.postinstall.includes('ngcc')) {
json.scripts.postinstall = `${json.scripts.postinstall} && ${command}`;
}
return json;
});
}
export default function (options: Schema): Rule {
return chain([
setDefaults(options),
// TODO: Remove this when ngcc can be run in parallel
addPostinstall(),
updateDependencies(options),
addUnitTestRunner(options),
addE2eTestRunner(options),
formatFiles(),
]);
}
| addE2eTestRunner |
en_TZ.go | // Code generated by make_resources.go; DO NOT EDIT.
package locales
import (
"github.com/razor-1/localizer-cldr"
"github.com/razor-1/localizer-cldr/resources/currency"
"github.com/razor-1/localizer-cldr/resources/language"
"github.com/razor-1/localizer-cldr/resources/territory"
)
func Get_en_TZ() *cldr.Locale | {
return &cldr.Locale{
Locale: "en_TZ",
Calendar: cldr.Calendar{Formats: cldr.CalendarFormats{Date: cldr.CalendarDateFormat{Full: "EEEE, MMMM d, y", Long: "MMMM d, y", Medium: "MMM d, y", Short: "M/d/yy"}, Time: cldr.CalendarDateFormat{Full: "HH:mm:ss zzzz", Long: "HH:mm:ss z", Medium: "HH:mm:ss", Short: "HH:mm"}, DateTime: cldr.CalendarDateFormat{Full: "{1} 'at' {0}", Long: "{1} 'at' {0}", Medium: "{1}, {0}", Short: "{1}, {0}"}, GMT: "GMT{0}"}, FormatNames: cldr.CalendarFormatNames{Months: cldr.CalendarMonthFormatNames{Abbreviated: cldr.CalendarMonthFormatNameValue{Jan: "Jan", Feb: "Feb", Mar: "Mar", Apr: "Apr", May: "May", Jun: "Jun", Jul: "Jul", Aug: "Aug", Sep: "Sep", Oct: "Oct", Nov: "Nov", Dec: "Dec"}, Narrow: cldr.CalendarMonthFormatNameValue{Jan: "J", Feb: "F", Mar: "M", Apr: "A", May: "M", Jun: "J", Jul: "J", Aug: "A", Sep: "S", Oct: "O", Nov: "N", Dec: "D"}, Short: cldr.CalendarMonthFormatNameValue{Jan: "", Feb: "", Mar: "", Apr: "", May: "", Jun: "", Jul: "", Aug: "", Sep: "", Oct: "", Nov: "", Dec: ""}, Wide: cldr.CalendarMonthFormatNameValue{Jan: "January", Feb: "February", Mar: "March", Apr: "April", May: "May", Jun: "June", Jul: "July", Aug: "August", Sep: "September", Oct: "October", Nov: "November", Dec: "December"}}, Days: cldr.CalendarDayFormatNames{Abbreviated: cldr.CalendarDayFormatNameValue{Sun: "Sun", Mon: "Mon", Tue: "Tue", Wed: "Wed", Thu: "Thu", Fri: "Fri", Sat: "Sat"}, Narrow: cldr.CalendarDayFormatNameValue{Sun: "S", Mon: "M", Tue: "T", Wed: "W", Thu: "T", Fri: "F", Sat: "S"}, Short: cldr.CalendarDayFormatNameValue{Sun: "Su", Mon: "Mo", Tue: "Tu", Wed: "We", Thu: "Th", Fri: "Fr", Sat: "Sa"}, Wide: cldr.CalendarDayFormatNameValue{Sun: "Sunday", Mon: "Monday", Tue: "Tuesday", Wed: "Wednesday", Thu: "Thursday", Fri: "Friday", Sat: "Saturday"}}, Periods: cldr.CalendarPeriodFormatNames{Abbreviated: cldr.CalendarPeriodFormatNameValue{AM: "AM", PM: "PM"}, Narrow: cldr.CalendarPeriodFormatNameValue{AM: "a", PM: "p"}, Short: cldr.CalendarPeriodFormatNameValue{AM: "", PM: ""}, Wide: cldr.CalendarPeriodFormatNameValue{AM: "AM", PM: "PM"}}}},
Number: cldr.Number{
Symbols: cldr.Symbols{Decimal: ".", Group: ",", Negative: "-", Percent: "%", PerMille: "‰"},
Formats: cldr.NumberFormats{Decimal: "#,##0.###", Currency: "¤#,##0.00", CurrencyAccounting: "¤#,##0.00;(¤#,##0.00)", Percent: "#,##0%"},
Currencies: cldr.Currencies{
currency.ADP: cldr.Currency{DisplayName: "Andorran Peseta", Symbol: ""},
currency.AED: cldr.Currency{DisplayName: "United Arab Emirates Dirham", Symbol: ""},
currency.AFA: cldr.Currency{DisplayName: "Afghan Afghani (1927–2002)", Symbol: ""},
currency.AFN: cldr.Currency{DisplayName: "Afghan Afghani", Symbol: ""},
currency.ALK: cldr.Currency{DisplayName: "Albanian Lek (1946–1965)", Symbol: ""},
currency.ALL: cldr.Currency{DisplayName: "Albanian Lek", Symbol: ""},
currency.AMD: cldr.Currency{DisplayName: "Armenian Dram", Symbol: ""},
currency.ANG: cldr.Currency{DisplayName: "Netherlands Antillean Guilder", Symbol: ""},
currency.AOA: cldr.Currency{DisplayName: "Angolan Kwanza", Symbol: "Kz"},
currency.AOK: cldr.Currency{DisplayName: "Angolan Kwanza (1977–1991)", Symbol: ""},
currency.AON: cldr.Currency{DisplayName: "Angolan New Kwanza (1990–2000)", Symbol: ""},
currency.AOR: cldr.Currency{DisplayName: "Angolan Readjusted Kwanza (1995–1999)", Symbol: ""},
currency.ARA: cldr.Currency{DisplayName: "Argentine Austral", Symbol: ""},
currency.ARL: cldr.Currency{DisplayName: "Argentine Peso Ley (1970–1983)", Symbol: ""},
currency.ARM: cldr.Currency{DisplayName: "Argentine Peso (1881–1970)", Symbol: ""},
currency.ARP: cldr.Currency{DisplayName: "Argentine Peso (1983–1985)", Symbol: ""},
currency.ARS: cldr.Currency{DisplayName: "Argentine Peso", Symbol: "$"},
currency.ATS: cldr.Currency{DisplayName: "Austrian Schilling", Symbol: ""},
currency.AUD: cldr.Currency{DisplayName: "Australian Dollar", Symbol: "A$"},
currency.AWG: cldr.Currency{DisplayName: "Aruban Florin", Symbol: ""},
currency.AZM: cldr.Currency{DisplayName: "Azerbaijani Manat (1993–2006)", Symbol: ""},
currency.AZN: cldr.Currency{DisplayName: "Azerbaijani Manat", Symbol: ""},
currency.BAD: cldr.Currency{DisplayName: "Bosnia-Herzegovina Dinar (1992–1994)", Symbol: ""},
currency.BAM: cldr.Currency{DisplayName: "Bosnia-Herzegovina Convertible Mark", Symbol: "KM"},
currency.BAN: cldr.Currency{DisplayName: "Bosnia-Herzegovina New Dinar (1994–1997)", Symbol: ""},
currency.BBD: cldr.Currency{DisplayName: "Barbadian Dollar", Symbol: "$"},
currency.BDT: cldr.Currency{DisplayName: "Bangladeshi Taka", Symbol: "৳"},
currency.BEC: cldr.Currency{DisplayName: "Belgian Franc (convertible)", Symbol: ""},
currency.BEF: cldr.Currency{DisplayName: "Belgian Franc", Symbol: ""},
currency.BEL: cldr.Currency{DisplayName: "Belgian Franc (financial)", Symbol: ""},
currency.BGL: cldr.Currency{DisplayName: "Bulgarian Hard Lev", Symbol: ""},
currency.BGM: cldr.Currency{DisplayName: "Bulgarian Socialist Lev", Symbol: ""},
currency.BGN: cldr.Currency{DisplayName: "Bulgarian Lev", Symbol: ""},
currency.BGO: cldr.Currency{DisplayName: "Bulgarian Lev (1879–1952)", Symbol: ""},
currency.BHD: cldr.Currency{DisplayName: "Bahraini Dinar", Symbol: ""},
currency.BIF: cldr.Currency{DisplayName: "Burundian Franc", Symbol: ""},
currency.BMD: cldr.Currency{DisplayName: "Bermudan Dollar", Symbol: "$"},
currency.BND: cldr.Currency{DisplayName: "Brunei Dollar", Symbol: "$"},
currency.BOB: cldr.Currency{DisplayName: "Bolivian Boliviano", Symbol: "Bs"},
currency.BOL: cldr.Currency{DisplayName: "Bolivian Boliviano (1863–1963)", Symbol: ""},
currency.BOP: cldr.Currency{DisplayName: "Bolivian Peso", Symbol: ""},
currency.BOV: cldr.Currency{DisplayName: "Bolivian Mvdol", Symbol: ""},
currency.BRB: cldr.Currency{DisplayName: "Brazilian New Cruzeiro (1967–1986)", Symbol: ""},
currency.BRC: cldr.Currency{DisplayName: "Brazilian Cruzado (1986–1989)", Symbol: ""},
currency.BRE: cldr.Currency{DisplayName: "Brazilian Cruzeiro (1990–1993)", Symbol: ""},
currency.BRL: cldr.Currency{DisplayName: "Brazilian Real", Symbol: "R$"},
currency.BRN: cldr.Currency{DisplayName: "Brazilian New Cruzado (1989–1990)", Symbol: ""},
currency.BRR: cldr.Currency{DisplayName: "Brazilian Cruzeiro (1993–1994)", Symbol: ""},
currency.BRZ: cldr.Currency{DisplayName: "Brazilian Cruzeiro (1942–1967)", Symbol: ""},
currency.BSD: cldr.Currency{DisplayName: "Bahamian Dollar", Symbol: "$"},
currency.BTN: cldr.Currency{DisplayName: "Bhutanese Ngultrum", Symbol: ""},
currency.BUK: cldr.Currency{DisplayName: "Burmese Kyat", Symbol: ""},
currency.BWP: cldr.Currency{DisplayName: "Botswanan Pula", Symbol: "P"},
currency.BYB: cldr.Currency{DisplayName: "Belarusian Ruble (1994–1999)", Symbol: ""},
currency.BYN: cldr.Currency{DisplayName: "Belarusian Ruble", Symbol: "р."},
currency.BYR: cldr.Currency{DisplayName: "Belarusian Ruble (2000–2016)", Symbol: ""},
currency.BZD: cldr.Currency{DisplayName: "Belize Dollar", Symbol: "$"},
currency.CAD: cldr.Currency{DisplayName: "Canadian Dollar", Symbol: "CA$"},
currency.CDF: cldr.Currency{DisplayName: "Congolese Franc", Symbol: ""},
currency.CHE: cldr.Currency{DisplayName: "WIR Euro", Symbol: ""},
currency.CHF: cldr.Currency{DisplayName: "Swiss Franc", Symbol: ""},
currency.CHW: cldr.Currency{DisplayName: "WIR Franc", Symbol: ""},
currency.CLE: cldr.Currency{DisplayName: "Chilean Escudo", Symbol: ""},
currency.CLF: cldr.Currency{DisplayName: "Chilean Unit of Account (UF)", Symbol: ""},
currency.CLP: cldr.Currency{DisplayName: "Chilean Peso", Symbol: "$"},
currency.CNH: cldr.Currency{DisplayName: "Chinese Yuan (offshore)", Symbol: ""},
currency.CNX: cldr.Currency{DisplayName: "Chinese People’s Bank Dollar", Symbol: ""},
currency.CNY: cldr.Currency{DisplayName: "Chinese Yuan", Symbol: "CN¥"},
currency.COP: cldr.Currency{DisplayName: "Colombian Peso", Symbol: "$"},
currency.COU: cldr.Currency{DisplayName: "Colombian Real Value Unit", Symbol: ""},
currency.CRC: cldr.Currency{DisplayName: "Costa Rican Colón", Symbol: "₡"},
currency.CSD: cldr.Currency{DisplayName: "Serbian Dinar (2002–2006)", Symbol: ""},
currency.CSK: cldr.Currency{DisplayName: "Czechoslovak Hard Koruna", Symbol: ""},
currency.CUC: cldr.Currency{DisplayName: "Cuban Convertible Peso", Symbol: "$"},
currency.CUP: cldr.Currency{DisplayName: "Cuban Peso", Symbol: "$"},
currency.CVE: cldr.Currency{DisplayName: "Cape Verdean Escudo", Symbol: ""},
currency.CYP: cldr.Currency{DisplayName: "Cypriot Pound", Symbol: ""},
currency.CZK: cldr.Currency{DisplayName: "Czech Koruna", Symbol: "Kč"},
currency.DDM: cldr.Currency{DisplayName: "East German Mark", Symbol: ""},
currency.DEM: cldr.Currency{DisplayName: "German Mark", Symbol: ""},
currency.DJF: cldr.Currency{DisplayName: "Djiboutian Franc", Symbol: ""},
currency.DKK: cldr.Currency{DisplayName: "Danish Krone", Symbol: "kr"},
currency.DOP: cldr.Currency{DisplayName: "Dominican Peso", Symbol: "$"},
currency.DZD: cldr.Currency{DisplayName: "Algerian Dinar", Symbol: ""},
currency.ECS: cldr.Currency{DisplayName: "Ecuadorian Sucre", Symbol: ""},
currency.ECV: cldr.Currency{DisplayName: "Ecuadorian Unit of Constant Value", Symbol: ""},
currency.EEK: cldr.Currency{DisplayName: "Estonian Kroon", Symbol: ""},
currency.EGP: cldr.Currency{DisplayName: "Egyptian Pound", Symbol: "E£"},
currency.ERN: cldr.Currency{DisplayName: "Eritrean Nakfa", Symbol: ""},
currency.ESA: cldr.Currency{DisplayName: "Spanish Peseta (A account)", Symbol: ""},
currency.ESB: cldr.Currency{DisplayName: "Spanish Peseta (convertible account)", Symbol: ""},
currency.ESP: cldr.Currency{DisplayName: "Spanish Peseta", Symbol: "₧"},
currency.ETB: cldr.Currency{DisplayName: "Ethiopian Birr", Symbol: ""},
currency.EUR: cldr.Currency{DisplayName: "Euro", Symbol: "€"},
currency.FIM: cldr.Currency{DisplayName: "Finnish Markka", Symbol: ""},
currency.FJD: cldr.Currency{DisplayName: "Fijian Dollar", Symbol: "$"},
currency.FKP: cldr.Currency{DisplayName: "Falkland Islands Pound", Symbol: "£"},
currency.FRF: cldr.Currency{DisplayName: "French Franc", Symbol: ""},
currency.GBP: cldr.Currency{DisplayName: "British Pound", Symbol: "£"},
currency.GEK: cldr.Currency{DisplayName: "Georgian Kupon Larit", Symbol: ""},
currency.GEL: cldr.Currency{DisplayName: "Georgian Lari", Symbol: "₾"},
currency.GHC: cldr.Currency{DisplayName: "Ghanaian Cedi (1979–2007)", Symbol: ""},
currency.GHS: cldr.Currency{DisplayName: "Ghanaian Cedi", Symbol: ""},
currency.GIP: cldr.Currency{DisplayName: "Gibraltar Pound", Symbol: "£"},
currency.GMD: cldr.Currency{DisplayName: "Gambian Dalasi", Symbol: ""},
currency.GNF: cldr.Currency{DisplayName: "Guinean Franc", Symbol: "FG"},
currency.GNS: cldr.Currency{DisplayName: "Guinean Syli", Symbol: ""},
currency.GQE: cldr.Currency{DisplayName: "Equatorial Guinean Ekwele", Symbol: ""},
currency.GRD: cldr.Currency{DisplayName: "Greek Drachma", Symbol: ""},
currency.GTQ: cldr.Currency{DisplayName: "Guatemalan Quetzal", Symbol: "Q"},
currency.GWE: cldr.Currency{DisplayName: "Portuguese Guinea Escudo", Symbol: ""},
currency.GWP: cldr.Currency{DisplayName: "Guinea-Bissau Peso", Symbol: ""},
currency.GYD: cldr.Currency{DisplayName: "Guyanaese Dollar", Symbol: "$"},
currency.HKD: cldr.Currency{DisplayName: "Hong Kong Dollar", Symbol: "HK$"},
currency.HNL: cldr.Currency{DisplayName: "Honduran Lempira", Symbol: "L"},
currency.HRD: cldr.Currency{DisplayName: "Croatian Dinar", Symbol: ""},
currency.HRK: cldr.Currency{DisplayName: "Croatian Kuna", Symbol: "kn"},
currency.HTG: cldr.Currency{DisplayName: "Haitian Gourde", Symbol: ""},
currency.HUF: cldr.Currency{DisplayName: "Hungarian Forint", Symbol: "Ft"},
currency.IDR: cldr.Currency{DisplayName: "Indonesian Rupiah", Symbol: "Rp"},
currency.IEP: cldr.Currency{DisplayName: "Irish Pound", Symbol: ""},
currency.ILP: cldr.Currency{DisplayName: "Israeli Pound", Symbol: ""},
currency.ILR: cldr.Currency{DisplayName: "Israeli Shekel (1980–1985)", Symbol: ""},
currency.ILS: cldr.Currency{DisplayName: "Israeli New Shekel", Symbol: "₪"},
currency.INR: cldr.Currency{DisplayName: "Indian Rupee", Symbol: "₹"},
currency.IQD: cldr.Currency{DisplayName: "Iraqi Dinar", Symbol: ""},
currency.IRR: cldr.Currency{DisplayName: "Iranian Rial", Symbol: ""},
currency.ISJ: cldr.Currency{DisplayName: "Icelandic Króna (1918–1981)", Symbol: ""},
currency.ISK: cldr.Currency{DisplayName: "Icelandic Króna", Symbol: "kr"},
currency.ITL: cldr.Currency{DisplayName: "Italian Lira", Symbol: ""},
currency.JMD: cldr.Currency{DisplayName: "Jamaican Dollar", Symbol: "$"},
currency.JOD: cldr.Currency{DisplayName: "Jordanian Dinar", Symbol: ""},
currency.JPY: cldr.Currency{DisplayName: "Japanese Yen", Symbol: "¥"},
currency.KES: cldr.Currency{DisplayName: "Kenyan Shilling", Symbol: ""},
currency.KGS: cldr.Currency{DisplayName: "Kyrgystani Som", Symbol: ""},
currency.KHR: cldr.Currency{DisplayName: "Cambodian Riel", Symbol: "៛"},
currency.KMF: cldr.Currency{DisplayName: "Comorian Franc", Symbol: "CF"},
currency.KPW: cldr.Currency{DisplayName: "North Korean Won", Symbol: "₩"},
currency.KRH: cldr.Currency{DisplayName: "South Korean Hwan (1953–1962)", Symbol: ""},
currency.KRO: cldr.Currency{DisplayName: "South Korean Won (1945–1953)", Symbol: ""},
currency.KRW: cldr.Currency{DisplayName: "South Korean Won", Symbol: "₩"},
currency.KWD: cldr.Currency{DisplayName: "Kuwaiti Dinar", Symbol: ""},
currency.KYD: cldr.Currency{DisplayName: "Cayman Islands Dollar", Symbol: "$"},
currency.KZT: cldr.Currency{DisplayName: "Kazakhstani Tenge", Symbol: "₸"},
currency.LAK: cldr.Currency{DisplayName: "Laotian Kip", Symbol: "₭"},
currency.LBP: cldr.Currency{DisplayName: "Lebanese Pound", Symbol: "L£"},
currency.LKR: cldr.Currency{DisplayName: "Sri Lankan Rupee", Symbol: "Rs"},
currency.LRD: cldr.Currency{DisplayName: "Liberian Dollar", Symbol: "$"},
currency.LSL: cldr.Currency{DisplayName: "Lesotho Loti", Symbol: ""},
currency.LTL: cldr.Currency{DisplayName: "Lithuanian Litas", Symbol: "Lt"},
currency.LTT: cldr.Currency{DisplayName: "Lithuanian Talonas", Symbol: ""},
currency.LUC: cldr.Currency{DisplayName: "Luxembourgian Convertible Franc", Symbol: ""},
currency.LUF: cldr.Currency{DisplayName: "Luxembourgian Franc", Symbol: ""},
currency.LUL: cldr.Currency{DisplayName: "Luxembourg Financial Franc", Symbol: ""},
currency.LVL: cldr.Currency{DisplayName: "Latvian Lats", Symbol: "Ls"},
currency.LVR: cldr.Currency{DisplayName: "Latvian Ruble", Symbol: ""},
currency.LYD: cldr.Currency{DisplayName: "Libyan Dinar", Symbol: ""},
currency.MAD: cldr.Currency{DisplayName: "Moroccan Dirham", Symbol: ""},
currency.MAF: cldr.Currency{DisplayName: "Moroccan Franc", Symbol: ""},
currency.MCF: cldr.Currency{DisplayName: "Monegasque Franc", Symbol: ""},
currency.MDC: cldr.Currency{DisplayName: "Moldovan Cupon", Symbol: ""},
currency.MDL: cldr.Currency{DisplayName: "Moldovan Leu", Symbol: ""},
currency.MGA: cldr.Currency{DisplayName: "Malagasy Ariary", Symbol: "Ar"},
currency.MGF: cldr.Currency{DisplayName: "Malagasy Franc", Symbol: ""},
currency.MKD: cldr.Currency{DisplayName: "Macedonian Denar", Symbol: ""},
currency.MKN: cldr.Currency{DisplayName: "Macedonian Denar (1992–1993)", Symbol: ""},
currency.MLF: cldr.Currency{DisplayName: "Malian Franc", Symbol: ""},
currency.MMK: cldr.Currency{DisplayName: "Myanmar Kyat", Symbol: "K"},
currency.MNT: cldr.Currency{DisplayName: "Mongolian Tugrik", Symbol: "₮"},
currency.MOP: cldr.Currency{DisplayName: "Macanese Pataca", Symbol: ""},
currency.MRO: cldr.Currency{DisplayName: "Mauritanian Ouguiya (1973–2017)", Symbol: ""},
currency.MRU: cldr.Currency{DisplayName: "Mauritanian Ouguiya", Symbol: ""},
currency.MTL: cldr.Currency{DisplayName: "Maltese Lira", Symbol: ""},
currency.MTP: cldr.Currency{DisplayName: "Maltese Pound", Symbol: ""},
currency.MUR: cldr.Currency{DisplayName: "Mauritian Rupee", Symbol: "Rs"},
currency.MVP: cldr.Currency{DisplayName: "Maldivian Rupee (1947–1981)", Symbol: ""},
currency.MVR: cldr.Currency{DisplayName: "Maldivian Rufiyaa", Symbol: ""},
currency.MWK: cldr.Currency{DisplayName: "Malawian Kwacha", Symbol: ""},
currency.MXN: cldr.Currency{DisplayName: "Mexican Peso", Symbol: "MX$"},
currency.MXP: cldr.Currency{DisplayName: "Mexican Silver Peso (1861–1992)", Symbol: ""},
currency.MXV: cldr.Currency{DisplayName: "Mexican Investment Unit", Symbol: ""},
currency.MYR: cldr.Currency{DisplayName: "Malaysian Ringgit", Symbol: "RM"},
currency.MZE: cldr.Currency{DisplayName: "Mozambican Escudo", Symbol: ""},
currency.MZM: cldr.Currency{DisplayName: "Mozambican Metical (1980–2006)", Symbol: ""},
currency.MZN: cldr.Currency{DisplayName: "Mozambican Metical", Symbol: ""},
currency.NAD: cldr.Currency{DisplayName: "Namibian Dollar", Symbol: "$"},
currency.NGN: cldr.Currency{DisplayName: "Nigerian Naira", Symbol: "₦"},
currency.NIC: cldr.Currency{DisplayName: "Nicaraguan Córdoba (1988–1991)", Symbol: ""},
currency.NIO: cldr.Currency{DisplayName: "Nicaraguan Córdoba", Symbol: "C$"},
currency.NLG: cldr.Currency{DisplayName: "Dutch Guilder", Symbol: ""},
currency.NOK: cldr.Currency{DisplayName: "Norwegian Krone", Symbol: "kr"},
currency.NPR: cldr.Currency{DisplayName: "Nepalese Rupee", Symbol: "Rs"},
currency.NZD: cldr.Currency{DisplayName: "New Zealand Dollar", Symbol: "NZ$"},
currency.OMR: cldr.Currency{DisplayName: "Omani Rial", Symbol: ""},
currency.PAB: cldr.Currency{DisplayName: "Panamanian Balboa", Symbol: ""},
currency.PEI: cldr.Currency{DisplayName: "Peruvian Inti", Symbol: ""},
currency.PEN: cldr.Currency{DisplayName: "Peruvian Sol", Symbol: ""},
currency.PES: cldr.Currency{DisplayName: "Peruvian Sol (1863–1965)", Symbol: ""},
currency.PGK: cldr.Currency{DisplayName: "Papua New Guinean Kina", Symbol: ""},
currency.PHP: cldr.Currency{DisplayName: "Philippine Piso", Symbol: "₱"},
currency.PKR: cldr.Currency{DisplayName: "Pakistani Rupee", Symbol: "Rs"},
currency.PLN: cldr.Currency{DisplayName: "Polish Zloty", Symbol: "zł"},
currency.PLZ: cldr.Currency{DisplayName: "Polish Zloty (1950–1995)", Symbol: ""},
currency.PTE: cldr.Currency{DisplayName: "Portuguese Escudo", Symbol: ""},
currency.PYG: cldr.Currency{DisplayName: "Paraguayan Guarani", Symbol: "₲"},
currency.QAR: cldr.Currency{DisplayName: "Qatari Rial", Symbol: ""},
currency.RHD: cldr.Currency{DisplayName: "Rhodesian Dollar", Symbol: ""},
currency.ROL: cldr.Currency{DisplayName: "Romanian Leu (1952–2006)", Symbol: ""},
currency.RON: cldr.Currency{DisplayName: "Romanian Leu", Symbol: "lei"},
currency.RSD: cldr.Currency{DisplayName: "Serbian Dinar", Symbol: ""},
currency.RUB: cldr.Currency{DisplayName: "Russian Ruble", Symbol: "₽"},
currency.RUR: cldr.Currency{DisplayName: "Russian Ruble (1991–1998)", Symbol: "р."},
currency.RWF: cldr.Currency{DisplayName: "Rwandan Franc", Symbol: "RF"},
currency.SAR: cldr.Currency{DisplayName: "Saudi Riyal", Symbol: ""},
currency.SBD: cldr.Currency{DisplayName: "Solomon Islands Dollar", Symbol: "$"},
currency.SCR: cldr.Currency{DisplayName: "Seychellois Rupee", Symbol: ""},
currency.SDD: cldr.Currency{DisplayName: "Sudanese Dinar (1992–2007)", Symbol: ""},
currency.SDG: cldr.Currency{DisplayName: "Sudanese Pound", Symbol: ""},
currency.SDP: cldr.Currency{DisplayName: "Sudanese Pound (1957–1998)", Symbol: ""},
currency.SEK: cldr.Currency{DisplayName: "Swedish Krona", Symbol: "kr"},
currency.SGD: cldr.Currency{DisplayName: "Singapore Dollar", Symbol: "$"},
currency.SHP: cldr.Currency{DisplayName: "St. Helena Pound", Symbol: "£"},
currency.SIT: cldr.Currency{DisplayName: "Slovenian Tolar", Symbol: ""},
currency.SKK: cldr.Currency{DisplayName: "Slovak Koruna", Symbol: ""},
currency.SLL: cldr.Currency{DisplayName: "Sierra Leonean Leone", Symbol: ""},
currency.SOS: cldr.Currency{DisplayName: "Somali Shilling", Symbol: ""},
currency.SRD: cldr.Currency{DisplayName: "Surinamese Dollar", Symbol: "$"},
currency.SRG: cldr.Currency{DisplayName: "Surinamese Guilder", Symbol: ""},
currency.SSP: cldr.Currency{DisplayName: "South Sudanese Pound", Symbol: "£"},
currency.STD: cldr.Currency{DisplayName: "São Tomé & Príncipe Dobra (1977–2017)", Symbol: ""},
currency.STN: cldr.Currency{DisplayName: "São Tomé & Príncipe Dobra", Symbol: "Db"},
currency.SUR: cldr.Currency{DisplayName: "Soviet Rouble", Symbol: ""},
currency.SVC: cldr.Currency{DisplayName: "Salvadoran Colón", Symbol: ""},
currency.SYP: cldr.Currency{DisplayName: "Syrian Pound", Symbol: "£"},
currency.SZL: cldr.Currency{DisplayName: "Swazi Lilangeni", Symbol: ""},
currency.THB: cldr.Currency{DisplayName: "Thai Baht", Symbol: "฿"},
currency.TJR: cldr.Currency{DisplayName: "Tajikistani Ruble", Symbol: ""},
currency.TJS: cldr.Currency{DisplayName: "Tajikistani Somoni", Symbol: ""},
currency.TMM: cldr.Currency{DisplayName: "Turkmenistani Manat (1993–2009)", Symbol: ""},
currency.TMT: cldr.Currency{DisplayName: "Turkmenistani Manat", Symbol: ""},
currency.TND: cldr.Currency{DisplayName: "Tunisian Dinar", Symbol: ""},
currency.TOP: cldr.Currency{DisplayName: "Tongan Paʻanga", Symbol: "T$"},
currency.TPE: cldr.Currency{DisplayName: "Timorese Escudo", Symbol: ""},
currency.TRL: cldr.Currency{DisplayName: "Turkish Lira (1922–2005)", Symbol: ""},
currency.TRY: cldr.Currency{DisplayName: "Turkish Lira", Symbol: "₺"},
currency.TTD: cldr.Currency{DisplayName: "Trinidad & Tobago Dollar", Symbol: "$"},
currency.TWD: cldr.Currency{DisplayName: "New Taiwan Dollar", Symbol: "NT$"},
currency.TZS: cldr.Currency{DisplayName: "Tanzanian Shilling", Symbol: "TSh"},
currency.UAH: cldr.Currency{DisplayName: "Ukrainian Hryvnia", Symbol: "₴"},
currency.UAK: cldr.Currency{DisplayName: "Ukrainian Karbovanets", Symbol: ""},
currency.UGS: cldr.Currency{DisplayName: "Ugandan Shilling (1966–1987)", Symbol: ""},
currency.UGX: cldr.Currency{DisplayName: "Ugandan Shilling", Symbol: ""},
currency.USD: cldr.Currency{DisplayName: "US Dollar", Symbol: "$"},
currency.USN: cldr.Currency{DisplayName: "US Dollar (Next day)", Symbol: ""},
currency.USS: cldr.Currency{DisplayName: "US Dollar (Same day)", Symbol: ""},
currency.UYI: cldr.Currency{DisplayName: "Uruguayan Peso (Indexed Units)", Symbol: ""},
currency.UYP: cldr.Currency{DisplayName: "Uruguayan Peso (1975–1993)", Symbol: ""},
currency.UYU: cldr.Currency{DisplayName: "Uruguayan Peso", Symbol: "$"},
currency.UYW: cldr.Currency{DisplayName: "Uruguayan Nominal Wage Index Unit", Symbol: ""},
currency.UZS: cldr.Currency{DisplayName: "Uzbekistani Som", Symbol: ""},
currency.VEB: cldr.Currency{DisplayName: "Venezuelan Bolívar (1871–2008)", Symbol: ""},
currency.VEF: cldr.Currency{DisplayName: "Venezuelan Bolívar (2008–2018)", Symbol: "Bs"},
currency.VES: cldr.Currency{DisplayName: "Venezuelan Bolívar", Symbol: ""},
currency.VND: cldr.Currency{DisplayName: "Vietnamese Dong", Symbol: "₫"},
currency.VNN: cldr.Currency{DisplayName: "Vietnamese Dong (1978–1985)", Symbol: ""},
currency.VUV: cldr.Currency{DisplayName: "Vanuatu Vatu", Symbol: ""},
currency.WST: cldr.Currency{DisplayName: "Samoan Tala", Symbol: ""},
currency.XAF: cldr.Currency{DisplayName: "Central African CFA Franc", Symbol: "FCFA"},
currency.XAG: cldr.Currency{DisplayName: "Silver", Symbol: ""},
currency.XAU: cldr.Currency{DisplayName: "Gold", Symbol: ""},
currency.XBA: cldr.Currency{DisplayName: "European Composite Unit", Symbol: ""},
currency.XBB: cldr.Currency{DisplayName: "European Monetary Unit", Symbol: ""},
currency.XBC: cldr.Currency{DisplayName: "European Unit of Account (XBC)", Symbol: ""},
currency.XBD: cldr.Currency{DisplayName: "European Unit of Account (XBD)", Symbol: ""},
currency.XCD: cldr.Currency{DisplayName: "East Caribbean Dollar", Symbol: "EC$"},
currency.XDR: cldr.Currency{DisplayName: "Special Drawing Rights", Symbol: ""},
currency.XEU: cldr.Currency{DisplayName: "European Currency Unit", Symbol: ""},
currency.XFO: cldr.Currency{DisplayName: "French Gold Franc", Symbol: ""},
currency.XFU: cldr.Currency{DisplayName: "French UIC-Franc", Symbol: ""},
currency.XOF: cldr.Currency{DisplayName: "West African CFA Franc", Symbol: "CFA"},
currency.XPD: cldr.Currency{DisplayName: "Palladium", Symbol: ""},
currency.XPF: cldr.Currency{DisplayName: "CFP Franc", Symbol: "CFPF"},
currency.XPT: cldr.Currency{DisplayName: "Platinum", Symbol: ""},
currency.XRE: cldr.Currency{DisplayName: "RINET Funds", Symbol: ""},
currency.XSU: cldr.Currency{DisplayName: "Sucre", Symbol: ""},
currency.XTS: cldr.Currency{DisplayName: "Testing Currency Code", Symbol: ""},
currency.XUA: cldr.Currency{DisplayName: "ADB Unit of Account", Symbol: ""},
currency.XXX: cldr.Currency{DisplayName: "Unknown Currency", Symbol: "¤"},
currency.YDD: cldr.Currency{DisplayName: "Yemeni Dinar", Symbol: ""},
currency.YER: cldr.Currency{DisplayName: "Yemeni Rial", Symbol: ""},
currency.YUD: cldr.Currency{DisplayName: "Yugoslavian Hard Dinar (1966–1990)", Symbol: ""},
currency.YUM: cldr.Currency{DisplayName: "Yugoslavian New Dinar (1994–2002)", Symbol: ""},
currency.YUN: cldr.Currency{DisplayName: "Yugoslavian Convertible Dinar (1990–1992)", Symbol: ""},
currency.YUR: cldr.Currency{DisplayName: "Yugoslavian Reformed Dinar (1992–1993)", Symbol: ""},
currency.ZAL: cldr.Currency{DisplayName: "South African Rand (financial)", Symbol: ""},
currency.ZAR: cldr.Currency{DisplayName: "South African Rand", Symbol: "R"},
currency.ZMK: cldr.Currency{DisplayName: "Zambian Kwacha (1968–2012)", Symbol: ""},
currency.ZMW: cldr.Currency{DisplayName: "Zambian Kwacha", Symbol: "ZK"},
currency.ZRN: cldr.Currency{DisplayName: "Zairean New Zaire (1993–1998)", Symbol: ""},
currency.ZRZ: cldr.Currency{DisplayName: "Zairean Zaire (1971–1993)", Symbol: ""},
currency.ZWD: cldr.Currency{DisplayName: "Zimbabwean Dollar (1980–2008)", Symbol: ""},
currency.ZWL: cldr.Currency{DisplayName: "Zimbabwean Dollar (2009)", Symbol: ""},
currency.ZWR: cldr.Currency{DisplayName: "Zimbabwean Dollar (2008)", Symbol: ""},
},
},
Display: cldr.LocaleDisplayPattern{Pattern: "{0} ({1})", Separator: "{0}, {1}", KeyTypePattern: "{0}: {1}"},
Languages: cldr.Languages{
language.AA: "Afar",
language.AB: "Abkhazian",
language.ACE: "Achinese",
language.ACH: "Acoli",
language.ADA: "Adangme",
language.ADY: "Adyghe",
language.AE: "Avestan",
language.AEB: "Tunisian Arabic",
language.AF: "Afrikaans",
language.AFH: "Afrihili",
language.AGQ: "Aghem",
language.AIN: "Ainu",
language.AK: "Akan",
language.AKK: "Akkadian",
language.AKZ: "Alabama",
language.ALE: "Aleut",
language.ALN: "Gheg Albanian",
language.ALT: "Southern Altai",
language.AM: "Amharic",
language.AN: "Aragonese",
language.ANG: "Old English",
language.ANP: "Angika",
language.AR: "Arabic",
language.AR_001: "Modern Standard Arabic",
language.ARC: "Aramaic",
language.ARN: "Mapuche",
language.ARO: "Araona",
language.ARP: "Arapaho",
language.ARQ: "Algerian Arabic",
language.ARS: "Arabic, Najdi",
language.ARW: "Arawak",
language.ARY: "Moroccan Arabic",
language.ARZ: "Egyptian Arabic",
language.AS: "Assamese",
language.ASA: "Asu",
language.ASE: "American Sign Language",
language.AST: "Asturian",
language.AV: "Avaric",
language.AVK: "Kotava",
language.AWA: "Awadhi",
language.AY: "Aymara",
language.AZ: "Azeri",
language.BA: "Bashkir",
language.BAL: "Baluchi",
language.BAN: "Balinese",
language.BAR: "Bavarian",
language.BAS: "Basaa",
language.BAX: "Bamun",
language.BBC: "Batak Toba",
language.BBJ: "Ghomala",
language.BE: "Belarusian",
language.BEJ: "Beja",
language.BEM: "Bemba",
language.BEW: "Betawi",
language.BEZ: "Bena",
language.BFD: "Bafut",
language.BFQ: "Badaga",
language.BG: "Bulgarian",
language.BGN: "Western Balochi",
language.BHO: "Bhojpuri",
language.BI: "Bislama",
language.BIK: "Bikol",
language.BIN: "Bini",
language.BJN: "Banjar",
language.BKM: "Kom",
language.BLA: "Siksika",
language.BM: "Bambara",
language.BN: "Bangla",
language.BO: "Tibetan",
language.BPY: "Bishnupriya",
language.BQI: "Bakhtiari",
language.BR: "Breton",
language.BRA: "Braj",
language.BRH: "Brahui",
language.BRX: "Bodo",
language.BS: "Bosnian",
language.BSS: "Akoose",
language.BUA: "Buriat",
language.BUG: "Buginese",
language.BUM: "Bulu",
language.BYN: "Blin",
language.BYV: "Medumba",
language.CA: "Catalan",
language.CAD: "Caddo",
language.CAR: "Carib",
language.CAY: "Cayuga",
language.CCH: "Atsam",
language.CCP: "Chakma",
language.CE: "Chechen",
language.CEB: "Cebuano",
language.CGG: "Chiga",
language.CH: "Chamorro",
language.CHB: "Chibcha",
language.CHG: "Chagatai",
language.CHK: "Chuukese",
language.CHM: "Mari",
language.CHN: "Chinook Jargon",
language.CHO: "Choctaw",
language.CHP: "Chipewyan",
language.CHR: "Cherokee",
language.CHY: "Cheyenne",
language.CIC: "Chickasaw",
language.CKB: "Kurdish, Sorani",
language.CO: "Corsican",
language.COP: "Coptic",
language.CPS: "Capiznon",
language.CR: "Cree",
language.CRH: "Crimean Turkish",
language.CRS: "Seselwa Creole French",
language.CS: "Czech",
language.CSB: "Kashubian",
language.CU: "Church Slavic",
language.CV: "Chuvash",
language.CY: "Welsh",
language.DA: "Danish",
language.DAK: "Dakota",
language.DAR: "Dargwa",
language.DAV: "Taita",
language.DE: "German",
language.DE_AT: "Austrian German",
language.DE_CH: "Swiss High German",
language.DEL: "Delaware",
language.DEN: "Slave",
language.DGR: "Dogrib",
language.DIN: "Dinka",
language.DJE: "Zarma",
language.DOI: "Dogri",
language.DSB: "Lower Sorbian",
language.DTP: "Central Dusun",
language.DUA: "Duala",
language.DUM: "Middle Dutch",
language.DV: "Divehi",
language.DYO: "Jola-Fonyi",
language.DYU: "Dyula",
language.DZ: "Dzongkha",
language.DZG: "Dazaga",
language.EBU: "Embu",
language.EE: "Ewe",
language.EFI: "Efik",
language.EGL: "Emilian",
language.EGY: "Ancient Egyptian",
language.EKA: "Ekajuk",
language.EL: "Greek",
language.ELX: "Elamite",
language.EN: "English",
language.EN_AU: "Australian English",
language.EN_CA: "Canadian English",
language.EN_GB: "UK English",
language.EN_US: "US English",
language.ENM: "Middle English",
language.EO: "Esperanto",
language.ES: "Spanish",
language.ES_419: "Latin American Spanish",
language.ES_ES: "European Spanish",
language.ES_MX: "Mexican Spanish",
language.ESU: "Central Yupik",
language.ET: "Estonian",
language.EU: "Basque",
language.EWO: "Ewondo",
language.EXT: "Extremaduran",
language.FA: "Persian",
language.FA_AF: "Dari",
language.FAN: "Fang",
language.FAT: "Fanti",
language.FF: "Fulah",
language.FI: "Finnish",
language.FIL: "Filipino",
language.FIT: "Tornedalen Finnish",
language.FJ: "Fijian",
language.FO: "Faroese",
language.FON: "Fon",
language.FR: "French",
language.FR_CA: "Canadian French",
language.FR_CH: "Swiss French",
language.FRC: "Cajun French",
language.FRM: "Middle French",
language.FRO: "Old French",
language.FRP: "Arpitan",
language.FRR: "Northern Frisian",
language.FRS: "Eastern Frisian",
language.FUR: "Friulian",
language.FY: "Western Frisian",
language.GA: "Irish",
language.GAA: "Ga",
language.GAG: "Gagauz",
language.GAN: "Gan Chinese",
language.GAY: "Gayo",
language.GBA: "Gbaya",
language.GBZ: "Zoroastrian Dari",
language.GD: "Scottish Gaelic",
language.GEZ: "Geez",
language.GIL: "Gilbertese",
language.GL: "Galician",
language.GLK: "Gilaki",
language.GMH: "Middle High German",
language.GN: "Guarani",
language.GOH: "Old High German",
language.GOM: "Goan Konkani",
language.GON: "Gondi",
language.GOR: "Gorontalo",
language.GOT: "Gothic",
language.GRB: "Grebo",
language.GRC: "Ancient Greek",
language.GSW: "Swiss German",
language.GU: "Gujarati",
language.GUC: "Wayuu",
language.GUR: "Frafra",
language.GUZ: "Gusii",
language.GV: "Manx",
language.GWI: "Gwichʼin",
language.HA: "Hausa",
language.HAI: "Haida",
language.HAK: "Hakka Chinese",
language.HAW: "Hawaiian",
language.HE: "Hebrew",
language.HI: "Hindi",
language.HIF: "Fiji Hindi",
language.HIL: "Hiligaynon",
language.HIT: "Hittite",
language.HMN: "Hmong",
language.HO: "Hiri Motu",
language.HR: "Croatian",
language.HSB: "Upper Sorbian",
language.HSN: "Xiang Chinese",
language.HT: "Haitian Creole",
language.HU: "Hungarian",
language.HUP: "Hupa",
language.HY: "Armenian",
language.HZ: "Herero",
language.IA: "Interlingua",
language.IBA: "Iban",
language.IBB: "Ibibio",
language.ID: "Indonesian",
language.IE: "Interlingue",
language.IG: "Igbo",
language.II: "Sichuan Yi",
language.IK: "Inupiaq",
language.ILO: "Iloko",
language.INH: "Ingush",
language.IO: "Ido",
language.IS: "Icelandic",
language.IT: "Italian",
language.IU: "Inuktitut",
language.IZH: "Ingrian",
language.JA: "Japanese",
language.JAM: "Jamaican Creole English",
language.JBO: "Lojban",
language.JGO: "Ngomba",
language.JMC: "Machame",
language.JPR: "Judeo-Persian",
language.JRB: "Judeo-Arabic",
language.JUT: "Jutish",
language.JV: "Javanese",
language.KA: "Georgian",
language.KAA: "Kara-Kalpak",
language.KAB: "Kabyle",
language.KAC: "Kachin",
language.KAJ: "Jju",
language.KAM: "Kamba",
language.KAW: "Kawi",
language.KBD: "Kabardian",
language.KBL: "Kanembu",
language.KCG: "Tyap",
language.KDE: "Makonde",
language.KEA: "Kabuverdianu",
language.KEN: "Kenyang",
language.KFO: "Koro",
language.KG: "Kongo",
language.KGP: "Kaingang",
language.KHA: "Khasi",
language.KHO: "Khotanese",
language.KHQ: "Koyra Chiini",
language.KHW: "Khowar",
language.KI: "Kikuyu",
language.KIU: "Kirmanjki",
language.KJ: "Kuanyama",
language.KK: "Kazakh",
language.KKJ: "Kako",
language.KL: "Kalaallisut",
language.KLN: "Kalenjin",
language.KM: "Khmer",
language.KMB: "Kimbundu",
language.KN: "Kannada",
language.KO: "Korean",
language.KOI: "Komi-Permyak",
language.KOK: "Konkani",
language.KOS: "Kosraean",
language.KPE: "Kpelle",
language.KR: "Kanuri",
language.KRC: "Karachay-Balkar",
language.KRI: "Krio",
language.KRJ: "Kinaray-a",
language.KRL: "Karelian",
language.KRU: "Kurukh",
language.KS: "Kashmiri",
language.KSB: "Shambala",
language.KSF: "Bafia",
language.KSH: "Colognian",
language.KU: "Kurdish",
language.KUM: "Kumyk",
language.KUT: "Kutenai",
language.KV: "Komi",
language.KW: "Cornish",
language.KY: "Kirghiz",
language.LA: "Latin",
language.LAD: "Ladino",
language.LAG: "Langi",
language.LAH: "Lahnda",
language.LAM: "Lamba",
language.LB: "Luxembourgish",
language.LEZ: "Lezghian",
language.LFN: "Lingua Franca Nova",
language.LG: "Ganda",
language.LI: "Limburgish",
language.LIJ: "Ligurian",
language.LIV: "Livonian",
language.LKT: "Lakota",
language.LMO: "Lombard",
language.LN: "Lingala",
language.LO: "Lao",
language.LOL: "Mongo",
language.LOU: "Louisiana Creole",
language.LOZ: "Lozi",
language.LRC: "Northern Luri",
language.LT: "Lithuanian",
language.LTG: "Latgalian",
language.LU: "Luba-Katanga",
language.LUA: "Luba-Lulua",
language.LUI: "Luiseno",
language.LUN: "Lunda",
language.LUO: "Luo",
language.LUS: "Mizo",
language.LUY: "Luyia",
language.LV: "Latvian",
language.LZH: "Literary Chinese",
language.LZZ: "Laz",
language.MAD: "Madurese",
language.MAF: "Mafa",
language.MAG: "Magahi",
language.MAI: "Maithili",
language.MAK: "Makasar",
language.MAN: "Mandingo",
language.MAS: "Masai",
language.MDE: "Maba",
language.MDF: "Moksha",
language.MDR: "Mandar",
language.MEN: "Mende",
language.MER: "Meru",
language.MFE: "Morisyen",
language.MG: "Malagasy",
language.MGA: "Middle Irish",
language.MGH: "Makhuwa-Meetto",
language.MGO: "Metaʼ",
language.MH: "Marshallese",
language.MI: "Maori",
language.MIC: "Mi'kmaq",
language.MIN: "Minangkabau",
language.MK: "Macedonian",
language.ML: "Malayalam",
language.MN: "Mongolian",
language.MNC: "Manchu",
language.MNI: "Manipuri",
language.MOH: "Mohawk",
language.MOS: "Mossi",
language.MR: "Marathi",
language.MRJ: "Western Mari",
language.MS: "Malay",
language.MT: "Maltese",
language.MUA: "Mundang",
language.MUL: "Multiple languages",
language.MUS: "Muscogee",
language.MWL: "Mirandese",
language.MWR: "Marwari",
language.MWV: "Mentawai",
language.MY: "Myanmar Language",
language.MYE: "Myene",
language.MYV: "Erzya",
language.MZN: "Mazanderani",
language.NA: "Nauru",
language.NAN: "Min Nan Chinese",
language.NAP: "Neapolitan",
language.NAQ: "Nama",
language.NB: "Norwegian Bokmål",
language.ND: "North Ndebele",
language.NDS: "Low German",
language.NDS_NL: "Low Saxon",
language.NE: "Nepali",
language.NEW: "Newari",
language.NG: "Ndonga",
language.NIA: "Nias",
language.NIU: "Niuean",
language.NJO: "Ao Naga",
language.NL: "Dutch",
language.NL_BE: "Flemish",
language.NMG: "Kwasio",
language.NN: "Norwegian Nynorsk",
language.NNH: "Ngiemboon",
language.NO: "Norwegian",
language.NOG: "Nogai",
language.NON: "Old Norse",
language.NOV: "Novial",
language.NQO: "N’Ko",
language.NR: "South Ndebele",
language.NSO: "Northern Sotho",
language.NUS: "Nuer",
language.NV: "Navajo",
language.NWC: "Classical Newari",
language.NY: "Nyanja",
language.NYM: "Nyamwezi",
language.NYN: "Nyankole",
language.NYO: "Nyoro",
language.NZI: "Nzima",
language.OC: "Occitan",
language.OJ: "Ojibwa",
language.OM: "Oromo",
language.OR: "Odia",
language.OS: "Ossetic",
language.OSA: "Osage",
language.OTA: "Ottoman Turkish",
language.PA: "Punjabi",
language.PAG: "Pangasinan",
language.PAL: "Pahlavi",
language.PAM: "Pampanga",
language.PAP: "Papiamento",
language.PAU: "Palauan",
language.PCD: "Picard",
language.PCM: "Nigerian Pidgin",
language.PDC: "Pennsylvania German",
language.PDT: "Plautdietsch",
language.PEO: "Old Persian",
language.PFL: "Palatine German",
language.PHN: "Phoenician",
language.PI: "Pali",
language.PL: "Polish",
language.PMS: "Piedmontese",
language.PNT: "Pontic",
language.PON: "Pohnpeian",
language.PRG: "Prussian",
language.PRO: "Old Provençal",
language.PS: "Pushto",
language.PT: "Portuguese",
language.PT_BR: "Brazilian Portuguese",
language.PT_PT: "European Portuguese",
language.QU: "Quechua",
language.QUC: "Kʼicheʼ",
language.QUG: "Chimborazo Highland Quichua",
language.RAJ: "Rajasthani",
language.RAP: "Rapanui",
language.RAR: "Rarotongan",
language.RGN: "Romagnol",
language.RIF: "Riffian",
language.RM: "Romansh",
language.RN: "Rundi",
language.RO: "Romanian",
language.RO_MD: "Moldavian",
language.ROF: "Rombo",
language.ROM: "Romany",
language.ROOT: "Root",
language.RTM: "Rotuman",
language.RU: "Russian",
language.RUE: "Rusyn",
language.RUG: "Roviana",
language.RUP: "Aromanian",
language.RW: "Kinyarwanda",
language.RWK: "Rwa",
language.SA: "Sanskrit",
language.SAD: "Sandawe",
language.SAH: "Sakha",
language.SAM: "Samaritan Aramaic",
language.SAQ: "Samburu",
language.SAS: "Sasak",
language.SAT: "Santali",
language.SAZ: "Saurashtra",
language.SBA: "Ngambay",
language.SBP: "Sangu",
language.SC: "Sardinian",
language.SCN: "Sicilian",
language.SCO: "Scots",
language.SD: "Sindhi",
language.SDC: "Sassarese Sardinian",
language.SDH: "Southern Kurdish",
language.SE: "Northern Sami",
language.SEE: "Seneca",
language.SEH: "Sena",
language.SEI: "Seri",
language.SEL: "Selkup",
language.SES: "Koyraboro Senni",
language.SG: "Sango",
language.SGA: "Old Irish",
language.SGS: "Samogitian",
language.SH: "Serbo-Croatian",
language.SHI: "Tachelhit",
language.SHN: "Shan",
language.SHU: "Chadian Arabic",
language.SI: "Sinhala",
language.SID: "Sidamo",
language.SK: "Slovak",
language.SL: "Slovenian",
language.SLI: "Lower Silesian",
language.SLY: "Selayar",
language.SM: "Samoan",
language.SMA: "Southern Sami",
language.SMJ: "Lule Sami",
language.SMN: "Inari Sami",
language.SMS: "Skolt Sami",
language.SN: "Shona",
language.SNK: "Soninke",
language.SO: "Somali",
language.SOG: "Sogdien",
language.SQ: "Albanian",
language.SR: "Serbian",
language.SR_ME: "Montenegrin",
language.SRN: "Sranan Tongo",
language.SRR: "Serer",
language.SS: "Swati",
language.SSY: "Saho",
language.ST: "Southern Sotho",
language.STQ: "Saterland Frisian",
language.SU: "Sundanese",
language.SUK: "Sukuma",
language.SUS: "Susu",
language.SUX: "Sumerian",
language.SV: "Swedish",
language.SW: "Swahili",
language.SW_CD: "Congo Swahili",
language.SWB: "Comorian",
language.SYC: "Classical Syriac",
language.SYR: "Syriac",
language.SZL: "Silesian",
language.TA: "Tamil",
language.TCY: "Tulu",
language.TE: "Telugu",
language.TEM: "Timne",
language.TEO: "Teso",
language.TER: "Tereno",
language.TET: "Tetum",
language.TG: "Tajik",
language.TH: "Thai",
language.TI: "Tigrinya",
language.TIG: "Tigre",
language.TIV: "Tiv",
language.TK: "Turkmen",
language.TKL: "Tokelau",
language.TKR: "Tsakhur",
language.TL: "Tagalog",
language.TLH: "Klingon",
language.TLI: "Tlingit",
language.TLY: "Talysh",
language.TMH: "Tamashek",
language.TN: "Tswana",
language.TO: "Tongan",
language.TOG: "Nyasa Tonga",
language.TPI: "Tok Pisin",
language.TR: "Turkish",
language.TRU: "Turoyo",
language.TRV: "Taroko",
language.TS: "Tsonga",
language.TSD: "Tsakonian",
language.TSI: "Tsimshian",
language.TT: "Tatar",
language.TTT: "Muslim Tat",
language.TUM: "Tumbuka",
language.TVL: "Tuvalu",
language.TW: "Twi",
language.TWQ: "Tasawaq",
language.TY: "Tahitian",
language.TYV: "Tuvinian",
language.TZM: "Central Atlas Tamazight",
language.UDM: "Udmurt",
language.UG: "Uighur",
language.UGA: "Ugaritic",
language.UK: "Ukrainian",
language.UMB: "Umbundu",
language.UND: "Unknown language",
language.UR: "Urdu",
language.UZ: "Uzbek",
language.VAI: "Vai",
language.VE: "Venda",
language.VEC: "Venetian",
language.VEP: "Veps",
language.VI: "Vietnamese",
language.VLS: "West Flemish",
language.VMF: "Main-Franconian",
language.VO: "Volapük",
language.VOT: "Votic",
language.VRO: "Võro",
language.VUN: "Vunjo",
language.WA: "Walloon",
language.WAE: "Walser",
language.WAL: "Wolaytta",
language.WAR: "Waray",
language.WAS: "Washo",
language.WBP: "Warlpiri",
language.WO: "Wolof",
language.WUU: "Wu Chinese",
language.XAL: "Kalmyk",
language.XH: "Xhosa",
language.XMF: "Mingrelian",
language.XOG: "Soga",
language.YAO: "Yao",
language.YAP: "Yapese",
language.YAV: "Yangben",
language.YBB: "Yemba",
language.YI: "Yiddish",
language.YO: "Yoruba",
language.YRL: "Nheengatu",
language.YUE: "Chinese, Cantonese",
language.ZA: "Zhuang",
language.ZAP: "Zapotec",
language.ZBL: "Blissymbols",
language.ZEA: "Zeelandic",
language.ZEN: "Zenaga",
language.ZGH: "Standard Moroccan Tamazight",
language.ZH: "Chinese, Mandarin",
language.ZH_HANS: "Simplified Mandarin Chinese",
language.ZH_HANT: "Traditional Mandarin Chinese",
language.ZU: "Zulu",
language.ZUN: "Zuni",
language.ZXX: "No linguistic content",
language.ZZA: "Zaza",
},
Territories: cldr.Territories{
territory.V_001: "World",
territory.V_002: "Africa",
territory.V_003: "North America",
territory.V_005: "South America",
territory.V_009: "Oceania",
territory.V_011: "Western Africa",
territory.V_013: "Central America",
territory.V_014: "Eastern Africa",
territory.V_015: "Northern Africa",
territory.V_017: "Middle Africa",
territory.V_018: "Southern Africa",
territory.V_019: "Americas",
territory.V_021: "Northern America",
territory.V_029: "Caribbean",
territory.V_030: "Eastern Asia",
territory.V_034: "Southern Asia",
territory.V_035: "Southeast Asia",
territory.V_039: "Southern Europe",
territory.V_053: "Australasia",
territory.V_054: "Melanesia",
territory.V_057: "Micronesian Region",
territory.V_061: "Polynesia",
territory.V_142: "Asia",
territory.V_143: "Central Asia",
territory.V_145: "Western Asia",
territory.V_150: "Europe",
territory.V_151: "Eastern Europe",
territory.V_154: "Northern Europe",
territory.V_155: "Western Europe",
territory.V_202: "Sub-Saharan Africa",
territory.V_419: "Latin America",
territory.AC: "Ascension Island",
territory.AD: "Andorra",
territory.AE: "United Arab Emirates",
territory.AF: "Afghanistan",
territory.AG: "Antigua & Barbuda",
territory.AI: "Anguilla",
territory.AL: "Albania",
territory.AM: "Armenia",
territory.AO: "Angola",
territory.AQ: "Antarctica",
territory.AR: "Argentina",
territory.AS: "American Samoa",
territory.AT: "Austria",
territory.AU: "Australia",
territory.AW: "Aruba",
territory.AX: "Åland Islands",
territory.AZ: "Azerbaijan",
territory.BA: "Bosnia & Herzegovina",
territory.BB: "Barbados",
territory.BD: "Bangladesh",
territory.BE: "Belgium",
territory.BF: "Burkina Faso",
territory.BG: "Bulgaria",
territory.BH: "Bahrain",
territory.BI: "Burundi",
territory.BJ: "Benin",
territory.BL: "St. Barthélemy",
territory.BM: "Bermuda",
territory.BN: "Brunei",
territory.BO: "Bolivia",
territory.BQ: "Caribbean Netherlands",
territory.BR: "Brazil",
territory.BS: "Bahamas",
territory.BT: "Bhutan",
territory.BV: "Bouvet Island",
territory.BW: "Botswana",
territory.BY: "Belarus",
territory.BZ: "Belize",
territory.CA: "Canada",
territory.CC: "Cocos (Keeling) Islands",
territory.CD: "Congo - Kinshasa",
territory.CF: "Central African Republic",
territory.CG: "Congo - Brazzaville",
territory.CH: "Switzerland",
territory.CI: "Côte d’Ivoire",
territory.CK: "Cook Islands",
territory.CL: "Chile",
territory.CM: "Cameroon",
territory.CN: "China",
territory.CO: "Colombia",
territory.CP: "Clipperton Island",
territory.CR: "Costa Rica",
territory.CU: "Cuba",
territory.CV: "Cape Verde",
territory.CW: "Curaçao",
territory.CX: "Christmas Island",
territory.CY: "Cyprus",
territory.CZ: "Czechia",
territory.DE: "Germany",
territory.DG: "Diego Garcia",
territory.DJ: "Djibouti",
territory.DK: "Denmark",
territory.DM: "Dominica",
territory.DO: "Dominican Republic",
territory.DZ: "Algeria",
territory.EA: "Ceuta & Melilla",
territory.EC: "Ecuador",
territory.EE: "Estonia",
territory.EG: "Egypt",
territory.EH: "Western Sahara",
territory.ER: "Eritrea",
territory.ES: "Spain",
territory.ET: "Ethiopia",
territory.EU: "European Union",
territory.EZ: "Eurozone",
territory.FI: "Finland",
territory.FJ: "Fiji",
territory.FK: "Falkland Islands",
territory.FM: "Micronesia",
territory.FO: "Faroe Islands",
territory.FR: "France",
territory.GA: "Gabon",
territory.GB: "United Kingdom",
territory.GD: "Grenada",
territory.GE: "Georgia",
territory.GF: "French Guiana",
territory.GG: "Guernsey",
territory.GH: "Ghana",
territory.GI: "Gibraltar",
territory.GL: "Greenland",
territory.GM: "Gambia",
territory.GN: "Guinea",
territory.GP: "Guadeloupe",
territory.GQ: "Equatorial Guinea",
territory.GR: "Greece",
territory.GS: "South Georgia & South Sandwich Islands",
territory.GT: "Guatemala",
territory.GU: "Guam",
territory.GW: "Guinea-Bissau",
territory.GY: "Guyana",
territory.HK: "Hong Kong SAR China",
territory.HM: "Heard & McDonald Islands",
territory.HN: "Honduras",
territory.HR: "Croatia",
territory.HT: "Haiti",
territory.HU: "Hungary",
territory.IC: "Canary Islands",
territory.ID: "Indonesia",
territory.IE: "Ireland",
territory.IL: "Israel",
territory.IM: "Isle of Man",
territory.IN: "India",
territory.IO: "British Indian Ocean Territory",
territory.IQ: "Iraq",
territory.IR: "Iran",
territory.IS: "Iceland",
territory.IT: "Italy",
territory.JE: "Jersey",
territory.JM: "Jamaica",
territory.JO: "Jordan",
territory.JP: "Japan",
territory.KE: "Kenya",
territory.KG: "Kyrgyzstan",
territory.KH: "Cambodia",
territory.KI: "Kiribati",
territory.KM: "Comoros",
territory.KN: "St. Kitts & Nevis",
territory.KP: "North Korea",
territory.KR: "South Korea",
territory.KW: "Kuwait",
territory.KY: "Cayman Islands",
territory.KZ: "Kazakhstan",
territory.LA: "Laos",
territory.LB: "Lebanon",
territory.LC: "St. Lucia",
territory.LI: "Liechtenstein",
territory.LK: "Sri Lanka",
territory.LR: "Liberia",
territory.LS: "Lesotho",
territory.LT: "Lithuania",
territory.LU: "Luxembourg",
territory.LV: "Latvia",
territory.LY: "Libya",
territory.MA: "Morocco",
territory.MC: "Monaco",
territory.MD: "Moldova",
territory.ME: "Montenegro",
territory.MF: "St. Martin",
territory.MG: "Madagascar",
territory.MH: "Marshall Islands",
territory.MK: "North Macedonia",
territory.ML: "Mali",
territory.MM: "Myanmar (Burma)",
territory.MN: "Mongolia",
territory.MO: "Macao SAR China",
territory.MP: "Northern Mariana Islands",
territory.MQ: "Martinique",
territory.MR: "Mauritania",
territory.MS: "Montserrat",
territory.MT: "Malta",
territory.MU: "Mauritius",
territory.MV: "Maldives",
territory.MW: "Malawi",
territory.MX: "Mexico",
territory.MY: "Malaysia",
territory.MZ: "Mozambique",
territory.NA: "Namibia",
territory.NC: "New Caledonia",
territory.NE: "Niger",
territory.NF: "Norfolk Island",
territory.NG: "Nigeria",
territory.NI: "Nicaragua",
territory.NL: "Netherlands",
territory.NO: "Norway",
territory.NP: "Nepal",
territory.NR: "Nauru",
territory.NU: "Niue",
territory.NZ: "New Zealand",
territory.OM: "Oman",
territory.PA: "Panama",
territory.PE: "Peru",
territory.PF: "French Polynesia",
territory.PG: "Papua New Guinea",
territory.PH: "Philippines",
territory.PK: "Pakistan",
territory.PL: "Poland",
territory.PM: "St. Pierre & Miquelon",
territory.PN: "Pitcairn Islands",
territory.PR: "Puerto Rico",
territory.PS: "Palestinian Territories",
territory.PT: "Portugal",
territory.PW: "Palau",
territory.PY: "Paraguay",
territory.QA: "Qatar",
territory.QO: "Outlying Oceania",
territory.RE: "Réunion",
territory.RO: "Romania",
territory.RS: "Serbia",
territory.RU: "Russia",
territory.RW: "Rwanda",
territory.SA: "Saudi Arabia",
territory.SB: "Solomon Islands",
territory.SC: "Seychelles",
territory.SD: "Sudan",
territory.SE: "Sweden",
territory.SG: "Singapore",
territory.SH: "St. Helena",
territory.SI: "Slovenia",
territory.SJ: "Svalbard & Jan Mayen",
territory.SK: "Slovakia",
territory.SL: "Sierra Leone",
territory.SM: "San Marino",
territory.SN: "Senegal",
territory.SO: "Somalia",
territory.SR: "Suriname",
territory.SS: "South Sudan",
territory.ST: "São Tomé & Príncipe",
territory.SV: "El Salvador",
territory.SX: "Sint Maarten",
territory.SY: "Syria",
territory.SZ: "Eswatini",
territory.TA: "Tristan da Cunha",
territory.TC: "Turks & Caicos Islands",
territory.TD: "Chad",
territory.TF: "French Southern Territories",
territory.TG: "Togo",
territory.TH: "Thailand",
territory.TJ: "Tajikistan",
territory.TK: "Tokelau",
territory.TL: "Timor-Leste",
territory.TM: "Turkmenistan",
territory.TN: "Tunisia",
territory.TO: "Tonga",
territory.TR: "Turkey",
territory.TT: "Trinidad & Tobago",
territory.TV: "Tuvalu",
territory.TW: "Taiwan",
territory.TZ: "Tanzania",
territory.UA: "Ukraine",
territory.UG: "Uganda",
territory.UM: "U.S. Outlying Islands",
territory.UN: "United Nations",
territory.US: "United States",
territory.UY: "Uruguay",
territory.UZ: "Uzbekistan",
territory.VA: "Vatican City",
territory.VC: "St. Vincent & Grenadines",
territory.VE: "Venezuela",
territory.VG: "British Virgin Islands",
territory.VI: "U.S. Virgin Islands",
territory.VN: "Vietnam",
territory.VU: "Vanuatu",
territory.WF: "Wallis & Futuna",
territory.WS: "Samoa",
territory.XA: "Pseudo-Accents",
territory.XB: "Pseudo-Bidi",
territory.XK: "Kosovo",
territory.YE: "Yemen",
territory.YT: "Mayotte",
territory.ZA: "South Africa",
territory.ZM: "Zambia",
territory.ZW: "Zimbabwe",
territory.ZZ: "Unknown Region",
},
}
}
|
|
_label.py | import _plotly_utils.basevalidators
class LabelValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self,
plotly_name='label',
parent_name='sankey.link.concentrationscales',
**kwargs
):
| super(LabelValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop('edit_type', 'calc'),
role=kwargs.pop('role', 'info'),
**kwargs
) |
|
constants.ts | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import { i18n } from '@kbn/i18n';
export const EMS_APP_NAME = 'kibana';
export const EMS_CATALOGUE_PATH = 'ems/catalogue';
export const EMS_FILES_CATALOGUE_PATH = 'ems/files';
export const EMS_FILES_API_PATH = 'ems/files';
export const EMS_FILES_DEFAULT_JSON_PATH = 'file';
export const EMS_GLYPHS_PATH = 'fonts';
export const EMS_SPRITES_PATH = 'sprites';
export const EMS_TILES_CATALOGUE_PATH = 'ems/tiles';
export const EMS_TILES_API_PATH = 'ems/tiles';
export const EMS_TILES_RASTER_STYLE_PATH = 'raster/style';
export const EMS_TILES_RASTER_TILE_PATH = 'raster/tile';
export const EMS_TILES_VECTOR_STYLE_PATH = 'vector/style';
export const EMS_TILES_VECTOR_SOURCE_PATH = 'vector/source';
export const EMS_TILES_VECTOR_TILE_PATH = 'vector/tile';
export const MAP_SAVED_OBJECT_TYPE = 'map';
export const APP_ID = 'maps';
export const APP_ICON = 'gisApp';
export const MAPS_APP_PATH = `app/${APP_ID}`;
export const MAP_PATH = 'map';
export const GIS_API_PATH = `api/${APP_ID}`;
export const INDEX_SETTINGS_API_PATH = `${GIS_API_PATH}/indexSettings`;
export const FONTS_API_PATH = `${GIS_API_PATH}/fonts`;
const MAP_BASE_URL = `/${MAPS_APP_PATH}/${MAP_PATH}`;
export function getNewMapPath() {
return MAP_BASE_URL;
}
export function getExistingMapPath(id: string) {
return `${MAP_BASE_URL}/${id}`;
}
export enum LAYER_TYPE {
TILE = 'TILE',
VECTOR = 'VECTOR',
VECTOR_TILE = 'VECTOR_TILE', // for static display of mvt vector tiles with a mapbox stylesheet. Does not support any ad-hoc configurations. Used for consuming EMS vector tiles.
HEATMAP = 'HEATMAP',
BLENDED_VECTOR = 'BLENDED_VECTOR',
TILED_VECTOR = 'TILED_VECTOR', // similar to a regular vector-layer, but it consumes the data as .mvt tilea iso GeoJson. It supports similar ad-hoc configurations like a regular vector layer (E.g. using IVectorStyle), although there is some loss of functionality e.g. does not support term joining
}
export enum SORT_ORDER {
ASC = 'asc',
DESC = 'desc',
}
export enum SOURCE_TYPES {
EMS_TMS = 'EMS_TMS',
EMS_FILE = 'EMS_FILE',
ES_GEO_GRID = 'ES_GEO_GRID',
ES_SEARCH = 'ES_SEARCH',
ES_PEW_PEW = 'ES_PEW_PEW',
ES_TERM_SOURCE = 'ES_TERM_SOURCE',
EMS_XYZ = 'EMS_XYZ', // identifies a custom TMS source. Name is a little unfortunate.
WMS = 'WMS',
KIBANA_TILEMAP = 'KIBANA_TILEMAP',
REGIONMAP_FILE = 'REGIONMAP_FILE',
GEOJSON_FILE = 'GEOJSON_FILE',
MVT_SINGLE_LAYER = 'MVT_SINGLE_LAYER',
}
export enum FIELD_ORIGIN {
SOURCE = 'source',
JOIN = 'join',
}
export const JOIN_FIELD_NAME_PREFIX = '__kbnjoin__';
export const META_DATA_REQUEST_ID_SUFFIX = 'meta';
export const FORMATTERS_DATA_REQUEST_ID_SUFFIX = 'formatters';
export const SOURCE_DATA_REQUEST_ID = 'source';
export const SOURCE_META_DATA_REQUEST_ID = `${SOURCE_DATA_REQUEST_ID}_${META_DATA_REQUEST_ID_SUFFIX}`;
export const SOURCE_FORMATTERS_DATA_REQUEST_ID = `${SOURCE_DATA_REQUEST_ID}_${FORMATTERS_DATA_REQUEST_ID_SUFFIX}`;
export const SOURCE_BOUNDS_DATA_REQUEST_ID = `${SOURCE_DATA_REQUEST_ID}_bounds`;
export const MIN_ZOOM = 0;
export const MAX_ZOOM = 24;
export const DECIMAL_DEGREES_PRECISION = 5; // meters precision
export const ZOOM_PRECISION = 2;
export const DEFAULT_MAX_RESULT_WINDOW = 10000;
export const DEFAULT_MAX_INNER_RESULT_WINDOW = 100;
export const DEFAULT_MAX_BUCKETS_LIMIT = 10000;
export const FEATURE_ID_PROPERTY_NAME = '__kbn__feature_id__';
export const FEATURE_VISIBLE_PROPERTY_NAME = '__kbn_isvisibleduetojoin__';
export const MB_SOURCE_ID_LAYER_ID_PREFIX_DELIMITER = '_';
export enum ES_GEO_FIELD_TYPE {
GEO_POINT = 'geo_point', | }
// Using strings instead of ES_GEO_FIELD_TYPE enum to avoid typeing errors where IFieldType.type is compared to value
export const ES_GEO_FIELD_TYPES = ['geo_point', 'geo_shape'];
export enum ES_SPATIAL_RELATIONS {
INTERSECTS = 'INTERSECTS',
DISJOINT = 'DISJOINT',
WITHIN = 'WITHIN',
}
export const GEO_JSON_TYPE = {
POINT: 'Point',
MULTI_POINT: 'MultiPoint',
LINE_STRING: 'LineString',
MULTI_LINE_STRING: 'MultiLineString',
POLYGON: 'Polygon',
MULTI_POLYGON: 'MultiPolygon',
GEOMETRY_COLLECTION: 'GeometryCollection',
};
export const POLYGON_COORDINATES_EXTERIOR_INDEX = 0;
export const LON_INDEX = 0;
export const LAT_INDEX = 1;
export const EMPTY_FEATURE_COLLECTION = {
type: 'FeatureCollection',
features: [],
};
export enum DRAW_TYPE {
BOUNDS = 'BOUNDS',
DISTANCE = 'DISTANCE',
POLYGON = 'POLYGON',
}
export const AGG_DELIMITER = '_of_';
export enum AGG_TYPE {
AVG = 'avg',
COUNT = 'count',
MAX = 'max',
MIN = 'min',
SUM = 'sum',
TERMS = 'terms',
UNIQUE_COUNT = 'cardinality',
}
export enum RENDER_AS {
HEATMAP = 'heatmap',
POINT = 'point',
GRID = 'grid',
}
export enum GRID_RESOLUTION {
COARSE = 'COARSE',
FINE = 'FINE',
MOST_FINE = 'MOST_FINE',
}
export const TOP_TERM_PERCENTAGE_SUFFIX = '__percentage';
export const COUNT_PROP_LABEL = i18n.translate('xpack.maps.aggs.defaultCountLabel', {
defaultMessage: 'count',
});
export const COUNT_PROP_NAME = 'doc_count';
export enum STYLE_TYPE {
STATIC = 'STATIC',
DYNAMIC = 'DYNAMIC',
}
export enum LAYER_STYLE_TYPE {
VECTOR = 'VECTOR',
HEATMAP = 'HEATMAP',
TILE = 'TILE',
}
export enum COLOR_MAP_TYPE {
CATEGORICAL = 'CATEGORICAL',
ORDINAL = 'ORDINAL',
}
export const CATEGORICAL_DATA_TYPES = ['string', 'ip', 'boolean'];
export const ORDINAL_DATA_TYPES = ['number', 'date'];
export enum SYMBOLIZE_AS_TYPES {
CIRCLE = 'circle',
ICON = 'icon',
}
export enum LABEL_BORDER_SIZES {
NONE = 'NONE',
SMALL = 'SMALL',
MEDIUM = 'MEDIUM',
LARGE = 'LARGE',
}
export const DEFAULT_ICON = 'marker';
export enum VECTOR_STYLES {
SYMBOLIZE_AS = 'symbolizeAs',
FILL_COLOR = 'fillColor',
LINE_COLOR = 'lineColor',
LINE_WIDTH = 'lineWidth',
ICON = 'icon',
ICON_SIZE = 'iconSize',
ICON_ORIENTATION = 'iconOrientation',
LABEL_TEXT = 'labelText',
LABEL_COLOR = 'labelColor',
LABEL_SIZE = 'labelSize',
LABEL_BORDER_COLOR = 'labelBorderColor',
LABEL_BORDER_SIZE = 'labelBorderSize',
}
export enum SCALING_TYPES {
LIMIT = 'LIMIT',
CLUSTERS = 'CLUSTERS',
TOP_HITS = 'TOP_HITS',
}
export const RGBA_0000 = 'rgba(0,0,0,0)';
export const SPATIAL_FILTERS_LAYER_ID = 'SPATIAL_FILTERS_LAYER_ID';
export enum INITIAL_LOCATION {
LAST_SAVED_LOCATION = 'LAST_SAVED_LOCATION',
FIXED_LOCATION = 'FIXED_LOCATION',
BROWSER_LOCATION = 'BROWSER_LOCATION',
}
export enum LAYER_WIZARD_CATEGORY {
ELASTICSEARCH = 'ELASTICSEARCH',
REFERENCE = 'REFERENCE',
SOLUTIONS = 'SOLUTIONS',
}
export enum VECTOR_SHAPE_TYPE {
POINT = 'POINT',
LINE = 'LINE',
POLYGON = 'POLYGON',
}
// https://docs.mapbox.com/mapbox-gl-js/style-spec/expressions/#data-expressions
export enum MB_LOOKUP_FUNCTION {
GET = 'get',
FEATURE_STATE = 'feature-state',
} | GEO_SHAPE = 'geo_shape', |
spider_test.py | # -*- coding: utf-8 -*-
"""
Created on Mon May 10 21:23:13 2021
@author: Administrator
"""
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../')
from utils import SpiderFormat # noqa: E402
from spider_factory import SpiderFactory # noqa: E402
def | ():
spider = SpiderFactory.create(SpiderFormat.ONNX)
assert spider is not None
def test_torchspider():
spider = SpiderFactory.create(SpiderFormat.TORCH)
assert spider is None
if __name__ == '__main__':
print('Hello, test')
test_onnxspider()
test_torchspider()
| test_onnxspider |
actionCreators.js | const addTask = task => ({
type: 'ADD_TASK',
task,
});
const addIdea = idea => ({
type: 'ADD_IDEA',
idea,
}); |
export { addTask, addIdea }; |
|
song.py | from pyrogram import Client, filters
import asyncio
import os
from pytube import YouTube
from pyrogram.types import InlineKeyboardMarkup
from pyrogram.types import InlineKeyboardButton
from youtubesearchpython import VideosSearch
from AlexaSongBot.mrdarkprince import ignore_blacklisted_users, get_arg
from AlexaSongBot import app, LOGGER
from AlexaSongBot.sql.chat_sql import add_chat_to_db
def yt_search(song):
videosSearch = VideosSearch(song, limit=1)
result = videosSearch.result()
if not result:
return False
else:
video_id = result["result"][0]["id"]
url = f"https://youtu.be/{video_id}"
return url
@app.on_message(filters.create(ignore_blacklisted_users) & filters.command("mt"))
async def | (client, message):
chat_id = message.chat.id
user_id = message.from_user["id"]
add_chat_to_db(str(chat_id))
args = get_arg(message) + " " + "song"
if args.startswith(" "):
await message.reply("Enter a song name. Check /help")
return ""
status = await message.reply("`🔎I\'m Uploading Your Music.. 📺 Please wait some time ⏳️`` ")
video_link = yt_search(args)
if not video_link:
await status.edit("😔Song not found.")
return ""
yt = YouTube(video_link)
audio = yt.streams.filter(only_audio=True).first()
try:
download = audio.download(filename=f"{str(user_id)}")
except Exception as ex:
await status.edit("Failed to download song")
LOGGER.error(ex)
return ""
rename = os.rename(download, f"{str(user_id)}.mp3")
await app.send_chat_action(message.chat.id, "upload_audio")
title = str(yt.title)
aswin = f"✣ **Music** : [{title[:40]}]({video_link})\n✣ **Uploaded** : [MT Music\'s](https://t.me/mt_music_24)"
await app.send_audio(
caption = aswin,
chat_id=message.chat.id,
audio=f"{str(user_id)}.mp3",
duration=int(yt.length),
title=str(yt.title),
performer=str('[MT Music\'s]'),
reply_to_message_id=message.message_id,
)
await status.delete()
os.remove(f"{str(user_id)}.mp3")
| song |
ClusterRoleBinding.py | # *** WARNING: this file was generated by the Pulumi Kubernetes codegen tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
from typing import Optional
import pulumi
import pulumi.runtime
from pulumi import Input, ResourceOptions
from ... import tables, version
class | (pulumi.CustomResource):
"""
ClusterRoleBinding references a ClusterRole, but not contain it. It can reference a ClusterRole
in the global namespace, and adds who information via Subject.
"""
apiVersion: pulumi.Output[str]
"""
APIVersion defines the versioned schema of this representation of an object. Servers should
convert recognized schemas to the latest internal value, and may reject unrecognized values.
More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
"""
kind: pulumi.Output[str]
"""
Kind is a string value representing the REST resource this object represents. Servers may infer
this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More
info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
"""
metadata: pulumi.Output[dict]
"""
Standard object's metadata.
"""
role_ref: pulumi.Output[dict]
"""
RoleRef can only reference a ClusterRole in the global namespace. If the RoleRef cannot be
resolved, the Authorizer must return an error.
"""
subjects: pulumi.Output[list]
"""
Subjects holds references to the objects the role applies to.
"""
def __init__(self, resource_name, opts=None, role_ref=None, metadata=None, subjects=None, __name__=None, __opts__=None):
"""
Create a ClusterRoleBinding resource with the given unique name, arguments, and options.
:param str resource_name: The _unique_ name of the resource.
:param pulumi.ResourceOptions opts: A bag of options that control this resource's behavior.
:param pulumi.Input[dict] role_ref: RoleRef can only reference a ClusterRole in the global namespace. If the RoleRef
cannot be resolved, the Authorizer must return an error.
:param pulumi.Input[dict] metadata: Standard object's metadata.
:param pulumi.Input[list] subjects: Subjects holds references to the objects the role applies to.
"""
if __name__ is not None:
warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning)
resource_name = __name__
if __opts__ is not None:
warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)
opts = __opts__
if not resource_name:
raise TypeError('Missing resource name argument (for URN creation)')
if not isinstance(resource_name, str):
raise TypeError('Expected resource name to be a string')
if opts and not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
__props__ = dict()
__props__['apiVersion'] = 'rbac.authorization.k8s.io/v1beta1'
__props__['kind'] = 'ClusterRoleBinding'
if role_ref is None:
raise TypeError('Missing required property role_ref')
__props__['roleRef'] = role_ref
__props__['metadata'] = metadata
__props__['subjects'] = subjects
__props__['status'] = None
additional_secret_outputs = [
]
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(
version=version.get_version(), additional_secret_outputs=additional_secret_outputs))
parent = opts.parent if opts and opts.parent else None
aliases = [
]
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(
version=version.get_version(), aliases=aliases))
super(ClusterRoleBinding, self).__init__(
"kubernetes:rbac.authorization.k8s.io/v1beta1:ClusterRoleBinding",
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name, id, opts=None):
"""
Get the state of an existing `ClusterRoleBinding` resource, as identified by `id`.
The ID is of the form `[namespace]/[name]`; if `[namespace]` is omitted,
then (per Kubernetes convention) the ID becomes `default/[name]`.
Pulumi will keep track of this resource using `resource_name` as the Pulumi ID.
:param str resource_name: _Unique_ name used to register this resource with Pulumi.
:param pulumi.Input[str] id: An ID for the Kubernetes resource to retrieve.
Takes the form `[namespace]/[name]` or `[name]`.
:param Optional[pulumi.ResourceOptions] opts: A bag of options that control this
resource's behavior.
"""
opts = ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
return ClusterRoleBinding(resource_name, opts)
def translate_output_property(self, prop: str) -> str:
return tables._CASING_FORWARD_TABLE.get(prop) or prop
def translate_input_property(self, prop: str) -> str:
return tables._CASING_BACKWARD_TABLE.get(prop) or prop
| ClusterRoleBinding |
features_duplicated.js | /*---
esid: sec-assignment-operators-static-semantics-early-errors
description: Duplicated values in "features" frontmatter
features: [object-spread, async-functions, object-spread]
---*/
async function f({ ...a }) {} | FEATURES
^ expected errors | v input
// Copyright (C) 2021 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file. |
|
settings.py | """
Django settings for reqs project.
Generated by 'django-admin startproject' using Django 2.1.3.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'ulm4!r3dj%@6&lc+9u11!*xffrv2g#4y4&^0@7@-(oy#rp25sy'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'reqs.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
| },
},
]
WSGI_APPLICATION = 'reqs.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/' | 'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
|
is-stream.ts | import { isWHATWGReadable } from './is-whatwg-readable'
import { isReadStream } from './is-read-stream'
import { isReadable } from './is-readable'
/**
* Checks if given value is ONLY fs.ReadStream OR stream.Readable instance
*/ | } | export function isStream(value): boolean {
return isWHATWGReadable(value) || isReadStream(value) || isReadable(value) |
ProfileImageInfo.ts | // Generated Source
import ProfileImageInfoUri from "./ProfileImageInfoUri";
interface ProfileImageInfo {
/**
* Link to a profile image. If an image is not uploaded for an extension, only uri is returned
*/
uri?: string; | /**
* Identifier of an image
*/
etag?: string;
/**
* The datetime when an image was last updated in ISO 8601 format, for example 2016-03-10T18:07:52.534Z
*/
lastModified?: string;
/**
* The type of an image
*/
contentType?: string;
/**
* List of URIs to profile images in different dimensions
*/
scales?: ProfileImageInfoUri[];
}
export default ProfileImageInfo; | |
code.py | #%%
import numpy as np
import pandas as pd
import time
from sklearn.base import BaseEstimator, TransformerMixin
from collections import defaultdict
from sklearn.model_selection import KFold, StratifiedKFold
class Timer:
def __enter__(self):
self.start=time.time()
return self
def __exit__(self, *args):
self.end=time.time()
self.hour, temp = divmod((self.end - self.start), 3600)
self.min, self.second = divmod(temp, 60)
self.hour, self.min, self.second = int(self.hour), int(self.min), round(self.second, 2)
return self
class BayCatEncoder(BaseEstimator, TransformerMixin):
def __init__(self,
group_cols,
target_col='target',
N_min=1, # the higher, the more regularization is introduced into the update.
CV=True,
n_fold=5,
verbosity=True,
delimiter='.',
drop_original=False,
drop_intermediate=False,
random_seed=2020):
self.group_cols = [group_cols] if isinstance(group_cols, str) else group_cols # List of column names combination: e.g. ['n1.n2.n4', 'n3.n4', 'n2'].
self.target_col = target_col # String: 'target' by default.
self.stats = defaultdict(dict) # key: column names combination; value: corresponding info about n, N, and computed code.
self.N_min = N_min # regularization control
self.drop_original = drop_original # toggle key for whether to drop original column name(s) or not.
self.CV = CV # Bool
self.n_fold = n_fold
self.drop_intermediate = drop_intermediate
self.delimiter = delimiter
self.verbosity = verbosity # Bool
self.seed = random_seed
self.set_original_col = set()
def | (self, X, y):
self.col_subsets = self._generate_subsets(self.group_cols)
df = pd.concat([X.copy(), y.copy()], axis=1)
assert(isinstance(self.target_col, str))
df.columns = X.columns.tolist() + [self.target_col]
assert(self._check_col_consistency(X))
if not self.CV:
self._single_fit(df)
else:
self._cv_fit(df)
return self
def _single_fit(self, df):
size_col_subsets = len(self.col_subsets)
count_subset = 0
print(f'start bayesian target encoding on cross features in the following order: {self.col_subsets}')
for subset in self.col_subsets:
count_subset += 1
with Timer() as t:
if self.verbosity: print(f'{subset} - Order {count_subset}/{size_col_subsets}')
df_stat, stat, cross_features = self._update(df, subset)
features_encoded = cross_features + '_code'
self.stats[cross_features] = pd.merge(
stat,
df_stat.groupby(subset)[features_encoded].mean(),
left_index=True,
right_index=True)
if self.verbosity: print(f'time elapsed: {t.hour} hours {t.min} mins {t.second} seconds')
return self
def _cv_fit(self, df):
kf = StratifiedKFold(n_splits = self.n_fold, shuffle = True, random_state=self.seed)
size_col_subsets = len(self.col_subsets)
count_subset = 0
for subset in self.col_subsets:
count_subset += 1
with Timer() as t:
for i, (tr_idx, val_idx) in enumerate(kf.split(df.drop(self.target_col, axis=1), df[self.target_col])):
if self.verbosity: print(f'{subset} - Order {count_subset}/{size_col_subsets} - Round {i+1}/{self.n_fold}')
df_tr, df_val = df.iloc[tr_idx].copy(), df.iloc[val_idx].copy() # Vital for avoid "A value is trying to be set on a copy of a slice from a DataFrame." warning.
df_stat, stat, cross_features = self._update(df_tr, subset)
features_encoded = cross_features + '_code'
df.loc[df.index[val_idx], features_encoded] = pd.merge(
df_val[subset],
df_stat.groupby(subset)[features_encoded].mean(),
left_on=subset,
right_index=True,
how='left'
)[features_encoded].copy() \
.fillna(df[self.target_col].mean())
self.stats[cross_features] = df.groupby(subset)[features_encoded].mean().to_frame()
if self.verbosity: print(f'time elapsed: {t.hour} hours {t.min} mins {t.second} seconds')
return self
def _update(self, df, subset):
self.global_prior_mean = df[self.target_col].mean()
if len(subset) == 1:
self.set_original_col.add(*subset)
upper_level_cols = 'global'
if not upper_level_cols + '_prior_mean' in df.columns:
df.loc[:, upper_level_cols + '_prior_mean'] = self.global_prior_mean
else:
upper_level_cols = self.delimiter.join(subset[:-1]) # e.g. the n1.n2 subset's upper level feature is `n1`.
if not upper_level_cols + '_prior_mean' in df.columns:
df.loc[:, upper_level_cols + '_prior_mean'] = pd.merge(
df[subset[:-1]],
self.stats[upper_level_cols][upper_level_cols + '_code'],
left_on=subset[:-1],
right_index=True,
how='left'
)[upper_level_cols + '_code'].copy()
stat = df.groupby(subset).agg(
n=(self.target_col, 'sum'),
N=(self.target_col, 'count'),
prior_mean=(upper_level_cols + '_prior_mean', 'mean')
)
# Calculate posterior mean
df_stat = pd.merge(df[subset], stat, left_on=subset, right_index=True, how='left')
df_stat['n'].mask(df_stat['n'].isnull(), df_stat['prior_mean'], inplace=True)
df_stat['N'].fillna(1., inplace=True)
df_stat.loc[:, 'N_prior'] = df_stat['N'].map(lambda x: max(self.N_min - x, 0))
df_stat.loc[:, 'alpha_prior'] = df_stat['prior_mean'] * df_stat['N_prior']
df_stat.loc[:, 'beta_prior'] = (1. - df_stat['prior_mean']) * df_stat['N_prior'] # Large N -> zero N_prior -> zero alpha_prior and zero beta_prior -> if n is zero as well -> alpha prior, beta prior both zero -> alpha zero -> posterior mean = zero as well.
if len(subset) == 1:
cross_features = subset[0]
else:
cross_features = self.delimiter.join(subset)
df_stat.loc[:, cross_features + '_code'] = df_stat.apply(self._stat_mean, axis=1) # core # TEST set!!
return df_stat, stat, cross_features
def _generate_subsets(self, groups, delimiter='.'):
subsets = defaultdict(list)
for g in groups:
chain = g.split(delimiter)
for i in range(len(chain)):
if chain[i] and not chain[:i+1] in subsets[i]: subsets[i].append(chain[:i+1])
ret = []
for _, v in subsets.items():
if not v in ret: ret.extend(v)
return ret
def _stat_mean(self, X):
df = X.copy()
alpha = df['alpha_prior'] + df['n']
beta = df['beta_prior'] + df['N'] - df['n']
return alpha / (alpha + beta)
def _check_col_consistency(self, df):
"""Check whether columns specified in `self.group_cols` are all included in `df`.
"""
s = set()
for col_subset in self.col_subsets:
s |= set(col_subset)
for col in s:
if not col in df.columns: return False
return True
def transform(self, X):
assert(self._check_col_consistency(X))
for subset in self.col_subsets:
key = '.'.join(subset)
X = pd.merge(
X,
self.stats[key][key + '_code'],
left_on=subset,
right_index=True,
how='left')
if len(subset) == 1:
X[key + '_code'].fillna(self.global_prior_mean, inplace=True)
else:
parent_key = '.'.join(subset[:-1]) + '_code'
X[key + '_code'].fillna(X[parent_key].mask(X[parent_key] > self.global_prior_mean, self.global_prior_mean), inplace=True)
if self.drop_original:
for col in self.set_original_col:
X.drop(col, axis=1, inplace=True)
X.rename(columns={col+'_code': col}, inplace=True)
if self.drop_intermediate:
for col in X.columns:
if col.endswith('_code') and not col.strip('_code') in self.group_cols:
X.drop(col, axis=1, inplace=True)
return X
#%%
if __name__ == '__main__':
np.random.seed(1)
k = 15
n1 = np.random.choice(['a','b'], k)
n2 = np.random.choice(['c','d'], k)
n3 = np.random.choice(['e','f'], k)
target = np.random.randint(0, 2, size=k)
train = pd.DataFrame(
{'n1': n1, 'n2': n2, 'n3':n3, 'target': target},
columns=['n1', 'n2', 'n3', 'target']
)
train.columns = ['n1','n2','n3', 'target']
train
k = 6
n4 = np.random.choice(['a','b'], k)
n5 = np.random.choice(['c','d'], k)
n6 = np.random.choice(['e','f'], k)
test = pd.DataFrame({'n4': n4, 'n2': n5, 'n3':n6})
test.columns = ['n1','n2','n3']
test
te = BayCatEncoder(
'n1.n2.n3', #['n1.n2.n3', 'n2.n3', 'n3'],
target_col='target',
drop_original=False,
drop_intermediate=False,
CV=False
) \
.fit(train.drop('target', axis=1), train.target)
# te.transform(test)
te.transform(test)
# %%
| fit |
defineQuerySelectExpressionForSqlSchemaProperty.ts | import { camelCase, snakeCase } from 'change-case';
import { DomainObjectPropertyMetadata } from 'domain-objects-metadata';
import { SqlSchemaPropertyMetadata } from '../../../domain/objects/SqlSchemaPropertyMetadata';
import { SqlSchemaReferenceMethod } from '../../../domain/objects/SqlSchemaReferenceMetadata';
import { SqlSchemaToDomainObjectRelationship } from '../../../domain/objects/SqlSchemaToDomainObjectRelationship';
import { UnexpectedCodePathDetectedError } from '../../UnexpectedCodePathDetectedError';
import { isADirectlyNestedDomainObjectProperty } from '../sqlSchemaRelationship/isADirectlyNestedDomainObjectProperty';
import { isAUserDefinedDomainObjectProperty } from '../sqlSchemaRelationship/isAUserDefinedDomainObjectProperty';
const indentByNestingDepth = ({
depthOfNesting,
selectExpression,
}: {
depthOfNesting: number;
selectExpression: string;
}) => {
const prefix = Array(depthOfNesting + 2)
.fill(' ')
.join('');
return selectExpression
.split('\n')
.map((str) => `${prefix}${str}`)
.join('\n')
.trim();
};
export const defineQuerySelectExpressionForSqlSchemaProperty = ({
sqlSchemaName,
sqlSchemaProperty,
domainObjectProperty,
allSqlSchemaRelationships,
depthOfNesting = 0,
}: {
sqlSchemaName: string;
sqlSchemaProperty: SqlSchemaPropertyMetadata;
domainObjectProperty: DomainObjectPropertyMetadata;
allSqlSchemaRelationships: SqlSchemaToDomainObjectRelationship[];
depthOfNesting?: number;
}): string => {
// simple case: property is represented in the db simply as a standard column
if (!sqlSchemaProperty.reference) return `${sqlSchemaName}.${sqlSchemaProperty.name}`;
// since we know its a reference, lookup the referenced sqlSchemaRelationship
const referencedSqlSchemaRelationship = allSqlSchemaRelationships.find(
(rel) => rel.name.domainObject === sqlSchemaProperty.reference!.of.name,
);
if (!referencedSqlSchemaRelationship)
throw new UnexpectedCodePathDetectedError({
reason: 'could not find referenced sql schema relationship for defining query input expression',
domainObjectName: snakeCase(sqlSchemaName),
domainObjectPropertyName: domainObjectProperty.name,
}); // fail fast, this should not occur
const referencedSqlSchemaName = referencedSqlSchemaRelationship.name.sqlSchema;
const selectExpressionAlias = depthOfNesting === 0 ? ` AS ${snakeCase(domainObjectProperty.name)}` : ''; // alias only required on root level property, not nested ones, since those are named through json syntax already
// reference by implicit uuid case
if (sqlSchemaProperty.reference.method === SqlSchemaReferenceMethod.IMPLICIT_BY_UUID) {
// solo case
if (!sqlSchemaProperty.isArray)
return `
(
SELECT ${referencedSqlSchemaName}.uuid
FROM ${referencedSqlSchemaName} WHERE ${referencedSqlSchemaName}.id = ${sqlSchemaName}.${sqlSchemaProperty.name}
)${selectExpressionAlias}
`.trim();
// array case
return `
(
SELECT COALESCE(array_agg(${referencedSqlSchemaName}.uuid ORDER BY ${referencedSqlSchemaName}_ref.array_order_index), array[]::uuid[]) AS array_agg
FROM ${referencedSqlSchemaName}
JOIN unnest(${sqlSchemaName}.${sqlSchemaProperty.name}) WITH ORDINALITY
AS ${referencedSqlSchemaName}_ref (id, array_order_index)
ON ${referencedSqlSchemaName}.id = ${referencedSqlSchemaName}_ref.id
)${selectExpressionAlias}
`.trim();
}
// directly nested reference case
if (sqlSchemaProperty.reference.method === SqlSchemaReferenceMethod.DIRECT_BY_NESTING) {
// solo case
if (!sqlSchemaProperty.isArray) {
return `
(
SELECT json_build_object(
${referencedSqlSchemaRelationship.properties
.filter(isAUserDefinedDomainObjectProperty)
.map(({ sqlSchema: referencedSqlSchemaProperty, domainObject: referencedDomainObjectProperty }) => {
const jsonKey = isADirectlyNestedDomainObjectProperty({
sqlSchema: referencedSqlSchemaProperty,
domainObject: referencedDomainObjectProperty,
})
? snakeCase(referencedDomainObjectProperty.name) // if its a directly nested domain object reference, then refer to it by domain object name
: referencedSqlSchemaProperty.name; // otherwise, by the sql property name
const jsonValueSelectExpression = indentByNestingDepth({
depthOfNesting,
selectExpression: defineQuerySelectExpressionForSqlSchemaProperty({
sqlSchemaName: referencedSqlSchemaName,
sqlSchemaProperty: referencedSqlSchemaProperty,
domainObjectProperty: referencedDomainObjectProperty,
allSqlSchemaRelationships,
depthOfNesting: depthOfNesting + 1,
}),
});
return `'${jsonKey}', ${jsonValueSelectExpression}`;
})
.join(',\n ')}
) AS json_build_object
FROM ${referencedSqlSchemaName} WHERE ${referencedSqlSchemaName}.id = ${sqlSchemaName}.${sqlSchemaProperty.name}
)${selectExpressionAlias}
`.trim();
}
// array case
return `
(
SELECT COALESCE(
json_agg(
json_build_object(
${referencedSqlSchemaRelationship.properties
.filter(isAUserDefinedDomainObjectProperty)
.map(({ sqlSchema: referencedSqlSchemaProperty, domainObject: referencedDomainObjectProperty }) => {
const jsonKey = isADirectlyNestedDomainObjectProperty({
sqlSchema: referencedSqlSchemaProperty,
domainObject: referencedDomainObjectProperty,
})
? snakeCase(referencedDomainObjectProperty.name) // if its a directly nested domain object reference, then refer to it by domain object name
: referencedSqlSchemaProperty.name; // otherwise, by the sql property name
const jsonValueSelectExpression = indentByNestingDepth({
depthOfNesting: depthOfNesting + 2, // 2, because we wrap in COALESCE + json_agg + json_build_object + its own padding
selectExpression: defineQuerySelectExpressionForSqlSchemaProperty({
sqlSchemaName: referencedSqlSchemaName,
sqlSchemaProperty: referencedSqlSchemaProperty,
domainObjectProperty: referencedDomainObjectProperty,
allSqlSchemaRelationships,
depthOfNesting: depthOfNesting + 1 + 2, // 2, because we wrap in COALESCE + json_agg + json_build_object + its own padding
}),
});
return `'${jsonKey}', ${jsonValueSelectExpression}`;
})
.join(',\n ')}
)
ORDER BY ${referencedSqlSchemaName}_ref.array_order_index
),
'[]'::json
) AS json_agg
FROM ${referencedSqlSchemaName}
JOIN unnest(${sqlSchemaName}.${sqlSchemaProperty.name}) WITH ORDINALITY
AS ${referencedSqlSchemaName}_ref (id, array_order_index)
ON ${referencedSqlSchemaName}.id = ${referencedSqlSchemaName}_ref.id
)${selectExpressionAlias}
`.trim();
}
| domainObjectPropertyName: domainObjectProperty.name,
}); // fail fast if our expectation is not met though
}; | // fail fast if we reach here, not expected
throw new UnexpectedCodePathDetectedError({
reason: 'did not handle the request with any defined conditions, for query select expression',
domainObjectName: camelCase(sqlSchemaName), |
request_multi_form.py | from simply_block.simply_sign import SimplySign
| # Token
public_key = "hmac_pub_1"
private_key = "hmac_priv_1"
# Required Params
url = "http://127.0.0.1:8000/v1/eth/contract/build/"
file_path = "/home/lenovo/Documents/simplyblock/ethereum-service/contracts/DappToken.sol"
data = {
'contract_name': 'contract_22'
}
files = {
'contract': file_path
}
# Request
response = SimplySign(private_key, public_key).gateway_request(url, data, files=files)
print(response)
print(response.text) | |
generated.rs | // =================================================================
//
// * WARNING *
//
// This file is generated!
//
// Changes made to this file will be overwritten. If changes are
// required to the generated code, the service_crategen project
// must be updated to generate the changes.
//
// =================================================================
use std::error::Error;
use std::fmt;
#[allow(warnings)]
use futures::future;
use futures::Future;
use rusoto_core::credential::ProvideAwsCredentials;
use rusoto_core::region;
use rusoto_core::request::{BufferedHttpResponse, DispatchSignedRequest};
use rusoto_core::{Client, RusotoError, RusotoFuture};
use rusoto_core::param::{Params, ServiceParams};
use rusoto_core::proto;
use rusoto_core::signature::SignedRequest;
use serde_json;
/// <p>Settings for logging access in a stage.</p>
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AccessLogSettings {
/// <p>The ARN of the CloudWatch Logs log group to receive access logs.</p>
#[serde(rename = "DestinationArn")]
#[serde(skip_serializing_if = "Option::is_none")]
pub destination_arn: Option<String>,
/// <p>A single line format of the access logs of data, as specified by selected $context
/// variables. The format must include at least $context.requestId.</p>
#[serde(rename = "Format")]
#[serde(skip_serializing_if = "Option::is_none")]
pub format: Option<String>,
}
/// <p>Represents an API.</p>
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct Api {
/// <p>The URI of the API, of the form {api-id}.execute-api.{region}.amazonaws.com. The
/// stage name is typically appended to this URI to form a complete path to a deployed
/// API stage.</p>
#[serde(rename = "ApiEndpoint")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_endpoint: Option<String>,
/// <p>The API ID.</p>
#[serde(rename = "ApiId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_id: Option<String>,
/// <p>An API key selection expression. See <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions">API Key Selection Expressions</a>.</p>
#[serde(rename = "ApiKeySelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_key_selection_expression: Option<String>,
/// <p>The timestamp when the API was created.</p>
#[serde(rename = "CreatedDate")]
#[serde(skip_serializing_if = "Option::is_none")]
pub created_date: Option<f64>,
/// <p>The description of the API.</p>
#[serde(rename = "Description")]
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// <p>Avoid validating models when creating a deployment.</p>
#[serde(rename = "DisableSchemaValidation")]
#[serde(skip_serializing_if = "Option::is_none")]
pub disable_schema_validation: Option<bool>,
/// <p>The name of the API.</p>
#[serde(rename = "Name")]
pub name: String,
/// <p>The API protocol: Currently only WEBSOCKET is supported.</p>
#[serde(rename = "ProtocolType")]
pub protocol_type: String,
/// <p>The route selection expression for the API.</p>
#[serde(rename = "RouteSelectionExpression")]
pub route_selection_expression: String,
/// <p>A version identifier for the API.</p>
#[serde(rename = "Version")]
#[serde(skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
/// <p>The warning messages reported when failonwarnings is turned on during
/// API import.</p>
#[serde(rename = "Warnings")]
#[serde(skip_serializing_if = "Option::is_none")]
pub warnings: Option<Vec<String>>,
}
/// <p>Represents an API mapping.</p>
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct ApiMapping {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The API mapping identifier.</p>
#[serde(rename = "ApiMappingId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_mapping_id: Option<String>,
/// <p>The API mapping key.</p>
#[serde(rename = "ApiMappingKey")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_mapping_key: Option<String>,
/// <p>The API stage.</p>
#[serde(rename = "Stage")]
pub stage: String,
}
/// <p>Represents an authorizer.</p>
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct Authorizer {
/// <p>Specifies the required credentials as an IAM role for API Gateway to invoke the
/// authorizer. To specify an IAM role for API Gateway to assume, use the role's Amazon
/// Resource Name (ARN). To use resource-based permissions on the Lambda function,
/// specify null.</p>
#[serde(rename = "AuthorizerCredentialsArn")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorizer_credentials_arn: Option<String>,
/// <p>The authorizer identifier.</p>
#[serde(rename = "AuthorizerId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorizer_id: Option<String>,
/// <p>The time to live (TTL), in seconds, of cached authorizer results. If it equals 0,
/// authorization caching is disabled. If it is greater than 0, API Gateway will cache
/// authorizer responses. If this field is not set, the default value is 300. The maximum
/// value is 3600, or 1 hour.</p>
#[serde(rename = "AuthorizerResultTtlInSeconds")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorizer_result_ttl_in_seconds: Option<i64>,
/// <p>The authorizer type. Currently the only valid value is REQUEST, for a
/// Lambda function using incoming request parameters.</p>
#[serde(rename = "AuthorizerType")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorizer_type: Option<String>,
/// <p>The authorizer's Uniform Resource Identifier (URI).
/// ForREQUEST authorizers, this must be a
/// well-formed Lambda function URI, for example,
/// arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:{account_id}:function:{lambda_function_name}/invocations.
/// In general, the URI has this form:
/// arn:aws:apigateway:{region}:lambda:path/{service_api}
/// , where {region} is the same as the region hosting the Lambda
/// function, path indicates that the remaining substring in the URI should be treated as
/// the path to the resource, including the initial /. For Lambda functions,
/// this is usually of the form
/// /2015-03-31/functions/[FunctionARN]/invocations.</p>
#[serde(rename = "AuthorizerUri")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorizer_uri: Option<String>,
/// <p>The identity source for which authorization is requested.</p><p>For the REQUEST authorizer, this is required when authorization
/// caching is enabled. The value is a comma-separated string of one or more mapping
/// expressions of the specified request parameters. For example, if an Auth
/// header and a Name query string parameters are defined as identity
/// sources, this value is method.request.header.Auth,
/// method.request.querystring.Name. These parameters will be used to
/// derive the authorization caching key and to perform runtime validation of the
/// REQUEST authorizer by verifying all of the identity-related request
/// parameters are present, not null, and non-empty. Only when this is true does the
/// authorizer invoke the authorizer Lambda function, otherwise, it returns a 401
/// Unauthorized response without calling the Lambda function. The valid value
/// is a string of comma-separated mapping expressions of the specified request
/// parameters. When the authorization caching is not enabled, this property is
/// optional.</p>
#[serde(rename = "IdentitySource")]
#[serde(skip_serializing_if = "Option::is_none")]
pub identity_source: Option<Vec<String>>,
/// <p>The
/// validation expression does not apply to the REQUEST authorizer.</p>
#[serde(rename = "IdentityValidationExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub identity_validation_expression: Option<String>,
/// <p>The name of the authorizer.</p>
#[serde(rename = "Name")]
pub name: String,
/// <p>For
/// REQUEST authorizer, this is not
/// defined.</p>
#[serde(rename = "ProviderArns")]
#[serde(skip_serializing_if = "Option::is_none")]
pub provider_arns: Option<Vec<String>>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct CreateApiMappingRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
#[serde(rename = "ApiMappingKey")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_mapping_key: Option<String>,
/// <p>The domain name.</p>
#[serde(rename = "DomainName")]
pub domain_name: String,
/// <p>The API stage.</p>
#[serde(rename = "Stage")]
pub stage: String,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct CreateApiMappingResponse {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_id: Option<String>,
/// <p>The API mapping identifier.</p>
#[serde(rename = "ApiMappingId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_mapping_id: Option<String>,
/// <p>The API mapping key.</p>
#[serde(rename = "ApiMappingKey")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_mapping_key: Option<String>,
/// <p>The API stage.</p>
#[serde(rename = "Stage")]
#[serde(skip_serializing_if = "Option::is_none")]
pub stage: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct CreateApiRequest {
/// <p>An API key selection expression. See <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions">API Key Selection Expressions</a>.</p>
#[serde(rename = "ApiKeySelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_key_selection_expression: Option<String>,
/// <p>The description of the API.</p>
#[serde(rename = "Description")]
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// <p>Avoid validating models when creating a deployment.</p>
#[serde(rename = "DisableSchemaValidation")]
#[serde(skip_serializing_if = "Option::is_none")]
pub disable_schema_validation: Option<bool>,
/// <p>The name of the API.</p>
#[serde(rename = "Name")]
pub name: String,
/// <p>The API protocol: Currently only WEBSOCKET is supported.</p>
#[serde(rename = "ProtocolType")]
pub protocol_type: String,
/// <p>The route selection expression for the API.</p>
#[serde(rename = "RouteSelectionExpression")]
pub route_selection_expression: String,
/// <p>A version identifier for the API.</p>
#[serde(rename = "Version")]
#[serde(skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct CreateApiResponse {
/// <p>The URI of the API, of the form {api-id}.execute-api.{region}.amazonaws.com. The
/// stage name is typically appended to this URI to form a complete path to a deployed
/// API stage.</p>
#[serde(rename = "ApiEndpoint")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_endpoint: Option<String>,
/// <p>The API ID.</p>
#[serde(rename = "ApiId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_id: Option<String>,
/// <p>An API key selection expression. See <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions">API Key Selection Expressions</a>.</p>
#[serde(rename = "ApiKeySelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_key_selection_expression: Option<String>,
/// <p>The timestamp when the API was created.</p>
#[serde(rename = "CreatedDate")]
#[serde(skip_serializing_if = "Option::is_none")]
pub created_date: Option<f64>,
/// <p>The description of the API.</p>
#[serde(rename = "Description")]
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// <p>Avoid validating models when creating a deployment.</p>
#[serde(rename = "DisableSchemaValidation")]
#[serde(skip_serializing_if = "Option::is_none")]
pub disable_schema_validation: Option<bool>,
/// <p>The name of the API.</p>
#[serde(rename = "Name")]
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// <p>The API protocol: Currently only WEBSOCKET is supported.</p>
#[serde(rename = "ProtocolType")]
#[serde(skip_serializing_if = "Option::is_none")]
pub protocol_type: Option<String>,
/// <p>The route selection expression for the API.</p>
#[serde(rename = "RouteSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub route_selection_expression: Option<String>,
/// <p>A version identifier for the API.</p>
#[serde(rename = "Version")]
#[serde(skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
/// <p>The warning messages reported when failonwarnings is turned on during
/// API import.</p>
#[serde(rename = "Warnings")]
#[serde(skip_serializing_if = "Option::is_none")]
pub warnings: Option<Vec<String>>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct CreateAuthorizerRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>Specifies the required credentials as an IAM role for API Gateway to invoke the
/// authorizer. To specify an IAM role for API Gateway to assume, use the role's Amazon
/// Resource Name (ARN). To use resource-based permissions on the Lambda function,
/// specify null.</p>
#[serde(rename = "AuthorizerCredentialsArn")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorizer_credentials_arn: Option<String>,
/// <p>The time to live (TTL), in seconds, of cached authorizer results. If it equals 0,
/// authorization caching is disabled. If it is greater than 0, API Gateway will cache
/// authorizer responses. If this field is not set, the default value is 300. The maximum
/// value is 3600, or 1 hour.</p>
#[serde(rename = "AuthorizerResultTtlInSeconds")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorizer_result_ttl_in_seconds: Option<i64>,
/// <p>The authorizer type. Currently the only valid value is REQUEST, for a
/// Lambda function using incoming request parameters.</p>
#[serde(rename = "AuthorizerType")]
pub authorizer_type: String,
/// <p>The authorizer's Uniform Resource Identifier (URI). For
/// REQUEST authorizers, this must be a
/// well-formed Lambda function URI, for example,
/// arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:{account_id}:function:{lambda_function_name}/invocations.
/// In general, the URI has this form:
/// arn:aws:apigateway:{region}:lambda:path/{service_api}
/// , where {region} is the same as the region hosting the Lambda
/// function, path indicates that the remaining substring in the URI should be treated as
/// the path to the resource, including the initial /. For Lambda functions,
/// this is usually of the form
/// /2015-03-31/functions/[FunctionARN]/invocations.</p>
#[serde(rename = "AuthorizerUri")]
pub authorizer_uri: String,
/// <p>The identity source for which authorization is requested.</p><p>For the REQUEST authorizer, this is required when authorization
/// caching is enabled. The value is a comma-separated string of one or more mapping
/// expressions of the specified request parameters. For example, if an Auth
/// header and a Name query string parameters are defined as identity
/// sources, this value is method.request.header.Auth,
/// method.request.querystring.Name. These parameters will be used to
/// derive the authorization caching key and to perform runtime validation of the
/// REQUEST authorizer by verifying all of the identity-related request
/// parameters are present, not null, and non-empty. Only when this is true does the
/// authorizer invoke the authorizer Lambda function, otherwise, it returns a 401
/// Unauthorized response without calling the Lambda function. The valid value
/// is a string of comma-separated mapping expressions of the specified request
/// parameters. When the authorization caching is not enabled, this property is
/// optional.</p>
#[serde(rename = "IdentitySource")]
pub identity_source: Vec<String>,
/// <p>The
/// validation expression does not apply to the REQUEST authorizer.</p>
#[serde(rename = "IdentityValidationExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub identity_validation_expression: Option<String>,
/// <p>The name of the authorizer.</p>
#[serde(rename = "Name")]
pub name: String,
/// <p>For
/// REQUEST authorizer, this is not
/// defined.</p>
#[serde(rename = "ProviderArns")]
#[serde(skip_serializing_if = "Option::is_none")]
pub provider_arns: Option<Vec<String>>,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct CreateAuthorizerResponse {
/// <p>Specifies the required credentials as an IAM role for API Gateway to invoke the
/// authorizer. To specify an IAM role for API Gateway to assume, use the role's Amazon
/// Resource Name (ARN). To use resource-based permissions on the Lambda function,
/// specify null.</p>
#[serde(rename = "AuthorizerCredentialsArn")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorizer_credentials_arn: Option<String>,
/// <p>The authorizer identifier.</p>
#[serde(rename = "AuthorizerId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorizer_id: Option<String>,
/// <p>The time to live (TTL), in seconds, of cached authorizer results. If it equals 0,
/// authorization caching is disabled. If it is greater than 0, API Gateway will cache
/// authorizer responses. If this field is not set, the default value is 300. The maximum
/// value is 3600, or 1 hour.</p>
#[serde(rename = "AuthorizerResultTtlInSeconds")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorizer_result_ttl_in_seconds: Option<i64>,
/// <p>The authorizer type. Currently the only valid value is REQUEST, for a
/// Lambda function using incoming request parameters.</p>
#[serde(rename = "AuthorizerType")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorizer_type: Option<String>,
/// <p>The authorizer's Uniform Resource Identifier (URI).
/// ForREQUEST authorizers, this must be a
/// well-formed Lambda function URI, for example,
/// arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:{account_id}:function:{lambda_function_name}/invocations.
/// In general, the URI has this form:
/// arn:aws:apigateway:{region}:lambda:path/{service_api}
/// , where {region} is the same as the region hosting the Lambda
/// function, path indicates that the remaining substring in the URI should be treated as
/// the path to the resource, including the initial /. For Lambda functions,
/// this is usually of the form
/// /2015-03-31/functions/[FunctionARN]/invocations.</p>
#[serde(rename = "AuthorizerUri")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorizer_uri: Option<String>,
/// <p>The identity source for which authorization is requested.</p><p>For the REQUEST authorizer, this is required when authorization
/// caching is enabled. The value is a comma-separated string of one or more mapping
/// expressions of the specified request parameters. For example, if an Auth
/// header and a Name query string parameters are defined as identity
/// sources, this value is method.request.header.Auth,
/// method.request.querystring.Name. These parameters will be used to
/// derive the authorization caching key and to perform runtime validation of the
/// REQUEST authorizer by verifying all of the identity-related request
/// parameters are present, not null, and non-empty. Only when this is true does the
/// authorizer invoke the authorizer Lambda function, otherwise, it returns a 401
/// Unauthorized response without calling the Lambda function. The valid value
/// is a string of comma-separated mapping expressions of the specified request
/// parameters. When the authorization caching is not enabled, this property is
/// optional.</p>
#[serde(rename = "IdentitySource")]
#[serde(skip_serializing_if = "Option::is_none")]
pub identity_source: Option<Vec<String>>,
/// <p>The
/// validation expression does not apply to the REQUEST authorizer.</p>
#[serde(rename = "IdentityValidationExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub identity_validation_expression: Option<String>,
/// <p>The name of the authorizer.</p>
#[serde(rename = "Name")]
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// <p>For
/// REQUEST authorizer, this is not
/// defined.</p>
#[serde(rename = "ProviderArns")]
#[serde(skip_serializing_if = "Option::is_none")]
pub provider_arns: Option<Vec<String>>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct CreateDeploymentRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The description for the deployment resource.</p>
#[serde(rename = "Description")]
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// <p>The name of the Stage resource for the Deployment
/// resource to create.</p>
#[serde(rename = "StageName")]
#[serde(skip_serializing_if = "Option::is_none")]
pub stage_name: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct CreateDeploymentResponse {
/// <p>The date and time when the Deployment resource was created.</p>
#[serde(rename = "CreatedDate")]
#[serde(skip_serializing_if = "Option::is_none")]
pub created_date: Option<f64>,
/// <p>The identifier for the deployment.</p>
#[serde(rename = "DeploymentId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub deployment_id: Option<String>,
/// <p>The status of the deployment: PENDING, FAILED, or
/// SUCCEEDED.</p>
#[serde(rename = "DeploymentStatus")]
#[serde(skip_serializing_if = "Option::is_none")]
pub deployment_status: Option<String>,
/// <p>May contain additional feedback on the status of an API deployment.</p>
#[serde(rename = "DeploymentStatusMessage")]
#[serde(skip_serializing_if = "Option::is_none")]
pub deployment_status_message: Option<String>,
/// <p>The description for the deployment.</p>
#[serde(rename = "Description")]
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct CreateDomainNameRequest {
/// <p>The domain name.</p>
#[serde(rename = "DomainName")]
pub domain_name: String,
/// <p>The domain name configurations.</p>
#[serde(rename = "DomainNameConfigurations")]
#[serde(skip_serializing_if = "Option::is_none")]
pub domain_name_configurations: Option<Vec<DomainNameConfiguration>>,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct CreateDomainNameResponse {
/// <p>The API mapping selection expression.</p>
#[serde(rename = "ApiMappingSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_mapping_selection_expression: Option<String>,
/// <p>The name of the DomainName resource.</p>
#[serde(rename = "DomainName")]
#[serde(skip_serializing_if = "Option::is_none")]
pub domain_name: Option<String>,
/// <p>The domain name configurations.</p>
#[serde(rename = "DomainNameConfigurations")]
#[serde(skip_serializing_if = "Option::is_none")]
pub domain_name_configurations: Option<Vec<DomainNameConfiguration>>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct CreateIntegrationRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The connection ID.</p>
#[serde(rename = "ConnectionId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub connection_id: Option<String>,
/// <p>The type of the network connection to the integration endpoint. Currently the only
/// valid value is INTERNET, for connections through the public routable
/// internet.</p>
#[serde(rename = "ConnectionType")]
#[serde(skip_serializing_if = "Option::is_none")]
pub connection_type: Option<String>,
/// <p>Specifies how to handle response payload content type conversions. Supported
/// values are CONVERT_TO_BINARY and CONVERT_TO_TEXT, with the
/// following behaviors:</p><p>
/// CONVERT_TO_BINARY: Converts a response payload from a Base64-encoded
/// string to the corresponding binary blob.</p><p>
/// CONVERT_TO_TEXT: Converts a response payload from a binary blob to a
/// Base64-encoded string.</p><p>If this property is not defined, the response payload will be passed through from
/// the integration response to the route response or method response without
/// modification.</p>
#[serde(rename = "ContentHandlingStrategy")]
#[serde(skip_serializing_if = "Option::is_none")]
pub content_handling_strategy: Option<String>,
/// <p>Specifies the credentials required for the integration, if any. For AWS
/// integrations, three options are available. To specify an IAM Role for API Gateway to
/// assume, use the role's Amazon Resource Name (ARN). To require that the caller's
/// identity be passed through from the request, specify the string
/// arn:aws:iam::*:user/*. To use resource-based permissions on supported
/// AWS services, specify null.</p>
#[serde(rename = "CredentialsArn")]
#[serde(skip_serializing_if = "Option::is_none")]
pub credentials_arn: Option<String>,
/// <p>The description of the integration.</p>
#[serde(rename = "Description")]
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// <p>Specifies the integration's HTTP method type.</p>
#[serde(rename = "IntegrationMethod")]
#[serde(skip_serializing_if = "Option::is_none")]
pub integration_method: Option<String>,
/// <p>The integration type of an integration. One of the following:</p><p>
/// AWS: for integrating the route or method request with an AWS service
/// action, including the Lambda function-invoking action. With the Lambda
/// function-invoking action, this is referred to as the Lambda custom integration. With
/// any other AWS service action, this is known as AWS integration.</p><p>
/// AWS_PROXY: for integrating the route or method request with the Lambda
/// function-invoking action with the client request passed through as-is. This
/// integration is also referred to as Lambda proxy integration.</p><p>
/// HTTP: for integrating the route or method request with an HTTP
/// endpoint. This
/// integration is also referred to as HTTP custom integration.</p><p>
/// HTTP_PROXY: for integrating route or method request with an HTTP
/// endpoint, with the client
/// request passed through as-is. This is also referred to as HTTP proxy
/// integration.</p><p>
/// MOCK: for integrating the route or method request with API Gateway as a
/// "loopback" endpoint without invoking any backend.</p>
#[serde(rename = "IntegrationType")]
pub integration_type: String,
/// <p>For a Lambda proxy integration, this is the URI of the Lambda function.</p>
#[serde(rename = "IntegrationUri")]
#[serde(skip_serializing_if = "Option::is_none")]
pub integration_uri: Option<String>,
/// <p>Specifies the pass-through behavior for incoming requests based on the
/// Content-Type header in the request, and the available mapping
/// templates specified as the requestTemplates property on the
/// Integration resource. There are three valid values:
/// WHEN_NO_MATCH, WHEN_NO_TEMPLATES, and
/// NEVER.</p><p>
/// WHEN_NO_MATCH passes the request body for unmapped content types through
/// to the integration backend without transformation.</p><p>
/// NEVER rejects unmapped content types with an HTTP 415 Unsupported
/// Media Type response.</p><p>
/// WHEN_NO_TEMPLATES allows pass-through when the integration has no
/// content types mapped to templates. However, if there is at least one content type
/// defined, unmapped content types will be rejected with the same HTTP 415
/// Unsupported Media Type response.</p>
#[serde(rename = "PassthroughBehavior")]
#[serde(skip_serializing_if = "Option::is_none")]
pub passthrough_behavior: Option<String>,
/// <p>A key-value map specifying request parameters that are passed from the method
/// request to the backend. The key is an integration request parameter name and the
/// associated value is a method request parameter value or static value that must be
/// enclosed within single quotes and pre-encoded as required by the backend. The method
/// request parameter value must match the pattern of
/// method.request.{location}.{name}
/// , where
/// {location}
/// is querystring, path, or header; and
/// {name}
/// must be a valid and unique method request parameter name.</p>
#[serde(rename = "RequestParameters")]
#[serde(skip_serializing_if = "Option::is_none")]
pub request_parameters: Option<::std::collections::HashMap<String, String>>,
/// <p>Represents a map of Velocity templates that are applied on the request payload
/// based on the value of the Content-Type header sent by the client. The content type
/// value is the key in this map, and the template (as a String) is the value.</p>
#[serde(rename = "RequestTemplates")]
#[serde(skip_serializing_if = "Option::is_none")]
pub request_templates: Option<::std::collections::HashMap<String, String>>,
/// <p>The template selection expression for the integration.</p>
#[serde(rename = "TemplateSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub template_selection_expression: Option<String>,
/// <p>Custom timeout between 50 and 29,000 milliseconds. The default value is 29,000
/// milliseconds or 29 seconds.</p>
#[serde(rename = "TimeoutInMillis")]
#[serde(skip_serializing_if = "Option::is_none")]
pub timeout_in_millis: Option<i64>,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct CreateIntegrationResponse {
/// <p>The connection ID.</p>
#[serde(rename = "ConnectionId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub connection_id: Option<String>,
/// <p>The type of the network connection to the integration endpoint. Currently the only
/// valid value is INTERNET, for connections through the public routable
/// internet.</p>
#[serde(rename = "ConnectionType")]
#[serde(skip_serializing_if = "Option::is_none")]
pub connection_type: Option<String>,
/// <p>Specifies how to handle response payload content type conversions. Supported
/// values are CONVERT_TO_BINARY and CONVERT_TO_TEXT, with the
/// following behaviors:</p><p>
/// CONVERT_TO_BINARY: Converts a response payload from a Base64-encoded
/// string to the corresponding binary blob.</p><p>
/// CONVERT_TO_TEXT: Converts a response payload from a binary blob to a
/// Base64-encoded string.</p><p>If this property is not defined, the response payload will be passed through from
/// the integration response to the route response or method response without
/// modification.</p>
#[serde(rename = "ContentHandlingStrategy")]
#[serde(skip_serializing_if = "Option::is_none")]
pub content_handling_strategy: Option<String>,
/// <p>Specifies the credentials required for the integration, if any. For AWS
/// integrations, three options are available. To specify an IAM Role for API Gateway to
/// assume, use the role's Amazon Resource Name (ARN). To require that the caller's
/// identity be passed through from the request, specify the string
/// arn:aws:iam::*:user/*. To use resource-based permissions on supported
/// AWS services, specify null.</p>
#[serde(rename = "CredentialsArn")]
#[serde(skip_serializing_if = "Option::is_none")]
pub credentials_arn: Option<String>,
/// <p>Represents the description of an integration.</p>
#[serde(rename = "Description")]
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// <p>Represents the identifier of an integration.</p>
#[serde(rename = "IntegrationId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub integration_id: Option<String>,
/// <p>Specifies the integration's HTTP method type.</p>
#[serde(rename = "IntegrationMethod")]
#[serde(skip_serializing_if = "Option::is_none")]
pub integration_method: Option<String>,
/// <p>The integration response selection expression for the integration. See <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-integration-response-selection-expressions">Integration Response Selection Expressions</a>.</p>
#[serde(rename = "IntegrationResponseSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub integration_response_selection_expression: Option<String>,
/// <p>The integration type of an integration. One of the following:</p><p>
/// AWS: for integrating the route or method request with an AWS service
/// action, including the Lambda function-invoking action. With the Lambda
/// function-invoking action, this is referred to as the Lambda custom integration. With
/// any other AWS service action, this is known as AWS integration.</p><p>
/// AWS_PROXY: for integrating the route or method request with the Lambda
/// function-invoking action with the client request passed through as-is. This
/// integration is also referred to as Lambda proxy integration.</p><p>
/// HTTP: for integrating the route or method request with an HTTP
/// endpoint. This
/// integration is also referred to as the HTTP custom integration.</p><p>
/// HTTP_PROXY: for integrating route or method request with an HTTP
/// endpoint, with the client
/// request passed through as-is. This is also referred to as HTTP proxy
/// integration.</p><p>
/// MOCK: for integrating the route or method request with API Gateway as a
/// "loopback" endpoint without invoking any backend.</p>
#[serde(rename = "IntegrationType")]
#[serde(skip_serializing_if = "Option::is_none")]
pub integration_type: Option<String>,
/// <p>For a Lambda proxy integration, this is the URI of the Lambda function.</p>
#[serde(rename = "IntegrationUri")]
#[serde(skip_serializing_if = "Option::is_none")]
pub integration_uri: Option<String>,
/// <p>Specifies the pass-through behavior for incoming requests based on the
/// Content-Type header in the request, and the available mapping
/// templates specified as the requestTemplates property on the
/// Integration resource. There are three valid values:
/// WHEN_NO_MATCH, WHEN_NO_TEMPLATES, and
/// NEVER.</p><p>
/// WHEN_NO_MATCH passes the request body for unmapped content types through
/// to the integration backend without transformation.</p><p>
/// NEVER rejects unmapped content types with an HTTP 415 Unsupported
/// Media Type response.</p><p>
/// WHEN_NO_TEMPLATES allows pass-through when the integration has no
/// content types mapped to templates. However, if there is at least one content type
/// defined, unmapped content types will be rejected with the same HTTP 415
/// Unsupported Media Type response.</p>
#[serde(rename = "PassthroughBehavior")]
#[serde(skip_serializing_if = "Option::is_none")]
pub passthrough_behavior: Option<String>,
/// <p>A key-value map specifying request parameters that are passed from the method
/// request to the backend. The key is an integration request parameter name and the
/// associated value is a method request parameter value or static value that must be
/// enclosed within single quotes and pre-encoded as required by the backend. The method
/// request parameter value must match the pattern of
/// method.request.{location}.{name}
/// , where
/// {location}
/// is querystring, path, or header; and
/// {name}
/// must be a valid and unique method request parameter name.</p>
#[serde(rename = "RequestParameters")]
#[serde(skip_serializing_if = "Option::is_none")]
pub request_parameters: Option<::std::collections::HashMap<String, String>>,
/// <p>Represents a map of Velocity templates that are applied on the request payload
/// based on the value of the Content-Type header sent by the client. The content type
/// value is the key in this map, and the template (as a String) is the value.</p>
#[serde(rename = "RequestTemplates")]
#[serde(skip_serializing_if = "Option::is_none")]
pub request_templates: Option<::std::collections::HashMap<String, String>>,
/// <p>The template selection expression for the integration.</p>
#[serde(rename = "TemplateSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub template_selection_expression: Option<String>,
/// <p>Custom timeout between 50 and 29,000 milliseconds. The default value is 29,000
/// milliseconds or 29 seconds.</p>
#[serde(rename = "TimeoutInMillis")]
#[serde(skip_serializing_if = "Option::is_none")]
pub timeout_in_millis: Option<i64>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct CreateIntegrationResponseRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>Specifies how to handle response payload content type conversions. Supported
/// values are CONVERT_TO_BINARY and CONVERT_TO_TEXT, with the
/// following behaviors:</p><p>
/// CONVERT_TO_BINARY: Converts a response payload from a Base64-encoded
/// string to the corresponding binary blob.</p><p>
/// CONVERT_TO_TEXT: Converts a response payload from a binary blob to a
/// Base64-encoded string.</p><p>If this property is not defined, the response payload will be passed through from
/// the integration response to the route response or method response without
/// modification.</p>
#[serde(rename = "ContentHandlingStrategy")]
#[serde(skip_serializing_if = "Option::is_none")]
pub content_handling_strategy: Option<String>,
/// <p>The integration ID.</p>
#[serde(rename = "IntegrationId")]
pub integration_id: String,
/// <p>The integration response key.</p>
#[serde(rename = "IntegrationResponseKey")]
pub integration_response_key: String,
/// <p>A key-value map specifying response parameters that are passed to the method
/// response from the backend. The key is a method response header parameter name and the
/// mapped value is an integration response header value, a static value enclosed within
/// a pair of single quotes, or a JSON expression from the integration response body. The
/// mapping key must match the pattern of method.response.header.{name},
/// where {name} is a valid and unique header name. The mapped non-static
/// value must match the pattern of integration.response.header.{name} or
/// integration.response.body.{JSON-expression}, where
/// {name} is a valid and unique response header name and
/// {JSON-expression} is a valid JSON expression without the $
/// prefix.</p>
#[serde(rename = "ResponseParameters")]
#[serde(skip_serializing_if = "Option::is_none")]
pub response_parameters: Option<::std::collections::HashMap<String, String>>,
/// <p>The collection of response templates for the integration response as a
/// string-to-string map of key-value pairs. Response templates are represented as a
/// key/value map, with a content-type as the key and a template as the value.</p>
#[serde(rename = "ResponseTemplates")]
#[serde(skip_serializing_if = "Option::is_none")]
pub response_templates: Option<::std::collections::HashMap<String, String>>,
/// <p>The template selection expression for the integration response.</p>
#[serde(rename = "TemplateSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub template_selection_expression: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct CreateIntegrationResponseResponse {
/// <p>Specifies how to handle response payload content type conversions. Supported
/// values are CONVERT_TO_BINARY and CONVERT_TO_TEXT, with the
/// following behaviors:</p><p>
/// CONVERT_TO_BINARY: Converts a response payload from a Base64-encoded
/// string to the corresponding binary blob.</p><p>
/// CONVERT_TO_TEXT: Converts a response payload from a binary blob to a
/// Base64-encoded string.</p><p>If this property is not defined, the response payload will be passed through from
/// the integration response to the route response or method response without
/// modification.</p>
#[serde(rename = "ContentHandlingStrategy")]
#[serde(skip_serializing_if = "Option::is_none")]
pub content_handling_strategy: Option<String>,
/// <p>The integration response ID.</p>
#[serde(rename = "IntegrationResponseId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub integration_response_id: Option<String>,
/// <p>The integration response key.</p>
#[serde(rename = "IntegrationResponseKey")]
#[serde(skip_serializing_if = "Option::is_none")]
pub integration_response_key: Option<String>,
/// <p>A key-value map specifying response parameters that are passed to the method
/// response from the backend. The key is a method response header parameter name and the
/// mapped value is an integration response header value, a static value enclosed within
/// a pair of single quotes, or a JSON expression from the integration response body. The
/// mapping key must match the pattern of method.response.header.{name}, where name is a
/// valid and unique header name. The mapped non-static value must match the pattern of
/// integration.response.header.{name} or integration.response.body.{JSON-expression},
/// where name is a valid and unique response header name and JSON-expression is a valid
/// JSON expression without the $ prefix.</p>
#[serde(rename = "ResponseParameters")]
#[serde(skip_serializing_if = "Option::is_none")]
pub response_parameters: Option<::std::collections::HashMap<String, String>>,
/// <p>The collection of response templates for the integration response as a
/// string-to-string map of key-value pairs. Response templates are represented as a
/// key/value map, with a content-type as the key and a template as the value.</p>
#[serde(rename = "ResponseTemplates")]
#[serde(skip_serializing_if = "Option::is_none")]
pub response_templates: Option<::std::collections::HashMap<String, String>>,
/// <p>The template selection expressions for the integration response.</p>
#[serde(rename = "TemplateSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub template_selection_expression: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct CreateModelRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The content-type for the model, for example, "application/json".</p>
#[serde(rename = "ContentType")]
#[serde(skip_serializing_if = "Option::is_none")]
pub content_type: Option<String>,
/// <p>The description of the model.</p>
#[serde(rename = "Description")]
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// <p>The name of the model. Must be alphanumeric.</p>
#[serde(rename = "Name")]
pub name: String,
/// <p>The schema for the model. For application/json models, this should be JSON schema
/// draft 4 model.</p>
#[serde(rename = "Schema")]
pub schema: String,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct CreateModelResponse {
/// <p>The content-type for the model, for example, "application/json".</p>
#[serde(rename = "ContentType")]
#[serde(skip_serializing_if = "Option::is_none")]
pub content_type: Option<String>,
/// <p>The description of the model.</p>
#[serde(rename = "Description")]
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// <p>The model identifier.</p>
#[serde(rename = "ModelId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub model_id: Option<String>,
/// <p>The name of the model. Must be alphanumeric.</p>
#[serde(rename = "Name")]
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// <p>The schema for the model. For application/json models, this should be JSON schema
/// draft 4 model.</p>
#[serde(rename = "Schema")]
#[serde(skip_serializing_if = "Option::is_none")]
pub schema: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct CreateRouteRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>Specifies whether an API key is required for the route.</p>
#[serde(rename = "ApiKeyRequired")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_key_required: Option<bool>,
/// <p>The authorization scopes supported by this
/// route.</p>
#[serde(rename = "AuthorizationScopes")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorization_scopes: Option<Vec<String>>,
/// <p>The authorization type for the route. Valid values are NONE for open
/// access, AWS_IAM for using AWS IAM permissions, and CUSTOM
/// for using a Lambda
/// authorizer.</p>
#[serde(rename = "AuthorizationType")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorization_type: Option<String>,
/// <p>The identifier of the Authorizer resource to be associated with this
/// route, if the authorizationType is CUSTOM
/// . The authorizer identifier is generated by API Gateway
/// when you created the authorizer.</p>
#[serde(rename = "AuthorizerId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorizer_id: Option<String>,
/// <p>The model selection expression for the route.</p>
#[serde(rename = "ModelSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub model_selection_expression: Option<String>,
/// <p>The operation name for the route.</p>
#[serde(rename = "OperationName")]
#[serde(skip_serializing_if = "Option::is_none")]
pub operation_name: Option<String>,
/// <p>The request models for the route.</p>
#[serde(rename = "RequestModels")]
#[serde(skip_serializing_if = "Option::is_none")]
pub request_models: Option<::std::collections::HashMap<String, String>>,
/// <p>The request parameters for the route.</p>
#[serde(rename = "RequestParameters")]
#[serde(skip_serializing_if = "Option::is_none")]
pub request_parameters: Option<::std::collections::HashMap<String, ParameterConstraints>>,
/// <p>The route key for the route.</p>
#[serde(rename = "RouteKey")]
pub route_key: String,
/// <p>The route response selection expression for the route.</p>
#[serde(rename = "RouteResponseSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub route_response_selection_expression: Option<String>,
/// <p>The target for the route.</p>
#[serde(rename = "Target")]
#[serde(skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct CreateRouteResponse {
/// <p>Specifies whether an API key is required for this route.</p>
#[serde(rename = "ApiKeyRequired")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_key_required: Option<bool>,
/// <p>A list of authorization scopes configured on a route. The scopes are used with a
/// COGNITO_USER_POOLS authorizer to authorize the method invocation. The authorization
/// works by matching the route scopes against the scopes parsed from the access token in
/// the incoming request. The method invocation is authorized if any route scope matches
/// a claimed scope in the access token. Otherwise, the invocation is not authorized.
/// When the route scope is configured, the client must provide an access token instead
/// of an identity token for authorization purposes.</p>
#[serde(rename = "AuthorizationScopes")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorization_scopes: Option<Vec<String>>,
/// <p>The authorization type for the route. Valid values are NONE for open
/// access, AWS_IAM for using AWS IAM permissions, and CUSTOM
/// for using a Lambda
/// authorizer</p>
#[serde(rename = "AuthorizationType")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorization_type: Option<String>,
/// <p>The identifier of the Authorizer resource to be associated with this
/// route, if the authorizationType is CUSTOM
/// . The authorizer identifier is generated by API Gateway
/// when you created the authorizer.</p>
#[serde(rename = "AuthorizerId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorizer_id: Option<String>,
/// <p>The model selection expression for the route.</p>
#[serde(rename = "ModelSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub model_selection_expression: Option<String>,
/// <p>The operation name for the route.</p>
#[serde(rename = "OperationName")]
#[serde(skip_serializing_if = "Option::is_none")]
pub operation_name: Option<String>,
/// <p>The request models for the route.</p>
#[serde(rename = "RequestModels")]
#[serde(skip_serializing_if = "Option::is_none")]
pub request_models: Option<::std::collections::HashMap<String, String>>,
/// <p>The request parameters for the route.</p>
#[serde(rename = "RequestParameters")]
#[serde(skip_serializing_if = "Option::is_none")]
pub request_parameters: Option<::std::collections::HashMap<String, ParameterConstraints>>,
/// <p>The route ID.</p>
#[serde(rename = "RouteId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub route_id: Option<String>,
/// <p>The route key for the route.</p>
#[serde(rename = "RouteKey")]
#[serde(skip_serializing_if = "Option::is_none")]
pub route_key: Option<String>,
/// <p>The route response selection expression for the route.</p>
#[serde(rename = "RouteResponseSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub route_response_selection_expression: Option<String>,
/// <p>The target for the route.</p>
#[serde(rename = "Target")]
#[serde(skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct CreateRouteResponseRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The model selection expression for the route response.</p>
#[serde(rename = "ModelSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub model_selection_expression: Option<String>,
/// <p>The response models for the route response.</p>
#[serde(rename = "ResponseModels")]
#[serde(skip_serializing_if = "Option::is_none")]
pub response_models: Option<::std::collections::HashMap<String, String>>,
/// <p>The route response parameters.</p>
#[serde(rename = "ResponseParameters")]
#[serde(skip_serializing_if = "Option::is_none")]
pub response_parameters: Option<::std::collections::HashMap<String, ParameterConstraints>>,
/// <p>The route ID.</p>
#[serde(rename = "RouteId")]
pub route_id: String,
/// <p>The route response key.</p>
#[serde(rename = "RouteResponseKey")]
pub route_response_key: String,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct CreateRouteResponseResponse {
/// <p>Represents the model selection expression of a route response.</p>
#[serde(rename = "ModelSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub model_selection_expression: Option<String>,
/// <p>Represents the response models of a route response.</p>
#[serde(rename = "ResponseModels")]
#[serde(skip_serializing_if = "Option::is_none")]
pub response_models: Option<::std::collections::HashMap<String, String>>,
/// <p>Represents the response parameters of a route response.</p>
#[serde(rename = "ResponseParameters")]
#[serde(skip_serializing_if = "Option::is_none")]
pub response_parameters: Option<::std::collections::HashMap<String, ParameterConstraints>>,
/// <p>Represents the identifier of a route response.</p>
#[serde(rename = "RouteResponseId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub route_response_id: Option<String>,
/// <p>Represents the route response key of a route response.</p>
#[serde(rename = "RouteResponseKey")]
#[serde(skip_serializing_if = "Option::is_none")]
pub route_response_key: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct CreateStageRequest {
/// <p>Settings for logging access in this stage.</p>
#[serde(rename = "AccessLogSettings")]
#[serde(skip_serializing_if = "Option::is_none")]
pub access_log_settings: Option<AccessLogSettings>,
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The identifier of a client certificate for a Stage.</p>
#[serde(rename = "ClientCertificateId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub client_certificate_id: Option<String>,
/// <p>The default route settings for the stage.</p>
#[serde(rename = "DefaultRouteSettings")]
#[serde(skip_serializing_if = "Option::is_none")]
pub default_route_settings: Option<RouteSettings>,
/// <p>The deployment identifier of the API stage.</p>
#[serde(rename = "DeploymentId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub deployment_id: Option<String>,
/// <p>The description for the API stage.</p>
#[serde(rename = "Description")]
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// <p>Route settings for the stage.</p>
#[serde(rename = "RouteSettings")]
#[serde(skip_serializing_if = "Option::is_none")]
pub route_settings: Option<::std::collections::HashMap<String, RouteSettings>>,
/// <p>The name of the stage.</p>
#[serde(rename = "StageName")]
pub stage_name: String,
/// <p>A map that defines the stage variables for a Stage. Variable names
/// can have alphanumeric and underscore characters, and the values must match
/// [A-Za-z0-9-._~:/?#&=,]+.</p>
#[serde(rename = "StageVariables")]
#[serde(skip_serializing_if = "Option::is_none")]
pub stage_variables: Option<::std::collections::HashMap<String, String>>,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct CreateStageResponse {
/// <p>Settings for logging access in this stage.</p>
#[serde(rename = "AccessLogSettings")]
#[serde(skip_serializing_if = "Option::is_none")]
pub access_log_settings: Option<AccessLogSettings>,
/// <p>The identifier of a client certificate for a Stage.</p>
#[serde(rename = "ClientCertificateId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub client_certificate_id: Option<String>,
/// <p>The timestamp when the stage was created.</p>
#[serde(rename = "CreatedDate")]
#[serde(skip_serializing_if = "Option::is_none")]
pub created_date: Option<f64>,
/// <p>Default route settings for the stage.</p>
#[serde(rename = "DefaultRouteSettings")]
#[serde(skip_serializing_if = "Option::is_none")]
pub default_route_settings: Option<RouteSettings>,
/// <p>The identifier of the Deployment that the Stage is
/// associated with.</p>
#[serde(rename = "DeploymentId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub deployment_id: Option<String>,
/// <p>The description of the stage.</p>
#[serde(rename = "Description")]
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// <p>The timestamp when the stage was last updated.</p>
#[serde(rename = "LastUpdatedDate")]
#[serde(skip_serializing_if = "Option::is_none")]
pub last_updated_date: Option<f64>,
/// <p>Route settings for the stage.</p>
#[serde(rename = "RouteSettings")]
#[serde(skip_serializing_if = "Option::is_none")]
pub route_settings: Option<::std::collections::HashMap<String, RouteSettings>>,
/// <p>The name of the stage.</p>
#[serde(rename = "StageName")]
#[serde(skip_serializing_if = "Option::is_none")]
pub stage_name: Option<String>,
/// <p>A map that defines the stage variables for a stage resource. Variable names can
/// have alphanumeric and underscore characters, and the values must match
/// [A-Za-z0-9-._~:/?#&=,]+.</p>
#[serde(rename = "StageVariables")]
#[serde(skip_serializing_if = "Option::is_none")]
pub stage_variables: Option<::std::collections::HashMap<String, String>>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct DeleteApiMappingRequest {
/// <p>The API mapping identifier.</p>
#[serde(rename = "ApiMappingId")]
pub api_mapping_id: String,
/// <p>The domain name.</p>
#[serde(rename = "DomainName")]
pub domain_name: String,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct DeleteApiRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct DeleteAuthorizerRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The authorizer identifier.</p>
#[serde(rename = "AuthorizerId")]
pub authorizer_id: String,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct DeleteDeploymentRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The deployment ID.</p>
#[serde(rename = "DeploymentId")]
pub deployment_id: String,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct DeleteDomainNameRequest {
/// <p>The domain name.</p>
#[serde(rename = "DomainName")]
pub domain_name: String,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct DeleteIntegrationRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The integration ID.</p>
#[serde(rename = "IntegrationId")]
pub integration_id: String,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct DeleteIntegrationResponseRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The integration ID.</p>
#[serde(rename = "IntegrationId")]
pub integration_id: String,
/// <p>The integration response ID.</p>
#[serde(rename = "IntegrationResponseId")]
pub integration_response_id: String,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct DeleteModelRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The model ID.</p>
#[serde(rename = "ModelId")]
pub model_id: String,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct DeleteRouteRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The route ID.</p>
#[serde(rename = "RouteId")]
pub route_id: String,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct DeleteRouteResponseRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The route ID.</p>
#[serde(rename = "RouteId")]
pub route_id: String,
/// <p>The route response ID.</p>
#[serde(rename = "RouteResponseId")]
pub route_response_id: String,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct DeleteStageRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The stage name.</p>
#[serde(rename = "StageName")]
pub stage_name: String,
}
/// <p>An immutable representation of an API that can be called by users. A
/// Deployment must be associated with a Stage for it to be
/// callable over the internet.</p>
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct Deployment {
/// <p>The date and time when the Deployment resource was created.</p>
#[serde(rename = "CreatedDate")]
#[serde(skip_serializing_if = "Option::is_none")]
pub created_date: Option<f64>,
/// <p>The identifier for the deployment.</p>
#[serde(rename = "DeploymentId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub deployment_id: Option<String>,
/// <p>The status of the deployment: PENDING, FAILED, or
/// SUCCEEDED.</p>
#[serde(rename = "DeploymentStatus")]
#[serde(skip_serializing_if = "Option::is_none")]
pub deployment_status: Option<String>,
/// <p>May contain additional feedback on the status of an API deployment.</p>
#[serde(rename = "DeploymentStatusMessage")]
#[serde(skip_serializing_if = "Option::is_none")]
pub deployment_status_message: Option<String>,
/// <p>The description for the deployment.</p>
#[serde(rename = "Description")]
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
/// <p>Represents a domain name.</p>
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct DomainName {
/// <p>The API mapping selection expression.</p>
#[serde(rename = "ApiMappingSelectionExpression")] | pub domain_name: String,
/// <p>The domain name configurations.</p>
#[serde(rename = "DomainNameConfigurations")]
#[serde(skip_serializing_if = "Option::is_none")]
pub domain_name_configurations: Option<Vec<DomainNameConfiguration>>,
}
/// <p>The domain name configuration.</p>
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DomainNameConfiguration {
/// <p>A domain name for the WebSocket API.</p>
#[serde(rename = "ApiGatewayDomainName")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_gateway_domain_name: Option<String>,
/// <p>An AWS-managed certificate that will be used by the edge-optimized endpoint for
/// this domain name. AWS Certificate Manager is the only supported source.</p>
#[serde(rename = "CertificateArn")]
#[serde(skip_serializing_if = "Option::is_none")]
pub certificate_arn: Option<String>,
/// <p>The user-friendly name of the certificate that will be used by the edge-optimized
/// endpoint for this domain name.</p>
#[serde(rename = "CertificateName")]
#[serde(skip_serializing_if = "Option::is_none")]
pub certificate_name: Option<String>,
/// <p>The timestamp when the certificate that was used by edge-optimized endpoint for
/// this domain name was uploaded.</p>
#[serde(rename = "CertificateUploadDate")]
#[serde(skip_serializing_if = "Option::is_none")]
pub certificate_upload_date: Option<f64>,
/// <p>The endpoint type.</p>
#[serde(rename = "EndpointType")]
#[serde(skip_serializing_if = "Option::is_none")]
pub endpoint_type: Option<String>,
/// <p>The Amazon Route 53 Hosted Zone ID of the endpoint.</p>
#[serde(rename = "HostedZoneId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub hosted_zone_id: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct GetApiMappingRequest {
/// <p>The API mapping identifier.</p>
#[serde(rename = "ApiMappingId")]
pub api_mapping_id: String,
/// <p>The domain name.</p>
#[serde(rename = "DomainName")]
pub domain_name: String,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct GetApiMappingResponse {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_id: Option<String>,
/// <p>The API mapping identifier.</p>
#[serde(rename = "ApiMappingId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_mapping_id: Option<String>,
/// <p>The API mapping key.</p>
#[serde(rename = "ApiMappingKey")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_mapping_key: Option<String>,
/// <p>The API stage.</p>
#[serde(rename = "Stage")]
#[serde(skip_serializing_if = "Option::is_none")]
pub stage: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct GetApiMappingsRequest {
/// <p>The domain name.</p>
#[serde(rename = "DomainName")]
pub domain_name: String,
/// <p>The maximum number of elements to be returned for this resource.</p>
#[serde(rename = "MaxResults")]
#[serde(skip_serializing_if = "Option::is_none")]
pub max_results: Option<String>,
/// <p>The next page of elements from this collection. Not valid for the last element of
/// the collection.</p>
#[serde(rename = "NextToken")]
#[serde(skip_serializing_if = "Option::is_none")]
pub next_token: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct GetApiMappingsResponse {
/// <p>The elements from this collection.</p>
#[serde(rename = "Items")]
#[serde(skip_serializing_if = "Option::is_none")]
pub items: Option<Vec<ApiMapping>>,
/// <p>The next page of elements from this collection. Not valid for the last element of
/// the collection.</p>
#[serde(rename = "NextToken")]
#[serde(skip_serializing_if = "Option::is_none")]
pub next_token: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct GetApiRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct GetApiResponse {
/// <p>The URI of the API, of the form {api-id}.execute-api.{region}.amazonaws.com. The
/// stage name is typically appended to this URI to form a complete path to a deployed
/// API stage.</p>
#[serde(rename = "ApiEndpoint")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_endpoint: Option<String>,
/// <p>The API ID.</p>
#[serde(rename = "ApiId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_id: Option<String>,
/// <p>An API key selection expression. See <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions">API Key Selection Expressions</a>.</p>
#[serde(rename = "ApiKeySelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_key_selection_expression: Option<String>,
/// <p>The timestamp when the API was created.</p>
#[serde(rename = "CreatedDate")]
#[serde(skip_serializing_if = "Option::is_none")]
pub created_date: Option<f64>,
/// <p>The description of the API.</p>
#[serde(rename = "Description")]
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// <p>Avoid validating models when creating a deployment.</p>
#[serde(rename = "DisableSchemaValidation")]
#[serde(skip_serializing_if = "Option::is_none")]
pub disable_schema_validation: Option<bool>,
/// <p>The name of the API.</p>
#[serde(rename = "Name")]
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// <p>The API protocol: Currently only WEBSOCKET is supported.</p>
#[serde(rename = "ProtocolType")]
#[serde(skip_serializing_if = "Option::is_none")]
pub protocol_type: Option<String>,
/// <p>The route selection expression for the API.</p>
#[serde(rename = "RouteSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub route_selection_expression: Option<String>,
/// <p>A version identifier for the API.</p>
#[serde(rename = "Version")]
#[serde(skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
/// <p>The warning messages reported when failonwarnings is turned on during
/// API import.</p>
#[serde(rename = "Warnings")]
#[serde(skip_serializing_if = "Option::is_none")]
pub warnings: Option<Vec<String>>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct GetApisRequest {
/// <p>The maximum number of elements to be returned for this resource.</p>
#[serde(rename = "MaxResults")]
#[serde(skip_serializing_if = "Option::is_none")]
pub max_results: Option<String>,
/// <p>The next page of elements from this collection. Not valid for the last element of
/// the collection.</p>
#[serde(rename = "NextToken")]
#[serde(skip_serializing_if = "Option::is_none")]
pub next_token: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct GetApisResponse {
/// <p>The elements from this collection.</p>
#[serde(rename = "Items")]
#[serde(skip_serializing_if = "Option::is_none")]
pub items: Option<Vec<Api>>,
/// <p>The next page of elements from this collection. Not valid for the last element of
/// the collection.</p>
#[serde(rename = "NextToken")]
#[serde(skip_serializing_if = "Option::is_none")]
pub next_token: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct GetAuthorizerRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The authorizer identifier.</p>
#[serde(rename = "AuthorizerId")]
pub authorizer_id: String,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct GetAuthorizerResponse {
/// <p>Specifies the required credentials as an IAM role for API Gateway to invoke the
/// authorizer. To specify an IAM role for API Gateway to assume, use the role's Amazon
/// Resource Name (ARN). To use resource-based permissions on the Lambda function,
/// specify null.</p>
#[serde(rename = "AuthorizerCredentialsArn")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorizer_credentials_arn: Option<String>,
/// <p>The authorizer identifier.</p>
#[serde(rename = "AuthorizerId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorizer_id: Option<String>,
/// <p>The time to live (TTL), in seconds, of cached authorizer results. If it equals 0,
/// authorization caching is disabled. If it is greater than 0, API Gateway will cache
/// authorizer responses. If this field is not set, the default value is 300. The maximum
/// value is 3600, or 1 hour.</p>
#[serde(rename = "AuthorizerResultTtlInSeconds")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorizer_result_ttl_in_seconds: Option<i64>,
/// <p>The authorizer type. Currently the only valid value is REQUEST, for a
/// Lambda function using incoming request parameters.</p>
#[serde(rename = "AuthorizerType")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorizer_type: Option<String>,
/// <p>The authorizer's Uniform Resource Identifier (URI).
/// ForREQUEST authorizers, this must be a
/// well-formed Lambda function URI, for example,
/// arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:{account_id}:function:{lambda_function_name}/invocations.
/// In general, the URI has this form:
/// arn:aws:apigateway:{region}:lambda:path/{service_api}
/// , where {region} is the same as the region hosting the Lambda
/// function, path indicates that the remaining substring in the URI should be treated as
/// the path to the resource, including the initial /. For Lambda functions,
/// this is usually of the form
/// /2015-03-31/functions/[FunctionARN]/invocations.</p>
#[serde(rename = "AuthorizerUri")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorizer_uri: Option<String>,
/// <p>The identity source for which authorization is requested.</p><p>For the REQUEST authorizer, this is required when authorization
/// caching is enabled. The value is a comma-separated string of one or more mapping
/// expressions of the specified request parameters. For example, if an Auth
/// header and a Name query string parameters are defined as identity
/// sources, this value is method.request.header.Auth,
/// method.request.querystring.Name. These parameters will be used to
/// derive the authorization caching key and to perform runtime validation of the
/// REQUEST authorizer by verifying all of the identity-related request
/// parameters are present, not null, and non-empty. Only when this is true does the
/// authorizer invoke the authorizer Lambda function, otherwise, it returns a 401
/// Unauthorized response without calling the Lambda function. The valid value
/// is a string of comma-separated mapping expressions of the specified request
/// parameters. When the authorization caching is not enabled, this property is
/// optional.</p>
#[serde(rename = "IdentitySource")]
#[serde(skip_serializing_if = "Option::is_none")]
pub identity_source: Option<Vec<String>>,
/// <p>The
/// validation expression does not apply to the REQUEST authorizer.</p>
#[serde(rename = "IdentityValidationExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub identity_validation_expression: Option<String>,
/// <p>The name of the authorizer.</p>
#[serde(rename = "Name")]
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// <p>For
/// REQUEST authorizer, this is not
/// defined.</p>
#[serde(rename = "ProviderArns")]
#[serde(skip_serializing_if = "Option::is_none")]
pub provider_arns: Option<Vec<String>>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct GetAuthorizersRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The maximum number of elements to be returned for this resource.</p>
#[serde(rename = "MaxResults")]
#[serde(skip_serializing_if = "Option::is_none")]
pub max_results: Option<String>,
/// <p>The next page of elements from this collection. Not valid for the last element of
/// the collection.</p>
#[serde(rename = "NextToken")]
#[serde(skip_serializing_if = "Option::is_none")]
pub next_token: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct GetAuthorizersResponse {
/// <p>The elements from this collection.</p>
#[serde(rename = "Items")]
#[serde(skip_serializing_if = "Option::is_none")]
pub items: Option<Vec<Authorizer>>,
/// <p>The next page of elements from this collection. Not valid for the last element of
/// the collection.</p>
#[serde(rename = "NextToken")]
#[serde(skip_serializing_if = "Option::is_none")]
pub next_token: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct GetDeploymentRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The deployment ID.</p>
#[serde(rename = "DeploymentId")]
pub deployment_id: String,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct GetDeploymentResponse {
/// <p>The date and time when the Deployment resource was created.</p>
#[serde(rename = "CreatedDate")]
#[serde(skip_serializing_if = "Option::is_none")]
pub created_date: Option<f64>,
/// <p>The identifier for the deployment.</p>
#[serde(rename = "DeploymentId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub deployment_id: Option<String>,
/// <p>The status of the deployment: PENDING, FAILED, or
/// SUCCEEDED.</p>
#[serde(rename = "DeploymentStatus")]
#[serde(skip_serializing_if = "Option::is_none")]
pub deployment_status: Option<String>,
/// <p>May contain additional feedback on the status of an API deployment.</p>
#[serde(rename = "DeploymentStatusMessage")]
#[serde(skip_serializing_if = "Option::is_none")]
pub deployment_status_message: Option<String>,
/// <p>The description for the deployment.</p>
#[serde(rename = "Description")]
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct GetDeploymentsRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The maximum number of elements to be returned for this resource.</p>
#[serde(rename = "MaxResults")]
#[serde(skip_serializing_if = "Option::is_none")]
pub max_results: Option<String>,
/// <p>The next page of elements from this collection. Not valid for the last element of
/// the collection.</p>
#[serde(rename = "NextToken")]
#[serde(skip_serializing_if = "Option::is_none")]
pub next_token: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct GetDeploymentsResponse {
/// <p>The elements from this collection.</p>
#[serde(rename = "Items")]
#[serde(skip_serializing_if = "Option::is_none")]
pub items: Option<Vec<Deployment>>,
/// <p>The next page of elements from this collection. Not valid for the last element of
/// the collection.</p>
#[serde(rename = "NextToken")]
#[serde(skip_serializing_if = "Option::is_none")]
pub next_token: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct GetDomainNameRequest {
/// <p>The domain name.</p>
#[serde(rename = "DomainName")]
pub domain_name: String,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct GetDomainNameResponse {
/// <p>The API mapping selection expression.</p>
#[serde(rename = "ApiMappingSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_mapping_selection_expression: Option<String>,
/// <p>The name of the DomainName resource.</p>
#[serde(rename = "DomainName")]
#[serde(skip_serializing_if = "Option::is_none")]
pub domain_name: Option<String>,
/// <p>The domain name configurations.</p>
#[serde(rename = "DomainNameConfigurations")]
#[serde(skip_serializing_if = "Option::is_none")]
pub domain_name_configurations: Option<Vec<DomainNameConfiguration>>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct GetDomainNamesRequest {
/// <p>The maximum number of elements to be returned for this resource.</p>
#[serde(rename = "MaxResults")]
#[serde(skip_serializing_if = "Option::is_none")]
pub max_results: Option<String>,
/// <p>The next page of elements from this collection. Not valid for the last element of
/// the collection.</p>
#[serde(rename = "NextToken")]
#[serde(skip_serializing_if = "Option::is_none")]
pub next_token: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct GetDomainNamesResponse {
/// <p>The elements from this collection.</p>
#[serde(rename = "Items")]
#[serde(skip_serializing_if = "Option::is_none")]
pub items: Option<Vec<DomainName>>,
/// <p>The next page of elements from this collection. Not valid for the last element of
/// the collection.</p>
#[serde(rename = "NextToken")]
#[serde(skip_serializing_if = "Option::is_none")]
pub next_token: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct GetIntegrationRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The integration ID.</p>
#[serde(rename = "IntegrationId")]
pub integration_id: String,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct GetIntegrationResponse {
/// <p>The connection ID.</p>
#[serde(rename = "ConnectionId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub connection_id: Option<String>,
/// <p>The type of the network connection to the integration endpoint. Currently the only
/// valid value is INTERNET, for connections through the public routable
/// internet.</p>
#[serde(rename = "ConnectionType")]
#[serde(skip_serializing_if = "Option::is_none")]
pub connection_type: Option<String>,
/// <p>Specifies how to handle response payload content type conversions. Supported
/// values are CONVERT_TO_BINARY and CONVERT_TO_TEXT, with the
/// following behaviors:</p><p>
/// CONVERT_TO_BINARY: Converts a response payload from a Base64-encoded
/// string to the corresponding binary blob.</p><p>
/// CONVERT_TO_TEXT: Converts a response payload from a binary blob to a
/// Base64-encoded string.</p><p>If this property is not defined, the response payload will be passed through from
/// the integration response to the route response or method response without
/// modification.</p>
#[serde(rename = "ContentHandlingStrategy")]
#[serde(skip_serializing_if = "Option::is_none")]
pub content_handling_strategy: Option<String>,
/// <p>Specifies the credentials required for the integration, if any. For AWS
/// integrations, three options are available. To specify an IAM Role for API Gateway to
/// assume, use the role's Amazon Resource Name (ARN). To require that the caller's
/// identity be passed through from the request, specify the string
/// arn:aws:iam::*:user/*. To use resource-based permissions on supported
/// AWS services, specify null.</p>
#[serde(rename = "CredentialsArn")]
#[serde(skip_serializing_if = "Option::is_none")]
pub credentials_arn: Option<String>,
/// <p>Represents the description of an integration.</p>
#[serde(rename = "Description")]
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// <p>Represents the identifier of an integration.</p>
#[serde(rename = "IntegrationId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub integration_id: Option<String>,
/// <p>Specifies the integration's HTTP method type.</p>
#[serde(rename = "IntegrationMethod")]
#[serde(skip_serializing_if = "Option::is_none")]
pub integration_method: Option<String>,
/// <p>The integration response selection expression for the integration. See <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-integration-response-selection-expressions">Integration Response Selection Expressions</a>.</p>
#[serde(rename = "IntegrationResponseSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub integration_response_selection_expression: Option<String>,
/// <p>The integration type of an integration. One of the following:</p><p>
/// AWS: for integrating the route or method request with an AWS service
/// action, including the Lambda function-invoking action. With the Lambda
/// function-invoking action, this is referred to as the Lambda custom integration. With
/// any other AWS service action, this is known as AWS integration.</p><p>
/// AWS_PROXY: for integrating the route or method request with the Lambda
/// function-invoking action with the client request passed through as-is. This
/// integration is also referred to as Lambda proxy integration.</p><p>
/// HTTP: for integrating the route or method request with an HTTP
/// endpoint. This
/// integration is also referred to as the HTTP custom integration.</p><p>
/// HTTP_PROXY: for integrating route or method request with an HTTP
/// endpoint, with the client
/// request passed through as-is. This is also referred to as HTTP proxy
/// integration.</p><p>
/// MOCK: for integrating the route or method request with API Gateway as a
/// "loopback" endpoint without invoking any backend.</p>
#[serde(rename = "IntegrationType")]
#[serde(skip_serializing_if = "Option::is_none")]
pub integration_type: Option<String>,
/// <p>For a Lambda proxy integration, this is the URI of the Lambda function.</p>
#[serde(rename = "IntegrationUri")]
#[serde(skip_serializing_if = "Option::is_none")]
pub integration_uri: Option<String>,
/// <p>Specifies the pass-through behavior for incoming requests based on the
/// Content-Type header in the request, and the available mapping
/// templates specified as the requestTemplates property on the
/// Integration resource. There are three valid values:
/// WHEN_NO_MATCH, WHEN_NO_TEMPLATES, and
/// NEVER.</p><p>
/// WHEN_NO_MATCH passes the request body for unmapped content types through
/// to the integration backend without transformation.</p><p>
/// NEVER rejects unmapped content types with an HTTP 415 Unsupported
/// Media Type response.</p><p>
/// WHEN_NO_TEMPLATES allows pass-through when the integration has no
/// content types mapped to templates. However, if there is at least one content type
/// defined, unmapped content types will be rejected with the same HTTP 415
/// Unsupported Media Type response.</p>
#[serde(rename = "PassthroughBehavior")]
#[serde(skip_serializing_if = "Option::is_none")]
pub passthrough_behavior: Option<String>,
/// <p>A key-value map specifying request parameters that are passed from the method
/// request to the backend. The key is an integration request parameter name and the
/// associated value is a method request parameter value or static value that must be
/// enclosed within single quotes and pre-encoded as required by the backend. The method
/// request parameter value must match the pattern of
/// method.request.{location}.{name}
/// , where
/// {location}
/// is querystring, path, or header; and
/// {name}
/// must be a valid and unique method request parameter name.</p>
#[serde(rename = "RequestParameters")]
#[serde(skip_serializing_if = "Option::is_none")]
pub request_parameters: Option<::std::collections::HashMap<String, String>>,
/// <p>Represents a map of Velocity templates that are applied on the request payload
/// based on the value of the Content-Type header sent by the client. The content type
/// value is the key in this map, and the template (as a String) is the value.</p>
#[serde(rename = "RequestTemplates")]
#[serde(skip_serializing_if = "Option::is_none")]
pub request_templates: Option<::std::collections::HashMap<String, String>>,
/// <p>The template selection expression for the integration.</p>
#[serde(rename = "TemplateSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub template_selection_expression: Option<String>,
/// <p>Custom timeout between 50 and 29,000 milliseconds. The default value is 29,000
/// milliseconds or 29 seconds.</p>
#[serde(rename = "TimeoutInMillis")]
#[serde(skip_serializing_if = "Option::is_none")]
pub timeout_in_millis: Option<i64>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct GetIntegrationResponseRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The integration ID.</p>
#[serde(rename = "IntegrationId")]
pub integration_id: String,
/// <p>The integration response ID.</p>
#[serde(rename = "IntegrationResponseId")]
pub integration_response_id: String,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct GetIntegrationResponseResponse {
/// <p>Specifies how to handle response payload content type conversions. Supported
/// values are CONVERT_TO_BINARY and CONVERT_TO_TEXT, with the
/// following behaviors:</p><p>
/// CONVERT_TO_BINARY: Converts a response payload from a Base64-encoded
/// string to the corresponding binary blob.</p><p>
/// CONVERT_TO_TEXT: Converts a response payload from a binary blob to a
/// Base64-encoded string.</p><p>If this property is not defined, the response payload will be passed through from
/// the integration response to the route response or method response without
/// modification.</p>
#[serde(rename = "ContentHandlingStrategy")]
#[serde(skip_serializing_if = "Option::is_none")]
pub content_handling_strategy: Option<String>,
/// <p>The integration response ID.</p>
#[serde(rename = "IntegrationResponseId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub integration_response_id: Option<String>,
/// <p>The integration response key.</p>
#[serde(rename = "IntegrationResponseKey")]
#[serde(skip_serializing_if = "Option::is_none")]
pub integration_response_key: Option<String>,
/// <p>A key-value map specifying response parameters that are passed to the method
/// response from the backend. The key is a method response header parameter name and the
/// mapped value is an integration response header value, a static value enclosed within
/// a pair of single quotes, or a JSON expression from the integration response body. The
/// mapping key must match the pattern of method.response.header.{name}, where name is a
/// valid and unique header name. The mapped non-static value must match the pattern of
/// integration.response.header.{name} or integration.response.body.{JSON-expression},
/// where name is a valid and unique response header name and JSON-expression is a valid
/// JSON expression without the $ prefix.</p>
#[serde(rename = "ResponseParameters")]
#[serde(skip_serializing_if = "Option::is_none")]
pub response_parameters: Option<::std::collections::HashMap<String, String>>,
/// <p>The collection of response templates for the integration response as a
/// string-to-string map of key-value pairs. Response templates are represented as a
/// key/value map, with a content-type as the key and a template as the value.</p>
#[serde(rename = "ResponseTemplates")]
#[serde(skip_serializing_if = "Option::is_none")]
pub response_templates: Option<::std::collections::HashMap<String, String>>,
/// <p>The template selection expressions for the integration response.</p>
#[serde(rename = "TemplateSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub template_selection_expression: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct GetIntegrationResponsesRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The integration ID.</p>
#[serde(rename = "IntegrationId")]
pub integration_id: String,
/// <p>The maximum number of elements to be returned for this resource.</p>
#[serde(rename = "MaxResults")]
#[serde(skip_serializing_if = "Option::is_none")]
pub max_results: Option<String>,
/// <p>The next page of elements from this collection. Not valid for the last element of
/// the collection.</p>
#[serde(rename = "NextToken")]
#[serde(skip_serializing_if = "Option::is_none")]
pub next_token: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct GetIntegrationResponsesResponse {
/// <p>The elements from this collection.</p>
#[serde(rename = "Items")]
#[serde(skip_serializing_if = "Option::is_none")]
pub items: Option<Vec<IntegrationResponse>>,
/// <p>The next page of elements from this collection. Not valid for the last element of
/// the collection.</p>
#[serde(rename = "NextToken")]
#[serde(skip_serializing_if = "Option::is_none")]
pub next_token: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct GetIntegrationsRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The maximum number of elements to be returned for this resource.</p>
#[serde(rename = "MaxResults")]
#[serde(skip_serializing_if = "Option::is_none")]
pub max_results: Option<String>,
/// <p>The next page of elements from this collection. Not valid for the last element of
/// the collection.</p>
#[serde(rename = "NextToken")]
#[serde(skip_serializing_if = "Option::is_none")]
pub next_token: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct GetIntegrationsResponse {
/// <p>The elements from this collection.</p>
#[serde(rename = "Items")]
#[serde(skip_serializing_if = "Option::is_none")]
pub items: Option<Vec<Integration>>,
/// <p>The next page of elements from this collection. Not valid for the last element of
/// the collection.</p>
#[serde(rename = "NextToken")]
#[serde(skip_serializing_if = "Option::is_none")]
pub next_token: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct GetModelRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The model ID.</p>
#[serde(rename = "ModelId")]
pub model_id: String,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct GetModelResponse {
/// <p>The content-type for the model, for example, "application/json".</p>
#[serde(rename = "ContentType")]
#[serde(skip_serializing_if = "Option::is_none")]
pub content_type: Option<String>,
/// <p>The description of the model.</p>
#[serde(rename = "Description")]
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// <p>The model identifier.</p>
#[serde(rename = "ModelId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub model_id: Option<String>,
/// <p>The name of the model. Must be alphanumeric.</p>
#[serde(rename = "Name")]
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// <p>The schema for the model. For application/json models, this should be JSON schema
/// draft 4 model.</p>
#[serde(rename = "Schema")]
#[serde(skip_serializing_if = "Option::is_none")]
pub schema: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct GetModelTemplateRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The model ID.</p>
#[serde(rename = "ModelId")]
pub model_id: String,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct GetModelTemplateResponse {
/// <p>The template value.</p>
#[serde(rename = "Value")]
#[serde(skip_serializing_if = "Option::is_none")]
pub value: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct GetModelsRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The maximum number of elements to be returned for this resource.</p>
#[serde(rename = "MaxResults")]
#[serde(skip_serializing_if = "Option::is_none")]
pub max_results: Option<String>,
/// <p>The next page of elements from this collection. Not valid for the last element of
/// the collection.</p>
#[serde(rename = "NextToken")]
#[serde(skip_serializing_if = "Option::is_none")]
pub next_token: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct GetModelsResponse {
/// <p>The elements from this collection.</p>
#[serde(rename = "Items")]
#[serde(skip_serializing_if = "Option::is_none")]
pub items: Option<Vec<Model>>,
/// <p>The next page of elements from this collection. Not valid for the last element of
/// the collection.</p>
#[serde(rename = "NextToken")]
#[serde(skip_serializing_if = "Option::is_none")]
pub next_token: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct GetRouteRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The route ID.</p>
#[serde(rename = "RouteId")]
pub route_id: String,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct GetRouteResponse {
/// <p>Specifies whether an API key is required for this route.</p>
#[serde(rename = "ApiKeyRequired")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_key_required: Option<bool>,
/// <p>A list of authorization scopes configured on a route. The scopes are used with a
/// COGNITO_USER_POOLS authorizer to authorize the method invocation. The authorization
/// works by matching the route scopes against the scopes parsed from the access token in
/// the incoming request. The method invocation is authorized if any route scope matches
/// a claimed scope in the access token. Otherwise, the invocation is not authorized.
/// When the route scope is configured, the client must provide an access token instead
/// of an identity token for authorization purposes.</p>
#[serde(rename = "AuthorizationScopes")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorization_scopes: Option<Vec<String>>,
/// <p>The authorization type for the route. Valid values are NONE for open
/// access, AWS_IAM for using AWS IAM permissions, and CUSTOM
/// for using a Lambda
/// authorizer</p>
#[serde(rename = "AuthorizationType")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorization_type: Option<String>,
/// <p>The identifier of the Authorizer resource to be associated with this
/// route, if the authorizationType is CUSTOM
/// . The authorizer identifier is generated by API Gateway
/// when you created the authorizer.</p>
#[serde(rename = "AuthorizerId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorizer_id: Option<String>,
/// <p>The model selection expression for the route.</p>
#[serde(rename = "ModelSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub model_selection_expression: Option<String>,
/// <p>The operation name for the route.</p>
#[serde(rename = "OperationName")]
#[serde(skip_serializing_if = "Option::is_none")]
pub operation_name: Option<String>,
/// <p>The request models for the route.</p>
#[serde(rename = "RequestModels")]
#[serde(skip_serializing_if = "Option::is_none")]
pub request_models: Option<::std::collections::HashMap<String, String>>,
/// <p>The request parameters for the route.</p>
#[serde(rename = "RequestParameters")]
#[serde(skip_serializing_if = "Option::is_none")]
pub request_parameters: Option<::std::collections::HashMap<String, ParameterConstraints>>,
/// <p>The route ID.</p>
#[serde(rename = "RouteId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub route_id: Option<String>,
/// <p>The route key for the route.</p>
#[serde(rename = "RouteKey")]
#[serde(skip_serializing_if = "Option::is_none")]
pub route_key: Option<String>,
/// <p>The route response selection expression for the route.</p>
#[serde(rename = "RouteResponseSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub route_response_selection_expression: Option<String>,
/// <p>The target for the route.</p>
#[serde(rename = "Target")]
#[serde(skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct GetRouteResponseRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The route ID.</p>
#[serde(rename = "RouteId")]
pub route_id: String,
/// <p>The route response ID.</p>
#[serde(rename = "RouteResponseId")]
pub route_response_id: String,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct GetRouteResponseResponse {
/// <p>Represents the model selection expression of a route response.</p>
#[serde(rename = "ModelSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub model_selection_expression: Option<String>,
/// <p>Represents the response models of a route response.</p>
#[serde(rename = "ResponseModels")]
#[serde(skip_serializing_if = "Option::is_none")]
pub response_models: Option<::std::collections::HashMap<String, String>>,
/// <p>Represents the response parameters of a route response.</p>
#[serde(rename = "ResponseParameters")]
#[serde(skip_serializing_if = "Option::is_none")]
pub response_parameters: Option<::std::collections::HashMap<String, ParameterConstraints>>,
/// <p>Represents the identifier of a route response.</p>
#[serde(rename = "RouteResponseId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub route_response_id: Option<String>,
/// <p>Represents the route response key of a route response.</p>
#[serde(rename = "RouteResponseKey")]
#[serde(skip_serializing_if = "Option::is_none")]
pub route_response_key: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct GetRouteResponsesRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The maximum number of elements to be returned for this resource.</p>
#[serde(rename = "MaxResults")]
#[serde(skip_serializing_if = "Option::is_none")]
pub max_results: Option<String>,
/// <p>The next page of elements from this collection. Not valid for the last element of
/// the collection.</p>
#[serde(rename = "NextToken")]
#[serde(skip_serializing_if = "Option::is_none")]
pub next_token: Option<String>,
/// <p>The route ID.</p>
#[serde(rename = "RouteId")]
pub route_id: String,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct GetRouteResponsesResponse {
/// <p>The elements from this collection.</p>
#[serde(rename = "Items")]
#[serde(skip_serializing_if = "Option::is_none")]
pub items: Option<Vec<RouteResponse>>,
/// <p>The next page of elements from this collection. Not valid for the last element of
/// the collection.</p>
#[serde(rename = "NextToken")]
#[serde(skip_serializing_if = "Option::is_none")]
pub next_token: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct GetRoutesRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The maximum number of elements to be returned for this resource.</p>
#[serde(rename = "MaxResults")]
#[serde(skip_serializing_if = "Option::is_none")]
pub max_results: Option<String>,
/// <p>The next page of elements from this collection. Not valid for the last element of
/// the collection.</p>
#[serde(rename = "NextToken")]
#[serde(skip_serializing_if = "Option::is_none")]
pub next_token: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct GetRoutesResponse {
/// <p>The elements from this collection.</p>
#[serde(rename = "Items")]
#[serde(skip_serializing_if = "Option::is_none")]
pub items: Option<Vec<Route>>,
/// <p>The next page of elements from this collection. Not valid for the last element of
/// the collection.</p>
#[serde(rename = "NextToken")]
#[serde(skip_serializing_if = "Option::is_none")]
pub next_token: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct GetStageRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The stage name.</p>
#[serde(rename = "StageName")]
pub stage_name: String,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct GetStageResponse {
/// <p>Settings for logging access in this stage.</p>
#[serde(rename = "AccessLogSettings")]
#[serde(skip_serializing_if = "Option::is_none")]
pub access_log_settings: Option<AccessLogSettings>,
/// <p>The identifier of a client certificate for a Stage.</p>
#[serde(rename = "ClientCertificateId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub client_certificate_id: Option<String>,
/// <p>The timestamp when the stage was created.</p>
#[serde(rename = "CreatedDate")]
#[serde(skip_serializing_if = "Option::is_none")]
pub created_date: Option<f64>,
/// <p>Default route settings for the stage.</p>
#[serde(rename = "DefaultRouteSettings")]
#[serde(skip_serializing_if = "Option::is_none")]
pub default_route_settings: Option<RouteSettings>,
/// <p>The identifier of the Deployment that the Stage is
/// associated with.</p>
#[serde(rename = "DeploymentId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub deployment_id: Option<String>,
/// <p>The description of the stage.</p>
#[serde(rename = "Description")]
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// <p>The timestamp when the stage was last updated.</p>
#[serde(rename = "LastUpdatedDate")]
#[serde(skip_serializing_if = "Option::is_none")]
pub last_updated_date: Option<f64>,
/// <p>Route settings for the stage.</p>
#[serde(rename = "RouteSettings")]
#[serde(skip_serializing_if = "Option::is_none")]
pub route_settings: Option<::std::collections::HashMap<String, RouteSettings>>,
/// <p>The name of the stage.</p>
#[serde(rename = "StageName")]
#[serde(skip_serializing_if = "Option::is_none")]
pub stage_name: Option<String>,
/// <p>A map that defines the stage variables for a stage resource. Variable names can
/// have alphanumeric and underscore characters, and the values must match
/// [A-Za-z0-9-._~:/?#&=,]+.</p>
#[serde(rename = "StageVariables")]
#[serde(skip_serializing_if = "Option::is_none")]
pub stage_variables: Option<::std::collections::HashMap<String, String>>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct GetStagesRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The maximum number of elements to be returned for this resource.</p>
#[serde(rename = "MaxResults")]
#[serde(skip_serializing_if = "Option::is_none")]
pub max_results: Option<String>,
/// <p>The next page of elements from this collection. Not valid for the last element of
/// the collection.</p>
#[serde(rename = "NextToken")]
#[serde(skip_serializing_if = "Option::is_none")]
pub next_token: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct GetStagesResponse {
/// <p>The elements from this collection.</p>
#[serde(rename = "Items")]
#[serde(skip_serializing_if = "Option::is_none")]
pub items: Option<Vec<Stage>>,
/// <p>The next page of elements from this collection. Not valid for the last element of
/// the collection.</p>
#[serde(rename = "NextToken")]
#[serde(skip_serializing_if = "Option::is_none")]
pub next_token: Option<String>,
}
/// <p>Represents an integration.</p>
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct Integration {
/// <p>The connection ID.</p>
#[serde(rename = "ConnectionId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub connection_id: Option<String>,
/// <p>The type of the network connection to the integration endpoint. Currently the only
/// valid value is INTERNET, for connections through the public routable
/// internet.</p>
#[serde(rename = "ConnectionType")]
#[serde(skip_serializing_if = "Option::is_none")]
pub connection_type: Option<String>,
/// <p>Specifies how to handle response payload content type conversions. Supported
/// values are CONVERT_TO_BINARY and CONVERT_TO_TEXT, with the
/// following behaviors:</p><p>
/// CONVERT_TO_BINARY: Converts a response payload from a Base64-encoded
/// string to the corresponding binary blob.</p><p>
/// CONVERT_TO_TEXT: Converts a response payload from a binary blob to a
/// Base64-encoded string.</p><p>If this property is not defined, the response payload will be passed through from
/// the integration response to the route response or method response without
/// modification.</p>
#[serde(rename = "ContentHandlingStrategy")]
#[serde(skip_serializing_if = "Option::is_none")]
pub content_handling_strategy: Option<String>,
/// <p>Specifies the credentials required for the integration, if any. For AWS
/// integrations, three options are available. To specify an IAM Role for API Gateway to
/// assume, use the role's Amazon Resource Name (ARN). To require that the caller's
/// identity be passed through from the request, specify the string
/// arn:aws:iam::*:user/*. To use resource-based permissions on supported
/// AWS services, specify null.</p>
#[serde(rename = "CredentialsArn")]
#[serde(skip_serializing_if = "Option::is_none")]
pub credentials_arn: Option<String>,
/// <p>Represents the description of an integration.</p>
#[serde(rename = "Description")]
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// <p>Represents the identifier of an integration.</p>
#[serde(rename = "IntegrationId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub integration_id: Option<String>,
/// <p>Specifies the integration's HTTP method type.</p>
#[serde(rename = "IntegrationMethod")]
#[serde(skip_serializing_if = "Option::is_none")]
pub integration_method: Option<String>,
/// <p>The integration response selection expression for the integration. See <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-integration-response-selection-expressions">Integration Response Selection Expressions</a>.</p>
#[serde(rename = "IntegrationResponseSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub integration_response_selection_expression: Option<String>,
/// <p>The integration type of an integration. One of the following:</p><p>
/// AWS: for integrating the route or method request with an AWS service
/// action, including the Lambda function-invoking action. With the Lambda
/// function-invoking action, this is referred to as the Lambda custom integration. With
/// any other AWS service action, this is known as AWS integration.</p><p>
/// AWS_PROXY: for integrating the route or method request with the Lambda
/// function-invoking action with the client request passed through as-is. This
/// integration is also referred to as Lambda proxy integration.</p><p>
/// HTTP: for integrating the route or method request with an HTTP
/// endpoint. This
/// integration is also referred to as the HTTP custom integration.</p><p>
/// HTTP_PROXY: for integrating route or method request with an HTTP
/// endpoint, with the client
/// request passed through as-is. This is also referred to as HTTP proxy
/// integration.</p><p>
/// MOCK: for integrating the route or method request with API Gateway as a
/// "loopback" endpoint without invoking any backend.</p>
#[serde(rename = "IntegrationType")]
#[serde(skip_serializing_if = "Option::is_none")]
pub integration_type: Option<String>,
/// <p>For a Lambda proxy integration, this is the URI of the Lambda function.</p>
#[serde(rename = "IntegrationUri")]
#[serde(skip_serializing_if = "Option::is_none")]
pub integration_uri: Option<String>,
/// <p>Specifies the pass-through behavior for incoming requests based on the
/// Content-Type header in the request, and the available mapping
/// templates specified as the requestTemplates property on the
/// Integration resource. There are three valid values:
/// WHEN_NO_MATCH, WHEN_NO_TEMPLATES, and
/// NEVER.</p><p>
/// WHEN_NO_MATCH passes the request body for unmapped content types through
/// to the integration backend without transformation.</p><p>
/// NEVER rejects unmapped content types with an HTTP 415 Unsupported
/// Media Type response.</p><p>
/// WHEN_NO_TEMPLATES allows pass-through when the integration has no
/// content types mapped to templates. However, if there is at least one content type
/// defined, unmapped content types will be rejected with the same HTTP 415
/// Unsupported Media Type response.</p>
#[serde(rename = "PassthroughBehavior")]
#[serde(skip_serializing_if = "Option::is_none")]
pub passthrough_behavior: Option<String>,
/// <p>A key-value map specifying request parameters that are passed from the method
/// request to the backend. The key is an integration request parameter name and the
/// associated value is a method request parameter value or static value that must be
/// enclosed within single quotes and pre-encoded as required by the backend. The method
/// request parameter value must match the pattern of
/// method.request.{location}.{name}
/// , where
/// {location}
/// is querystring, path, or header; and
/// {name}
/// must be a valid and unique method request parameter name.</p>
#[serde(rename = "RequestParameters")]
#[serde(skip_serializing_if = "Option::is_none")]
pub request_parameters: Option<::std::collections::HashMap<String, String>>,
/// <p>Represents a map of Velocity templates that are applied on the request payload
/// based on the value of the Content-Type header sent by the client. The content type
/// value is the key in this map, and the template (as a String) is the value.</p>
#[serde(rename = "RequestTemplates")]
#[serde(skip_serializing_if = "Option::is_none")]
pub request_templates: Option<::std::collections::HashMap<String, String>>,
/// <p>The template selection expression for the integration.</p>
#[serde(rename = "TemplateSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub template_selection_expression: Option<String>,
/// <p>Custom timeout between 50 and 29,000 milliseconds. The default value is 29,000
/// milliseconds or 29 seconds.</p>
#[serde(rename = "TimeoutInMillis")]
#[serde(skip_serializing_if = "Option::is_none")]
pub timeout_in_millis: Option<i64>,
}
/// <p>Represents an integration response.</p>
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct IntegrationResponse {
/// <p>Specifies how to handle response payload content type conversions. Supported
/// values are CONVERT_TO_BINARY and CONVERT_TO_TEXT, with the
/// following behaviors:</p><p>
/// CONVERT_TO_BINARY: Converts a response payload from a Base64-encoded
/// string to the corresponding binary blob.</p><p>
/// CONVERT_TO_TEXT: Converts a response payload from a binary blob to a
/// Base64-encoded string.</p><p>If this property is not defined, the response payload will be passed through from
/// the integration response to the route response or method response without
/// modification.</p>
#[serde(rename = "ContentHandlingStrategy")]
#[serde(skip_serializing_if = "Option::is_none")]
pub content_handling_strategy: Option<String>,
/// <p>The integration response ID.</p>
#[serde(rename = "IntegrationResponseId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub integration_response_id: Option<String>,
/// <p>The integration response key.</p>
#[serde(rename = "IntegrationResponseKey")]
pub integration_response_key: String,
/// <p>A key-value map specifying response parameters that are passed to the method
/// response from the backend. The key is a method response header parameter name and the
/// mapped value is an integration response header value, a static value enclosed within
/// a pair of single quotes, or a JSON expression from the integration response body. The
/// mapping key must match the pattern of method.response.header.{name}, where name is a
/// valid and unique header name. The mapped non-static value must match the pattern of
/// integration.response.header.{name} or integration.response.body.{JSON-expression},
/// where name is a valid and unique response header name and JSON-expression is a valid
/// JSON expression without the $ prefix.</p>
#[serde(rename = "ResponseParameters")]
#[serde(skip_serializing_if = "Option::is_none")]
pub response_parameters: Option<::std::collections::HashMap<String, String>>,
/// <p>The collection of response templates for the integration response as a
/// string-to-string map of key-value pairs. Response templates are represented as a
/// key/value map, with a content-type as the key and a template as the value.</p>
#[serde(rename = "ResponseTemplates")]
#[serde(skip_serializing_if = "Option::is_none")]
pub response_templates: Option<::std::collections::HashMap<String, String>>,
/// <p>The template selection expressions for the integration response.</p>
#[serde(rename = "TemplateSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub template_selection_expression: Option<String>,
}
/// <p>Represents a data model for an API. See <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/models-mappings.html">Create Models and Mapping Templates for Request and Response
/// Mappings</a>.</p>
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct Model {
/// <p>The content-type for the model, for example, "application/json".</p>
#[serde(rename = "ContentType")]
#[serde(skip_serializing_if = "Option::is_none")]
pub content_type: Option<String>,
/// <p>The description of the model.</p>
#[serde(rename = "Description")]
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// <p>The model identifier.</p>
#[serde(rename = "ModelId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub model_id: Option<String>,
/// <p>The name of the model. Must be alphanumeric.</p>
#[serde(rename = "Name")]
pub name: String,
/// <p>The schema for the model. For application/json models, this should be JSON schema
/// draft 4 model.</p>
#[serde(rename = "Schema")]
#[serde(skip_serializing_if = "Option::is_none")]
pub schema: Option<String>,
}
/// <p>Validation constraints imposed on parameters of a request (path, query string,
/// headers).</p>
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ParameterConstraints {
/// <p>Whether or not the parameter is required.</p>
#[serde(rename = "Required")]
#[serde(skip_serializing_if = "Option::is_none")]
pub required: Option<bool>,
}
/// <p>Represents a route.</p>
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct Route {
/// <p>Specifies whether an API key is required for this route.</p>
#[serde(rename = "ApiKeyRequired")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_key_required: Option<bool>,
/// <p>A list of authorization scopes configured on a route. The scopes are used with a
/// COGNITO_USER_POOLS authorizer to authorize the method invocation. The authorization
/// works by matching the route scopes against the scopes parsed from the access token in
/// the incoming request. The method invocation is authorized if any route scope matches
/// a claimed scope in the access token. Otherwise, the invocation is not authorized.
/// When the route scope is configured, the client must provide an access token instead
/// of an identity token for authorization purposes.</p>
#[serde(rename = "AuthorizationScopes")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorization_scopes: Option<Vec<String>>,
/// <p>The authorization type for the route. Valid values are NONE for open
/// access, AWS_IAM for using AWS IAM permissions, and CUSTOM
/// for using a Lambda
/// authorizer</p>
#[serde(rename = "AuthorizationType")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorization_type: Option<String>,
/// <p>The identifier of the Authorizer resource to be associated with this
/// route, if the authorizationType is CUSTOM
/// . The authorizer identifier is generated by API Gateway
/// when you created the authorizer.</p>
#[serde(rename = "AuthorizerId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorizer_id: Option<String>,
/// <p>The model selection expression for the route.</p>
#[serde(rename = "ModelSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub model_selection_expression: Option<String>,
/// <p>The operation name for the route.</p>
#[serde(rename = "OperationName")]
#[serde(skip_serializing_if = "Option::is_none")]
pub operation_name: Option<String>,
/// <p>The request models for the route.</p>
#[serde(rename = "RequestModels")]
#[serde(skip_serializing_if = "Option::is_none")]
pub request_models: Option<::std::collections::HashMap<String, String>>,
/// <p>The request parameters for the route.</p>
#[serde(rename = "RequestParameters")]
#[serde(skip_serializing_if = "Option::is_none")]
pub request_parameters: Option<::std::collections::HashMap<String, ParameterConstraints>>,
/// <p>The route ID.</p>
#[serde(rename = "RouteId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub route_id: Option<String>,
/// <p>The route key for the route.</p>
#[serde(rename = "RouteKey")]
pub route_key: String,
/// <p>The route response selection expression for the route.</p>
#[serde(rename = "RouteResponseSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub route_response_selection_expression: Option<String>,
/// <p>The target for the route.</p>
#[serde(rename = "Target")]
#[serde(skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
}
/// <p>Represents a route response.</p>
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct RouteResponse {
/// <p>Represents the model selection expression of a route response.</p>
#[serde(rename = "ModelSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub model_selection_expression: Option<String>,
/// <p>Represents the response models of a route response.</p>
#[serde(rename = "ResponseModels")]
#[serde(skip_serializing_if = "Option::is_none")]
pub response_models: Option<::std::collections::HashMap<String, String>>,
/// <p>Represents the response parameters of a route response.</p>
#[serde(rename = "ResponseParameters")]
#[serde(skip_serializing_if = "Option::is_none")]
pub response_parameters: Option<::std::collections::HashMap<String, ParameterConstraints>>,
/// <p>Represents the identifier of a route response.</p>
#[serde(rename = "RouteResponseId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub route_response_id: Option<String>,
/// <p>Represents the route response key of a route response.</p>
#[serde(rename = "RouteResponseKey")]
pub route_response_key: String,
}
/// <p>Represents a collection of route settings.</p>
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RouteSettings {
/// <p>Specifies whether (true) or not (false) data trace
/// logging is enabled for this route. This property affects the log entries pushed to
/// Amazon CloudWatch Logs.</p>
#[serde(rename = "DataTraceEnabled")]
#[serde(skip_serializing_if = "Option::is_none")]
pub data_trace_enabled: Option<bool>,
/// <p>Specifies whether detailed metrics are enabled.</p>
#[serde(rename = "DetailedMetricsEnabled")]
#[serde(skip_serializing_if = "Option::is_none")]
pub detailed_metrics_enabled: Option<bool>,
/// <p>Specifies the logging level for this route: DEBUG, INFO,
/// or WARN. This property affects the log entries pushed to Amazon
/// CloudWatch Logs.</p>
#[serde(rename = "LoggingLevel")]
#[serde(skip_serializing_if = "Option::is_none")]
pub logging_level: Option<String>,
/// <p>Specifies the throttling burst limit.</p>
#[serde(rename = "ThrottlingBurstLimit")]
#[serde(skip_serializing_if = "Option::is_none")]
pub throttling_burst_limit: Option<i64>,
/// <p>Specifies the throttling rate limit.</p>
#[serde(rename = "ThrottlingRateLimit")]
#[serde(skip_serializing_if = "Option::is_none")]
pub throttling_rate_limit: Option<f64>,
}
/// <p>Represents an API stage.</p>
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct Stage {
/// <p>Settings for logging access in this stage.</p>
#[serde(rename = "AccessLogSettings")]
#[serde(skip_serializing_if = "Option::is_none")]
pub access_log_settings: Option<AccessLogSettings>,
/// <p>The identifier of a client certificate for a Stage.</p>
#[serde(rename = "ClientCertificateId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub client_certificate_id: Option<String>,
/// <p>The timestamp when the stage was created.</p>
#[serde(rename = "CreatedDate")]
#[serde(skip_serializing_if = "Option::is_none")]
pub created_date: Option<f64>,
/// <p>Default route settings for the stage.</p>
#[serde(rename = "DefaultRouteSettings")]
#[serde(skip_serializing_if = "Option::is_none")]
pub default_route_settings: Option<RouteSettings>,
/// <p>The identifier of the Deployment that the Stage is
/// associated with.</p>
#[serde(rename = "DeploymentId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub deployment_id: Option<String>,
/// <p>The description of the stage.</p>
#[serde(rename = "Description")]
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// <p>The timestamp when the stage was last updated.</p>
#[serde(rename = "LastUpdatedDate")]
#[serde(skip_serializing_if = "Option::is_none")]
pub last_updated_date: Option<f64>,
/// <p>Route settings for the stage.</p>
#[serde(rename = "RouteSettings")]
#[serde(skip_serializing_if = "Option::is_none")]
pub route_settings: Option<::std::collections::HashMap<String, RouteSettings>>,
/// <p>The name of the stage.</p>
#[serde(rename = "StageName")]
pub stage_name: String,
/// <p>A map that defines the stage variables for a stage resource. Variable names can
/// have alphanumeric and underscore characters, and the values must match
/// [A-Za-z0-9-._~:/?#&=,]+.</p>
#[serde(rename = "StageVariables")]
#[serde(skip_serializing_if = "Option::is_none")]
pub stage_variables: Option<::std::collections::HashMap<String, String>>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct UpdateApiMappingRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The API mapping identifier.</p>
#[serde(rename = "ApiMappingId")]
pub api_mapping_id: String,
/// <p>The API mapping key.</p>
#[serde(rename = "ApiMappingKey")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_mapping_key: Option<String>,
/// <p>The domain name.</p>
#[serde(rename = "DomainName")]
pub domain_name: String,
/// <p>The API stage.</p>
#[serde(rename = "Stage")]
#[serde(skip_serializing_if = "Option::is_none")]
pub stage: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct UpdateApiMappingResponse {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_id: Option<String>,
/// <p>The API mapping identifier.</p>
#[serde(rename = "ApiMappingId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_mapping_id: Option<String>,
/// <p>The API mapping key.</p>
#[serde(rename = "ApiMappingKey")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_mapping_key: Option<String>,
/// <p>The API stage.</p>
#[serde(rename = "Stage")]
#[serde(skip_serializing_if = "Option::is_none")]
pub stage: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct UpdateApiRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>An API key selection expression. See <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions">API Key Selection Expressions</a>.</p>
#[serde(rename = "ApiKeySelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_key_selection_expression: Option<String>,
/// <p>The description of the API.</p>
#[serde(rename = "Description")]
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// <p>Avoid validating models when creating a deployment.</p>
#[serde(rename = "DisableSchemaValidation")]
#[serde(skip_serializing_if = "Option::is_none")]
pub disable_schema_validation: Option<bool>,
/// <p>The name of the API.</p>
#[serde(rename = "Name")]
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// <p>The route selection expression for the API.</p>
#[serde(rename = "RouteSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub route_selection_expression: Option<String>,
/// <p>A version identifier for the API.</p>
#[serde(rename = "Version")]
#[serde(skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct UpdateApiResponse {
/// <p>The URI of the API, of the form {api-id}.execute-api.{region}.amazonaws.com. The
/// stage name is typically appended to this URI to form a complete path to a deployed
/// API stage.</p>
#[serde(rename = "ApiEndpoint")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_endpoint: Option<String>,
/// <p>The API ID.</p>
#[serde(rename = "ApiId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_id: Option<String>,
/// <p>An API key selection expression. See <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions">API Key Selection Expressions</a>.</p>
#[serde(rename = "ApiKeySelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_key_selection_expression: Option<String>,
/// <p>The timestamp when the API was created.</p>
#[serde(rename = "CreatedDate")]
#[serde(skip_serializing_if = "Option::is_none")]
pub created_date: Option<f64>,
/// <p>The description of the API.</p>
#[serde(rename = "Description")]
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// <p>Avoid validating models when creating a deployment.</p>
#[serde(rename = "DisableSchemaValidation")]
#[serde(skip_serializing_if = "Option::is_none")]
pub disable_schema_validation: Option<bool>,
/// <p>The name of the API.</p>
#[serde(rename = "Name")]
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// <p>The API protocol: Currently only WEBSOCKET is supported.</p>
#[serde(rename = "ProtocolType")]
#[serde(skip_serializing_if = "Option::is_none")]
pub protocol_type: Option<String>,
/// <p>The route selection expression for the API.</p>
#[serde(rename = "RouteSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub route_selection_expression: Option<String>,
/// <p>A version identifier for the API.</p>
#[serde(rename = "Version")]
#[serde(skip_serializing_if = "Option::is_none")]
pub version: Option<String>,
/// <p>The warning messages reported when failonwarnings is turned on during
/// API import.</p>
#[serde(rename = "Warnings")]
#[serde(skip_serializing_if = "Option::is_none")]
pub warnings: Option<Vec<String>>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct UpdateAuthorizerRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>Specifies the required credentials as an IAM role for API Gateway to invoke the
/// authorizer. To specify an IAM role for API Gateway to assume, use the role's Amazon
/// Resource Name (ARN). To use resource-based permissions on the Lambda function,
/// specify null.</p>
#[serde(rename = "AuthorizerCredentialsArn")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorizer_credentials_arn: Option<String>,
/// <p>The authorizer identifier.</p>
#[serde(rename = "AuthorizerId")]
pub authorizer_id: String,
/// <p>The time to live (TTL), in seconds, of cached authorizer results. If it is zero,
/// authorization caching is disabled. If it is greater than zero, API Gateway will cache
/// authorizer responses. If this field is not set, the default value is 300. The maximum
/// value is 3600, or 1 hour.</p>
#[serde(rename = "AuthorizerResultTtlInSeconds")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorizer_result_ttl_in_seconds: Option<i64>,
/// <p>The authorizer type. Currently the only valid value is REQUEST, for a
/// Lambda function using incoming request parameters.</p>
#[serde(rename = "AuthorizerType")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorizer_type: Option<String>,
/// <p>The authorizer's Uniform Resource Identifier (URI). For
/// REQUEST authorizers, this must be a
/// well-formed Lambda function URI, for example,
/// arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:{account_id}:function:{lambda_function_name}/invocations.
/// In general, the URI has this form:
/// arn:aws:apigateway:{region}:lambda:path/{service_api}
/// , where {region} is the same as the region hosting the Lambda
/// function, path indicates that the remaining substring in the URI should be treated as
/// the path to the resource, including the initial /. For Lambda functions,
/// this is usually of the form
/// /2015-03-31/functions/[FunctionARN]/invocations.</p>
#[serde(rename = "AuthorizerUri")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorizer_uri: Option<String>,
/// <p>The identity source for which authorization is requested.</p><p>For the REQUEST authorizer, this is required when authorization
/// caching is enabled. The value is a comma-separated string of one or more mapping
/// expressions of the specified request parameters. For example, if an Auth header, a
/// Name query string parameter are defined as identity sources, this value is
/// $method.request.header.Auth, $method.request.querystring.Name. These
/// parameters will be used to derive the authorization caching key and to perform
/// runtime validation of the REQUEST authorizer by verifying all of the
/// identity-related request parameters are present, not null and non-empty. Only when
/// this is true does the authorizer invoke the authorizer Lambda function, otherwise, it
/// returns a 401 Unauthorized response without calling the Lambda function.
/// The valid value is a string of comma-separated mapping expressions of the specified
/// request parameters. When the authorization caching is not enabled, this property is
/// optional.</p>
#[serde(rename = "IdentitySource")]
#[serde(skip_serializing_if = "Option::is_none")]
pub identity_source: Option<Vec<String>>,
/// <p>The
/// validation expression does not apply to the REQUEST authorizer.</p>
#[serde(rename = "IdentityValidationExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub identity_validation_expression: Option<String>,
/// <p>The name of the authorizer.</p>
#[serde(rename = "Name")]
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// <p>For
/// REQUEST authorizer, this is not
/// defined.</p>
#[serde(rename = "ProviderArns")]
#[serde(skip_serializing_if = "Option::is_none")]
pub provider_arns: Option<Vec<String>>,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct UpdateAuthorizerResponse {
/// <p>Specifies the required credentials as an IAM role for API Gateway to invoke the
/// authorizer. To specify an IAM role for API Gateway to assume, use the role's Amazon
/// Resource Name (ARN). To use resource-based permissions on the Lambda function,
/// specify null.</p>
#[serde(rename = "AuthorizerCredentialsArn")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorizer_credentials_arn: Option<String>,
/// <p>The authorizer identifier.</p>
#[serde(rename = "AuthorizerId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorizer_id: Option<String>,
/// <p>The time to live (TTL), in seconds, of cached authorizer results. If it equals 0,
/// authorization caching is disabled. If it is greater than 0, API Gateway will cache
/// authorizer responses. If this field is not set, the default value is 300. The maximum
/// value is 3600, or 1 hour.</p>
#[serde(rename = "AuthorizerResultTtlInSeconds")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorizer_result_ttl_in_seconds: Option<i64>,
/// <p>The authorizer type. Currently the only valid value is REQUEST, for a
/// Lambda function using incoming request parameters.</p>
#[serde(rename = "AuthorizerType")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorizer_type: Option<String>,
/// <p>The authorizer's Uniform Resource Identifier (URI).
/// ForREQUEST authorizers, this must be a
/// well-formed Lambda function URI, for example,
/// arn:aws:apigateway:us-west-2:lambda:path/2015-03-31/functions/arn:aws:lambda:us-west-2:{account_id}:function:{lambda_function_name}/invocations.
/// In general, the URI has this form:
/// arn:aws:apigateway:{region}:lambda:path/{service_api}
/// , where {region} is the same as the region hosting the Lambda
/// function, path indicates that the remaining substring in the URI should be treated as
/// the path to the resource, including the initial /. For Lambda functions,
/// this is usually of the form
/// /2015-03-31/functions/[FunctionARN]/invocations.</p>
#[serde(rename = "AuthorizerUri")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorizer_uri: Option<String>,
/// <p>The identity source for which authorization is requested.</p><p>For the REQUEST authorizer, this is required when authorization
/// caching is enabled. The value is a comma-separated string of one or more mapping
/// expressions of the specified request parameters. For example, if an Auth
/// header and a Name query string parameters are defined as identity
/// sources, this value is method.request.header.Auth,
/// method.request.querystring.Name. These parameters will be used to
/// derive the authorization caching key and to perform runtime validation of the
/// REQUEST authorizer by verifying all of the identity-related request
/// parameters are present, not null, and non-empty. Only when this is true does the
/// authorizer invoke the authorizer Lambda function, otherwise, it returns a 401
/// Unauthorized response without calling the Lambda function. The valid value
/// is a string of comma-separated mapping expressions of the specified request
/// parameters. When the authorization caching is not enabled, this property is
/// optional.</p>
#[serde(rename = "IdentitySource")]
#[serde(skip_serializing_if = "Option::is_none")]
pub identity_source: Option<Vec<String>>,
/// <p>The
/// validation expression does not apply to the REQUEST authorizer.</p>
#[serde(rename = "IdentityValidationExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub identity_validation_expression: Option<String>,
/// <p>The name of the authorizer.</p>
#[serde(rename = "Name")]
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// <p>For
/// REQUEST authorizer, this is not
/// defined.</p>
#[serde(rename = "ProviderArns")]
#[serde(skip_serializing_if = "Option::is_none")]
pub provider_arns: Option<Vec<String>>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct UpdateDeploymentRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The deployment ID.</p>
#[serde(rename = "DeploymentId")]
pub deployment_id: String,
/// <p>The description for the deployment resource.</p>
#[serde(rename = "Description")]
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct UpdateDeploymentResponse {
/// <p>The date and time when the Deployment resource was created.</p>
#[serde(rename = "CreatedDate")]
#[serde(skip_serializing_if = "Option::is_none")]
pub created_date: Option<f64>,
/// <p>The identifier for the deployment.</p>
#[serde(rename = "DeploymentId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub deployment_id: Option<String>,
/// <p>The status of the deployment: PENDING, FAILED, or
/// SUCCEEDED.</p>
#[serde(rename = "DeploymentStatus")]
#[serde(skip_serializing_if = "Option::is_none")]
pub deployment_status: Option<String>,
/// <p>May contain additional feedback on the status of an API deployment.</p>
#[serde(rename = "DeploymentStatusMessage")]
#[serde(skip_serializing_if = "Option::is_none")]
pub deployment_status_message: Option<String>,
/// <p>The description for the deployment.</p>
#[serde(rename = "Description")]
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct UpdateDomainNameRequest {
/// <p>The domain name.</p>
#[serde(rename = "DomainName")]
pub domain_name: String,
/// <p>The domain name configurations.</p>
#[serde(rename = "DomainNameConfigurations")]
#[serde(skip_serializing_if = "Option::is_none")]
pub domain_name_configurations: Option<Vec<DomainNameConfiguration>>,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct UpdateDomainNameResponse {
/// <p>The API mapping selection expression.</p>
#[serde(rename = "ApiMappingSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_mapping_selection_expression: Option<String>,
/// <p>The name of the DomainName resource.</p>
#[serde(rename = "DomainName")]
#[serde(skip_serializing_if = "Option::is_none")]
pub domain_name: Option<String>,
/// <p>The domain name configurations.</p>
#[serde(rename = "DomainNameConfigurations")]
#[serde(skip_serializing_if = "Option::is_none")]
pub domain_name_configurations: Option<Vec<DomainNameConfiguration>>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct UpdateIntegrationRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The connection ID.</p>
#[serde(rename = "ConnectionId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub connection_id: Option<String>,
/// <p>The type of the network connection to the integration endpoint. Currently the only
/// valid value is INTERNET, for connections through the public routable
/// internet.</p>
#[serde(rename = "ConnectionType")]
#[serde(skip_serializing_if = "Option::is_none")]
pub connection_type: Option<String>,
/// <p>Specifies how to handle response payload content type conversions. Supported
/// values are CONVERT_TO_BINARY and CONVERT_TO_TEXT, with the
/// following behaviors:</p><p>
/// CONVERT_TO_BINARY: Converts a response payload from a Base64-encoded
/// string to the corresponding binary blob.</p><p>
/// CONVERT_TO_TEXT: Converts a response payload from a binary blob to a
/// Base64-encoded string.</p><p>If this property is not defined, the response payload will be passed through from
/// the integration response to the route response or method response without
/// modification.</p>
#[serde(rename = "ContentHandlingStrategy")]
#[serde(skip_serializing_if = "Option::is_none")]
pub content_handling_strategy: Option<String>,
/// <p>Specifies the credentials required for the integration, if any. For AWS
/// integrations, three options are available. To specify an IAM Role for API Gateway to
/// assume, use the role's Amazon Resource Name (ARN). To require that the caller's
/// identity be passed through from the request, specify the string
/// arn:aws:iam::*:user/*. To use resource-based permissions on supported
/// AWS services, specify null.</p>
#[serde(rename = "CredentialsArn")]
#[serde(skip_serializing_if = "Option::is_none")]
pub credentials_arn: Option<String>,
/// <p>The description of the integration</p>
#[serde(rename = "Description")]
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// <p>The integration ID.</p>
#[serde(rename = "IntegrationId")]
pub integration_id: String,
/// <p>Specifies the integration's HTTP method type.</p>
#[serde(rename = "IntegrationMethod")]
#[serde(skip_serializing_if = "Option::is_none")]
pub integration_method: Option<String>,
/// <p>The integration type of an integration. One of the following:</p><p>
/// AWS: for integrating the route or method request with an AWS service
/// action, including the Lambda function-invoking action. With the Lambda
/// function-invoking action, this is referred to as the Lambda custom integration. With
/// any other AWS service action, this is known as AWS integration.</p><p>
/// AWS_PROXY: for integrating the route or method request with the Lambda
/// function-invoking action with the client request passed through as-is. This
/// integration is also referred to as Lambda proxy integration.</p><p>
/// HTTP: for integrating the route or method request with an HTTP
/// endpoint. This
/// integration is also referred to as the HTTP custom integration.</p><p>
/// HTTP_PROXY: for integrating route or method request with an HTTP
/// endpoint, with the client
/// request passed through as-is. This is also referred to as HTTP proxy
/// integration.</p><p>
/// MOCK: for integrating the route or method request with API Gateway as a
/// "loopback" endpoint without invoking any backend.</p>
#[serde(rename = "IntegrationType")]
#[serde(skip_serializing_if = "Option::is_none")]
pub integration_type: Option<String>,
/// <p>For a Lambda proxy integration, this is the URI of the Lambda function.</p>
#[serde(rename = "IntegrationUri")]
#[serde(skip_serializing_if = "Option::is_none")]
pub integration_uri: Option<String>,
/// <p>Specifies the pass-through behavior for incoming requests based on the
/// Content-Type header in the request, and the available mapping
/// templates specified as the requestTemplates property on the
/// Integration resource. There are three valid values:
/// WHEN_NO_MATCH, WHEN_NO_TEMPLATES, and
/// NEVER.</p><p>
/// WHEN_NO_MATCH passes the request body for unmapped content types through
/// to the integration backend without transformation.</p><p>
/// NEVER rejects unmapped content types with an HTTP 415 Unsupported
/// Media Type response.</p><p>
/// WHEN_NO_TEMPLATES allows pass-through when the integration has no
/// content types mapped to templates. However, if there is at least one content type
/// defined, unmapped content types will be rejected with the same HTTP 415
/// Unsupported Media Type response.</p>
#[serde(rename = "PassthroughBehavior")]
#[serde(skip_serializing_if = "Option::is_none")]
pub passthrough_behavior: Option<String>,
/// <p>A key-value map specifying request parameters that are passed from the method
/// request to the backend. The key is an integration request parameter name and the
/// associated value is a method request parameter value or static value that must be
/// enclosed within single quotes and pre-encoded as required by the backend. The method
/// request parameter value must match the pattern of
/// method.request.{location}.{name}
/// , where
/// {location}
/// is querystring, path, or header; and
/// {name}
/// must be a valid and unique method request parameter name.</p>
#[serde(rename = "RequestParameters")]
#[serde(skip_serializing_if = "Option::is_none")]
pub request_parameters: Option<::std::collections::HashMap<String, String>>,
/// <p>Represents a map of Velocity templates that are applied on the request payload
/// based on the value of the Content-Type header sent by the client. The content type
/// value is the key in this map, and the template (as a String) is the value.</p>
#[serde(rename = "RequestTemplates")]
#[serde(skip_serializing_if = "Option::is_none")]
pub request_templates: Option<::std::collections::HashMap<String, String>>,
/// <p>The template selection expression for the integration.</p>
#[serde(rename = "TemplateSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub template_selection_expression: Option<String>,
/// <p>Custom timeout between 50 and 29,000 milliseconds. The default value is 29,000
/// milliseconds or 29 seconds.</p>
#[serde(rename = "TimeoutInMillis")]
#[serde(skip_serializing_if = "Option::is_none")]
pub timeout_in_millis: Option<i64>,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct UpdateIntegrationResponse {
/// <p>The connection ID.</p>
#[serde(rename = "ConnectionId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub connection_id: Option<String>,
/// <p>The type of the network connection to the integration endpoint. Currently the only
/// valid value is INTERNET, for connections through the public routable
/// internet.</p>
#[serde(rename = "ConnectionType")]
#[serde(skip_serializing_if = "Option::is_none")]
pub connection_type: Option<String>,
/// <p>Specifies how to handle response payload content type conversions. Supported
/// values are CONVERT_TO_BINARY and CONVERT_TO_TEXT, with the
/// following behaviors:</p><p>
/// CONVERT_TO_BINARY: Converts a response payload from a Base64-encoded
/// string to the corresponding binary blob.</p><p>
/// CONVERT_TO_TEXT: Converts a response payload from a binary blob to a
/// Base64-encoded string.</p><p>If this property is not defined, the response payload will be passed through from
/// the integration response to the route response or method response without
/// modification.</p>
#[serde(rename = "ContentHandlingStrategy")]
#[serde(skip_serializing_if = "Option::is_none")]
pub content_handling_strategy: Option<String>,
/// <p>Specifies the credentials required for the integration, if any. For AWS
/// integrations, three options are available. To specify an IAM Role for API Gateway to
/// assume, use the role's Amazon Resource Name (ARN). To require that the caller's
/// identity be passed through from the request, specify the string
/// arn:aws:iam::*:user/*. To use resource-based permissions on supported
/// AWS services, specify null.</p>
#[serde(rename = "CredentialsArn")]
#[serde(skip_serializing_if = "Option::is_none")]
pub credentials_arn: Option<String>,
/// <p>Represents the description of an integration.</p>
#[serde(rename = "Description")]
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// <p>Represents the identifier of an integration.</p>
#[serde(rename = "IntegrationId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub integration_id: Option<String>,
/// <p>Specifies the integration's HTTP method type.</p>
#[serde(rename = "IntegrationMethod")]
#[serde(skip_serializing_if = "Option::is_none")]
pub integration_method: Option<String>,
/// <p>The integration response selection expression for the integration. See <a href="https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-integration-response-selection-expressions">Integration Response Selection Expressions</a>.</p>
#[serde(rename = "IntegrationResponseSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub integration_response_selection_expression: Option<String>,
/// <p>The integration type of an integration. One of the following:</p><p>
/// AWS: for integrating the route or method request with an AWS service
/// action, including the Lambda function-invoking action. With the Lambda
/// function-invoking action, this is referred to as the Lambda custom integration. With
/// any other AWS service action, this is known as AWS integration.</p><p>
/// AWS_PROXY: for integrating the route or method request with the Lambda
/// function-invoking action with the client request passed through as-is. This
/// integration is also referred to as Lambda proxy integration.</p><p>
/// HTTP: for integrating the route or method request with an HTTP
/// endpoint. This
/// integration is also referred to as the HTTP custom integration.</p><p>
/// HTTP_PROXY: for integrating route or method request with an HTTP
/// endpoint, with the client
/// request passed through as-is. This is also referred to as HTTP proxy
/// integration.</p><p>
/// MOCK: for integrating the route or method request with API Gateway as a
/// "loopback" endpoint without invoking any backend.</p>
#[serde(rename = "IntegrationType")]
#[serde(skip_serializing_if = "Option::is_none")]
pub integration_type: Option<String>,
/// <p>For a Lambda proxy integration, this is the URI of the Lambda function.</p>
#[serde(rename = "IntegrationUri")]
#[serde(skip_serializing_if = "Option::is_none")]
pub integration_uri: Option<String>,
/// <p>Specifies the pass-through behavior for incoming requests based on the
/// Content-Type header in the request, and the available mapping
/// templates specified as the requestTemplates property on the
/// Integration resource. There are three valid values:
/// WHEN_NO_MATCH, WHEN_NO_TEMPLATES, and
/// NEVER.</p><p>
/// WHEN_NO_MATCH passes the request body for unmapped content types through
/// to the integration backend without transformation.</p><p>
/// NEVER rejects unmapped content types with an HTTP 415 Unsupported
/// Media Type response.</p><p>
/// WHEN_NO_TEMPLATES allows pass-through when the integration has no
/// content types mapped to templates. However, if there is at least one content type
/// defined, unmapped content types will be rejected with the same HTTP 415
/// Unsupported Media Type response.</p>
#[serde(rename = "PassthroughBehavior")]
#[serde(skip_serializing_if = "Option::is_none")]
pub passthrough_behavior: Option<String>,
/// <p>A key-value map specifying request parameters that are passed from the method
/// request to the backend. The key is an integration request parameter name and the
/// associated value is a method request parameter value or static value that must be
/// enclosed within single quotes and pre-encoded as required by the backend. The method
/// request parameter value must match the pattern of
/// method.request.{location}.{name}
/// , where
/// {location}
/// is querystring, path, or header; and
/// {name}
/// must be a valid and unique method request parameter name.</p>
#[serde(rename = "RequestParameters")]
#[serde(skip_serializing_if = "Option::is_none")]
pub request_parameters: Option<::std::collections::HashMap<String, String>>,
/// <p>Represents a map of Velocity templates that are applied on the request payload
/// based on the value of the Content-Type header sent by the client. The content type
/// value is the key in this map, and the template (as a String) is the value.</p>
#[serde(rename = "RequestTemplates")]
#[serde(skip_serializing_if = "Option::is_none")]
pub request_templates: Option<::std::collections::HashMap<String, String>>,
/// <p>The template selection expression for the integration.</p>
#[serde(rename = "TemplateSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub template_selection_expression: Option<String>,
/// <p>Custom timeout between 50 and 29,000 milliseconds. The default value is 29,000
/// milliseconds or 29 seconds.</p>
#[serde(rename = "TimeoutInMillis")]
#[serde(skip_serializing_if = "Option::is_none")]
pub timeout_in_millis: Option<i64>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct UpdateIntegrationResponseRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>Specifies how to handle response payload content type conversions. Supported
/// values are CONVERT_TO_BINARY and CONVERT_TO_TEXT, with the
/// following behaviors:</p><p>
/// CONVERT_TO_BINARY: Converts a response payload from a Base64-encoded
/// string to the corresponding binary blob.</p><p>
/// CONVERT_TO_TEXT: Converts a response payload from a binary blob to a
/// Base64-encoded string.</p><p>If this property is not defined, the response payload will be passed through from
/// the integration response to the route response or method response without
/// modification.</p>
#[serde(rename = "ContentHandlingStrategy")]
#[serde(skip_serializing_if = "Option::is_none")]
pub content_handling_strategy: Option<String>,
/// <p>The integration ID.</p>
#[serde(rename = "IntegrationId")]
pub integration_id: String,
/// <p>The integration response ID.</p>
#[serde(rename = "IntegrationResponseId")]
pub integration_response_id: String,
/// <p>The integration response key.</p>
#[serde(rename = "IntegrationResponseKey")]
#[serde(skip_serializing_if = "Option::is_none")]
pub integration_response_key: Option<String>,
/// <p>A key-value map specifying response parameters that are passed to the method
/// response from the backend. The key is a method response header parameter name and the
/// mapped value is an integration response header value, a static value enclosed within
/// a pair of single quotes, or a JSON expression from the integration response body. The
/// mapping key must match the pattern of
/// method.response.header.{name}
/// , where name is a valid and unique header name. The mapped non-static value
/// must match the pattern of
/// integration.response.header.{name}
/// or
/// integration.response.body.{JSON-expression}
/// , where
/// {name}
/// is a valid and unique response header name and
/// {JSON-expression}
/// is a valid JSON expression without the $ prefix.</p>
#[serde(rename = "ResponseParameters")]
#[serde(skip_serializing_if = "Option::is_none")]
pub response_parameters: Option<::std::collections::HashMap<String, String>>,
/// <p>The collection of response templates for the integration response as a
/// string-to-string map of key-value pairs. Response templates are represented as a
/// key/value map, with a content-type as the key and a template as the value.</p>
#[serde(rename = "ResponseTemplates")]
#[serde(skip_serializing_if = "Option::is_none")]
pub response_templates: Option<::std::collections::HashMap<String, String>>,
/// <p>The template selection expression for the integration response.</p>
#[serde(rename = "TemplateSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub template_selection_expression: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct UpdateIntegrationResponseResponse {
/// <p>Specifies how to handle response payload content type conversions. Supported
/// values are CONVERT_TO_BINARY and CONVERT_TO_TEXT, with the
/// following behaviors:</p><p>
/// CONVERT_TO_BINARY: Converts a response payload from a Base64-encoded
/// string to the corresponding binary blob.</p><p>
/// CONVERT_TO_TEXT: Converts a response payload from a binary blob to a
/// Base64-encoded string.</p><p>If this property is not defined, the response payload will be passed through from
/// the integration response to the route response or method response without
/// modification.</p>
#[serde(rename = "ContentHandlingStrategy")]
#[serde(skip_serializing_if = "Option::is_none")]
pub content_handling_strategy: Option<String>,
/// <p>The integration response ID.</p>
#[serde(rename = "IntegrationResponseId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub integration_response_id: Option<String>,
/// <p>The integration response key.</p>
#[serde(rename = "IntegrationResponseKey")]
#[serde(skip_serializing_if = "Option::is_none")]
pub integration_response_key: Option<String>,
/// <p>A key-value map specifying response parameters that are passed to the method
/// response from the backend. The key is a method response header parameter name and the
/// mapped value is an integration response header value, a static value enclosed within
/// a pair of single quotes, or a JSON expression from the integration response body. The
/// mapping key must match the pattern of method.response.header.{name}, where name is a
/// valid and unique header name. The mapped non-static value must match the pattern of
/// integration.response.header.{name} or integration.response.body.{JSON-expression},
/// where name is a valid and unique response header name and JSON-expression is a valid
/// JSON expression without the $ prefix.</p>
#[serde(rename = "ResponseParameters")]
#[serde(skip_serializing_if = "Option::is_none")]
pub response_parameters: Option<::std::collections::HashMap<String, String>>,
/// <p>The collection of response templates for the integration response as a
/// string-to-string map of key-value pairs. Response templates are represented as a
/// key/value map, with a content-type as the key and a template as the value.</p>
#[serde(rename = "ResponseTemplates")]
#[serde(skip_serializing_if = "Option::is_none")]
pub response_templates: Option<::std::collections::HashMap<String, String>>,
/// <p>The template selection expressions for the integration response.</p>
#[serde(rename = "TemplateSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub template_selection_expression: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct UpdateModelRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The content-type for the model, for example, "application/json".</p>
#[serde(rename = "ContentType")]
#[serde(skip_serializing_if = "Option::is_none")]
pub content_type: Option<String>,
/// <p>The description of the model.</p>
#[serde(rename = "Description")]
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// <p>The model ID.</p>
#[serde(rename = "ModelId")]
pub model_id: String,
/// <p>The name of the model.</p>
#[serde(rename = "Name")]
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// <p>The schema for the model. For application/json models, this should be JSON schema
/// draft 4 model.</p>
#[serde(rename = "Schema")]
#[serde(skip_serializing_if = "Option::is_none")]
pub schema: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct UpdateModelResponse {
/// <p>The content-type for the model, for example, "application/json".</p>
#[serde(rename = "ContentType")]
#[serde(skip_serializing_if = "Option::is_none")]
pub content_type: Option<String>,
/// <p>The description of the model.</p>
#[serde(rename = "Description")]
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// <p>The model identifier.</p>
#[serde(rename = "ModelId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub model_id: Option<String>,
/// <p>The name of the model. Must be alphanumeric.</p>
#[serde(rename = "Name")]
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// <p>The schema for the model. For application/json models, this should be JSON schema
/// draft 4 model.</p>
#[serde(rename = "Schema")]
#[serde(skip_serializing_if = "Option::is_none")]
pub schema: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct UpdateRouteRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>Specifies whether an API key is required for the route.</p>
#[serde(rename = "ApiKeyRequired")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_key_required: Option<bool>,
/// <p>The authorization scopes supported by this
/// route.</p>
#[serde(rename = "AuthorizationScopes")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorization_scopes: Option<Vec<String>>,
/// <p>The authorization type for the route. Valid values are NONE for open
/// access, AWS_IAM for using AWS IAM permissions, and CUSTOM
/// for using a Lambda
/// authorizer.</p>
#[serde(rename = "AuthorizationType")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorization_type: Option<String>,
/// <p>The identifier of the Authorizer resource to be associated with this
/// route, if the authorizationType is CUSTOM
/// . The authorizer identifier is generated by API Gateway
/// when you created the authorizer.</p>
#[serde(rename = "AuthorizerId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorizer_id: Option<String>,
/// <p>The model selection expression for the route.</p>
#[serde(rename = "ModelSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub model_selection_expression: Option<String>,
/// <p>The operation name for the route.</p>
#[serde(rename = "OperationName")]
#[serde(skip_serializing_if = "Option::is_none")]
pub operation_name: Option<String>,
/// <p>The request models for the route.</p>
#[serde(rename = "RequestModels")]
#[serde(skip_serializing_if = "Option::is_none")]
pub request_models: Option<::std::collections::HashMap<String, String>>,
/// <p>The request parameters for the route.</p>
#[serde(rename = "RequestParameters")]
#[serde(skip_serializing_if = "Option::is_none")]
pub request_parameters: Option<::std::collections::HashMap<String, ParameterConstraints>>,
/// <p>The route ID.</p>
#[serde(rename = "RouteId")]
pub route_id: String,
/// <p>The route key for the route.</p>
#[serde(rename = "RouteKey")]
#[serde(skip_serializing_if = "Option::is_none")]
pub route_key: Option<String>,
/// <p>The route response selection expression for the route.</p>
#[serde(rename = "RouteResponseSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub route_response_selection_expression: Option<String>,
/// <p>The target for the route.</p>
#[serde(rename = "Target")]
#[serde(skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct UpdateRouteResponse {
/// <p>Specifies whether an API key is required for this route.</p>
#[serde(rename = "ApiKeyRequired")]
#[serde(skip_serializing_if = "Option::is_none")]
pub api_key_required: Option<bool>,
/// <p>A list of authorization scopes configured on a route. The scopes are used with a
/// COGNITO_USER_POOLS authorizer to authorize the method invocation. The authorization
/// works by matching the route scopes against the scopes parsed from the access token in
/// the incoming request. The method invocation is authorized if any route scope matches
/// a claimed scope in the access token. Otherwise, the invocation is not authorized.
/// When the route scope is configured, the client must provide an access token instead
/// of an identity token for authorization purposes.</p>
#[serde(rename = "AuthorizationScopes")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorization_scopes: Option<Vec<String>>,
/// <p>The authorization type for the route. Valid values are NONE for open
/// access, AWS_IAM for using AWS IAM permissions, and CUSTOM
/// for using a Lambda
/// authorizer</p>
#[serde(rename = "AuthorizationType")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorization_type: Option<String>,
/// <p>The identifier of the Authorizer resource to be associated with this
/// route, if the authorizationType is CUSTOM
/// . The authorizer identifier is generated by API Gateway
/// when you created the authorizer.</p>
#[serde(rename = "AuthorizerId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub authorizer_id: Option<String>,
/// <p>The model selection expression for the route.</p>
#[serde(rename = "ModelSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub model_selection_expression: Option<String>,
/// <p>The operation name for the route.</p>
#[serde(rename = "OperationName")]
#[serde(skip_serializing_if = "Option::is_none")]
pub operation_name: Option<String>,
/// <p>The request models for the route.</p>
#[serde(rename = "RequestModels")]
#[serde(skip_serializing_if = "Option::is_none")]
pub request_models: Option<::std::collections::HashMap<String, String>>,
/// <p>The request parameters for the route.</p>
#[serde(rename = "RequestParameters")]
#[serde(skip_serializing_if = "Option::is_none")]
pub request_parameters: Option<::std::collections::HashMap<String, ParameterConstraints>>,
/// <p>The route ID.</p>
#[serde(rename = "RouteId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub route_id: Option<String>,
/// <p>The route key for the route.</p>
#[serde(rename = "RouteKey")]
#[serde(skip_serializing_if = "Option::is_none")]
pub route_key: Option<String>,
/// <p>The route response selection expression for the route.</p>
#[serde(rename = "RouteResponseSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub route_response_selection_expression: Option<String>,
/// <p>The target for the route.</p>
#[serde(rename = "Target")]
#[serde(skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct UpdateRouteResponseRequest {
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The model selection expression for the route response.</p>
#[serde(rename = "ModelSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub model_selection_expression: Option<String>,
/// <p>The response models for the route response.</p>
#[serde(rename = "ResponseModels")]
#[serde(skip_serializing_if = "Option::is_none")]
pub response_models: Option<::std::collections::HashMap<String, String>>,
/// <p>The route response parameters.</p>
#[serde(rename = "ResponseParameters")]
#[serde(skip_serializing_if = "Option::is_none")]
pub response_parameters: Option<::std::collections::HashMap<String, ParameterConstraints>>,
/// <p>The route ID.</p>
#[serde(rename = "RouteId")]
pub route_id: String,
/// <p>The route response ID.</p>
#[serde(rename = "RouteResponseId")]
pub route_response_id: String,
/// <p>The route response key.</p>
#[serde(rename = "RouteResponseKey")]
#[serde(skip_serializing_if = "Option::is_none")]
pub route_response_key: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct UpdateRouteResponseResponse {
/// <p>Represents the model selection expression of a route response.</p>
#[serde(rename = "ModelSelectionExpression")]
#[serde(skip_serializing_if = "Option::is_none")]
pub model_selection_expression: Option<String>,
/// <p>Represents the response models of a route response.</p>
#[serde(rename = "ResponseModels")]
#[serde(skip_serializing_if = "Option::is_none")]
pub response_models: Option<::std::collections::HashMap<String, String>>,
/// <p>Represents the response parameters of a route response.</p>
#[serde(rename = "ResponseParameters")]
#[serde(skip_serializing_if = "Option::is_none")]
pub response_parameters: Option<::std::collections::HashMap<String, ParameterConstraints>>,
/// <p>Represents the identifier of a route response.</p>
#[serde(rename = "RouteResponseId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub route_response_id: Option<String>,
/// <p>Represents the route response key of a route response.</p>
#[serde(rename = "RouteResponseKey")]
#[serde(skip_serializing_if = "Option::is_none")]
pub route_response_key: Option<String>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize)]
pub struct UpdateStageRequest {
/// <p>Settings for logging access in this stage.</p>
#[serde(rename = "AccessLogSettings")]
#[serde(skip_serializing_if = "Option::is_none")]
pub access_log_settings: Option<AccessLogSettings>,
/// <p>The API identifier.</p>
#[serde(rename = "ApiId")]
pub api_id: String,
/// <p>The identifier of a client certificate for a Stage.</p>
#[serde(rename = "ClientCertificateId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub client_certificate_id: Option<String>,
/// <p>The default route settings for the stage.</p>
#[serde(rename = "DefaultRouteSettings")]
#[serde(skip_serializing_if = "Option::is_none")]
pub default_route_settings: Option<RouteSettings>,
/// <p>The deployment identifier for the API stage.</p>
#[serde(rename = "DeploymentId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub deployment_id: Option<String>,
/// <p>The description for the API stage.</p>
#[serde(rename = "Description")]
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// <p>Route settings for the stage.</p>
#[serde(rename = "RouteSettings")]
#[serde(skip_serializing_if = "Option::is_none")]
pub route_settings: Option<::std::collections::HashMap<String, RouteSettings>>,
/// <p>The stage name.</p>
#[serde(rename = "StageName")]
pub stage_name: String,
/// <p>A map that defines the stage variables for a Stage. Variable names
/// can have alphanumeric and underscore characters, and the values must match
/// [A-Za-z0-9-._~:/?#&=,]+.</p>
#[serde(rename = "StageVariables")]
#[serde(skip_serializing_if = "Option::is_none")]
pub stage_variables: Option<::std::collections::HashMap<String, String>>,
}
#[derive(Default, Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(test, derive(Serialize))]
pub struct UpdateStageResponse {
/// <p>Settings for logging access in this stage.</p>
#[serde(rename = "AccessLogSettings")]
#[serde(skip_serializing_if = "Option::is_none")]
pub access_log_settings: Option<AccessLogSettings>,
/// <p>The identifier of a client certificate for a Stage.</p>
#[serde(rename = "ClientCertificateId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub client_certificate_id: Option<String>,
/// <p>The timestamp when the stage was created.</p>
#[serde(rename = "CreatedDate")]
#[serde(skip_serializing_if = "Option::is_none")]
pub created_date: Option<f64>,
/// <p>Default route settings for the stage.</p>
#[serde(rename = "DefaultRouteSettings")]
#[serde(skip_serializing_if = "Option::is_none")]
pub default_route_settings: Option<RouteSettings>,
/// <p>The identifier of the Deployment that the Stage is
/// associated with.</p>
#[serde(rename = "DeploymentId")]
#[serde(skip_serializing_if = "Option::is_none")]
pub deployment_id: Option<String>,
/// <p>The description of the stage.</p>
#[serde(rename = "Description")]
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// <p>The timestamp when the stage was last updated.</p>
#[serde(rename = "LastUpdatedDate")]
#[serde(skip_serializing_if = "Option::is_none")]
pub last_updated_date: Option<f64>,
/// <p>Route settings for the stage.</p>
#[serde(rename = "RouteSettings")]
#[serde(skip_serializing_if = "Option::is_none")]
pub route_settings: Option<::std::collections::HashMap<String, RouteSettings>>,
/// <p>The name of the stage.</p>
#[serde(rename = "StageName")]
#[serde(skip_serializing_if = "Option::is_none")]
pub stage_name: Option<String>,
/// <p>A map that defines the stage variables for a stage resource. Variable names can
/// have alphanumeric and underscore characters, and the values must match
/// [A-Za-z0-9-._~:/?#&=,]+.</p>
#[serde(rename = "StageVariables")]
#[serde(skip_serializing_if = "Option::is_none")]
pub stage_variables: Option<::std::collections::HashMap<String, String>>,
}
/// Errors returned by CreateApi
#[derive(Debug, PartialEq)]
pub enum CreateApiError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The requested operation would cause a conflict with the current state of a service
/// resource associated with the request. Resolve the conflict before retrying this
/// request. See the accompanying error message for details.</p>
Conflict(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl CreateApiError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<CreateApiError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(CreateApiError::BadRequest(err.msg))
}
"ConflictException" => {
return RusotoError::Service(CreateApiError::Conflict(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(CreateApiError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(CreateApiError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for CreateApiError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for CreateApiError {
fn description(&self) -> &str {
match *self {
CreateApiError::BadRequest(ref cause) => cause,
CreateApiError::Conflict(ref cause) => cause,
CreateApiError::NotFound(ref cause) => cause,
CreateApiError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by CreateApiMapping
#[derive(Debug, PartialEq)]
pub enum CreateApiMappingError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The requested operation would cause a conflict with the current state of a service
/// resource associated with the request. Resolve the conflict before retrying this
/// request. See the accompanying error message for details.</p>
Conflict(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl CreateApiMappingError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<CreateApiMappingError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(CreateApiMappingError::BadRequest(err.msg))
}
"ConflictException" => {
return RusotoError::Service(CreateApiMappingError::Conflict(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(CreateApiMappingError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(CreateApiMappingError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for CreateApiMappingError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for CreateApiMappingError {
fn description(&self) -> &str {
match *self {
CreateApiMappingError::BadRequest(ref cause) => cause,
CreateApiMappingError::Conflict(ref cause) => cause,
CreateApiMappingError::NotFound(ref cause) => cause,
CreateApiMappingError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by CreateAuthorizer
#[derive(Debug, PartialEq)]
pub enum CreateAuthorizerError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The requested operation would cause a conflict with the current state of a service
/// resource associated with the request. Resolve the conflict before retrying this
/// request. See the accompanying error message for details.</p>
Conflict(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl CreateAuthorizerError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<CreateAuthorizerError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(CreateAuthorizerError::BadRequest(err.msg))
}
"ConflictException" => {
return RusotoError::Service(CreateAuthorizerError::Conflict(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(CreateAuthorizerError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(CreateAuthorizerError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for CreateAuthorizerError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for CreateAuthorizerError {
fn description(&self) -> &str {
match *self {
CreateAuthorizerError::BadRequest(ref cause) => cause,
CreateAuthorizerError::Conflict(ref cause) => cause,
CreateAuthorizerError::NotFound(ref cause) => cause,
CreateAuthorizerError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by CreateDeployment
#[derive(Debug, PartialEq)]
pub enum CreateDeploymentError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The requested operation would cause a conflict with the current state of a service
/// resource associated with the request. Resolve the conflict before retrying this
/// request. See the accompanying error message for details.</p>
Conflict(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl CreateDeploymentError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<CreateDeploymentError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(CreateDeploymentError::BadRequest(err.msg))
}
"ConflictException" => {
return RusotoError::Service(CreateDeploymentError::Conflict(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(CreateDeploymentError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(CreateDeploymentError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for CreateDeploymentError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for CreateDeploymentError {
fn description(&self) -> &str {
match *self {
CreateDeploymentError::BadRequest(ref cause) => cause,
CreateDeploymentError::Conflict(ref cause) => cause,
CreateDeploymentError::NotFound(ref cause) => cause,
CreateDeploymentError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by CreateDomainName
#[derive(Debug, PartialEq)]
pub enum CreateDomainNameError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The requested operation would cause a conflict with the current state of a service
/// resource associated with the request. Resolve the conflict before retrying this
/// request. See the accompanying error message for details.</p>
Conflict(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl CreateDomainNameError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<CreateDomainNameError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(CreateDomainNameError::BadRequest(err.msg))
}
"ConflictException" => {
return RusotoError::Service(CreateDomainNameError::Conflict(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(CreateDomainNameError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(CreateDomainNameError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for CreateDomainNameError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for CreateDomainNameError {
fn description(&self) -> &str {
match *self {
CreateDomainNameError::BadRequest(ref cause) => cause,
CreateDomainNameError::Conflict(ref cause) => cause,
CreateDomainNameError::NotFound(ref cause) => cause,
CreateDomainNameError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by CreateIntegration
#[derive(Debug, PartialEq)]
pub enum CreateIntegrationError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The requested operation would cause a conflict with the current state of a service
/// resource associated with the request. Resolve the conflict before retrying this
/// request. See the accompanying error message for details.</p>
Conflict(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl CreateIntegrationError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<CreateIntegrationError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(CreateIntegrationError::BadRequest(err.msg))
}
"ConflictException" => {
return RusotoError::Service(CreateIntegrationError::Conflict(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(CreateIntegrationError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(CreateIntegrationError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for CreateIntegrationError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for CreateIntegrationError {
fn description(&self) -> &str {
match *self {
CreateIntegrationError::BadRequest(ref cause) => cause,
CreateIntegrationError::Conflict(ref cause) => cause,
CreateIntegrationError::NotFound(ref cause) => cause,
CreateIntegrationError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by CreateIntegrationResponse
#[derive(Debug, PartialEq)]
pub enum CreateIntegrationResponseError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The requested operation would cause a conflict with the current state of a service
/// resource associated with the request. Resolve the conflict before retrying this
/// request. See the accompanying error message for details.</p>
Conflict(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl CreateIntegrationResponseError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<CreateIntegrationResponseError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(CreateIntegrationResponseError::BadRequest(
err.msg,
))
}
"ConflictException" => {
return RusotoError::Service(CreateIntegrationResponseError::Conflict(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(CreateIntegrationResponseError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(CreateIntegrationResponseError::TooManyRequests(
err.msg,
))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for CreateIntegrationResponseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for CreateIntegrationResponseError {
fn description(&self) -> &str {
match *self {
CreateIntegrationResponseError::BadRequest(ref cause) => cause,
CreateIntegrationResponseError::Conflict(ref cause) => cause,
CreateIntegrationResponseError::NotFound(ref cause) => cause,
CreateIntegrationResponseError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by CreateModel
#[derive(Debug, PartialEq)]
pub enum CreateModelError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The requested operation would cause a conflict with the current state of a service
/// resource associated with the request. Resolve the conflict before retrying this
/// request. See the accompanying error message for details.</p>
Conflict(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl CreateModelError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<CreateModelError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(CreateModelError::BadRequest(err.msg))
}
"ConflictException" => {
return RusotoError::Service(CreateModelError::Conflict(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(CreateModelError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(CreateModelError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for CreateModelError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for CreateModelError {
fn description(&self) -> &str {
match *self {
CreateModelError::BadRequest(ref cause) => cause,
CreateModelError::Conflict(ref cause) => cause,
CreateModelError::NotFound(ref cause) => cause,
CreateModelError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by CreateRoute
#[derive(Debug, PartialEq)]
pub enum CreateRouteError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The requested operation would cause a conflict with the current state of a service
/// resource associated with the request. Resolve the conflict before retrying this
/// request. See the accompanying error message for details.</p>
Conflict(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl CreateRouteError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<CreateRouteError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(CreateRouteError::BadRequest(err.msg))
}
"ConflictException" => {
return RusotoError::Service(CreateRouteError::Conflict(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(CreateRouteError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(CreateRouteError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for CreateRouteError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for CreateRouteError {
fn description(&self) -> &str {
match *self {
CreateRouteError::BadRequest(ref cause) => cause,
CreateRouteError::Conflict(ref cause) => cause,
CreateRouteError::NotFound(ref cause) => cause,
CreateRouteError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by CreateRouteResponse
#[derive(Debug, PartialEq)]
pub enum CreateRouteResponseError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The requested operation would cause a conflict with the current state of a service
/// resource associated with the request. Resolve the conflict before retrying this
/// request. See the accompanying error message for details.</p>
Conflict(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl CreateRouteResponseError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<CreateRouteResponseError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(CreateRouteResponseError::BadRequest(err.msg))
}
"ConflictException" => {
return RusotoError::Service(CreateRouteResponseError::Conflict(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(CreateRouteResponseError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(CreateRouteResponseError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for CreateRouteResponseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for CreateRouteResponseError {
fn description(&self) -> &str {
match *self {
CreateRouteResponseError::BadRequest(ref cause) => cause,
CreateRouteResponseError::Conflict(ref cause) => cause,
CreateRouteResponseError::NotFound(ref cause) => cause,
CreateRouteResponseError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by CreateStage
#[derive(Debug, PartialEq)]
pub enum CreateStageError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The requested operation would cause a conflict with the current state of a service
/// resource associated with the request. Resolve the conflict before retrying this
/// request. See the accompanying error message for details.</p>
Conflict(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl CreateStageError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<CreateStageError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(CreateStageError::BadRequest(err.msg))
}
"ConflictException" => {
return RusotoError::Service(CreateStageError::Conflict(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(CreateStageError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(CreateStageError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for CreateStageError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for CreateStageError {
fn description(&self) -> &str {
match *self {
CreateStageError::BadRequest(ref cause) => cause,
CreateStageError::Conflict(ref cause) => cause,
CreateStageError::NotFound(ref cause) => cause,
CreateStageError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by DeleteApi
#[derive(Debug, PartialEq)]
pub enum DeleteApiError {
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl DeleteApiError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<DeleteApiError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"NotFoundException" => {
return RusotoError::Service(DeleteApiError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(DeleteApiError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for DeleteApiError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for DeleteApiError {
fn description(&self) -> &str {
match *self {
DeleteApiError::NotFound(ref cause) => cause,
DeleteApiError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by DeleteApiMapping
#[derive(Debug, PartialEq)]
pub enum DeleteApiMappingError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl DeleteApiMappingError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<DeleteApiMappingError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(DeleteApiMappingError::BadRequest(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(DeleteApiMappingError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(DeleteApiMappingError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for DeleteApiMappingError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for DeleteApiMappingError {
fn description(&self) -> &str {
match *self {
DeleteApiMappingError::BadRequest(ref cause) => cause,
DeleteApiMappingError::NotFound(ref cause) => cause,
DeleteApiMappingError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by DeleteAuthorizer
#[derive(Debug, PartialEq)]
pub enum DeleteAuthorizerError {
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl DeleteAuthorizerError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<DeleteAuthorizerError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"NotFoundException" => {
return RusotoError::Service(DeleteAuthorizerError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(DeleteAuthorizerError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for DeleteAuthorizerError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for DeleteAuthorizerError {
fn description(&self) -> &str {
match *self {
DeleteAuthorizerError::NotFound(ref cause) => cause,
DeleteAuthorizerError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by DeleteDeployment
#[derive(Debug, PartialEq)]
pub enum DeleteDeploymentError {
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl DeleteDeploymentError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<DeleteDeploymentError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"NotFoundException" => {
return RusotoError::Service(DeleteDeploymentError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(DeleteDeploymentError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for DeleteDeploymentError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for DeleteDeploymentError {
fn description(&self) -> &str {
match *self {
DeleteDeploymentError::NotFound(ref cause) => cause,
DeleteDeploymentError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by DeleteDomainName
#[derive(Debug, PartialEq)]
pub enum DeleteDomainNameError {
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl DeleteDomainNameError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<DeleteDomainNameError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"NotFoundException" => {
return RusotoError::Service(DeleteDomainNameError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(DeleteDomainNameError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for DeleteDomainNameError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for DeleteDomainNameError {
fn description(&self) -> &str {
match *self {
DeleteDomainNameError::NotFound(ref cause) => cause,
DeleteDomainNameError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by DeleteIntegration
#[derive(Debug, PartialEq)]
pub enum DeleteIntegrationError {
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl DeleteIntegrationError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<DeleteIntegrationError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"NotFoundException" => {
return RusotoError::Service(DeleteIntegrationError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(DeleteIntegrationError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for DeleteIntegrationError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for DeleteIntegrationError {
fn description(&self) -> &str {
match *self {
DeleteIntegrationError::NotFound(ref cause) => cause,
DeleteIntegrationError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by DeleteIntegrationResponse
#[derive(Debug, PartialEq)]
pub enum DeleteIntegrationResponseError {
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl DeleteIntegrationResponseError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<DeleteIntegrationResponseError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"NotFoundException" => {
return RusotoError::Service(DeleteIntegrationResponseError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(DeleteIntegrationResponseError::TooManyRequests(
err.msg,
))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for DeleteIntegrationResponseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for DeleteIntegrationResponseError {
fn description(&self) -> &str {
match *self {
DeleteIntegrationResponseError::NotFound(ref cause) => cause,
DeleteIntegrationResponseError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by DeleteModel
#[derive(Debug, PartialEq)]
pub enum DeleteModelError {
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl DeleteModelError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<DeleteModelError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"NotFoundException" => {
return RusotoError::Service(DeleteModelError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(DeleteModelError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for DeleteModelError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for DeleteModelError {
fn description(&self) -> &str {
match *self {
DeleteModelError::NotFound(ref cause) => cause,
DeleteModelError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by DeleteRoute
#[derive(Debug, PartialEq)]
pub enum DeleteRouteError {
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl DeleteRouteError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<DeleteRouteError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"NotFoundException" => {
return RusotoError::Service(DeleteRouteError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(DeleteRouteError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for DeleteRouteError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for DeleteRouteError {
fn description(&self) -> &str {
match *self {
DeleteRouteError::NotFound(ref cause) => cause,
DeleteRouteError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by DeleteRouteResponse
#[derive(Debug, PartialEq)]
pub enum DeleteRouteResponseError {
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl DeleteRouteResponseError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<DeleteRouteResponseError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"NotFoundException" => {
return RusotoError::Service(DeleteRouteResponseError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(DeleteRouteResponseError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for DeleteRouteResponseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for DeleteRouteResponseError {
fn description(&self) -> &str {
match *self {
DeleteRouteResponseError::NotFound(ref cause) => cause,
DeleteRouteResponseError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by DeleteStage
#[derive(Debug, PartialEq)]
pub enum DeleteStageError {
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl DeleteStageError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<DeleteStageError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"NotFoundException" => {
return RusotoError::Service(DeleteStageError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(DeleteStageError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for DeleteStageError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for DeleteStageError {
fn description(&self) -> &str {
match *self {
DeleteStageError::NotFound(ref cause) => cause,
DeleteStageError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by GetApi
#[derive(Debug, PartialEq)]
pub enum GetApiError {
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl GetApiError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetApiError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"NotFoundException" => return RusotoError::Service(GetApiError::NotFound(err.msg)),
"TooManyRequestsException" => {
return RusotoError::Service(GetApiError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for GetApiError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for GetApiError {
fn description(&self) -> &str {
match *self {
GetApiError::NotFound(ref cause) => cause,
GetApiError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by GetApiMapping
#[derive(Debug, PartialEq)]
pub enum GetApiMappingError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl GetApiMappingError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetApiMappingError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(GetApiMappingError::BadRequest(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(GetApiMappingError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(GetApiMappingError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for GetApiMappingError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for GetApiMappingError {
fn description(&self) -> &str {
match *self {
GetApiMappingError::BadRequest(ref cause) => cause,
GetApiMappingError::NotFound(ref cause) => cause,
GetApiMappingError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by GetApiMappings
#[derive(Debug, PartialEq)]
pub enum GetApiMappingsError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl GetApiMappingsError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetApiMappingsError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(GetApiMappingsError::BadRequest(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(GetApiMappingsError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(GetApiMappingsError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for GetApiMappingsError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for GetApiMappingsError {
fn description(&self) -> &str {
match *self {
GetApiMappingsError::BadRequest(ref cause) => cause,
GetApiMappingsError::NotFound(ref cause) => cause,
GetApiMappingsError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by GetApis
#[derive(Debug, PartialEq)]
pub enum GetApisError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl GetApisError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetApisError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(GetApisError::BadRequest(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(GetApisError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(GetApisError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for GetApisError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for GetApisError {
fn description(&self) -> &str {
match *self {
GetApisError::BadRequest(ref cause) => cause,
GetApisError::NotFound(ref cause) => cause,
GetApisError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by GetAuthorizer
#[derive(Debug, PartialEq)]
pub enum GetAuthorizerError {
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl GetAuthorizerError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetAuthorizerError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"NotFoundException" => {
return RusotoError::Service(GetAuthorizerError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(GetAuthorizerError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for GetAuthorizerError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for GetAuthorizerError {
fn description(&self) -> &str {
match *self {
GetAuthorizerError::NotFound(ref cause) => cause,
GetAuthorizerError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by GetAuthorizers
#[derive(Debug, PartialEq)]
pub enum GetAuthorizersError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl GetAuthorizersError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetAuthorizersError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(GetAuthorizersError::BadRequest(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(GetAuthorizersError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(GetAuthorizersError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for GetAuthorizersError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for GetAuthorizersError {
fn description(&self) -> &str {
match *self {
GetAuthorizersError::BadRequest(ref cause) => cause,
GetAuthorizersError::NotFound(ref cause) => cause,
GetAuthorizersError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by GetDeployment
#[derive(Debug, PartialEq)]
pub enum GetDeploymentError {
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl GetDeploymentError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetDeploymentError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"NotFoundException" => {
return RusotoError::Service(GetDeploymentError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(GetDeploymentError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for GetDeploymentError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for GetDeploymentError {
fn description(&self) -> &str {
match *self {
GetDeploymentError::NotFound(ref cause) => cause,
GetDeploymentError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by GetDeployments
#[derive(Debug, PartialEq)]
pub enum GetDeploymentsError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl GetDeploymentsError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetDeploymentsError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(GetDeploymentsError::BadRequest(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(GetDeploymentsError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(GetDeploymentsError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for GetDeploymentsError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for GetDeploymentsError {
fn description(&self) -> &str {
match *self {
GetDeploymentsError::BadRequest(ref cause) => cause,
GetDeploymentsError::NotFound(ref cause) => cause,
GetDeploymentsError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by GetDomainName
#[derive(Debug, PartialEq)]
pub enum GetDomainNameError {
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl GetDomainNameError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetDomainNameError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"NotFoundException" => {
return RusotoError::Service(GetDomainNameError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(GetDomainNameError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for GetDomainNameError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for GetDomainNameError {
fn description(&self) -> &str {
match *self {
GetDomainNameError::NotFound(ref cause) => cause,
GetDomainNameError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by GetDomainNames
#[derive(Debug, PartialEq)]
pub enum GetDomainNamesError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl GetDomainNamesError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetDomainNamesError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(GetDomainNamesError::BadRequest(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(GetDomainNamesError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(GetDomainNamesError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for GetDomainNamesError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for GetDomainNamesError {
fn description(&self) -> &str {
match *self {
GetDomainNamesError::BadRequest(ref cause) => cause,
GetDomainNamesError::NotFound(ref cause) => cause,
GetDomainNamesError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by GetIntegration
#[derive(Debug, PartialEq)]
pub enum GetIntegrationError {
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl GetIntegrationError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetIntegrationError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"NotFoundException" => {
return RusotoError::Service(GetIntegrationError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(GetIntegrationError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for GetIntegrationError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for GetIntegrationError {
fn description(&self) -> &str {
match *self {
GetIntegrationError::NotFound(ref cause) => cause,
GetIntegrationError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by GetIntegrationResponse
#[derive(Debug, PartialEq)]
pub enum GetIntegrationResponseError {
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl GetIntegrationResponseError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetIntegrationResponseError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"NotFoundException" => {
return RusotoError::Service(GetIntegrationResponseError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(GetIntegrationResponseError::TooManyRequests(
err.msg,
))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for GetIntegrationResponseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for GetIntegrationResponseError {
fn description(&self) -> &str {
match *self {
GetIntegrationResponseError::NotFound(ref cause) => cause,
GetIntegrationResponseError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by GetIntegrationResponses
#[derive(Debug, PartialEq)]
pub enum GetIntegrationResponsesError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl GetIntegrationResponsesError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetIntegrationResponsesError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(GetIntegrationResponsesError::BadRequest(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(GetIntegrationResponsesError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(GetIntegrationResponsesError::TooManyRequests(
err.msg,
))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for GetIntegrationResponsesError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for GetIntegrationResponsesError {
fn description(&self) -> &str {
match *self {
GetIntegrationResponsesError::BadRequest(ref cause) => cause,
GetIntegrationResponsesError::NotFound(ref cause) => cause,
GetIntegrationResponsesError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by GetIntegrations
#[derive(Debug, PartialEq)]
pub enum GetIntegrationsError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl GetIntegrationsError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetIntegrationsError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(GetIntegrationsError::BadRequest(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(GetIntegrationsError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(GetIntegrationsError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for GetIntegrationsError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for GetIntegrationsError {
fn description(&self) -> &str {
match *self {
GetIntegrationsError::BadRequest(ref cause) => cause,
GetIntegrationsError::NotFound(ref cause) => cause,
GetIntegrationsError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by GetModel
#[derive(Debug, PartialEq)]
pub enum GetModelError {
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl GetModelError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetModelError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"NotFoundException" => {
return RusotoError::Service(GetModelError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(GetModelError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for GetModelError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for GetModelError {
fn description(&self) -> &str {
match *self {
GetModelError::NotFound(ref cause) => cause,
GetModelError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by GetModelTemplate
#[derive(Debug, PartialEq)]
pub enum GetModelTemplateError {
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl GetModelTemplateError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetModelTemplateError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"NotFoundException" => {
return RusotoError::Service(GetModelTemplateError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(GetModelTemplateError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for GetModelTemplateError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for GetModelTemplateError {
fn description(&self) -> &str {
match *self {
GetModelTemplateError::NotFound(ref cause) => cause,
GetModelTemplateError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by GetModels
#[derive(Debug, PartialEq)]
pub enum GetModelsError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl GetModelsError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetModelsError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(GetModelsError::BadRequest(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(GetModelsError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(GetModelsError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for GetModelsError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for GetModelsError {
fn description(&self) -> &str {
match *self {
GetModelsError::BadRequest(ref cause) => cause,
GetModelsError::NotFound(ref cause) => cause,
GetModelsError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by GetRoute
#[derive(Debug, PartialEq)]
pub enum GetRouteError {
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl GetRouteError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetRouteError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"NotFoundException" => {
return RusotoError::Service(GetRouteError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(GetRouteError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for GetRouteError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for GetRouteError {
fn description(&self) -> &str {
match *self {
GetRouteError::NotFound(ref cause) => cause,
GetRouteError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by GetRouteResponse
#[derive(Debug, PartialEq)]
pub enum GetRouteResponseError {
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl GetRouteResponseError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetRouteResponseError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"NotFoundException" => {
return RusotoError::Service(GetRouteResponseError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(GetRouteResponseError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for GetRouteResponseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for GetRouteResponseError {
fn description(&self) -> &str {
match *self {
GetRouteResponseError::NotFound(ref cause) => cause,
GetRouteResponseError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by GetRouteResponses
#[derive(Debug, PartialEq)]
pub enum GetRouteResponsesError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl GetRouteResponsesError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetRouteResponsesError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(GetRouteResponsesError::BadRequest(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(GetRouteResponsesError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(GetRouteResponsesError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for GetRouteResponsesError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for GetRouteResponsesError {
fn description(&self) -> &str {
match *self {
GetRouteResponsesError::BadRequest(ref cause) => cause,
GetRouteResponsesError::NotFound(ref cause) => cause,
GetRouteResponsesError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by GetRoutes
#[derive(Debug, PartialEq)]
pub enum GetRoutesError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl GetRoutesError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetRoutesError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(GetRoutesError::BadRequest(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(GetRoutesError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(GetRoutesError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for GetRoutesError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for GetRoutesError {
fn description(&self) -> &str {
match *self {
GetRoutesError::BadRequest(ref cause) => cause,
GetRoutesError::NotFound(ref cause) => cause,
GetRoutesError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by GetStage
#[derive(Debug, PartialEq)]
pub enum GetStageError {
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl GetStageError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetStageError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"NotFoundException" => {
return RusotoError::Service(GetStageError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(GetStageError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for GetStageError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for GetStageError {
fn description(&self) -> &str {
match *self {
GetStageError::NotFound(ref cause) => cause,
GetStageError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by GetStages
#[derive(Debug, PartialEq)]
pub enum GetStagesError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl GetStagesError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetStagesError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(GetStagesError::BadRequest(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(GetStagesError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(GetStagesError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for GetStagesError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for GetStagesError {
fn description(&self) -> &str {
match *self {
GetStagesError::BadRequest(ref cause) => cause,
GetStagesError::NotFound(ref cause) => cause,
GetStagesError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by UpdateApi
#[derive(Debug, PartialEq)]
pub enum UpdateApiError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The requested operation would cause a conflict with the current state of a service
/// resource associated with the request. Resolve the conflict before retrying this
/// request. See the accompanying error message for details.</p>
Conflict(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl UpdateApiError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<UpdateApiError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(UpdateApiError::BadRequest(err.msg))
}
"ConflictException" => {
return RusotoError::Service(UpdateApiError::Conflict(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(UpdateApiError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(UpdateApiError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for UpdateApiError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for UpdateApiError {
fn description(&self) -> &str {
match *self {
UpdateApiError::BadRequest(ref cause) => cause,
UpdateApiError::Conflict(ref cause) => cause,
UpdateApiError::NotFound(ref cause) => cause,
UpdateApiError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by UpdateApiMapping
#[derive(Debug, PartialEq)]
pub enum UpdateApiMappingError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The requested operation would cause a conflict with the current state of a service
/// resource associated with the request. Resolve the conflict before retrying this
/// request. See the accompanying error message for details.</p>
Conflict(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl UpdateApiMappingError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<UpdateApiMappingError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(UpdateApiMappingError::BadRequest(err.msg))
}
"ConflictException" => {
return RusotoError::Service(UpdateApiMappingError::Conflict(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(UpdateApiMappingError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(UpdateApiMappingError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for UpdateApiMappingError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for UpdateApiMappingError {
fn description(&self) -> &str {
match *self {
UpdateApiMappingError::BadRequest(ref cause) => cause,
UpdateApiMappingError::Conflict(ref cause) => cause,
UpdateApiMappingError::NotFound(ref cause) => cause,
UpdateApiMappingError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by UpdateAuthorizer
#[derive(Debug, PartialEq)]
pub enum UpdateAuthorizerError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The requested operation would cause a conflict with the current state of a service
/// resource associated with the request. Resolve the conflict before retrying this
/// request. See the accompanying error message for details.</p>
Conflict(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl UpdateAuthorizerError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<UpdateAuthorizerError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(UpdateAuthorizerError::BadRequest(err.msg))
}
"ConflictException" => {
return RusotoError::Service(UpdateAuthorizerError::Conflict(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(UpdateAuthorizerError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(UpdateAuthorizerError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for UpdateAuthorizerError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for UpdateAuthorizerError {
fn description(&self) -> &str {
match *self {
UpdateAuthorizerError::BadRequest(ref cause) => cause,
UpdateAuthorizerError::Conflict(ref cause) => cause,
UpdateAuthorizerError::NotFound(ref cause) => cause,
UpdateAuthorizerError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by UpdateDeployment
#[derive(Debug, PartialEq)]
pub enum UpdateDeploymentError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The requested operation would cause a conflict with the current state of a service
/// resource associated with the request. Resolve the conflict before retrying this
/// request. See the accompanying error message for details.</p>
Conflict(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl UpdateDeploymentError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<UpdateDeploymentError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(UpdateDeploymentError::BadRequest(err.msg))
}
"ConflictException" => {
return RusotoError::Service(UpdateDeploymentError::Conflict(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(UpdateDeploymentError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(UpdateDeploymentError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for UpdateDeploymentError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for UpdateDeploymentError {
fn description(&self) -> &str {
match *self {
UpdateDeploymentError::BadRequest(ref cause) => cause,
UpdateDeploymentError::Conflict(ref cause) => cause,
UpdateDeploymentError::NotFound(ref cause) => cause,
UpdateDeploymentError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by UpdateDomainName
#[derive(Debug, PartialEq)]
pub enum UpdateDomainNameError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The requested operation would cause a conflict with the current state of a service
/// resource associated with the request. Resolve the conflict before retrying this
/// request. See the accompanying error message for details.</p>
Conflict(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl UpdateDomainNameError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<UpdateDomainNameError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(UpdateDomainNameError::BadRequest(err.msg))
}
"ConflictException" => {
return RusotoError::Service(UpdateDomainNameError::Conflict(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(UpdateDomainNameError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(UpdateDomainNameError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for UpdateDomainNameError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for UpdateDomainNameError {
fn description(&self) -> &str {
match *self {
UpdateDomainNameError::BadRequest(ref cause) => cause,
UpdateDomainNameError::Conflict(ref cause) => cause,
UpdateDomainNameError::NotFound(ref cause) => cause,
UpdateDomainNameError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by UpdateIntegration
#[derive(Debug, PartialEq)]
pub enum UpdateIntegrationError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The requested operation would cause a conflict with the current state of a service
/// resource associated with the request. Resolve the conflict before retrying this
/// request. See the accompanying error message for details.</p>
Conflict(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl UpdateIntegrationError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<UpdateIntegrationError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(UpdateIntegrationError::BadRequest(err.msg))
}
"ConflictException" => {
return RusotoError::Service(UpdateIntegrationError::Conflict(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(UpdateIntegrationError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(UpdateIntegrationError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for UpdateIntegrationError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for UpdateIntegrationError {
fn description(&self) -> &str {
match *self {
UpdateIntegrationError::BadRequest(ref cause) => cause,
UpdateIntegrationError::Conflict(ref cause) => cause,
UpdateIntegrationError::NotFound(ref cause) => cause,
UpdateIntegrationError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by UpdateIntegrationResponse
#[derive(Debug, PartialEq)]
pub enum UpdateIntegrationResponseError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The requested operation would cause a conflict with the current state of a service
/// resource associated with the request. Resolve the conflict before retrying this
/// request. See the accompanying error message for details.</p>
Conflict(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl UpdateIntegrationResponseError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<UpdateIntegrationResponseError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(UpdateIntegrationResponseError::BadRequest(
err.msg,
))
}
"ConflictException" => {
return RusotoError::Service(UpdateIntegrationResponseError::Conflict(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(UpdateIntegrationResponseError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(UpdateIntegrationResponseError::TooManyRequests(
err.msg,
))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for UpdateIntegrationResponseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for UpdateIntegrationResponseError {
fn description(&self) -> &str {
match *self {
UpdateIntegrationResponseError::BadRequest(ref cause) => cause,
UpdateIntegrationResponseError::Conflict(ref cause) => cause,
UpdateIntegrationResponseError::NotFound(ref cause) => cause,
UpdateIntegrationResponseError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by UpdateModel
#[derive(Debug, PartialEq)]
pub enum UpdateModelError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The requested operation would cause a conflict with the current state of a service
/// resource associated with the request. Resolve the conflict before retrying this
/// request. See the accompanying error message for details.</p>
Conflict(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl UpdateModelError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<UpdateModelError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(UpdateModelError::BadRequest(err.msg))
}
"ConflictException" => {
return RusotoError::Service(UpdateModelError::Conflict(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(UpdateModelError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(UpdateModelError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for UpdateModelError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for UpdateModelError {
fn description(&self) -> &str {
match *self {
UpdateModelError::BadRequest(ref cause) => cause,
UpdateModelError::Conflict(ref cause) => cause,
UpdateModelError::NotFound(ref cause) => cause,
UpdateModelError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by UpdateRoute
#[derive(Debug, PartialEq)]
pub enum UpdateRouteError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The requested operation would cause a conflict with the current state of a service
/// resource associated with the request. Resolve the conflict before retrying this
/// request. See the accompanying error message for details.</p>
Conflict(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl UpdateRouteError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<UpdateRouteError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(UpdateRouteError::BadRequest(err.msg))
}
"ConflictException" => {
return RusotoError::Service(UpdateRouteError::Conflict(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(UpdateRouteError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(UpdateRouteError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for UpdateRouteError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for UpdateRouteError {
fn description(&self) -> &str {
match *self {
UpdateRouteError::BadRequest(ref cause) => cause,
UpdateRouteError::Conflict(ref cause) => cause,
UpdateRouteError::NotFound(ref cause) => cause,
UpdateRouteError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by UpdateRouteResponse
#[derive(Debug, PartialEq)]
pub enum UpdateRouteResponseError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The requested operation would cause a conflict with the current state of a service
/// resource associated with the request. Resolve the conflict before retrying this
/// request. See the accompanying error message for details.</p>
Conflict(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl UpdateRouteResponseError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<UpdateRouteResponseError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(UpdateRouteResponseError::BadRequest(err.msg))
}
"ConflictException" => {
return RusotoError::Service(UpdateRouteResponseError::Conflict(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(UpdateRouteResponseError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(UpdateRouteResponseError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for UpdateRouteResponseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for UpdateRouteResponseError {
fn description(&self) -> &str {
match *self {
UpdateRouteResponseError::BadRequest(ref cause) => cause,
UpdateRouteResponseError::Conflict(ref cause) => cause,
UpdateRouteResponseError::NotFound(ref cause) => cause,
UpdateRouteResponseError::TooManyRequests(ref cause) => cause,
}
}
}
/// Errors returned by UpdateStage
#[derive(Debug, PartialEq)]
pub enum UpdateStageError {
/// <p>The request is not valid, for example, the input is incomplete or incorrect. See
/// the accompanying error message for details.</p>
BadRequest(String),
/// <p>The requested operation would cause a conflict with the current state of a service
/// resource associated with the request. Resolve the conflict before retrying this
/// request. See the accompanying error message for details.</p>
Conflict(String),
/// <p>The resource specified in the request was not found. See the message
/// field for more information.</p>
NotFound(String),
/// <p>A limit has been exceeded. See the accompanying error message for details.</p>
TooManyRequests(String),
}
impl UpdateStageError {
pub fn from_response(res: BufferedHttpResponse) -> RusotoError<UpdateStageError> {
if let Some(err) = proto::json::Error::parse_rest(&res) {
match err.typ.as_str() {
"BadRequestException" => {
return RusotoError::Service(UpdateStageError::BadRequest(err.msg))
}
"ConflictException" => {
return RusotoError::Service(UpdateStageError::Conflict(err.msg))
}
"NotFoundException" => {
return RusotoError::Service(UpdateStageError::NotFound(err.msg))
}
"TooManyRequestsException" => {
return RusotoError::Service(UpdateStageError::TooManyRequests(err.msg))
}
"ValidationException" => return RusotoError::Validation(err.msg),
_ => {}
}
}
return RusotoError::Unknown(res);
}
}
impl fmt::Display for UpdateStageError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.description())
}
}
impl Error for UpdateStageError {
fn description(&self) -> &str {
match *self {
UpdateStageError::BadRequest(ref cause) => cause,
UpdateStageError::Conflict(ref cause) => cause,
UpdateStageError::NotFound(ref cause) => cause,
UpdateStageError::TooManyRequests(ref cause) => cause,
}
}
}
/// Trait representing the capabilities of the AmazonApiGatewayV2 API. AmazonApiGatewayV2 clients implement this trait.
pub trait ApiGatewayV2 {
/// <p>Creates an Api resource.</p>
fn create_api(
&self,
input: CreateApiRequest,
) -> RusotoFuture<CreateApiResponse, CreateApiError>;
/// <p>Creates an API mapping.</p>
fn create_api_mapping(
&self,
input: CreateApiMappingRequest,
) -> RusotoFuture<CreateApiMappingResponse, CreateApiMappingError>;
/// <p>Creates an Authorizer for an API.</p>
fn create_authorizer(
&self,
input: CreateAuthorizerRequest,
) -> RusotoFuture<CreateAuthorizerResponse, CreateAuthorizerError>;
/// <p>Creates a Deployment for an API.</p>
fn create_deployment(
&self,
input: CreateDeploymentRequest,
) -> RusotoFuture<CreateDeploymentResponse, CreateDeploymentError>;
/// <p>Creates a domain name.</p>
fn create_domain_name(
&self,
input: CreateDomainNameRequest,
) -> RusotoFuture<CreateDomainNameResponse, CreateDomainNameError>;
/// <p>Creates an Integration.</p>
fn create_integration(
&self,
input: CreateIntegrationRequest,
) -> RusotoFuture<CreateIntegrationResponse, CreateIntegrationError>;
/// <p>Creates an IntegrationResponses.</p>
fn create_integration_response(
&self,
input: CreateIntegrationResponseRequest,
) -> RusotoFuture<CreateIntegrationResponseResponse, CreateIntegrationResponseError>;
/// <p>Creates a Model for an API.</p>
fn create_model(
&self,
input: CreateModelRequest,
) -> RusotoFuture<CreateModelResponse, CreateModelError>;
/// <p>Creates a Route for an API.</p>
fn create_route(
&self,
input: CreateRouteRequest,
) -> RusotoFuture<CreateRouteResponse, CreateRouteError>;
/// <p>Creates a RouteResponse for a Route.</p>
fn create_route_response(
&self,
input: CreateRouteResponseRequest,
) -> RusotoFuture<CreateRouteResponseResponse, CreateRouteResponseError>;
/// <p>Creates a Stage for an API.</p>
fn create_stage(
&self,
input: CreateStageRequest,
) -> RusotoFuture<CreateStageResponse, CreateStageError>;
/// <p>Deletes an Api resource.</p>
fn delete_api(&self, input: DeleteApiRequest) -> RusotoFuture<(), DeleteApiError>;
/// <p>Deletes an API mapping.</p>
fn delete_api_mapping(
&self,
input: DeleteApiMappingRequest,
) -> RusotoFuture<(), DeleteApiMappingError>;
/// <p>Deletes an Authorizer.</p>
fn delete_authorizer(
&self,
input: DeleteAuthorizerRequest,
) -> RusotoFuture<(), DeleteAuthorizerError>;
/// <p>Deletes a Deployment.</p>
fn delete_deployment(
&self,
input: DeleteDeploymentRequest,
) -> RusotoFuture<(), DeleteDeploymentError>;
/// <p>Deletes a domain name.</p>
fn delete_domain_name(
&self,
input: DeleteDomainNameRequest,
) -> RusotoFuture<(), DeleteDomainNameError>;
/// <p>Deletes an Integration.</p>
fn delete_integration(
&self,
input: DeleteIntegrationRequest,
) -> RusotoFuture<(), DeleteIntegrationError>;
/// <p>Deletes an IntegrationResponses.</p>
fn delete_integration_response(
&self,
input: DeleteIntegrationResponseRequest,
) -> RusotoFuture<(), DeleteIntegrationResponseError>;
/// <p>Deletes a Model.</p>
fn delete_model(&self, input: DeleteModelRequest) -> RusotoFuture<(), DeleteModelError>;
/// <p>Deletes a Route.</p>
fn delete_route(&self, input: DeleteRouteRequest) -> RusotoFuture<(), DeleteRouteError>;
/// <p>Deletes a RouteResponse.</p>
fn delete_route_response(
&self,
input: DeleteRouteResponseRequest,
) -> RusotoFuture<(), DeleteRouteResponseError>;
/// <p>Deletes a Stage.</p>
fn delete_stage(&self, input: DeleteStageRequest) -> RusotoFuture<(), DeleteStageError>;
/// <p>Gets an Api resource.</p>
fn get_api(&self, input: GetApiRequest) -> RusotoFuture<GetApiResponse, GetApiError>;
/// <p>The API mapping.</p>
fn get_api_mapping(
&self,
input: GetApiMappingRequest,
) -> RusotoFuture<GetApiMappingResponse, GetApiMappingError>;
/// <p>The API mappings.</p>
fn get_api_mappings(
&self,
input: GetApiMappingsRequest,
) -> RusotoFuture<GetApiMappingsResponse, GetApiMappingsError>;
/// <p>Gets a collection of Api resources.</p>
fn get_apis(&self, input: GetApisRequest) -> RusotoFuture<GetApisResponse, GetApisError>;
/// <p>Gets an Authorizer.</p>
fn get_authorizer(
&self,
input: GetAuthorizerRequest,
) -> RusotoFuture<GetAuthorizerResponse, GetAuthorizerError>;
/// <p>Gets the Authorizers for an API.</p>
fn get_authorizers(
&self,
input: GetAuthorizersRequest,
) -> RusotoFuture<GetAuthorizersResponse, GetAuthorizersError>;
/// <p>Gets a Deployment.</p>
fn get_deployment(
&self,
input: GetDeploymentRequest,
) -> RusotoFuture<GetDeploymentResponse, GetDeploymentError>;
/// <p>Gets the Deployments for an API.</p>
fn get_deployments(
&self,
input: GetDeploymentsRequest,
) -> RusotoFuture<GetDeploymentsResponse, GetDeploymentsError>;
/// <p>Gets a domain name.</p>
fn get_domain_name(
&self,
input: GetDomainNameRequest,
) -> RusotoFuture<GetDomainNameResponse, GetDomainNameError>;
/// <p>Gets the domain names for an AWS account.</p>
fn get_domain_names(
&self,
input: GetDomainNamesRequest,
) -> RusotoFuture<GetDomainNamesResponse, GetDomainNamesError>;
/// <p>Gets an Integration.</p>
fn get_integration(
&self,
input: GetIntegrationRequest,
) -> RusotoFuture<GetIntegrationResponse, GetIntegrationError>;
/// <p>Gets an IntegrationResponses.</p>
fn get_integration_response(
&self,
input: GetIntegrationResponseRequest,
) -> RusotoFuture<GetIntegrationResponseResponse, GetIntegrationResponseError>;
/// <p>Gets the IntegrationResponses for an Integration.</p>
fn get_integration_responses(
&self,
input: GetIntegrationResponsesRequest,
) -> RusotoFuture<GetIntegrationResponsesResponse, GetIntegrationResponsesError>;
/// <p>Gets the Integrations for an API.</p>
fn get_integrations(
&self,
input: GetIntegrationsRequest,
) -> RusotoFuture<GetIntegrationsResponse, GetIntegrationsError>;
/// <p>Gets a Model.</p>
fn get_model(&self, input: GetModelRequest) -> RusotoFuture<GetModelResponse, GetModelError>;
/// <p>Gets a model template.</p>
fn get_model_template(
&self,
input: GetModelTemplateRequest,
) -> RusotoFuture<GetModelTemplateResponse, GetModelTemplateError>;
/// <p>Gets the Models for an API.</p>
fn get_models(
&self,
input: GetModelsRequest,
) -> RusotoFuture<GetModelsResponse, GetModelsError>;
/// <p>Gets a Route.</p>
fn get_route(&self, input: GetRouteRequest) -> RusotoFuture<GetRouteResponse, GetRouteError>;
/// <p>Gets a RouteResponse.</p>
fn get_route_response(
&self,
input: GetRouteResponseRequest,
) -> RusotoFuture<GetRouteResponseResponse, GetRouteResponseError>;
/// <p>Gets the RouteResponses for a Route.</p>
fn get_route_responses(
&self,
input: GetRouteResponsesRequest,
) -> RusotoFuture<GetRouteResponsesResponse, GetRouteResponsesError>;
/// <p>Gets the Routes for an API.</p>
fn get_routes(
&self,
input: GetRoutesRequest,
) -> RusotoFuture<GetRoutesResponse, GetRoutesError>;
/// <p>Gets a Stage.</p>
fn get_stage(&self, input: GetStageRequest) -> RusotoFuture<GetStageResponse, GetStageError>;
/// <p>Gets the Stages for an API.</p>
fn get_stages(
&self,
input: GetStagesRequest,
) -> RusotoFuture<GetStagesResponse, GetStagesError>;
/// <p>Updates an Api resource.</p>
fn update_api(
&self,
input: UpdateApiRequest,
) -> RusotoFuture<UpdateApiResponse, UpdateApiError>;
/// <p>The API mapping.</p>
fn update_api_mapping(
&self,
input: UpdateApiMappingRequest,
) -> RusotoFuture<UpdateApiMappingResponse, UpdateApiMappingError>;
/// <p>Updates an Authorizer.</p>
fn update_authorizer(
&self,
input: UpdateAuthorizerRequest,
) -> RusotoFuture<UpdateAuthorizerResponse, UpdateAuthorizerError>;
/// <p>Updates a Deployment.</p>
fn update_deployment(
&self,
input: UpdateDeploymentRequest,
) -> RusotoFuture<UpdateDeploymentResponse, UpdateDeploymentError>;
/// <p>Updates a domain name.</p>
fn update_domain_name(
&self,
input: UpdateDomainNameRequest,
) -> RusotoFuture<UpdateDomainNameResponse, UpdateDomainNameError>;
/// <p>Updates an Integration.</p>
fn update_integration(
&self,
input: UpdateIntegrationRequest,
) -> RusotoFuture<UpdateIntegrationResponse, UpdateIntegrationError>;
/// <p>Updates an IntegrationResponses.</p>
fn update_integration_response(
&self,
input: UpdateIntegrationResponseRequest,
) -> RusotoFuture<UpdateIntegrationResponseResponse, UpdateIntegrationResponseError>;
/// <p>Updates a Model.</p>
fn update_model(
&self,
input: UpdateModelRequest,
) -> RusotoFuture<UpdateModelResponse, UpdateModelError>;
/// <p>Updates a Route.</p>
fn update_route(
&self,
input: UpdateRouteRequest,
) -> RusotoFuture<UpdateRouteResponse, UpdateRouteError>;
/// <p>Updates a RouteResponse.</p>
fn update_route_response(
&self,
input: UpdateRouteResponseRequest,
) -> RusotoFuture<UpdateRouteResponseResponse, UpdateRouteResponseError>;
/// <p>Updates a Stage.</p>
fn update_stage(
&self,
input: UpdateStageRequest,
) -> RusotoFuture<UpdateStageResponse, UpdateStageError>;
}
/// A client for the AmazonApiGatewayV2 API.
#[derive(Clone)]
pub struct ApiGatewayV2Client {
client: Client,
region: region::Region,
}
impl ApiGatewayV2Client {
/// Creates a client backed by the default tokio event loop.
///
/// The client will use the default credentials provider and tls client.
pub fn new(region: region::Region) -> ApiGatewayV2Client {
ApiGatewayV2Client {
client: Client::shared(),
region,
}
}
pub fn new_with<P, D>(
request_dispatcher: D,
credentials_provider: P,
region: region::Region,
) -> ApiGatewayV2Client
where
P: ProvideAwsCredentials + Send + Sync + 'static,
P::Future: Send,
D: DispatchSignedRequest + Send + Sync + 'static,
D::Future: Send,
{
ApiGatewayV2Client {
client: Client::new_with(credentials_provider, request_dispatcher),
region,
}
}
}
impl ApiGatewayV2 for ApiGatewayV2Client {
/// <p>Creates an Api resource.</p>
fn create_api(
&self,
input: CreateApiRequest,
) -> RusotoFuture<CreateApiResponse, CreateApiError> {
let request_uri = "/v2/apis";
let mut request = SignedRequest::new("POST", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
let encoded = Some(serde_json::to_vec(&input).unwrap());
request.set_payload(encoded);
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 201 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<CreateApiResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(CreateApiError::from_response(response))),
)
}
})
}
/// <p>Creates an API mapping.</p>
fn create_api_mapping(
&self,
input: CreateApiMappingRequest,
) -> RusotoFuture<CreateApiMappingResponse, CreateApiMappingError> {
let request_uri = format!(
"/v2/domainnames/{domain_name}/apimappings",
domain_name = input.domain_name
);
let mut request = SignedRequest::new("POST", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
let encoded = Some(serde_json::to_vec(&input).unwrap());
request.set_payload(encoded);
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 201 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<CreateApiMappingResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(CreateApiMappingError::from_response(response))),
)
}
})
}
/// <p>Creates an Authorizer for an API.</p>
fn create_authorizer(
&self,
input: CreateAuthorizerRequest,
) -> RusotoFuture<CreateAuthorizerResponse, CreateAuthorizerError> {
let request_uri = format!("/v2/apis/{api_id}/authorizers", api_id = input.api_id);
let mut request = SignedRequest::new("POST", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
let encoded = Some(serde_json::to_vec(&input).unwrap());
request.set_payload(encoded);
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 201 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<CreateAuthorizerResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(CreateAuthorizerError::from_response(response))),
)
}
})
}
/// <p>Creates a Deployment for an API.</p>
fn create_deployment(
&self,
input: CreateDeploymentRequest,
) -> RusotoFuture<CreateDeploymentResponse, CreateDeploymentError> {
let request_uri = format!("/v2/apis/{api_id}/deployments", api_id = input.api_id);
let mut request = SignedRequest::new("POST", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
let encoded = Some(serde_json::to_vec(&input).unwrap());
request.set_payload(encoded);
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 201 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<CreateDeploymentResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(CreateDeploymentError::from_response(response))),
)
}
})
}
/// <p>Creates a domain name.</p>
fn create_domain_name(
&self,
input: CreateDomainNameRequest,
) -> RusotoFuture<CreateDomainNameResponse, CreateDomainNameError> {
let request_uri = "/v2/domainnames";
let mut request = SignedRequest::new("POST", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
let encoded = Some(serde_json::to_vec(&input).unwrap());
request.set_payload(encoded);
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 201 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<CreateDomainNameResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(CreateDomainNameError::from_response(response))),
)
}
})
}
/// <p>Creates an Integration.</p>
fn create_integration(
&self,
input: CreateIntegrationRequest,
) -> RusotoFuture<CreateIntegrationResponse, CreateIntegrationError> {
let request_uri = format!("/v2/apis/{api_id}/integrations", api_id = input.api_id);
let mut request = SignedRequest::new("POST", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
let encoded = Some(serde_json::to_vec(&input).unwrap());
request.set_payload(encoded);
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 201 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<CreateIntegrationResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(CreateIntegrationError::from_response(response))),
)
}
})
}
/// <p>Creates an IntegrationResponses.</p>
fn create_integration_response(
&self,
input: CreateIntegrationResponseRequest,
) -> RusotoFuture<CreateIntegrationResponseResponse, CreateIntegrationResponseError> {
let request_uri = format!(
"/v2/apis/{api_id}/integrations/{integration_id}/integrationresponses",
api_id = input.api_id,
integration_id = input.integration_id
);
let mut request = SignedRequest::new("POST", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
let encoded = Some(serde_json::to_vec(&input).unwrap());
request.set_payload(encoded);
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 201 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<CreateIntegrationResponseResponse, _>()?;
Ok(result)
}))
} else {
Box::new(response.buffer().from_err().and_then(|response| {
Err(CreateIntegrationResponseError::from_response(response))
}))
}
})
}
/// <p>Creates a Model for an API.</p>
fn create_model(
&self,
input: CreateModelRequest,
) -> RusotoFuture<CreateModelResponse, CreateModelError> {
let request_uri = format!("/v2/apis/{api_id}/models", api_id = input.api_id);
let mut request = SignedRequest::new("POST", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
let encoded = Some(serde_json::to_vec(&input).unwrap());
request.set_payload(encoded);
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 201 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<CreateModelResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(CreateModelError::from_response(response))),
)
}
})
}
/// <p>Creates a Route for an API.</p>
fn create_route(
&self,
input: CreateRouteRequest,
) -> RusotoFuture<CreateRouteResponse, CreateRouteError> {
let request_uri = format!("/v2/apis/{api_id}/routes", api_id = input.api_id);
let mut request = SignedRequest::new("POST", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
let encoded = Some(serde_json::to_vec(&input).unwrap());
request.set_payload(encoded);
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 201 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<CreateRouteResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(CreateRouteError::from_response(response))),
)
}
})
}
/// <p>Creates a RouteResponse for a Route.</p>
fn create_route_response(
&self,
input: CreateRouteResponseRequest,
) -> RusotoFuture<CreateRouteResponseResponse, CreateRouteResponseError> {
let request_uri = format!(
"/v2/apis/{api_id}/routes/{route_id}/routeresponses",
api_id = input.api_id,
route_id = input.route_id
);
let mut request = SignedRequest::new("POST", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
let encoded = Some(serde_json::to_vec(&input).unwrap());
request.set_payload(encoded);
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 201 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<CreateRouteResponseResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response.buffer().from_err().and_then(|response| {
Err(CreateRouteResponseError::from_response(response))
}),
)
}
})
}
/// <p>Creates a Stage for an API.</p>
fn create_stage(
&self,
input: CreateStageRequest,
) -> RusotoFuture<CreateStageResponse, CreateStageError> {
let request_uri = format!("/v2/apis/{api_id}/stages", api_id = input.api_id);
let mut request = SignedRequest::new("POST", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
let encoded = Some(serde_json::to_vec(&input).unwrap());
request.set_payload(encoded);
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 201 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<CreateStageResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(CreateStageError::from_response(response))),
)
}
})
}
/// <p>Deletes an Api resource.</p>
fn delete_api(&self, input: DeleteApiRequest) -> RusotoFuture<(), DeleteApiError> {
let request_uri = format!("/v2/apis/{api_id}", api_id = input.api_id);
let mut request = SignedRequest::new("DELETE", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 204 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = ::std::mem::drop(response);
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(DeleteApiError::from_response(response))),
)
}
})
}
/// <p>Deletes an API mapping.</p>
fn delete_api_mapping(
&self,
input: DeleteApiMappingRequest,
) -> RusotoFuture<(), DeleteApiMappingError> {
let request_uri = format!(
"/v2/domainnames/{domain_name}/apimappings/{api_mapping_id}",
api_mapping_id = input.api_mapping_id,
domain_name = input.domain_name
);
let mut request = SignedRequest::new("DELETE", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 204 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = ::std::mem::drop(response);
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(DeleteApiMappingError::from_response(response))),
)
}
})
}
/// <p>Deletes an Authorizer.</p>
fn delete_authorizer(
&self,
input: DeleteAuthorizerRequest,
) -> RusotoFuture<(), DeleteAuthorizerError> {
let request_uri = format!(
"/v2/apis/{api_id}/authorizers/{authorizer_id}",
api_id = input.api_id,
authorizer_id = input.authorizer_id
);
let mut request = SignedRequest::new("DELETE", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 204 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = ::std::mem::drop(response);
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(DeleteAuthorizerError::from_response(response))),
)
}
})
}
/// <p>Deletes a Deployment.</p>
fn delete_deployment(
&self,
input: DeleteDeploymentRequest,
) -> RusotoFuture<(), DeleteDeploymentError> {
let request_uri = format!(
"/v2/apis/{api_id}/deployments/{deployment_id}",
api_id = input.api_id,
deployment_id = input.deployment_id
);
let mut request = SignedRequest::new("DELETE", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 204 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = ::std::mem::drop(response);
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(DeleteDeploymentError::from_response(response))),
)
}
})
}
/// <p>Deletes a domain name.</p>
fn delete_domain_name(
&self,
input: DeleteDomainNameRequest,
) -> RusotoFuture<(), DeleteDomainNameError> {
let request_uri = format!(
"/v2/domainnames/{domain_name}",
domain_name = input.domain_name
);
let mut request = SignedRequest::new("DELETE", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 204 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = ::std::mem::drop(response);
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(DeleteDomainNameError::from_response(response))),
)
}
})
}
/// <p>Deletes an Integration.</p>
fn delete_integration(
&self,
input: DeleteIntegrationRequest,
) -> RusotoFuture<(), DeleteIntegrationError> {
let request_uri = format!(
"/v2/apis/{api_id}/integrations/{integration_id}",
api_id = input.api_id,
integration_id = input.integration_id
);
let mut request = SignedRequest::new("DELETE", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 204 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = ::std::mem::drop(response);
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(DeleteIntegrationError::from_response(response))),
)
}
})
}
/// <p>Deletes an IntegrationResponses.</p>
fn delete_integration_response(
&self,
input: DeleteIntegrationResponseRequest,
) -> RusotoFuture<(), DeleteIntegrationResponseError> {
let request_uri = format!("/v2/apis/{api_id}/integrations/{integration_id}/integrationresponses/{integration_response_id}", api_id = input.api_id, integration_id = input.integration_id, integration_response_id = input.integration_response_id);
let mut request = SignedRequest::new("DELETE", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 204 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = ::std::mem::drop(response);
Ok(result)
}))
} else {
Box::new(response.buffer().from_err().and_then(|response| {
Err(DeleteIntegrationResponseError::from_response(response))
}))
}
})
}
/// <p>Deletes a Model.</p>
fn delete_model(&self, input: DeleteModelRequest) -> RusotoFuture<(), DeleteModelError> {
let request_uri = format!(
"/v2/apis/{api_id}/models/{model_id}",
api_id = input.api_id,
model_id = input.model_id
);
let mut request = SignedRequest::new("DELETE", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 204 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = ::std::mem::drop(response);
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(DeleteModelError::from_response(response))),
)
}
})
}
/// <p>Deletes a Route.</p>
fn delete_route(&self, input: DeleteRouteRequest) -> RusotoFuture<(), DeleteRouteError> {
let request_uri = format!(
"/v2/apis/{api_id}/routes/{route_id}",
api_id = input.api_id,
route_id = input.route_id
);
let mut request = SignedRequest::new("DELETE", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 204 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = ::std::mem::drop(response);
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(DeleteRouteError::from_response(response))),
)
}
})
}
/// <p>Deletes a RouteResponse.</p>
fn delete_route_response(
&self,
input: DeleteRouteResponseRequest,
) -> RusotoFuture<(), DeleteRouteResponseError> {
let request_uri = format!(
"/v2/apis/{api_id}/routes/{route_id}/routeresponses/{route_response_id}",
api_id = input.api_id,
route_id = input.route_id,
route_response_id = input.route_response_id
);
let mut request = SignedRequest::new("DELETE", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 204 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = ::std::mem::drop(response);
Ok(result)
}))
} else {
Box::new(
response.buffer().from_err().and_then(|response| {
Err(DeleteRouteResponseError::from_response(response))
}),
)
}
})
}
/// <p>Deletes a Stage.</p>
fn delete_stage(&self, input: DeleteStageRequest) -> RusotoFuture<(), DeleteStageError> {
let request_uri = format!(
"/v2/apis/{api_id}/stages/{stage_name}",
api_id = input.api_id,
stage_name = input.stage_name
);
let mut request = SignedRequest::new("DELETE", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 204 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = ::std::mem::drop(response);
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(DeleteStageError::from_response(response))),
)
}
})
}
/// <p>Gets an Api resource.</p>
fn get_api(&self, input: GetApiRequest) -> RusotoFuture<GetApiResponse, GetApiError> {
let request_uri = format!("/v2/apis/{api_id}", api_id = input.api_id);
let mut request = SignedRequest::new("GET", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 200 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<GetApiResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(GetApiError::from_response(response))),
)
}
})
}
/// <p>The API mapping.</p>
fn get_api_mapping(
&self,
input: GetApiMappingRequest,
) -> RusotoFuture<GetApiMappingResponse, GetApiMappingError> {
let request_uri = format!(
"/v2/domainnames/{domain_name}/apimappings/{api_mapping_id}",
api_mapping_id = input.api_mapping_id,
domain_name = input.domain_name
);
let mut request = SignedRequest::new("GET", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 200 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<GetApiMappingResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(GetApiMappingError::from_response(response))),
)
}
})
}
/// <p>The API mappings.</p>
fn get_api_mappings(
&self,
input: GetApiMappingsRequest,
) -> RusotoFuture<GetApiMappingsResponse, GetApiMappingsError> {
let request_uri = format!(
"/v2/domainnames/{domain_name}/apimappings",
domain_name = input.domain_name
);
let mut request = SignedRequest::new("GET", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
let mut params = Params::new();
if let Some(ref x) = input.max_results {
params.put("maxResults", x);
}
if let Some(ref x) = input.next_token {
params.put("nextToken", x);
}
request.set_params(params);
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 200 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<GetApiMappingsResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(GetApiMappingsError::from_response(response))),
)
}
})
}
/// <p>Gets a collection of Api resources.</p>
fn get_apis(&self, input: GetApisRequest) -> RusotoFuture<GetApisResponse, GetApisError> {
let request_uri = "/v2/apis";
let mut request = SignedRequest::new("GET", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
let mut params = Params::new();
if let Some(ref x) = input.max_results {
params.put("maxResults", x);
}
if let Some(ref x) = input.next_token {
params.put("nextToken", x);
}
request.set_params(params);
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 200 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<GetApisResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(GetApisError::from_response(response))),
)
}
})
}
/// <p>Gets an Authorizer.</p>
fn get_authorizer(
&self,
input: GetAuthorizerRequest,
) -> RusotoFuture<GetAuthorizerResponse, GetAuthorizerError> {
let request_uri = format!(
"/v2/apis/{api_id}/authorizers/{authorizer_id}",
api_id = input.api_id,
authorizer_id = input.authorizer_id
);
let mut request = SignedRequest::new("GET", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 200 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<GetAuthorizerResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(GetAuthorizerError::from_response(response))),
)
}
})
}
/// <p>Gets the Authorizers for an API.</p>
fn get_authorizers(
&self,
input: GetAuthorizersRequest,
) -> RusotoFuture<GetAuthorizersResponse, GetAuthorizersError> {
let request_uri = format!("/v2/apis/{api_id}/authorizers", api_id = input.api_id);
let mut request = SignedRequest::new("GET", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
let mut params = Params::new();
if let Some(ref x) = input.max_results {
params.put("maxResults", x);
}
if let Some(ref x) = input.next_token {
params.put("nextToken", x);
}
request.set_params(params);
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 200 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<GetAuthorizersResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(GetAuthorizersError::from_response(response))),
)
}
})
}
/// <p>Gets a Deployment.</p>
fn get_deployment(
&self,
input: GetDeploymentRequest,
) -> RusotoFuture<GetDeploymentResponse, GetDeploymentError> {
let request_uri = format!(
"/v2/apis/{api_id}/deployments/{deployment_id}",
api_id = input.api_id,
deployment_id = input.deployment_id
);
let mut request = SignedRequest::new("GET", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 200 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<GetDeploymentResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(GetDeploymentError::from_response(response))),
)
}
})
}
/// <p>Gets the Deployments for an API.</p>
fn get_deployments(
&self,
input: GetDeploymentsRequest,
) -> RusotoFuture<GetDeploymentsResponse, GetDeploymentsError> {
let request_uri = format!("/v2/apis/{api_id}/deployments", api_id = input.api_id);
let mut request = SignedRequest::new("GET", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
let mut params = Params::new();
if let Some(ref x) = input.max_results {
params.put("maxResults", x);
}
if let Some(ref x) = input.next_token {
params.put("nextToken", x);
}
request.set_params(params);
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 200 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<GetDeploymentsResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(GetDeploymentsError::from_response(response))),
)
}
})
}
/// <p>Gets a domain name.</p>
fn get_domain_name(
&self,
input: GetDomainNameRequest,
) -> RusotoFuture<GetDomainNameResponse, GetDomainNameError> {
let request_uri = format!(
"/v2/domainnames/{domain_name}",
domain_name = input.domain_name
);
let mut request = SignedRequest::new("GET", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 200 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<GetDomainNameResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(GetDomainNameError::from_response(response))),
)
}
})
}
/// <p>Gets the domain names for an AWS account.</p>
fn get_domain_names(
&self,
input: GetDomainNamesRequest,
) -> RusotoFuture<GetDomainNamesResponse, GetDomainNamesError> {
let request_uri = "/v2/domainnames";
let mut request = SignedRequest::new("GET", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
let mut params = Params::new();
if let Some(ref x) = input.max_results {
params.put("maxResults", x);
}
if let Some(ref x) = input.next_token {
params.put("nextToken", x);
}
request.set_params(params);
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 200 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<GetDomainNamesResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(GetDomainNamesError::from_response(response))),
)
}
})
}
/// <p>Gets an Integration.</p>
fn get_integration(
&self,
input: GetIntegrationRequest,
) -> RusotoFuture<GetIntegrationResponse, GetIntegrationError> {
let request_uri = format!(
"/v2/apis/{api_id}/integrations/{integration_id}",
api_id = input.api_id,
integration_id = input.integration_id
);
let mut request = SignedRequest::new("GET", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 200 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<GetIntegrationResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(GetIntegrationError::from_response(response))),
)
}
})
}
/// <p>Gets an IntegrationResponses.</p>
fn get_integration_response(
&self,
input: GetIntegrationResponseRequest,
) -> RusotoFuture<GetIntegrationResponseResponse, GetIntegrationResponseError> {
let request_uri = format!("/v2/apis/{api_id}/integrations/{integration_id}/integrationresponses/{integration_response_id}", api_id = input.api_id, integration_id = input.integration_id, integration_response_id = input.integration_response_id);
let mut request = SignedRequest::new("GET", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 200 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<GetIntegrationResponseResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response.buffer().from_err().and_then(|response| {
Err(GetIntegrationResponseError::from_response(response))
}),
)
}
})
}
/// <p>Gets the IntegrationResponses for an Integration.</p>
fn get_integration_responses(
&self,
input: GetIntegrationResponsesRequest,
) -> RusotoFuture<GetIntegrationResponsesResponse, GetIntegrationResponsesError> {
let request_uri = format!(
"/v2/apis/{api_id}/integrations/{integration_id}/integrationresponses",
api_id = input.api_id,
integration_id = input.integration_id
);
let mut request = SignedRequest::new("GET", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
let mut params = Params::new();
if let Some(ref x) = input.max_results {
params.put("maxResults", x);
}
if let Some(ref x) = input.next_token {
params.put("nextToken", x);
}
request.set_params(params);
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 200 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<GetIntegrationResponsesResponse, _>()?;
Ok(result)
}))
} else {
Box::new(response.buffer().from_err().and_then(|response| {
Err(GetIntegrationResponsesError::from_response(response))
}))
}
})
}
/// <p>Gets the Integrations for an API.</p>
fn get_integrations(
&self,
input: GetIntegrationsRequest,
) -> RusotoFuture<GetIntegrationsResponse, GetIntegrationsError> {
let request_uri = format!("/v2/apis/{api_id}/integrations", api_id = input.api_id);
let mut request = SignedRequest::new("GET", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
let mut params = Params::new();
if let Some(ref x) = input.max_results {
params.put("maxResults", x);
}
if let Some(ref x) = input.next_token {
params.put("nextToken", x);
}
request.set_params(params);
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 200 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<GetIntegrationsResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(GetIntegrationsError::from_response(response))),
)
}
})
}
/// <p>Gets a Model.</p>
fn get_model(&self, input: GetModelRequest) -> RusotoFuture<GetModelResponse, GetModelError> {
let request_uri = format!(
"/v2/apis/{api_id}/models/{model_id}",
api_id = input.api_id,
model_id = input.model_id
);
let mut request = SignedRequest::new("GET", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 200 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<GetModelResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(GetModelError::from_response(response))),
)
}
})
}
/// <p>Gets a model template.</p>
fn get_model_template(
&self,
input: GetModelTemplateRequest,
) -> RusotoFuture<GetModelTemplateResponse, GetModelTemplateError> {
let request_uri = format!(
"/v2/apis/{api_id}/models/{model_id}/template",
api_id = input.api_id,
model_id = input.model_id
);
let mut request = SignedRequest::new("GET", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 200 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<GetModelTemplateResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(GetModelTemplateError::from_response(response))),
)
}
})
}
/// <p>Gets the Models for an API.</p>
fn get_models(
&self,
input: GetModelsRequest,
) -> RusotoFuture<GetModelsResponse, GetModelsError> {
let request_uri = format!("/v2/apis/{api_id}/models", api_id = input.api_id);
let mut request = SignedRequest::new("GET", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
let mut params = Params::new();
if let Some(ref x) = input.max_results {
params.put("maxResults", x);
}
if let Some(ref x) = input.next_token {
params.put("nextToken", x);
}
request.set_params(params);
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 200 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<GetModelsResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(GetModelsError::from_response(response))),
)
}
})
}
/// <p>Gets a Route.</p>
fn get_route(&self, input: GetRouteRequest) -> RusotoFuture<GetRouteResponse, GetRouteError> {
let request_uri = format!(
"/v2/apis/{api_id}/routes/{route_id}",
api_id = input.api_id,
route_id = input.route_id
);
let mut request = SignedRequest::new("GET", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 200 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<GetRouteResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(GetRouteError::from_response(response))),
)
}
})
}
/// <p>Gets a RouteResponse.</p>
fn get_route_response(
&self,
input: GetRouteResponseRequest,
) -> RusotoFuture<GetRouteResponseResponse, GetRouteResponseError> {
let request_uri = format!(
"/v2/apis/{api_id}/routes/{route_id}/routeresponses/{route_response_id}",
api_id = input.api_id,
route_id = input.route_id,
route_response_id = input.route_response_id
);
let mut request = SignedRequest::new("GET", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 200 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<GetRouteResponseResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(GetRouteResponseError::from_response(response))),
)
}
})
}
/// <p>Gets the RouteResponses for a Route.</p>
fn get_route_responses(
&self,
input: GetRouteResponsesRequest,
) -> RusotoFuture<GetRouteResponsesResponse, GetRouteResponsesError> {
let request_uri = format!(
"/v2/apis/{api_id}/routes/{route_id}/routeresponses",
api_id = input.api_id,
route_id = input.route_id
);
let mut request = SignedRequest::new("GET", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
let mut params = Params::new();
if let Some(ref x) = input.max_results {
params.put("maxResults", x);
}
if let Some(ref x) = input.next_token {
params.put("nextToken", x);
}
request.set_params(params);
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 200 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<GetRouteResponsesResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(GetRouteResponsesError::from_response(response))),
)
}
})
}
/// <p>Gets the Routes for an API.</p>
fn get_routes(
&self,
input: GetRoutesRequest,
) -> RusotoFuture<GetRoutesResponse, GetRoutesError> {
let request_uri = format!("/v2/apis/{api_id}/routes", api_id = input.api_id);
let mut request = SignedRequest::new("GET", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
let mut params = Params::new();
if let Some(ref x) = input.max_results {
params.put("maxResults", x);
}
if let Some(ref x) = input.next_token {
params.put("nextToken", x);
}
request.set_params(params);
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 200 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<GetRoutesResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(GetRoutesError::from_response(response))),
)
}
})
}
/// <p>Gets a Stage.</p>
fn get_stage(&self, input: GetStageRequest) -> RusotoFuture<GetStageResponse, GetStageError> {
let request_uri = format!(
"/v2/apis/{api_id}/stages/{stage_name}",
api_id = input.api_id,
stage_name = input.stage_name
);
let mut request = SignedRequest::new("GET", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 200 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<GetStageResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(GetStageError::from_response(response))),
)
}
})
}
/// <p>Gets the Stages for an API.</p>
fn get_stages(
&self,
input: GetStagesRequest,
) -> RusotoFuture<GetStagesResponse, GetStagesError> {
let request_uri = format!("/v2/apis/{api_id}/stages", api_id = input.api_id);
let mut request = SignedRequest::new("GET", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
let mut params = Params::new();
if let Some(ref x) = input.max_results {
params.put("maxResults", x);
}
if let Some(ref x) = input.next_token {
params.put("nextToken", x);
}
request.set_params(params);
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 200 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<GetStagesResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(GetStagesError::from_response(response))),
)
}
})
}
/// <p>Updates an Api resource.</p>
fn update_api(
&self,
input: UpdateApiRequest,
) -> RusotoFuture<UpdateApiResponse, UpdateApiError> {
let request_uri = format!("/v2/apis/{api_id}", api_id = input.api_id);
let mut request = SignedRequest::new("PATCH", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
let encoded = Some(serde_json::to_vec(&input).unwrap());
request.set_payload(encoded);
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 200 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<UpdateApiResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(UpdateApiError::from_response(response))),
)
}
})
}
/// <p>The API mapping.</p>
fn update_api_mapping(
&self,
input: UpdateApiMappingRequest,
) -> RusotoFuture<UpdateApiMappingResponse, UpdateApiMappingError> {
let request_uri = format!(
"/v2/domainnames/{domain_name}/apimappings/{api_mapping_id}",
api_mapping_id = input.api_mapping_id,
domain_name = input.domain_name
);
let mut request = SignedRequest::new("PATCH", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
let encoded = Some(serde_json::to_vec(&input).unwrap());
request.set_payload(encoded);
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 200 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<UpdateApiMappingResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(UpdateApiMappingError::from_response(response))),
)
}
})
}
/// <p>Updates an Authorizer.</p>
fn update_authorizer(
&self,
input: UpdateAuthorizerRequest,
) -> RusotoFuture<UpdateAuthorizerResponse, UpdateAuthorizerError> {
let request_uri = format!(
"/v2/apis/{api_id}/authorizers/{authorizer_id}",
api_id = input.api_id,
authorizer_id = input.authorizer_id
);
let mut request = SignedRequest::new("PATCH", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
let encoded = Some(serde_json::to_vec(&input).unwrap());
request.set_payload(encoded);
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 200 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<UpdateAuthorizerResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(UpdateAuthorizerError::from_response(response))),
)
}
})
}
/// <p>Updates a Deployment.</p>
fn update_deployment(
&self,
input: UpdateDeploymentRequest,
) -> RusotoFuture<UpdateDeploymentResponse, UpdateDeploymentError> {
let request_uri = format!(
"/v2/apis/{api_id}/deployments/{deployment_id}",
api_id = input.api_id,
deployment_id = input.deployment_id
);
let mut request = SignedRequest::new("PATCH", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
let encoded = Some(serde_json::to_vec(&input).unwrap());
request.set_payload(encoded);
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 200 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<UpdateDeploymentResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(UpdateDeploymentError::from_response(response))),
)
}
})
}
/// <p>Updates a domain name.</p>
fn update_domain_name(
&self,
input: UpdateDomainNameRequest,
) -> RusotoFuture<UpdateDomainNameResponse, UpdateDomainNameError> {
let request_uri = format!(
"/v2/domainnames/{domain_name}",
domain_name = input.domain_name
);
let mut request = SignedRequest::new("PATCH", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
let encoded = Some(serde_json::to_vec(&input).unwrap());
request.set_payload(encoded);
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 200 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<UpdateDomainNameResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(UpdateDomainNameError::from_response(response))),
)
}
})
}
/// <p>Updates an Integration.</p>
fn update_integration(
&self,
input: UpdateIntegrationRequest,
) -> RusotoFuture<UpdateIntegrationResponse, UpdateIntegrationError> {
let request_uri = format!(
"/v2/apis/{api_id}/integrations/{integration_id}",
api_id = input.api_id,
integration_id = input.integration_id
);
let mut request = SignedRequest::new("PATCH", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
let encoded = Some(serde_json::to_vec(&input).unwrap());
request.set_payload(encoded);
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 200 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<UpdateIntegrationResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(UpdateIntegrationError::from_response(response))),
)
}
})
}
/// <p>Updates an IntegrationResponses.</p>
fn update_integration_response(
&self,
input: UpdateIntegrationResponseRequest,
) -> RusotoFuture<UpdateIntegrationResponseResponse, UpdateIntegrationResponseError> {
let request_uri = format!("/v2/apis/{api_id}/integrations/{integration_id}/integrationresponses/{integration_response_id}", api_id = input.api_id, integration_id = input.integration_id, integration_response_id = input.integration_response_id);
let mut request = SignedRequest::new("PATCH", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
let encoded = Some(serde_json::to_vec(&input).unwrap());
request.set_payload(encoded);
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 200 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<UpdateIntegrationResponseResponse, _>()?;
Ok(result)
}))
} else {
Box::new(response.buffer().from_err().and_then(|response| {
Err(UpdateIntegrationResponseError::from_response(response))
}))
}
})
}
/// <p>Updates a Model.</p>
fn update_model(
&self,
input: UpdateModelRequest,
) -> RusotoFuture<UpdateModelResponse, UpdateModelError> {
let request_uri = format!(
"/v2/apis/{api_id}/models/{model_id}",
api_id = input.api_id,
model_id = input.model_id
);
let mut request = SignedRequest::new("PATCH", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
let encoded = Some(serde_json::to_vec(&input).unwrap());
request.set_payload(encoded);
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 200 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<UpdateModelResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(UpdateModelError::from_response(response))),
)
}
})
}
/// <p>Updates a Route.</p>
fn update_route(
&self,
input: UpdateRouteRequest,
) -> RusotoFuture<UpdateRouteResponse, UpdateRouteError> {
let request_uri = format!(
"/v2/apis/{api_id}/routes/{route_id}",
api_id = input.api_id,
route_id = input.route_id
);
let mut request = SignedRequest::new("PATCH", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
let encoded = Some(serde_json::to_vec(&input).unwrap());
request.set_payload(encoded);
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 200 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<UpdateRouteResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(UpdateRouteError::from_response(response))),
)
}
})
}
/// <p>Updates a RouteResponse.</p>
fn update_route_response(
&self,
input: UpdateRouteResponseRequest,
) -> RusotoFuture<UpdateRouteResponseResponse, UpdateRouteResponseError> {
let request_uri = format!(
"/v2/apis/{api_id}/routes/{route_id}/routeresponses/{route_response_id}",
api_id = input.api_id,
route_id = input.route_id,
route_response_id = input.route_response_id
);
let mut request = SignedRequest::new("PATCH", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
let encoded = Some(serde_json::to_vec(&input).unwrap());
request.set_payload(encoded);
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 200 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<UpdateRouteResponseResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response.buffer().from_err().and_then(|response| {
Err(UpdateRouteResponseError::from_response(response))
}),
)
}
})
}
/// <p>Updates a Stage.</p>
fn update_stage(
&self,
input: UpdateStageRequest,
) -> RusotoFuture<UpdateStageResponse, UpdateStageError> {
let request_uri = format!(
"/v2/apis/{api_id}/stages/{stage_name}",
api_id = input.api_id,
stage_name = input.stage_name
);
let mut request = SignedRequest::new("PATCH", "apigateway", &self.region, &request_uri);
request.set_content_type("application/x-amz-json-1.1".to_owned());
let encoded = Some(serde_json::to_vec(&input).unwrap());
request.set_payload(encoded);
self.client.sign_and_dispatch(request, |response| {
if response.status.as_u16() == 200 {
Box::new(response.buffer().from_err().and_then(|response| {
let result = proto::json::ResponsePayload::new(&response)
.deserialize::<UpdateStageResponse, _>()?;
Ok(result)
}))
} else {
Box::new(
response
.buffer()
.from_err()
.and_then(|response| Err(UpdateStageError::from_response(response))),
)
}
})
}
} | #[serde(skip_serializing_if = "Option::is_none")]
pub api_mapping_selection_expression: Option<String>,
/// <p>The name of the DomainName resource.</p>
#[serde(rename = "DomainName")] |
lib.rs | // Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
pub use vm_fdt::{Error as FdtError, FdtWriter};
use vm_memory::{
guest_memory::Error as GuestMemoryError, Bytes, GuestAddress, GuestMemory, GuestMemoryRegion,
};
// This is an arbitrary number to specify the node for the GIC.
// If we had a more complex interrupt architecture, then we'd need an enum for
// these.
const PHANDLE_GIC: u32 = 1;
pub const AARCH64_FDT_MAX_SIZE: u64 = 0x200000;
// This indicates the start of DRAM inside the physical address space.
pub const AARCH64_PHYS_MEM_START: u64 = 0x80000000;
// This is the base address of MMIO devices.
pub const AARCH64_MMIO_BASE: u64 = 1 << 30;
const AARCH64_AXI_BASE: u64 = 0x40000000;
// These constants indicate the address space used by the ARM vGIC.
const AARCH64_GIC_DIST_SIZE: u64 = 0x10000;
const AARCH64_GIC_CPUI_SIZE: u64 = 0x20000;
// This is the minimum number of SPI interrupts aligned to 32 + 32 for the
// PPI (16) and GSI (16).
pub const AARCH64_GIC_NR_IRQS: u32 = 64;
// These constants indicate the placement of the GIC registers in the physical
// address space.
pub const AARCH64_GIC_DIST_BASE: u64 = AARCH64_AXI_BASE - AARCH64_GIC_DIST_SIZE;
pub const AARCH64_GIC_CPUI_BASE: u64 = AARCH64_GIC_DIST_BASE - AARCH64_GIC_CPUI_SIZE;
pub const AARCH64_GIC_REDIST_SIZE: u64 = 0x20000;
// These are specified by the Linux GIC bindings
const GIC_FDT_IRQ_NUM_CELLS: u32 = 3;
const GIC_FDT_IRQ_TYPE_SPI: u32 = 0;
const GIC_FDT_IRQ_TYPE_PPI: u32 = 1;
const GIC_FDT_IRQ_PPI_CPU_SHIFT: u32 = 8;
const GIC_FDT_IRQ_PPI_CPU_MASK: u32 = 0xff << GIC_FDT_IRQ_PPI_CPU_SHIFT;
const IRQ_TYPE_EDGE_RISING: u32 = 0x00000001;
const IRQ_TYPE_LEVEL_HIGH: u32 = 0x00000004;
const IRQ_TYPE_LEVEL_LOW: u32 = 0x00000008;
// PMU PPI interrupt, same as qemu
const AARCH64_PMU_IRQ: u32 = 7;
#[derive(Debug)]
pub enum Error {
Fdt(FdtError),
Memory(GuestMemoryError),
}
impl From<FdtError> for Error {
fn from(inner: FdtError) -> Self {
Error::Fdt(inner)
}
}
impl From<GuestMemoryError> for Error {
fn from(inner: GuestMemoryError) -> Self {
Error::Memory(inner)
}
}
pub type Result<T> = std::result::Result<T, Error>;
pub fn create_fdt<T: GuestMemory>(
cmdline: &str,
num_vcpus: u32,
guest_mem: &T,
fdt_load_offset: u64,
) -> Result<()> {
let mut fdt = FdtWriter::new()?;
// The whole thing is put into one giant node with s
// ome top level properties
let root_node = fdt.begin_node("")?;
fdt.property_u32("interrupt-parent", PHANDLE_GIC)?;
fdt.property_string("compatible", "linux,dummy-virt")?;
fdt.property_u32("#address-cells", 0x2)?;
fdt.property_u32("#size-cells", 0x2)?;
create_chosen_node(&mut fdt, cmdline)?;
let mem_size: u64 = guest_mem.iter().map(|region| region.len() as u64).sum();
create_memory_node(&mut fdt, mem_size)?;
create_cpu_nodes(&mut fdt, num_vcpus)?;
create_gic_node(&mut fdt, true, num_vcpus as u64)?;
create_serial_node(&mut fdt)?;
create_rtc_node(&mut fdt)?;
create_timer_node(&mut fdt, num_vcpus)?;
create_psci_node(&mut fdt)?;
create_pmu_node(&mut fdt, num_vcpus)?;
fdt.end_node(root_node)?;
let fdt_final = fdt.finish()?;
let fdt_address = GuestAddress(AARCH64_PHYS_MEM_START + fdt_load_offset);
guest_mem.write_slice(fdt_final.as_slice(), fdt_address)?;
Ok(())
}
fn create_chosen_node(fdt: &mut FdtWriter, cmdline: &str) -> Result<()> {
let chosen_node = fdt.begin_node("chosen")?;
fdt.property_string("bootargs", cmdline)?;
fdt.end_node(chosen_node)?;
Ok(())
}
fn create_memory_node(fdt: &mut FdtWriter, mem_size: u64) -> Result<()> {
let mem_reg_prop = [AARCH64_PHYS_MEM_START, mem_size];
let memory_node = fdt.begin_node("memory")?;
fdt.property_string("device_type", "memory")?;
fdt.property_array_u64("reg", &mem_reg_prop)?;
fdt.end_node(memory_node)?;
Ok(())
}
fn create_cpu_nodes(fdt: &mut FdtWriter, num_cpus: u32) -> Result<()> {
let cpus_node = fdt.begin_node("cpus")?;
fdt.property_u32("#address-cells", 0x1)?;
fdt.property_u32("#size-cells", 0x0)?;
for cpu_id in 0..num_cpus {
let cpu_name = format!("cpu@{:x}", cpu_id);
let cpu_node = fdt.begin_node(&cpu_name)?;
fdt.property_string("device_type", "cpu")?;
fdt.property_string("compatible", "arm,arm-v8")?;
fdt.property_string("enable-method", "psci")?;
fdt.property_u32("reg", cpu_id)?;
fdt.end_node(cpu_node)?;
}
fdt.end_node(cpus_node)?;
Ok(())
}
fn create_gic_node(fdt: &mut FdtWriter, is_gicv3: bool, num_cpus: u64) -> Result<()> {
let mut gic_reg_prop = [AARCH64_GIC_DIST_BASE, AARCH64_GIC_DIST_SIZE, 0, 0];
let intc_node = fdt.begin_node("intc")?;
if is_gicv3 {
fdt.property_string("compatible", "arm,gic-v3")?;
gic_reg_prop[2] = AARCH64_GIC_DIST_BASE - (AARCH64_GIC_REDIST_SIZE * num_cpus);
gic_reg_prop[3] = AARCH64_GIC_REDIST_SIZE * num_cpus;
} else {
fdt.property_string("compatible", "arm,cortex-a15-gic")?;
gic_reg_prop[2] = AARCH64_GIC_CPUI_BASE;
gic_reg_prop[3] = AARCH64_GIC_CPUI_SIZE;
}
fdt.property_u32("#interrupt-cells", GIC_FDT_IRQ_NUM_CELLS)?;
fdt.property_null("interrupt-controller")?;
fdt.property_array_u64("reg", &gic_reg_prop)?;
fdt.property_phandle(PHANDLE_GIC)?;
fdt.property_u32("#address-cells", 2)?;
fdt.property_u32("#size-cells", 2)?;
fdt.end_node(intc_node)?;
Ok(())
}
fn create_psci_node(fdt: &mut FdtWriter) -> Result<()> {
let compatible = "arm,psci-0.2";
let psci_node = fdt.begin_node("psci")?;
fdt.property_string("compatible", compatible)?;
// Two methods available: hvc and smc.
// As per documentation, PSCI calls between a guest and hypervisor may use the HVC conduit instead of SMC.
// So, since we are using kvm, we need to use hvc.
fdt.property_string("method", "hvc")?;
fdt.end_node(psci_node)?;
Ok(())
}
fn create_serial_node(fdt: &mut FdtWriter) -> Result<()> {
let addr = 0x40000000;
let serial_node = fdt.begin_node(&format!("uart@{:x}", addr))?;
fdt.property_string("compatible", "ns16550a")?;
let serial_reg_prop = [addr, 0x1000];
fdt.property_array_u64("reg", &serial_reg_prop)?;
// fdt.property_u32("clock-frequency", AARCH64_SERIAL_SPEED)?;
const CLK_PHANDLE: u32 = 24;
fdt.property_u32("clocks", CLK_PHANDLE)?;
fdt.property_string("clock-names", "apb_pclk")?;
let irq = [GIC_FDT_IRQ_TYPE_SPI, 4, IRQ_TYPE_EDGE_RISING];
fdt.property_array_u32("interrupts", &irq)?;
fdt.end_node(serial_node)?;
Ok(())
}
fn create_timer_node(fdt: &mut FdtWriter, num_cpus: u32) -> Result<()> {
// These are fixed interrupt numbers for the timer device.
let irqs = [13, 14, 11, 10];
let compatible = "arm,armv8-timer";
let cpu_mask: u32 =
(((1 << num_cpus) - 1) << GIC_FDT_IRQ_PPI_CPU_SHIFT) & GIC_FDT_IRQ_PPI_CPU_MASK;
let mut timer_reg_cells = Vec::new();
for &irq in &irqs {
timer_reg_cells.push(GIC_FDT_IRQ_TYPE_PPI);
timer_reg_cells.push(irq);
timer_reg_cells.push(cpu_mask | IRQ_TYPE_LEVEL_LOW);
}
let timer_node = fdt.begin_node("timer")?;
fdt.property_string("compatible", compatible)?;
fdt.property_array_u32("interrupts", &timer_reg_cells)?;
fdt.property_null("always-on")?;
fdt.end_node(timer_node)?;
Ok(())
}
fn create_pmu_node(fdt: &mut FdtWriter, num_cpus: u32) -> Result<()> {
let compatible = "arm,armv8-pmuv3";
let cpu_mask: u32 =
(((1 << num_cpus) - 1) << GIC_FDT_IRQ_PPI_CPU_SHIFT) & GIC_FDT_IRQ_PPI_CPU_MASK;
let irq = [
GIC_FDT_IRQ_TYPE_PPI,
AARCH64_PMU_IRQ,
cpu_mask | IRQ_TYPE_LEVEL_HIGH,
];
let pmu_node = fdt.begin_node("pmu")?;
fdt.property_string("compatible", compatible)?;
fdt.property_array_u32("interrupts", &irq)?;
fdt.end_node(pmu_node)?;
Ok(())
}
fn | (fdt: &mut FdtWriter) -> Result<()> {
// the kernel driver for pl030 really really wants a clock node
// associated with an AMBA device or it will fail to probe, so we
// need to make up a clock node to associate with the pl030 rtc
// node and an associated handle with a unique phandle value.
const CLK_PHANDLE: u32 = 24;
let clock_node = fdt.begin_node("apb-pclk")?;
fdt.property_u32("#clock-cells", 0)?;
fdt.property_string("compatible", "fixed-clock")?;
fdt.property_u32("clock-frequency", 24_000_000)?;
fdt.property_string("clock-output-names", "clk24mhz")?;
fdt.property_phandle(CLK_PHANDLE)?;
fdt.end_node(clock_node)?;
let rtc_addr = 0x40001000;
let rtc_name = format!("rtc@{:x}", rtc_addr);
let reg = [rtc_addr, 0x1000];
let irq = [GIC_FDT_IRQ_TYPE_SPI, 33, IRQ_TYPE_LEVEL_HIGH];
let rtc_node = fdt.begin_node(&rtc_name)?;
fdt.property_string_list(
"compatible",
vec![String::from("arm,pl031"), String::from("arm,primecell")],
)?;
// const PL030_AMBA_ID: u32 = 0x00041030;
// fdt.property_string("arm,pl031", PL030_AMBA_ID)?;
fdt.property_array_u64("reg", ®)?;
fdt.property_array_u32("interrupts", &irq)?;
fdt.property_u32("clocks", CLK_PHANDLE)?;
fdt.property_string("clock-names", "apb_pclk")?;
fdt.end_node(rtc_node)?;
Ok(())
}
| create_rtc_node |
token.go | package token
import "fmt"
type Pos int
func (p Pos) String() string {
return fmt.Sprint(p)
}
type Type int
const (
T_Unknown Type = 0 | T_Right_P // )
T_Number // [0-9]+
T_String //
T_Ident // others
)
type Token interface {
Type() Type
Pos() Pos
String() string // <token:%pos:%type:%details>
}
type NumberToken struct {
pos Pos
number string
}
func Number(pos Pos, num string) NumberToken {
return NumberToken{
pos: pos,
number: num,
}
}
func (t *NumberToken) Type() Type {
return T_Number
}
func (t *NumberToken) Pos() Pos {
return t.pos
}
func (t *NumberToken) Number() string {
return t.number
}
func (t *NumberToken) String() string {
return fmt.Sprintf("<token:%s:number: %s>", t.Pos, t.number)
} | T_Left_P // ( |
tests.rs | // Copyright 2017 Parity Technologies (UK) Ltd.
// Copyright 2020 Netwarps Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//! Contains the unit tests of the library.
#![cfg(test)]
use super::negotiator::Negotiator;
use super::{NegotiationError, ReadEx, Version, WriteEx};
use async_trait::async_trait;
use bytes::Bytes;
use futures::channel::mpsc;
use futures::prelude::*;
use libp2prs_runtime::{
net::{TcpListener, TcpStream},
task,
};
use std::io;
#[derive(Debug)]
pub struct Memory<T> {
tx: mpsc::Sender<T>,
rx: mpsc::Receiver<T>,
recv_drian: Option<T>,
}
impl Memory<Bytes> {
pub fn pair() -> (Self, Self) {
let (tx1, rx1) = mpsc::channel(1);
let (tx2, rx2) = mpsc::channel(1);
(
Memory {
tx: tx1,
rx: rx2,
recv_drian: None,
},
Memory {
tx: tx2,
rx: rx1,
recv_drian: None,
},
)
}
fn drain(&mut self, buf: &mut [u8]) -> Option<usize> {
if let Some(b) = &mut self.recv_drian {
// calculate number of bytes that we can copy
let n = ::std::cmp::min(buf.len(), b.len());
if n == 0 {
return None;
}
buf[..n].copy_from_slice(b[..n].as_ref());
*b = b.split_off(n);
Some(n)
} else {
None
}
}
}
#[async_trait]
impl ReadEx for Memory<Bytes> {
async fn read2(&mut self, buf: &mut [u8]) -> io::Result<usize> {
if let Some(n) = self.drain(buf) {
return Ok(n);
}
let b = self.rx.next().await.expect("recv next");
self.recv_drian.replace(b);
Ok(self.drain(buf).expect("must be Some(n)"))
}
}
#[async_trait]
impl WriteEx for Memory<Bytes> {
async fn write2(&mut self, buf: &[u8]) -> io::Result<usize> {
log::debug!("write data: {:?}", buf);
self.tx
.send(Bytes::copy_from_slice(buf))
.await
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
Ok(buf.len())
}
async fn flush2(&mut self) -> io::Result<()> {
Ok(())
}
async fn close2(&mut self) -> io::Result<()> {
Ok(())
}
}
#[test]
fn select_proto_basic() {
async fn run(_version: Version) {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let listener_addr = listener.local_addr().unwrap();
let server = task::spawn(async move {
let connec = listener.accept().await.unwrap().0;
let protos = vec!["/proto11", "/proto2"];
let neg = Negotiator::new_with_protocols(protos);
let (proto, mut io) = neg.negotiate(connec).await.expect("negotiate");
assert_eq!(proto, "/proto2");
let mut out = vec![0; 32];
let n = io.read(&mut out).await.unwrap();
out.truncate(n);
assert_eq!(out, b"ping");
io.write_all(b"pong").await.unwrap();
io.flush().await.unwrap();
});
let client = task::spawn(async move {
let connec = TcpStream::connect(&listener_addr).await.unwrap();
let protos = vec!["/proto31", "/proto2"];
let neg = Negotiator::new_with_protocols(protos);
let (proto, mut io) = neg.select_one(connec).await.expect("select_one");
assert_eq!(proto, "/proto2");
io.write_all(b"ping").await.unwrap();
io.flush().await.unwrap();
let mut out = vec![0; 32];
let n = io.read(&mut out).await.unwrap();
out.truncate(n);
assert_eq!(out, b"pong");
});
server.await;
client.await;
}
task::block_on(run(Version::V1));
}
#[test]
fn no_protocol_found() {
async fn run(_version: Version) |
task::block_on(run(Version::V1));
}
#[test]
fn select_proto_serial() {
async fn run(_version: Version) {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let listener_addr = listener.local_addr().unwrap();
let server = task::spawn(async move {
let connec = listener.accept().await.unwrap().0;
let protos = vec![b"/proto1", b"/proto2"];
let neg = Negotiator::new_with_protocols(protos);
let (proto, _) = neg.negotiate(connec).await.expect("negotiate");
assert_eq!(proto, b"/proto2");
});
let client = task::spawn(async move {
let connec = TcpStream::connect(&listener_addr).await.unwrap();
let protos = vec![b"/proto3", b"/proto2"];
let neg = Negotiator::new_with_protocols(protos);
let (proto, _) = neg.select_one(connec).await.expect("select_one");
assert_eq!(proto, b"/proto2");
});
server.await;
client.await;
}
task::block_on(run(Version::V1));
}
| {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let listener_addr = listener.local_addr().unwrap();
let server = task::spawn(async move {
let connec = listener.accept().await.unwrap().0;
let protos = vec![b"/proto1", b"/proto2"];
let neg = Negotiator::new_with_protocols(protos);
// We don't explicitly check for `Failed` because the client might close the connection when it
// realizes that we have no protocol in common.
assert!(neg.negotiate(connec).await.is_err());
});
let client = task::spawn(async move {
let connec = TcpStream::connect(&listener_addr).await.unwrap();
let protos = vec![b"/proto3", b"/proto4"];
let neg = Negotiator::new_with_protocols(protos);
match neg.select_one(connec).await {
Err(NegotiationError::Failed(_)) => {}
Ok(_) => {}
Err(_) => panic!(),
}
});
server.await;
client.await;
} |
context.go | // Copyright 2018 PingCAP, 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package sessionctx
import (
"context"
"fmt"
"github.com/pingcap/parser/ast"
"github.com/pingcap/parser/model"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/owner"
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/util"
"github.com/pingcap/tidb/util/kvcache"
"github.com/pingcap/tipb/go-binlog"
)
// Context is an interface for transaction and executive args environment.
type Context interface {
// NewTxn creates a new transaction for further execution.
// If old transaction is valid, it is committed first.
// It's used in BEGIN statement and DDL statements to commit old transaction.
NewTxn(context.Context) error
// Txn returns the current transaction which is created before executing a statement.
// The returned kv.Transaction is not nil, but it maybe pending or invalid.
// If the active parameter is true, call this function will wait for the pending txn
// to become valid.
Txn(active bool) (kv.Transaction, error)
// GetClient gets a kv.Client.
GetClient() kv.Client
// GetClient gets a kv.Client.
GetMPPClient() kv.MPPClient
// SetValue saves a value associated with this context for key.
SetValue(key fmt.Stringer, value interface{})
// Value returns the value associated with this context for key.
Value(key fmt.Stringer) interface{}
// ClearValue clears the value associated with this context for key.
ClearValue(key fmt.Stringer)
GetSessionVars() *variable.SessionVars
GetSessionManager() util.SessionManager
// RefreshTxnCtx commits old transaction without retry,
// and creates a new transaction.
// now just for load data and batch insert.
RefreshTxnCtx(context.Context) error
// RefreshVars refreshes modified global variable to current session.
// only used to daemon session like `statsHandle` to detect global variable change.
RefreshVars(context.Context) error
// InitTxnWithStartTS initializes a transaction with startTS.
// It should be called right before we builds an executor.
InitTxnWithStartTS(startTS uint64) error
// NewTxnWithStalenessOption initializes a transaction with StalenessTxnOption
NewTxnWithStalenessOption(ctx context.Context, option StalenessTxnOption) error
// GetStore returns the store of session.
GetStore() kv.Storage
// PreparedPlanCache returns the cache of the physical plan
PreparedPlanCache() *kvcache.SimpleLRUCache
// StoreQueryFeedback stores the query feedback.
StoreQueryFeedback(feedback interface{})
// HasDirtyContent checks whether there's dirty update on the given table.
HasDirtyContent(tid int64) bool
// StmtCommit flush all changes by the statement to the underlying transaction.
StmtCommit()
// StmtRollback provides statement level rollback.
StmtRollback()
// StmtGetMutation gets the binlog mutation for current statement.
StmtGetMutation(int64) *binlog.TableMutation
// DDLOwnerChecker returns owner.DDLOwnerChecker.
DDLOwnerChecker() owner.DDLOwnerChecker
// AddTableLock adds table lock to the session lock map.
AddTableLock([]model.TableLockTpInfo)
// ReleaseTableLocks releases table locks in the session lock map.
ReleaseTableLocks(locks []model.TableLockTpInfo)
// ReleaseTableLockByTableID releases table locks in the session lock map by table ID.
ReleaseTableLockByTableIDs(tableIDs []int64)
// CheckTableLocked checks the table lock.
CheckTableLocked(tblID int64) (bool, model.TableLockType)
// GetAllTableLocks gets all table locks table id and db id hold by the session.
GetAllTableLocks() []model.TableLockTpInfo
// ReleaseAllTableLocks releases all table locks hold by the session.
ReleaseAllTableLocks()
// HasLockedTables uses to check whether this session locked any tables.
HasLockedTables() bool
// PrepareTSFuture uses to prepare timestamp by future.
PrepareTSFuture(ctx context.Context)
// StoreIndexUsage stores the index usage information.
StoreIndexUsage(tblID int64, idxID int64, rowsSelected int64)
}
type basicCtxType int
func (t basicCtxType) String() string {
switch t {
case QueryString:
return "query_string"
case Initing:
return "initing"
case LastExecuteDDL:
return "last_execute_ddl"
}
return "unknown"
}
// Context keys.
const (
// QueryString is the key for original query string.
QueryString basicCtxType = 1
// Initing is the key for indicating if the server is running bootstrap or upgrade job.
Initing basicCtxType = 2
// LastExecuteDDL is the key for whether the session execute a ddl command last time.
LastExecuteDDL basicCtxType = 3
)
type connIDCtxKeyType struct{}
// ConnID is the key in context.
var ConnID = connIDCtxKeyType{}
// SetCommitCtx sets connection id into context
func SetCommitCtx(ctx context.Context, sessCtx Context) context.Context |
// StalenessTxnOption represents available options for the InitTxnWithStaleness
type StalenessTxnOption struct {
Mode ast.TimestampBoundMode
PrevSec uint64
StartTS uint64
}
| {
return context.WithValue(ctx, ConnID, sessCtx.GetSessionVars().ConnectionID)
} |
affine.rs | use nalgebra::{Matrix3, Matrix4, Scalar, Vector3, U3};
#[cfg(feature = "nifti_images")]
use nifti::NiftiHeader;
#[cfg(feature = "nifti_images")]
use crate::{Affine4, CHeader};
| T: Copy + Scalar,
{
let translation = Vector3::<T>::new(affine[12], affine[13], affine[14]);
let affine = affine.fixed_slice::<U3, U3>(0, 0).into_owned();
(affine, translation)
}
#[cfg(feature = "nifti_images")]
pub fn rasmm_to_trackvis(h: &NiftiHeader) -> Affine4 {
trackvis_to_rasmm(h).try_inverse().unwrap()
}
#[cfg(feature = "nifti_images")]
pub fn trackvis_to_rasmm(h: &NiftiHeader) -> Affine4 {
let c_header = CHeader::from_nifti(h.dim, h.pixdim, h.srow_x, h.srow_y, h.srow_z);
c_header.get_affine_to_rasmm()
} | pub fn get_affine_and_translation<T>(affine: &Matrix4<T>) -> (Matrix3<T>, Vector3<T>)
where |
type_uint_test.go | package generic
import (
"encoding/json"
"reflect"
"testing"
"github.com/stretchr/testify/assert"
)
type TestUintStruct struct {
Int Uint `json:"int"`
Float Uint `json:"float"`
Bool Uint `json:"bool"`
String Uint `json:"string"`
NullValue Uint `json:"null_value"`
}
func TestMarshalUint(t *testing.T) {
expected := Uint{
ValidFlag: true,
uint: 100,
}
i := 100
actual, err := MarshalUint(i)
if err != nil {
t.Errorf("Not Expected error when MarshalUint. error:%v", err.Error())
}
if actual != expected {
t.Errorf("actual:%v, expected:%v", actual, expected)
}
}
func TestMustUint(t *testing.T) {
tests := []struct {
name string
args interface{}
want Uint
wantPanic bool
}{
{
name: "valid",
args: 456,
want: Uint{
ValidFlag: true,
uint: 456,
},
wantPanic: false,
},
{
name: "panic",
args: "valid paramenter",
want: Uint{
ValidFlag: false,
},
wantPanic: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.wantPanic {
p := assert.Panics(t, func() {
MustUint(tt.args)
})
if !p {
t.Errorf("MustUint() panic = %v, want panic %v", p, tt.wantPanic)
}
return
}
if got := MustUint(tt.args); !reflect.DeepEqual(got, tt.want) {
t.Errorf("MustUint() = %v, want %v", got, tt.want)
}
})
}
}
func TestUintJsonUnmarshalAndMarshal(t *testing.T) {
var ts TestUintStruct
jstr := `{"int":10,"float":1.0,"bool":true,"string":"50","null_value":null}`
expected := `{"int":10,"float":1,"bool":1,"string":50,"null_value":null}`
err := json.Unmarshal([]byte(jstr), &ts)
if err != nil {
t.Errorf("Not Expected error when json.Unmarshal. error:%v", err.Error())
}
b, err := json.Marshal(ts)
if err != nil {
t.Errorf("Not Expected error when json.Marshal. error:%v", err.Error())
}
actual := string(b)
if actual != expected {
t.Errorf("actual:%s, expected:%s", actual, expected)
}
}
func TestUintJsonUnmarshalInvalid(t *testing.T) {
u := Uint{}
if err := u.UnmarshalJSON([]byte(`"0`)); err == nil {
t.Errorf("Expected error when json.Unmarshal, but not; %#v", u)
}
}
func TestUintJsonError(t *testing.T) {
var ts TestUintStruct
jstr := `{"int":-10,"float":1.0,"bool":true,"string":"50","null_value":null}`
expected := `{"int":null,"float":null,"bool":null,"string":null,"null_value":null}`
err := json.Unmarshal([]byte(jstr), &ts)
if err == nil {
t.Error("Expected error when json.Unmarshal.")
}
b, err := json.Marshal(ts)
if err != nil {
t.Errorf("Not Expected error when json.Marshal. error:%v", err.Error())
}
actual := string(b)
if actual != expected {
t.Errorf("actual:%s, expected:%s", actual, expected)
}
}
func TestUintSetNil(t *testing.T) |
func TestUintSetInt64(t *testing.T) {
var v int64 = 100
var expected uint64 = 100
tu := Uint{}
err := tu.Set(v)
if err != nil {
t.Errorf("Not Expected error. error:%v", err.Error())
}
if tu.Weak() != expected {
t.Errorf("This value should return 100 (uint64). value:%#v", tu.Weak())
}
}
func TestUintSetNumericString(t *testing.T) {
v := "56"
var expected uint64 = 56
tu := Uint{}
err := tu.Set(v)
if err != nil {
t.Errorf("Not Expected error. error:%v", err.Error())
}
if tu.Weak() != expected {
t.Errorf("This value should return nil. error:%#v", tu.Weak())
}
}
func TestUintSetNonNumericString(t *testing.T) {
v := "a"
var expected uint64
tu := Uint{}
err := tu.Set(v)
if err == nil {
t.Error("Expected error.")
}
if tu.Weak() == expected {
t.Errorf("This value should return 0. value:%#v", tu.Weak())
}
}
func TestUintUint(t *testing.T) {
var expected uint = 123456789
ti := Uint{
ValidFlag: true,
uint: uint64(expected),
}
if ti.Uint() != expected {
t.Errorf("actual:%d, expected:%d", ti.Uint(), expected)
}
}
func TestUintUintInvalid(t *testing.T) {
ti := Uint{
ValidFlag: false,
uint: 123456789,
}
if ti.Uint() != 0 {
t.Errorf("actual:%d, expected:0", ti.Uint())
}
}
func TestUintUint32(t *testing.T) {
var expected uint32 = 123456789
ti := Uint{
ValidFlag: true,
uint: uint64(expected),
}
if ti.Uint32() != expected {
t.Errorf("actual:%d, expected:%d", ti.Uint32(), expected)
}
}
func TestUintUint32Invalid(t *testing.T) {
ti := Uint{
ValidFlag: false,
uint: 123456789,
}
if ti.Uint32() != 0 {
t.Errorf("actual:%d, expected:0", ti.Uint32())
}
}
func TestUintUint64(t *testing.T) {
var expected uint64 = 123456789
ti := Uint{
ValidFlag: true,
uint: expected,
}
if ti.Uint64() != expected {
t.Errorf("actual:%d, expected:%d", ti.Uint64(), expected)
}
}
func TestUintUint64Invalid(t *testing.T) {
ti := Uint{
ValidFlag: false,
uint: 123456789,
}
if ti.Uint64() != 0 {
t.Errorf("actual:%d, expected:0", ti.Uint64())
}
}
func TestUintString(t *testing.T) {
var expected = "123456789"
ti := Uint{}
ti.Set(expected) // nolint
if ti.String() != expected {
t.Errorf("actual:%s, expected:%s", ti.String(), expected)
}
}
func TestUintStringInvalid(t *testing.T) {
ti := Uint{
ValidFlag: false,
uint: 123456789,
}
if ti.String() != "" {
t.Errorf("expected empty string, actual:%s", ti.String())
}
}
| {
tu := Uint{}
err := tu.Set(nil)
if err != nil {
t.Errorf("Not Expected error. error:%v", err.Error())
}
if tu.Weak() != nil {
t.Errorf("This value should return nil. error:%#v", tu.Weak())
}
} |
iocon_pio1_9.rs | #[doc = "Reader of register IOCON_PIO1_9"]
pub type R = crate::R<u32, super::IOCON_PIO1_9>;
#[doc = "Writer for register IOCON_PIO1_9"]
pub type W = crate::W<u32, super::IOCON_PIO1_9>;
#[doc = "Register IOCON_PIO1_9 `reset()`'s with value 0xd0"]
impl crate::ResetValue for super::IOCON_PIO1_9 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0xd0
}
}
#[doc = "Configure pin function.\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FUNC_A {
#[doc = "0: Pin function PIO1_9"]
PIO1_9,
#[doc = "1: Pin function CT16B1_MAT0"]
CT16B1_MAT0,
#[doc = "2: Pin function MOSI1"]
MOSI1,
}
impl From<FUNC_A> for u8 {
#[inline(always)]
fn from(variant: FUNC_A) -> Self {
match variant {
FUNC_A::PIO1_9 => 0,
FUNC_A::CT16B1_MAT0 => 1,
FUNC_A::MOSI1 => 2,
}
}
}
#[doc = "Reader of field `FUNC`"]
pub type FUNC_R = crate::R<u8, FUNC_A>;
impl FUNC_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, FUNC_A> {
use crate::Variant::*;
match self.bits {
0 => Val(FUNC_A::PIO1_9),
1 => Val(FUNC_A::CT16B1_MAT0),
2 => Val(FUNC_A::MOSI1),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `PIO1_9`"]
#[inline(always)]
pub fn is_pio1_9(&self) -> bool {
*self == FUNC_A::PIO1_9
}
#[doc = "Checks if the value of the field is `CT16B1_MAT0`"]
#[inline(always)]
pub fn is_ct16b1_mat0(&self) -> bool {
*self == FUNC_A::CT16B1_MAT0
}
#[doc = "Checks if the value of the field is `MOSI1`"]
#[inline(always)]
pub fn is_mosi1(&self) -> bool {
*self == FUNC_A::MOSI1
}
}
#[doc = "Write proxy for field `FUNC`"]
pub struct FUNC_W<'a> {
w: &'a mut W,
}
impl<'a> FUNC_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: FUNC_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "Pin function PIO1_9"]
#[inline(always)]
pub fn pio1_9(self) -> &'a mut W {
self.variant(FUNC_A::PIO1_9)
}
#[doc = "Pin function CT16B1_MAT0"]
#[inline(always)]
pub fn ct16b1_mat0(self) -> &'a mut W {
self.variant(FUNC_A::CT16B1_MAT0)
}
#[doc = "Pin function MOSI1"]
#[inline(always)]
pub fn mosi1(self) -> &'a mut W {
self.variant(FUNC_A::MOSI1)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x07) | ((value as u32) & 0x07);
self.w
}
}
#[doc = "Pin function mode (on-chip pull-up/pull-down resistor control).\n\nValue on reset: 2"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum MODE_A {
#[doc = "0: Inactive (no pull-down/pull-up resistor enabled)"]
INACTIVE_NO_PULL_DO,
#[doc = "1: Pull-down resistor enabled"]
PULL_DOWN_RESISTOR_E,
#[doc = "2: Pull-up resistor enabled"]
PULL_UP_RESISTOR_ENA,
#[doc = "3: Repeater mode"]
REPEATER_MODE_,
}
impl From<MODE_A> for u8 {
#[inline(always)]
fn from(variant: MODE_A) -> Self {
match variant {
MODE_A::INACTIVE_NO_PULL_DO => 0,
MODE_A::PULL_DOWN_RESISTOR_E => 1,
MODE_A::PULL_UP_RESISTOR_ENA => 2,
MODE_A::REPEATER_MODE_ => 3,
}
}
}
#[doc = "Reader of field `MODE`"]
pub type MODE_R = crate::R<u8, MODE_A>;
impl MODE_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> MODE_A {
match self.bits {
0 => MODE_A::INACTIVE_NO_PULL_DO,
1 => MODE_A::PULL_DOWN_RESISTOR_E,
2 => MODE_A::PULL_UP_RESISTOR_ENA,
3 => MODE_A::REPEATER_MODE_,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `INACTIVE_NO_PULL_DO`"]
#[inline(always)]
pub fn is_inactive_no_pull_do(&self) -> bool {
*self == MODE_A::INACTIVE_NO_PULL_DO
}
#[doc = "Checks if the value of the field is `PULL_DOWN_RESISTOR_E`"]
#[inline(always)]
pub fn is_pull_down_resistor_e(&self) -> bool {
*self == MODE_A::PULL_DOWN_RESISTOR_E
}
#[doc = "Checks if the value of the field is `PULL_UP_RESISTOR_ENA`"]
#[inline(always)]
pub fn is_pull_up_resistor_ena(&self) -> bool {
*self == MODE_A::PULL_UP_RESISTOR_ENA
}
#[doc = "Checks if the value of the field is `REPEATER_MODE_`"]
#[inline(always)]
pub fn is_repeater_mode_(&self) -> bool {
*self == MODE_A::REPEATER_MODE_
}
}
#[doc = "Write proxy for field `MODE`"]
pub struct MODE_W<'a> {
w: &'a mut W,
}
impl<'a> MODE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn | (self, variant: MODE_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "Inactive (no pull-down/pull-up resistor enabled)"]
#[inline(always)]
pub fn inactive_no_pull_do(self) -> &'a mut W {
self.variant(MODE_A::INACTIVE_NO_PULL_DO)
}
#[doc = "Pull-down resistor enabled"]
#[inline(always)]
pub fn pull_down_resistor_e(self) -> &'a mut W {
self.variant(MODE_A::PULL_DOWN_RESISTOR_E)
}
#[doc = "Pull-up resistor enabled"]
#[inline(always)]
pub fn pull_up_resistor_ena(self) -> &'a mut W {
self.variant(MODE_A::PULL_UP_RESISTOR_ENA)
}
#[doc = "Repeater mode"]
#[inline(always)]
pub fn repeater_mode_(self) -> &'a mut W {
self.variant(MODE_A::REPEATER_MODE_)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 3)) | (((value as u32) & 0x03) << 3);
self.w
}
}
#[doc = "Hysteresis.\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum HYSTERESIS_A {
#[doc = "0: Disable"]
DISABLE,
#[doc = "1: Enable"]
ENABLE,
}
impl From<HYSTERESIS_A> for bool {
#[inline(always)]
fn from(variant: HYSTERESIS_A) -> Self {
match variant {
HYSTERESIS_A::DISABLE => false,
HYSTERESIS_A::ENABLE => true,
}
}
}
#[doc = "Reader of field `HYSTERESIS`"]
pub type HYSTERESIS_R = crate::R<bool, HYSTERESIS_A>;
impl HYSTERESIS_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> HYSTERESIS_A {
match self.bits {
false => HYSTERESIS_A::DISABLE,
true => HYSTERESIS_A::ENABLE,
}
}
#[doc = "Checks if the value of the field is `DISABLE`"]
#[inline(always)]
pub fn is_disable(&self) -> bool {
*self == HYSTERESIS_A::DISABLE
}
#[doc = "Checks if the value of the field is `ENABLE`"]
#[inline(always)]
pub fn is_enable(&self) -> bool {
*self == HYSTERESIS_A::ENABLE
}
}
#[doc = "Write proxy for field `HYSTERESIS`"]
pub struct HYSTERESIS_W<'a> {
w: &'a mut W,
}
impl<'a> HYSTERESIS_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: HYSTERESIS_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Disable"]
#[inline(always)]
pub fn disable(self) -> &'a mut W {
self.variant(HYSTERESIS_A::DISABLE)
}
#[doc = "Enable"]
#[inline(always)]
pub fn enable(self) -> &'a mut W {
self.variant(HYSTERESIS_A::ENABLE)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "Selects pseudo open-drain mode.\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum OPEN_DRAIN_A {
#[doc = "0: Standard GPIO output"]
GPIO_OUTPUT,
#[doc = "1: Open-drain output"]
OPEN_DRAIN_OUTPUT,
}
impl From<OPEN_DRAIN_A> for bool {
#[inline(always)]
fn from(variant: OPEN_DRAIN_A) -> Self {
match variant {
OPEN_DRAIN_A::GPIO_OUTPUT => false,
OPEN_DRAIN_A::OPEN_DRAIN_OUTPUT => true,
}
}
}
#[doc = "Reader of field `OPEN_DRAIN`"]
pub type OPEN_DRAIN_R = crate::R<bool, OPEN_DRAIN_A>;
impl OPEN_DRAIN_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> OPEN_DRAIN_A {
match self.bits {
false => OPEN_DRAIN_A::GPIO_OUTPUT,
true => OPEN_DRAIN_A::OPEN_DRAIN_OUTPUT,
}
}
#[doc = "Checks if the value of the field is `GPIO_OUTPUT`"]
#[inline(always)]
pub fn is_gpio_output(&self) -> bool {
*self == OPEN_DRAIN_A::GPIO_OUTPUT
}
#[doc = "Checks if the value of the field is `OPEN_DRAIN_OUTPUT`"]
#[inline(always)]
pub fn is_open_drain_output(&self) -> bool {
*self == OPEN_DRAIN_A::OPEN_DRAIN_OUTPUT
}
}
#[doc = "Write proxy for field `OPEN_DRAIN`"]
pub struct OPEN_DRAIN_W<'a> {
w: &'a mut W,
}
impl<'a> OPEN_DRAIN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: OPEN_DRAIN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Standard GPIO output"]
#[inline(always)]
pub fn gpio_output(self) -> &'a mut W {
self.variant(OPEN_DRAIN_A::GPIO_OUTPUT)
}
#[doc = "Open-drain output"]
#[inline(always)]
pub fn open_drain_output(self) -> &'a mut W {
self.variant(OPEN_DRAIN_A::OPEN_DRAIN_OUTPUT)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10);
self.w
}
}
impl R {
#[doc = "Bits 0:2 - Configure pin function."]
#[inline(always)]
pub fn func(&self) -> FUNC_R {
FUNC_R::new((self.bits & 0x07) as u8)
}
#[doc = "Bits 3:4 - Pin function mode (on-chip pull-up/pull-down resistor control)."]
#[inline(always)]
pub fn mode(&self) -> MODE_R {
MODE_R::new(((self.bits >> 3) & 0x03) as u8)
}
#[doc = "Bit 5 - Hysteresis."]
#[inline(always)]
pub fn hysteresis(&self) -> HYSTERESIS_R {
HYSTERESIS_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 10 - Selects pseudo open-drain mode."]
#[inline(always)]
pub fn open_drain(&self) -> OPEN_DRAIN_R {
OPEN_DRAIN_R::new(((self.bits >> 10) & 0x01) != 0)
}
}
impl W {
#[doc = "Bits 0:2 - Configure pin function."]
#[inline(always)]
pub fn func(&mut self) -> FUNC_W {
FUNC_W { w: self }
}
#[doc = "Bits 3:4 - Pin function mode (on-chip pull-up/pull-down resistor control)."]
#[inline(always)]
pub fn mode(&mut self) -> MODE_W {
MODE_W { w: self }
}
#[doc = "Bit 5 - Hysteresis."]
#[inline(always)]
pub fn hysteresis(&mut self) -> HYSTERESIS_W {
HYSTERESIS_W { w: self }
}
#[doc = "Bit 10 - Selects pseudo open-drain mode."]
#[inline(always)]
pub fn open_drain(&mut self) -> OPEN_DRAIN_W {
OPEN_DRAIN_W { w: self }
}
}
| variant |
plugin.rs | use crate::EditorState;
use super::{
ray_impact::voxel_cursor_impact_system,
voxel_cursor::{voxel_clicking_system, VoxelCursorStates},
VoxelCursorRayImpact,
};
use bevy::{app::prelude::*, ecs::prelude::*};
/// Manages the `VoxelCursorRayImpact` and `VoxelCursorStates` resources.
pub struct VoxelPickingPlugin;
impl Plugin for VoxelPickingPlugin {
fn | (&self, app: &mut AppBuilder) {
app.insert_resource(VoxelCursorRayImpact::default())
.insert_resource(VoxelCursorStates::default())
.add_system_set(
SystemSet::on_update(EditorState::Editing)
.with_system(voxel_cursor_impact_system.system())
.with_system(voxel_clicking_system.system()),
);
}
}
| build |
NavDrawerLink.tsx | import ListItem from "@material-ui/core/ListItem";
import ListItemIcon from "@material-ui/core/ListItemIcon";
import ListItemText from "@material-ui/core/ListItemText";
import React, { ReactNode } from "react";
interface NavDrawerProps {
name: string;
children: ReactNode;
}
const NavDrawerLink: React.FC<NavDrawerProps> = ({ name, children }) => {
return (
<ListItem button> | );
};
export default NavDrawerLink; | <ListItemIcon>{children}</ListItemIcon>
<ListItemText primary={name} />
</ListItem> |
test_sknet.py | # -*- coding: utf-8 -*-
"""
@date: 2020/11/21 下午4:16
@file: test_resnest.py
@author: zj
@description:
"""
import torch
from zcls.config import cfg
from zcls.config.key_word import KEY_OUTPUT
from zcls.model.recognizers.resnet.resnet import ResNet
def test_data(model, input_shape, output_shape):
data = torch.randn(input_shape)
outputs = model(data)[KEY_OUTPUT]
print(outputs.shape)
assert outputs.shape == output_shape
def test_sknet():
conf | f __name__ == '__main__':
print('*' * 10 + ' sknet')
test_sknet()
| ig_file = 'configs/benchmarks/resnet-resnext/sknet50_zcls_imagenet_224.yaml'
cfg.merge_from_file(config_file)
model = ResNet(cfg)
print(model)
test_data(model, (3, 3, 224, 224), (3, 1000))
i |
constant_string_test.rs | extern crate div;
use div::class::ConstantString;
use div::class::ConstantTag;
use div::class::U8Reader;
#[test]
fn test_constant_string() | {
let mut u8_reader = U8Reader::new(&[0x00, 0x15]);
let constant_string = ConstantString::new(&mut u8_reader);
assert_eq!(ConstantTag::String, constant_string.tag);
assert_eq!(21, constant_string.string_index);
assert_eq!(2, u8_reader.position);
} |
|
token.rs | /// Used to identify which `Evented` value is associated with an `Event`
/// notification returned by `Poll`.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct | (pub usize);
impl From<usize> for Token {
fn from(val: usize) -> Token {
Token(val)
}
}
impl From<Token> for usize {
fn from(val: Token) -> usize {
val.0
}
}
| Token |
index.ts | import headings from '@rigor789/remark-autolink-headings';
import frontmatter from 'remark-frontmatter';
import math from 'remark-math';
import katex from 'remark-html-katex';
import gemojiToEmoji from 'remark-gemoji-to-emoji';
import parseFrontmatter from 'remark-parse-yaml';
import shortcodes from 'remark-shortcodes';
import slug from 'remark-slug';
import remarkAttr from 'remark-attr';
import reporter from 'vfile-reporter';
import sectionize from 'remark-sectionize';
| import { customBlocksOptions } from './plugins/remark-custom-blocks';
import { customBlockquotes, customBlockquotesOptions } from './plugins/remark-custom-blockquotes';
import { shortCodeProps } from './plugins/short-codes';
import { prism } from './plugins/prism';
import { mermaid } from './plugins/mermaid';
import visit from 'unist-util-visit';
import { Root } from 'mdast';
import { VFile } from 'vfile';
import { Transformer } from 'unified';
export { customBlocks, customBlockquotes, prism, mermaid, reporter, getTitle };
export function moveIds(): Transformer {
return (tree: Root, file: VFile) => {
return visit(tree, 'heading', (node: any, index: number, parent: any) => {
if (parent.type === 'section' && node.data && node.data.hProperties && node.data.hProperties.id) {
parent.data = parent.data || Object.create(null);
parent.data.hProperties = parent.data.hProperties || Object.create(null);
parent.data.hProperties.id = node.data.hProperties.id;
delete node.data.hProperties.id;
}
return true;
});
};
}
export const plugins = [
frontmatter,
parseFrontmatter,
readMatter,
getTitle,
infoString,
[ remarkAttr, { scope: 'permissive' } ],
slug,
[ headings, { behaviour: 'append' } ],
sectionize,
moveIds,
math,
katex,
gemojiToEmoji,
infoStringToAttr,
[ customBlocks, customBlocksOptions ],
[ customBlockquotes, customBlockquotesOptions ],
shortcodes,
shortCodeProps,
mermaid,
prism
];
export const settings = {};
export const preset = {
settings,
plugins,
reporter
};
export default preset; | import customBlocks from './plugins/remark-custom-blocks-plugin';
import { readMatter, getTitle } from './plugins/frontmatter';
import { infoString, infoStringToAttr } from './plugins/misc'; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.