file_name
stringlengths 3
137
| prefix
stringlengths 0
918k
| suffix
stringlengths 0
962k
| middle
stringlengths 0
812k
|
---|---|---|---|
inspect_matches.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import utool as ut
import ubelt as ub
try:
import wbia.guitool as gt
from wbia.guitool import mpl_widget
INSPECT_BASE = gt.GuitoolWidget
MatplotlibWidget = mpl_widget.MatplotlibWidget
except (ImportError, TypeError):
import warnings
warnings.warn('WARNING: guitool not available')
MatplotlibWidget = object
INSPECT_BASE = object
def lazy_test_annot(key):
import numpy as np
rchip_fpath = ut.grab_test_imgpath(key)
annot = ut.LazyDict(
{
'aid': key.split('.')[0],
'nid': key[0:4],
'rchip_fpath': rchip_fpath,
'gps': (np.nan, np.nan),
'yaw': np.nan,
'view': np.nan,
'qual': np.nan,
'time': np.nan,
}
)
return annot
try:
import wbia.dtool
MatchDisplayConfig = wbia.dtool.from_param_info_list(
[
ut.ParamInfo('overlay', True),
ut.ParamInfo('show_all_kpts', False),
ut.ParamInfo('mask_blend', 0.0, min_=0, max_=1),
ut.ParamInfo('heatmask', True, hideif=':not overlay'),
ut.ParamInfo('show_homog', False, hideif=':not overlay'),
ut.ParamInfo('show_ori', False, hideif=':not overlay'),
ut.ParamInfo('show_ell', False, hideif=':not overlay'),
ut.ParamInfo('show_pts', False, hideif=':not overlay'),
ut.ParamInfo('show_lines', False, hideif=lambda cfg: not cfg['overlay']),
ut.ParamInfo('show_rect', False, hideif=':not overlay'),
ut.ParamInfo('show_eig', False, hideif=':not overlay'),
ut.ParamInfo('ell_alpha', 0.6, min_=0, max_=1, hideif=':not overlay'),
ut.ParamInfo('line_alpha', 0.35, min_=0, max_=1, hideif=':not overlay'),
]
)
except (ImportError, TypeError):
pass
class MatchInspector(INSPECT_BASE):
"""
A widget that contains
(1) a viewport that displays an annotation pair with matches overlayed.
(2) a control panel for tuning matching parameters
(3) a text area displaying information about the match vector
CommandLine:
python -m vtool.inspect_matches MatchInspector:0 --show
python -m vtool.inspect_matches MatchInspector:1 --show
python -m vtool.inspect_matches MatchInspector:1 --db GZ_Master1 --aids=1041,1045 --show
Example:
>>> # SCRIPT
>>> from vtool.inspect_matches import * # NOQA
>>> import vtool as vt
>>> gt.ensure_qapp()
>>> ut.qtensure()
>>> annot1 = lazy_test_annot('easy1.png')
>>> annot2 = lazy_test_annot('easy2.png')
>>> match = vt.PairwiseMatch(annot1, annot2)
>>> self = MatchInspector(match=match)
>>> self.show()
>>> # xdoctest: +REQUIRES(--show)
>>> #self.update()
>>> gt.qtapp_loop(qwin=self, freq=10)
Example:
>>> # SCRIPT
>>> from vtool.inspect_matches import * # NOQA
>>> import vtool as vt
>>> import wbia
>>> gt.ensure_qapp()
>>> ut.qtensure()
>>> ibs = wbia.opendb(defaultdb='PZ_MTEST')
>>> aids = ub.argval('--aids', default=[1, 2])
>>> print('aids = %r' % (aids,))
>>> annots = ibs.annots(aids)
>>> annot1 = annots[0]._make_lazy_dict()
>>> annot2 = annots[1]._make_lazy_dict()
>>> cfgdict = MatchDisplayConfig().asdict()
>>> cfgdict = ut.argparse_dict(cfgdict)
>>> match = vt.PairwiseMatch(annot1, annot2)
>>> self = MatchInspector(match=match, cfgdict=cfgdict)
>>> self.show()
>>> # xdoctest: +REQUIRES(--show)
>>> #self.update()
>>> gt.qtapp_loop(qwin=self, freq=10)
"""
def showEvent(self, event):
super(MatchInspector, self).showEvent(event)
# Fire initialize event after we show the GUI
# QtCore.QTimer.singleShot(50, self.init_inference)
self.first_show()
def first_show(self, state=None):
if self.match is not None:
# Show the match if updating is on, otherwise just draw the annot
# pair
if self.autoupdate_cb.checkState():
self.update()
else:
self.draw_pair()
def set_match(self, match=None, on_context=None, info_text=None):
self.match = match
self.info_text = info_text
self.on_context = on_context
if self.isVisible():
self.first_show()
def initialize(
self, match=None, on_context=None, autoupdate=True, info_text=None, cfgdict=None
):
|
def execContextMenu(self, qpoint):
if self.on_context:
options = self.on_context()
else:
options = [('No context set', None)]
gt.popup_menu(self, qpoint, options)
def screenshot(self):
import wbia.plottool as pt
with pt.RenderingContext() as render:
self.match.show(**self.disp_config)
fpaths = gt.newFileDialog('.', mode='save', exec_=True)
if fpaths is not None and len(fpaths) > 0:
fpath = fpaths[0]
if not fpath.endswith('.jpg'):
fpath += '.jpg'
import vtool as vt
vt.imwrite(fpath, render.image)
def embed(self):
match = self.match # NOQA
import utool
utool.embed()
def _new_config_widget(self, cfg, changed=None):
from wbia.guitool import PrefWidget2
user_mode = 0
cfg_widget = PrefWidget2.EditConfigWidget(
config=cfg, user_mode=user_mode, parent=self, changed=changed
)
return cfg_widget
def closeEvent(self, event):
from wbia.plottool import abstract_interaction
abstract_interaction.unregister_interaction(self)
super(MatchInspector, self).closeEvent(event)
def _setup_configs(self, cfgdict=None):
from vtool import matching
import wbia.dtool
# import pyhesaff
# default_dict = pyhesaff.get_hesaff_default_params()
# default_dict = vt.get_extract_features_default_params()
TmpFeatConfig = wbia.dtool.from_param_info_list(matching.VSONE_FEAT_CONFIG)
TmpNChipConfig = wbia.dtool.from_param_info_list(matching.NORM_CHIP_CONFIG)
# [
# ut.ParamInfo(key, val) for key, val in default_dict.items()
# # ut.ParamInfo('affine_invariance', True),
# # ut.ParamInfo('rotation_invariance', False),
# ])
self.featconfig = TmpFeatConfig()
self.chipconfig = TmpNChipConfig()
TmpVsOneConfig = wbia.dtool.from_param_info_list(matching.VSONE_DEFAULT_CONFIG)
self.config = TmpVsOneConfig()
self.disp_config = MatchDisplayConfig()
if cfgdict is not None:
print('[inspect_match] default cfgdict = %r' % (cfgdict,))
self.config.update(**cfgdict)
self.featconfig.update(**cfgdict)
self.chipconfig.update(**cfgdict)
self.disp_config.update(**cfgdict)
# Make config widgets after setting defaults
self.chipconfig_widget = self._new_config_widget(
self.chipconfig, changed=self.on_chip_cfg_changed
)
self.featconfig_widget = self._new_config_widget(
self.featconfig, changed=self.on_feat_cfg_changed
)
self.config_widget = self._new_config_widget(
self.config, changed=self.on_cfg_changed
)
self.disp_config_widget = self._new_config_widget(
self.disp_config, changed=self.on_cfg_changed
)
def _setup_layout(self, autoupdate=True):
from wbia.guitool.__PYQT__ import QtWidgets
self.menubar = gt.newMenubar(self)
self.menuFile = self.menubar.newMenu('Dev')
self.menuFile.newAction(triggered=self.embed)
self.menuFile.newAction(triggered=self.screenshot)
splitter1 = self.addNewSplitter(orientation='horiz')
config_vframe = splitter1.newWidget()
splitter2 = splitter1.addNewSplitter(orientation='vert')
config_vframe.addWidget(QtWidgets.QLabel('Chip Config'))
config_vframe.addWidget(self.chipconfig_widget)
config_vframe.addWidget(QtWidgets.QLabel('Feat Config'))
config_vframe.addWidget(self.featconfig_widget)
config_vframe.addWidget(QtWidgets.QLabel('Query Config'))
config_vframe.addWidget(self.config_widget)
config_vframe.addWidget(QtWidgets.QLabel('Display Config'))
config_vframe.addWidget(self.disp_config_widget)
# update_hframe = config_vframe.addNewWidget(orientation='horiz')
# update_hframe.addNewButton('Update', pressed=self.update)
self.autoupdate_cb = config_vframe.addNewCheckBox(
'auto-update', checked=autoupdate, changed=self.first_show
)
self.mpl_widget = MatplotlibWidget(parent=self)
splitter2.addWidget(self.mpl_widget)
self.infobox = splitter2.addNewTextEdit()
def execute_vsone(self):
from vtool import matching
print('[inspect_match] Execute vsone')
cfgdict = {}
cfgdict.update(self.featconfig.asdict())
cfgdict.update(self.chipconfig.asdict())
match = self.match
match.verbose = True
match._inplace_default = True
matching.ensure_metadata_vsone(match.annot1, match.annot2, cfgdict=cfgdict)
match_config = self.config.asdict()
match.apply_all(match_config)
def draw_pair(self):
if self.match is None:
return
self.mpl_widget.clf()
ax = self.mpl_widget.ax
info_html = ''
if self.info_text is not None:
info_html = '<pre>' + self.info_text + '</pre>'
self.infobox.setText(info_html)
self.match.show(ax=ax, overlay=False)
self.mpl_widget.fig.canvas.draw()
def draw_vsone(self):
match = self.match
summary = match._make_local_summary_feature_vector(summary_ops={'sum'})
info_html = ''
if self.info_text is not None:
info_html = '<pre>' + self.info_text + '</pre>'
feat_html = '<pre>' + ut.align(ub.repr2(summary), ':') + '</pre>'
self.infobox.setText(info_html + feat_html)
self.mpl_widget.clf()
ax = self.mpl_widget.ax
match.show(ax=ax, **self.disp_config)
# fig.show()
self.mpl_widget.fig.canvas.draw()
def update(self, state=None):
if self.autoupdate_cb.checkState() and self.match is not None:
self.execute_vsone()
self.draw_vsone()
def on_cfg_changed(self, *args):
self.update()
self.cfg_needs_update = True
def on_chip_cfg_changed(self, *args):
print('Update feats')
feat_keys = ['nchip', 'vecs', 'kpts', '_feats', 'flann']
self.match.annot1._mutable = True
self.match.annot2._mutable = True
for key in feat_keys:
if key in self.match.annot1:
del self.match.annot1[key]
if key in self.match.annot2:
del self.match.annot2[key]
self.update()
self.cfg_needs_update = True
def on_feat_cfg_changed(self, *args):
print('Update feats')
feat_keys = ['vecs', 'kpts', '_feats', 'flann']
self.match.annot1._mutable = True
self.match.annot2._mutable = True
for key in feat_keys:
if key in self.match.annot1:
del self.match.annot1[key]
if key in self.match.annot2:
del self.match.annot2[key]
self.update()
self.cfg_needs_update = True
def make_match_interaction(matches, metadata, type_='RAT+SV', **kwargs):
import wbia.plottool.interact_matches
# import wbia.plottool as pt
fm, fs = matches[type_][0:2]
try:
H1 = metadata['H_' + type_.split('+')[0]]
except Exception:
H1 = None
# fm, fs = matches['RAT'][0:2]
annot1 = metadata['annot1']
annot2 = metadata['annot2']
rchip1, kpts1, vecs1 = ub.dict_take(annot1, ['nchip', 'kpts', 'vecs'])
rchip2, kpts2, vecs2 = ub.dict_take(annot2, ['nchip', 'kpts', 'vecs'])
# pt.show_chipmatch2(rchip1, rchip2, kpts1, kpts2, fm=fm, fs=fs)
fsv = fs[:, None]
interact = wbia.plottool.interact_matches.MatchInteraction2(
rchip1, rchip2, kpts1, kpts2, fm, fs, fsv, vecs1, vecs2, H1=H1, **kwargs
)
return interact
def show_matching_dict(matches, metadata, *args, **kwargs):
interact = make_match_interaction(matches, metadata, *args, **kwargs)
interact.show_page()
return interact
if __name__ == '__main__':
"""
CommandLine:
xdoctest -m vtool.inspect_matches
"""
import xdoctest
xdoctest.doctest_module(__file__)
| from wbia.plottool import abstract_interaction
from wbia.guitool.__PYQT__ import QtCore
self.set_match(match, on_context, info_text)
self._setup_configs(cfgdict=cfgdict)
self._setup_layout(autoupdate=autoupdate)
abstract_interaction.register_interaction(self)
self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.customContextMenuRequested.connect(self.execContextMenu) |
main.rs | //! nRF9160 Rust Demo
//!
//! This is a demo application for the nRF9160-DK. See the [README.md] file
//! for more details.
//!
//! Copyright (c) 42 Technology Ltd 2019
//! Licensed under the MIT or Apache-2.0 licences, at your option.
#![no_std]
#![no_main]
#![allow(deprecated)]
// ==========================================================================
//
// Modules and Crates
//
// ==========================================================================
extern crate cortex_m_rt as rt;
extern crate tinyrlibc;
#[cfg(not(any(feature = "nrf9160dk", feature = "icarus")))]
compile_error!("Must enable nrf9160dk or icarus features to select a board.");
#[cfg(feature = "nrf9160dk")]
extern crate nrf9160_dk_bsp as bsp;
#[cfg(feature = "icarus")]
extern crate actinius_icarus_bsp as bsp;
mod secrets;
// ==========================================================================
//
// Imports
//
// ==========================================================================
use core::fmt::Write;
use core::panic::PanicInfo;
use bsp::pac::interrupt;
use bsp::prelude::*;
use rt::entry;
// ==========================================================================
//
// Private Types
//
// ==========================================================================
/// Our menu system holds a context object for us, of this type.
struct Context {
timer: bsp::hal::Timer<bsp::pac::TIMER0_NS>,
}
#[derive(Debug)]
enum Error {
Nrfxlib(nrfxlib::Error),
WriteError,
ReadError,
}
// ==========================================================================
//
// Private Global Data
//
// ==========================================================================
/// This is the main menu
static ROOT_MENU: menu::Menu<Context> = menu::Menu {
label: "root",
items: &[
&menu::Item {
item_type: menu::ItemType::Callback(command_on),
command: "on",
help: Some("Power on modem"),
},
&menu::Item {
item_type: menu::ItemType::Callback(command_mode),
command: "mode",
help: Some("Get/set XSYSTEMMODE (NB-IOT, LTE-M, and/or GPS)"),
},
&menu::Item {
item_type: menu::ItemType::Callback(command_flight),
command: "flight",
help: Some("Enter flight mode"),
},
&menu::Item {
item_type: menu::ItemType::Callback(command_off),
command: "off",
help: Some("Power off modem"),
},
&menu::Item {
item_type: menu::ItemType::Callback(command_wait),
command: "wait",
help: Some("Wait for signal"),
},
&menu::Item {
item_type: menu::ItemType::Callback(command_stat),
command: "stat",
help: Some("Show registration and general modem status"),
},
&menu::Item {
item_type: menu::ItemType::Callback(command_get),
command: "get",
help: Some("Do an HTTP GET"),
},
&menu::Item {
item_type: menu::ItemType::Callback(command_store),
command: "store",
help: Some("Write the TLS keys to Flash"),
},
&menu::Item {
item_type: menu::ItemType::Callback(command_panic),
command: "panic",
help: Some("Deliberately crash"),
},
&menu::Item {
item_type: menu::ItemType::Callback(command_fix),
command: "fix",
help: Some("Get a GPS fix"),
},
&menu::Item {
item_type: menu::ItemType::Callback(command_go_at),
command: "go_at",
help: Some("Enter AT over UART mode"),
},
&menu::Item {
item_type: menu::ItemType::Callback(command_go_at_fun),
command: "AT+CFUN?",
help: Some("Enter AT mode if an AT command is entered..."),
},
],
entry: None,
exit: None,
};
/// A UART we can access from anywhere (with run-time lock checking).
static GLOBAL_UART: spin::Mutex<Option<bsp::hal::uarte::Uarte<bsp::pac::UARTE0_NS>>> =
spin::Mutex::new(None);
/// The tag we use for our crypto keys (which we pass when saving the keys to
/// flash and then also when opening a TLS socket).
const SECURITY_TAG: u32 = 0;
// ==========================================================================
//
// Macros
//
// ==========================================================================
#[macro_export]
macro_rules! print {
($($arg:tt)*) => {
{
use core::fmt::Write as _;
if let Some(ref mut uart) = *crate::GLOBAL_UART.lock() {
let _err = write!(*uart, $($arg)*);
}
}
};
}
#[macro_export]
macro_rules! println {
() => (print!("\n"));
($($arg:tt)*) => {
{
use core::fmt::Write as _;
if let Some(ref mut uart) = *crate::GLOBAL_UART.lock() {
let _err = writeln!(*uart, $($arg)*);
}
}
};
}
// ==========================================================================
//
// Public Functions and Impls
//
// ==========================================================================
#[entry]
fn main() -> ! {
let mut board = bsp::Board::take().unwrap();
#[cfg(feature = "nrf9160dk")]
let (mut led1, mut led2) = (board.leds.led_1, board.leds.led_2);
#[cfg(feature = "icarus")]
let (mut led1, mut led2) = (board.leds.red, board.leds.green);
board.NVIC.enable(bsp::pac::Interrupt::EGU1);
board.NVIC.enable(bsp::pac::Interrupt::EGU2);
// Enabled by bsd_init();
// board.NVIC.enable(bsp::pac::Interrupt::IPC);
// Only use top three bits, so shift by up by 8 - 3 = 5 bits
unsafe {
board.NVIC.set_priority(bsp::pac::Interrupt::EGU2, 4 << 5);
board.NVIC.set_priority(bsp::pac::Interrupt::EGU1, 4 << 5);
board.NVIC.set_priority(bsp::pac::Interrupt::IPC, 0 << 5);
}
*GLOBAL_UART.lock() = Some(board.cdc_uart);
// Set one LED on so we know we're running
led1.enable();
println!("This is Rust on the nRF9160 LTE SiP");
println!("Copyright (c) 42 Technology Ltd, 2019.");
// Work around https://www.nordicsemi.com/DocLib/Content/Errata/nRF9160_EngA/latest/ERR/nRF9160/EngineeringA/latest/anomaly_160_17
// *(volatile uint32_t *)0x40005C04 = 0x02ul;
unsafe {
core::ptr::write_volatile(0x4000_5C04 as *mut u32, 0x02);
}
// Start the Nordic library
println!("Calling nrfxlib::init()...");
nrfxlib::init();
// Set another LED to we know the library has initialised
led2.enable();
// Start the menu system
let mut buffer = [0u8; 64];
let mut context = Context {
timer: bsp::hal::timer::Timer::new(board.TIMER0_NS),
};
let mut runner = menu::Runner::new(&ROOT_MENU, &mut buffer, &mut context);
loop {
// Grab the UART and maybe get a character
let maybe_c = if let Some(ref mut uart) = *crate::GLOBAL_UART.lock() {
let mut uart_rx_buf = [0u8; 1];
if uart.read(&mut uart_rx_buf).is_ok() {
Some(uart_rx_buf[0])
} else {
None
}
} else {
None
};
// If we did, give it to the menu (without holding the UART lock)
if let Some(c) = maybe_c {
runner.input_byte(c);
}
}
}
/// Interrupt Handler for LTE related hardware. Defer straight to the library.
#[interrupt]
fn EGU1() {
nrfxlib::application_irq_handler();
cortex_m::asm::sev();
}
/// Interrupt Handler for LTE related hardware. Defer straight to the library.
#[interrupt]
fn EGU2() {
nrfxlib::trace_irq_handler();
cortex_m::asm::sev();
}
/// Interrupt Handler for LTE related hardware. Defer straight to the library.
#[interrupt]
fn IPC() {
nrfxlib::ipc_irq_handler();
cortex_m::asm::sev();
}
/// Debug function our C code can use to print messages to the UART.
#[no_mangle]
unsafe extern "C" fn rust_print(data: *const u8) {
extern "C" {
fn strlen(s: *const u8) -> isize;
}
let len = strlen(data);
let slice = core::slice::from_raw_parts(data, len as usize);
let string = core::str::from_utf8_unchecked(slice);
print!("{}", &string);
}
/// Called when our code panics.
#[inline(never)]
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
println!("{:?}", info);
loop {
cortex_m::asm::nop();
}
}
// ==========================================================================
//
// Private Functions and Impls
//
// ==========================================================================
/// The modem starts up in the powered-off state. This turns it on.
fn command_on(
_menu: &menu::Menu<Context>,
_item: &menu::Item<Context>,
_args: &str,
_context: &mut Context,
) {
println!("Configure GNSS antenna...");
match nrfxlib::modem::configure_gnss_on_pca10090ns() {
Ok(_) => {
println!("GNSS antenna enabled.");
}
Err(e) => {
println!("Error turning GNSS antenna on: {:?}", e);
}
}
print!("Turning modem on...");
match nrfxlib::modem::on() {
Ok(_) => {
println!("Modem now on.");
}
Err(e) => {
println!("Error turning modem on: {:?}", e);
}
}
println!("Opening socket...");
let gnss = nrfxlib::gnss::GnssSocket::new().expect("GnssSocket::new");
// Same as the Nordic demo app
println!("Set fix interval to 1...");
if let Err(e) = gnss.set_fix_interval(1) {
println!("Failed to set fix interval. GPS may be disabled - see 'mode'. Error {:?}", e);
return;
}
println!("Set fix retry to 0...");
if let Err(e) = gnss.set_fix_retry(0) {
println!("Failed to set fix retry. GPS may be disabled - see 'mode'. Error {:?}", e);
return;
}
let mask = nrfxlib::gnss::NmeaMask::new();
println!("Setting NMEA mask to {:?}", mask);
if let Err(e) = gnss.set_nmea_mask(mask) {
println!("Failed to set NMEA mask. GPS may be disabled - see 'mode'. Error {:?}", e);
return;
}
println!("Starting gnss...");
if let Err(e) = gnss.start() {
println!("Failed to start GPS. GPS may be disabled - see 'mode'. Error {:?}", e);
return;
}
println!("GPS started OK.");
}
/// The modem starts up in the powered-off state. This turns it on.
fn command_mode(
_menu: &menu::Menu<Context>,
_item: &menu::Item<Context>,
args: &str,
_context: &mut Context,
) |
/// This puts the modem into flight mode. Needed if you want to fiddle with
/// some particular parameters that can't be set when it's on.
fn command_flight(
_menu: &menu::Menu<Context>,
_item: &menu::Item<Context>,
_args: &str,
_context: &mut Context,
) {
print!("Taking modem offline...");
match nrfxlib::modem::flight_mode() {
Ok(_) => {
println!("Modem now in flight mode.");
}
Err(e) => {
println!("Error taking modem offline: {:?}", e);
}
}
}
/// Powers the modem right off.
fn command_off(
_menu: &menu::Menu<Context>,
_item: &menu::Item<Context>,
_args: &str,
_context: &mut Context,
) {
print!("Turning modem off...");
match nrfxlib::modem::off() {
Ok(_) => {
println!("Modem now off.");
}
Err(e) => {
println!("Error turning modem off: {:?}", e);
}
}
}
/// Wait for signal
fn command_wait(
_menu: &menu::Menu<Context>,
_item: &menu::Item<Context>,
_args: &str,
_context: &mut Context,
) {
print!("Waiting for signal...");
match nrfxlib::modem::wait_for_lte() {
Ok(_) => {
println!("Modem now registered.");
}
Err(e) => {
println!("Error getting registration: {:?}", e);
}
}
}
/// Show registration and general modem status.
fn command_stat(
_menu: &menu::Menu<Context>,
_item: &menu::Item<Context>,
_args: &str,
_context: &mut Context,
) {
for cmd in &[
"AT+CFUN?",
"AT+CEREG?",
"AT%XSNRSQ?",
"AT+CESQ",
"AT%XTEMP?",
"AT+CGCONTRDP=0",
"AT+CCLK?",
"AT%XMONITOR",
"AT+CGDCONT?",
"AT+CGPADDR",
"AT%XCONNSTAT?",
] {
print_at_results(cmd);
}
}
fn print_at_results(cmd: &str) {
if let Err(e) = nrfxlib::at::send_at_command(cmd, |s| {
println!("> {}", s);
}) {
println!("Err running {:?}: {:?}", cmd, e);
}
}
/// Do an HTTP GET
fn command_get(
_menu: &menu::Menu<Context>,
_item: &menu::Item<Context>,
_args: &str,
context: &mut Context,
) {
let f = || -> Result<(), Error> {
let host = "jsonplaceholder.typicode.com";
let port = 443;
let url = "/todos/1";
// We make a secure connection here, using our pre-saved certs
println!("Making socket..");
let mut skt = nrfxlib::tls::TlsSocket::new(true, &[SECURITY_TAG])?;
println!("Connecting to {}..", host);
skt.connect(host, port)?;
println!("Writing...");
write!(
skt,
"GET {url} HTTP/1.1\r\n\
Host: {host}:{port}\r\n\
Connection: close\r\n\
User-Agent: rust/nrf\r\n\
\r\n",
url = url,
host = host,
port = port,
)
.map_err(|_e| Error::WriteError)?;
loop {
let mut buf = [0u8; 32];
let x = skt.recv_wait(&mut buf)?;
if let Ok(s) = core::str::from_utf8(&buf[0..x]) {
print!("{}", s);
} else {
print!("{:?}", &buf[0..x]);
}
if x < buf.len() {
break;
}
}
Ok(())
};
// Start a timer
context.timer.start(0xFFFF_FFFFu32);
// Run the function
let result = f();
// Print the result
let now = context.timer.read();
println!(
"Got {:?} after {} seconds",
result,
(now as f32) / 1_000_000.0
);
}
/// Store the certificates into nrfxlib, so the TLS sockets can use them.
fn command_store(
_menu: &menu::Menu<Context>,
_item: &menu::Item<Context>,
_args: &str,
_context: &mut Context,
) {
let f = || -> Result<(), Error> {
nrfxlib::tls::provision_certificates(SECURITY_TAG, Some(secrets::CA_CHAIN), None, None)?;
Ok(())
};
let result = f();
println!("Got {:?}", result);
}
/// Deliberately crash
fn command_panic(
_menu: &menu::Menu<Context>,
_item: &menu::Item<Context>,
_args: &str,
_context: &mut Context,
) {
panic!("command_panic was called!")
}
/// Get a GPS fix
fn command_fix(
_menu: &menu::Menu<Context>,
_item: &menu::Item<Context>,
_args: &str,
_context: &mut Context,
) {
let gps = nrfxlib::gnss::GnssSocket::new().expect("GnssSocket::new");
match gps.get_fix() {
Ok(None) => println!("No data available"),
Ok(Some(fix)) => {
println!("{:#?}", fix);
}
Err(e) => println!("Error: {:?}", e),
}
}
/// Enter AT over UART mode
fn command_go_at(
_menu: &menu::Menu<Context>,
_item: &menu::Item<Context>,
_args: &str,
context: &mut Context,
) {
let mut f = || -> Result<(), Error> {
let at_socket = nrfxlib::at::AtSocket::new()?;
let mut input_buffer: heapless::Vec<u8, heapless::consts::U256> = heapless::Vec::new();
loop {
let mut temp_buf = [0u8; 1];
// Read from console UART
let res = if let Some(ref mut uart) = *crate::GLOBAL_UART.lock() {
Some(uart.read_timeout(&mut temp_buf, &mut context.timer, 100_000))
} else {
None
};
match res {
Some(Err(bsp::hal::uarte::Error::Timeout(_n))) => {
// Do nothing. N must be 0 because we only pass a 1 byte buffer to read into
}
Some(Err(_)) => {
return Err(Error::ReadError);
}
Some(Ok(_)) => {
// Send character to modem, unless it's Ctrl+C (0x03), in which
// case exit.
print!("{}", temp_buf[0] as char);
if temp_buf == [0x03] {
break;
} else if temp_buf == [b'\n'] || temp_buf == [b'\r'] {
println!();
input_buffer.extend(b"\r\n");
at_socket.write(&input_buffer)?;
input_buffer.clear();
} else {
input_buffer.extend(&temp_buf);
}
}
None => {
println!("Failed to grab UART lock!");
}
}
let mut buffer = [0u8; 128];
// Now check the AT socket for data
match at_socket.recv(&mut buffer)? {
Some(n) => {
if let Some(ref mut uart) = *crate::GLOBAL_UART.lock() {
// Subtract 1 to avoid printing final NUL byte
uart.write(&buffer[0..n - 1])
.map_err(|_| Error::WriteError)?;
}
}
None => {
// Do nothing
}
}
}
Ok(())
};
println!("OK\r\n");
if let Err(e) = f() {
println!("Error: {:?}", e);
}
}
/// Handle the first AT command the link monitor sends, then enter AT mode.
fn command_go_at_fun(
menu: &menu::Menu<Context>,
item: &menu::Item<Context>,
args: &str,
context: &mut Context,
) {
match nrfxlib::at::send_at_command("AT+CFUN?", |s| {
println!("{}", s);
}) {
Ok(_) => {
// Jump to the normal AT handler (which prints OK when it starts)
command_go_at(menu, item, args, context);
}
Err(_) => {
// Quit with an error.
println!("ERROR");
}
}
}
impl core::fmt::Write for Context {
fn write_str(&mut self, message: &str) -> core::fmt::Result {
if let Some(ref mut uart) = *crate::GLOBAL_UART.lock() {
write!(uart, "{}", message)?;
}
Ok(())
}
}
impl From<nrfxlib::Error> for Error {
fn from(err: nrfxlib::Error) -> Error {
Error::Nrfxlib(err)
}
}
// ==========================================================================
//
// End of file
//
// ==========================================================================
| {
let mut args_iter = args.split_whitespace();
let _command = args_iter.next();
let mut modes = (0, 0, 0);
for arg in args_iter {
if arg.eq_ignore_ascii_case("gps") {
println!("Enabling GPS.");
modes.2 = 1;
} else if arg.eq_ignore_ascii_case("nbiot") || arg.eq_ignore_ascii_case("nb-iot") {
println!("Enabling NB-IoT.");
modes.1 = 1;
} else if arg.eq_ignore_ascii_case("ltem") || arg.eq_ignore_ascii_case("lte-m") {
println!("Enabling LTE-M.");
modes.0 = 1;
} else {
println!("Don't understand argument {:?}.", arg);
println!("Try 'nbiot', 'ltem' and/or 'gps'");
return;
}
}
// They've enabled something
if modes != (0, 0, 0) {
let mut command: heapless::String<heapless::consts::U32> = heapless::String::new();
write!(
command,
"AT%XSYSTEMMODE={},{},{},0",
modes.0, modes.1, modes.2
)
.unwrap();
if let Err(e) = nrfxlib::at::send_at_command(&command, |_| {}) {
println!("Err running {}: {:?}", command, e);
}
}
if let Err(e) = nrfxlib::at::send_at_command("AT%XSYSTEMMODE?", |s| {
println!("> {}", s);
// TODO parse result here
}) {
println!("Err running AT%XSYSTEMMODE: {:?}", e);
}
} |
blockr.py | """
blockr.io
"""
import logging
import hashlib
from hashlib import sha256
import requests
from .. import config
from binascii import hexlify, unhexlify
def getUrl(request_string):
return requests.get(request_string).json()
def setHost():
config.BLOCKCHAIN_CONNECT = ('http://tbtc.blockr.io' if config.TESTNET else 'http://btc.blockr.io')
#And fix this
def check():
return getInfo()
def getInfo():
result = getUrl(config.BLOCKCHAIN_CONNECT + '/api/v1/coin/info', )
if 'status' in result and result['status'] == 'success':
return {
"info": {
"blocks": result['data']['last_block']['nb'],
"difficulty": result['data']['last_block']['difficulty']
}
}
return result
def getUtxo(address):
result = getUrl(config.BLOCKCHAIN_CONNECT + '/api/v1/address/unspent/{}/'.format(address))
if 'status' in result and result['status'] == 'success':
utxo = []
for txo in result['data']['unspent']:
newtxo = {
'address': address,
'txid': txo['tx'],
'vout': txo['n'],
'ts': 0,
'scriptPubKey': txo['script'],
'amount': float(txo['amount']),
'confirmations': txo['confirmations'],
'confirmationsFromCache': False
}
utxo.append(newtxo)
return utxo
return None
def getAddressInfo(address):
infos = getUrl(config.BLOCKCHAIN_CONNECT + '/api/v1/address/info/{}'.format(address), )
if 'status' in infos and infos['status'] == 'success':
txs = getUrl(config.BLOCKCHAIN_CONNECT + '/api/v1/address/txs/{}'.format(address), )
if 'status' in txs and txs['status'] == 'success':
transactions = []
for tx in txs['data']['txs']:
transactions.append(tx['tx'])
return {
'addrStr': address,
'balance': infos['data']['balance'],
'balanceSat': infos['data']['balance'] * config.UNIT,
'totalReceived': infos['data']['totalreceived'],
'totalReceivedSat': infos['data']['totalreceived'] * config.UNIT,
'unconfirmedBalance': 0,
'unconfirmedBalanceSat': 0,
'unconfirmedTxApperances': 0,
'txApperances': txs['data']['nb_txs'],
'transactions': transactions
}
return None
def getTxInfo(tx_hash):
tx = getUrl(config.BLOCKCHAIN_CONNECT + '/api/v1/tx/raw/{}'.format(tx_hash))
if tx.get('status') == 'success':
valueOut = 0
for vout in tx['data']['tx']['vout']:
valueOut += vout['value']
return {
'txid': tx_hash,
'version': tx['data']['tx']['version'],
'locktime': tx['data']['tx']['locktime'],
'blockhash': tx['data']['tx'].get('blockhash', None),
'confirmations': tx['data']['tx'].get('confirmations', None),
'time': tx['data']['tx'].get('time', None),
'blocktime': tx['data']['tx'].get('blocktime', None),
'valueOut': valueOut,
'vin': tx['data']['tx']['vin'],
'vout': tx['data']['tx']['vout']
}
return None
def sourceAddressesFromTX(tx_full):
'''Return source (outbound) addresses for a bitcoin tx'''
return [addressForPubKey(i['scriptSig']['asm'].split(" ")[1]) for i in tx_full['vin']]
#This can be replaced with the pycoin function
_b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
def addressForPubKey(pubkey_hex, testnet=None):
if testnet is None:
testnet = config.TESTNET
ripehash = hashlib.new('ripemd160')
step1 = unhexlify(pubkey_hex)
step2 = sha256(step1).digest()
ripehash.update(step2)
if testnet:
step4 = b'\x6F' + ripehash.digest()
else:
step4 = b'\x00' + ripehash.digest()
step5 = sha256(step4).digest()
step6 = sha256(step5).digest()
chksum = step6[:4]
address = step4 + chksum
addr_58 = encodeBase58(address)
return addr_58
def | (v):
long_value = int.from_bytes(v, 'big')
result = ''
while long_value >= 58:
div, mod = divmod(long_value, 58)
result = _b58chars[mod] + result
long_value = div
result = _b58chars[long_value] + result
nPad = 0
for c in v:
if c == ord(b'\0'): nPad += 1
else: break
return (_b58chars[0]*nPad) + result
| encodeBase58 |
router.go | package api
import (
"net/http"
"github.com/ncarlier/webhookd/pkg/config"
) |
// Register HTTP routes...
for _, route := range routes(conf) {
handler := route.HandlerFunc(conf)
for _, mw := range route.Middlewares {
handler = mw(handler)
}
router.Handle(route.Path, handler)
}
return router
} |
// NewRouter creates router with declared routes
func NewRouter(conf *config.Config) *http.ServeMux {
router := http.NewServeMux() |
server.go | package server
import (
"context"
"net/http"
"time"
"github.com/alexanderbez/titan/config"
"github.com/alexanderbez/titan/core"
)
// Server is a simple wrapper around an embedded HTTP server with a logger and
// database.
type Server struct {
*http.Server
db core.DB
logger core.Logger
}
// CreateServer attempts to start a RESTful JSON HTTP service. If the server
// fails to start, an error is returned.
func | (cfg config.Config, db core.DB, logger core.Logger) (*Server, error) {
srvr := &Server{
db: db,
logger: logger.With("module", "server"),
}
srvr.Server = &http.Server{
Addr: cfg.Network.ListenAddr,
Handler: srvr.createRouter(),
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 15 * time.Second,
}
errCh := make(chan error)
// start the server in a go-routine and write to a channel if an error occurs
go func() {
if err := srvr.Server.ListenAndServe(); err != nil {
errCh <- err
}
}()
// Check if there was an error returned by starting the server or wait enough
// time to safely return.
select {
case err := <-errCh:
return nil, err
case <-time.After(1 * time.Second):
return srvr, nil
}
}
// Close attempts to perform a clean shutdown of the server.
func (srvr *Server) Close() {
srvr.logger.Info("shutting down server")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
srvr.SetKeepAlivesEnabled(false)
if err := srvr.Shutdown(ctx); err != nil {
srvr.logger.Fatalf("failed to gracefully shutdown server: %v\n", err)
}
}
| CreateServer |
constrained_type_params.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use rustc::ty::{self, Ty};
use rustc::ty::fold::{TypeFoldable, TypeVisitor};
use rustc::util::nodemap::FxHashSet;
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct Parameter(pub u32);
impl From<ty::ParamTy> for Parameter {
fn from(param: ty::ParamTy) -> Self { Parameter(param.idx) }
}
impl From<ty::EarlyBoundRegion> for Parameter {
fn from(param: ty::EarlyBoundRegion) -> Self { Parameter(param.index) }
}
/// If `include_projections` is false, returns the list of parameters that are
/// constrained by `t` - i.e. the value of each parameter in the list is
/// uniquely determined by `t` (see RFC 447). If it is true, return the list
/// of parameters whose values are needed in order to constrain `ty` - these
/// differ, with the latter being a superset, in the presence of projections.
pub fn parameters_for<'tcx, T>(t: &T,
include_nonconstraining: bool)
-> Vec<Parameter>
where T: TypeFoldable<'tcx>
|
struct ParameterCollector {
parameters: Vec<Parameter>,
include_nonconstraining: bool
}
impl<'tcx> TypeVisitor<'tcx> for ParameterCollector {
fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
match t.sty {
ty::TyProjection(..) | ty::TyAnon(..) if !self.include_nonconstraining => {
// projections are not injective
return false;
}
ty::TyParam(data) => {
self.parameters.push(Parameter::from(data));
}
_ => {}
}
t.super_visit_with(self)
}
fn visit_region(&mut self, r: &'tcx ty::Region) -> bool {
match *r {
ty::ReEarlyBound(data) => {
self.parameters.push(Parameter::from(data));
}
_ => {}
}
false
}
}
pub fn identify_constrained_type_params<'tcx>(predicates: &[ty::Predicate<'tcx>],
impl_trait_ref: Option<ty::TraitRef<'tcx>>,
input_parameters: &mut FxHashSet<Parameter>)
{
let mut predicates = predicates.to_owned();
setup_constraining_predicates(&mut predicates, impl_trait_ref, input_parameters);
}
/// Order the predicates in `predicates` such that each parameter is
/// constrained before it is used, if that is possible, and add the
/// paramaters so constrained to `input_parameters`. For example,
/// imagine the following impl:
///
/// impl<T: Debug, U: Iterator<Item=T>> Trait for U
///
/// The impl's predicates are collected from left to right. Ignoring
/// the implicit `Sized` bounds, these are
/// * T: Debug
/// * U: Iterator
/// * <U as Iterator>::Item = T -- a desugared ProjectionPredicate
///
/// When we, for example, try to go over the trait-reference
/// `IntoIter<u32> as Trait`, we substitute the impl parameters with fresh
/// variables and match them with the impl trait-ref, so we know that
/// `$U = IntoIter<u32>`.
///
/// However, in order to process the `$T: Debug` predicate, we must first
/// know the value of `$T` - which is only given by processing the
/// projection. As we occasionally want to process predicates in a single
/// pass, we want the projection to come first. In fact, as projections
/// can (acyclically) depend on one another - see RFC447 for details - we
/// need to topologically sort them.
///
/// We *do* have to be somewhat careful when projection targets contain
/// projections themselves, for example in
/// impl<S,U,V,W> Trait for U where
/// /* 0 */ S: Iterator<Item=U>,
/// /* - */ U: Iterator,
/// /* 1 */ <U as Iterator>::Item: ToOwned<Owned=(W,<V as Iterator>::Item)>
/// /* 2 */ W: Iterator<Item=V>
/// /* 3 */ V: Debug
/// we have to evaluate the projections in the order I wrote them:
/// `V: Debug` requires `V` to be evaluated. The only projection that
/// *determines* `V` is 2 (1 contains it, but *does not determine it*,
/// as it is only contained within a projection), but that requires `W`
/// which is determined by 1, which requires `U`, that is determined
/// by 0. I should probably pick a less tangled example, but I can't
/// think of any.
pub fn setup_constraining_predicates<'tcx>(predicates: &mut [ty::Predicate<'tcx>],
impl_trait_ref: Option<ty::TraitRef<'tcx>>,
input_parameters: &mut FxHashSet<Parameter>)
{
// The canonical way of doing the needed topological sort
// would be a DFS, but getting the graph and its ownership
// right is annoying, so I am using an in-place fixed-point iteration,
// which is `O(nt)` where `t` is the depth of type-parameter constraints,
// remembering that `t` should be less than 7 in practice.
//
// Basically, I iterate over all projections and swap every
// "ready" projection to the start of the list, such that
// all of the projections before `i` are topologically sorted
// and constrain all the parameters in `input_parameters`.
//
// In the example, `input_parameters` starts by containing `U` - which
// is constrained by the trait-ref - and so on the first pass we
// observe that `<U as Iterator>::Item = T` is a "ready" projection that
// constrains `T` and swap it to front. As it is the sole projection,
// no more swaps can take place afterwards, with the result being
// * <U as Iterator>::Item = T
// * T: Debug
// * U: Iterator
debug!("setup_constraining_predicates: predicates={:?} \
impl_trait_ref={:?} input_parameters={:?}",
predicates, impl_trait_ref, input_parameters);
let mut i = 0;
let mut changed = true;
while changed {
changed = false;
for j in i..predicates.len() {
if let ty::Predicate::Projection(ref poly_projection) = predicates[j] {
// Note that we can skip binder here because the impl
// trait ref never contains any late-bound regions.
let projection = poly_projection.skip_binder();
// Special case: watch out for some kind of sneaky attempt
// to project out an associated type defined by this very
// trait.
let unbound_trait_ref = &projection.projection_ty.trait_ref;
if Some(unbound_trait_ref.clone()) == impl_trait_ref {
continue;
}
// A projection depends on its input types and determines its output
// type. For example, if we have
// `<<T as Bar>::Baz as Iterator>::Output = <U as Iterator>::Output`
// Then the projection only applies if `T` is known, but it still
// does not determine `U`.
let inputs = parameters_for(&projection.projection_ty.trait_ref, true);
let relies_only_on_inputs = inputs.iter().all(|p| input_parameters.contains(&p));
if !relies_only_on_inputs {
continue;
}
input_parameters.extend(parameters_for(&projection.ty, false));
} else {
continue;
}
// fancy control flow to bypass borrow checker
predicates.swap(i, j);
i += 1;
changed = true;
}
debug!("setup_constraining_predicates: predicates={:?} \
i={} impl_trait_ref={:?} input_parameters={:?}",
predicates, i, impl_trait_ref, input_parameters);
}
}
| {
let mut collector = ParameterCollector {
parameters: vec![],
include_nonconstraining: include_nonconstraining
};
t.visit_with(&mut collector);
collector.parameters
} |
combine_ne_terms.py | #!/usr/bin/python3
# Copyright 2021 FBK
# 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
# The script takes two positional arguments:
# 1. The IOB file containing the NE annotations
# 2. The IOB file containing the terminology annotation
# And it deals with the merge of the two files into a single IOB file
# giving priority to NE when there is a conflict in the annotations and
# recovering from possibly different tokenization of the two files.
# The output is written to stdout, so an example of usage of this script is:
# python combine_ne_terms.py ne.iob.en terms.iob.en > all.iob.en
# If using, please cite:
# M. Gaido et al., 2021. Is "moby dick" a Whale or a Bird? Named Entities and Terminology in Speech Translation,
# Proceedings of the 2021 Conference on Empirical Methods in Natural Language Processing (EMNLP)
import sys
ner_detected_fn = sys.argv[1]
term_detected_fn = sys.argv[2]
def select_type(types):
# It might continue in the next line...
if types[-1] != "O":
return types[-1]
return sorted(types, key=types.count, reverse=True)[0]
NER_BUFFER = []
NER_TYPES_BUFFER = []
term_line = None
prev_type = None
l_idx = 0
with open(ner_detected_fn) as ner_f, open(term_detected_fn) as term_f:
for ner_line in ner_f:
ner_items = ner_line.split('\t')
if len(ner_items) < 3:
term_line = term_f.readline()
assert len(term_line.split('\t')) < 3, "Mismatch at line: {} --- {}".format(ner_line, term_line)
l_idx = 0
sys.stdout.write(ner_line)
else:
assert len(ner_items) == 3
if len(NER_BUFFER) == 0:
term_line = term_f.readline()
term_items = [t.strip() for t in term_line.split("\t")]
NER_BUFFER.append(ner_items[1])
ner_term = "".join(NER_BUFFER)
ner_type = ner_items[2].strip()
if ner_term == term_items[1]:
if NER_TYPES_BUFFER:
NER_TYPES_BUFFER.append(ner_type)
ner_types = [t.split("-")[-1] for t in NER_TYPES_BUFFER]
ner_type = select_type(ner_types)
if ner_type != "O":
if "B" in [t.split("-")[0] for t in NER_TYPES_BUFFER]:
ner_type = "B-" + ner_type
else:
ner_type = "I-" + ner_type
NER_BUFFER = []
NER_TYPES_BUFFER = []
else:
if len(ner_term) < len(term_items[1]):
NER_TYPES_BUFFER.append(ner_type)
continue
else:
term_term = term_items[1]
term_types_buffer = [term_items[2]]
term_ids = []
if len(term_items) > 3:
term_ids.append(term_items[3])
missing_ner_items = False
while term_term != ner_term:
if len(ner_term) > len(term_term):
term_line = term_f.readline()
term_items = term_line.split("\t")
term_term += term_items[1]
term_types_buffer.append(term_items[2].strip())
if len(term_items) > 3:
term_ids.append(term_items[3].strip())
else:
missing_ner_items = True
break
term_types = [t.split("-")[-1] for t in term_types_buffer]
term_type = select_type(term_types)
if term_type != "O":
if "B" in [t.split("-")[0] for t in term_types_buffer]:
term_type = "B-" + term_type
else:
term_type = "I-" + term_type
term_items = [term_items[0], term_term, term_type, "".join(term_ids)]
else:
term_items = [term_items[0], term_term, term_type]
if missing_ner_items:
continue
else:
NER_BUFFER = []
NER_TYPES_BUFFER = []
l_idx += 1
if ner_type.strip() == 'O':
if term_items[2] == "I-TERM" and prev_type not in ["B-TERM", "I-TERM"]:
# Most likely part of a term has been considered as a NE, so ignore it
term_items[2] = "O"
sys.stdout.write("{}\t{}\n".format(l_idx, "\t".join(term_items[1:]))) | sys.stdout.write("{}\t{}\t{}\n".format(l_idx, ner_term, ner_type))
prev_type = ner_type | prev_type = term_items[2]
else:
if ner_type.startswith("I-") and prev_type not in [ner_type, "B-" + ner_type.split("-")[1]]:
ner_type = "B-" + ner_type.split("-")[1] |
char.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Character manipulation.
//!
//! For more details, see ::unicode::char (a.k.a. std::char)
#![allow(non_snake_case)]
#![doc(primitive = "char")]
use mem::transmute;
use option::{None, Option, Some};
use iter::range_step;
use slice::SlicePrelude;
// UTF-8 ranges and tags for encoding characters
static TAG_CONT: u8 = 0b1000_0000u8;
static TAG_TWO_B: u8 = 0b1100_0000u8;
static TAG_THREE_B: u8 = 0b1110_0000u8;
static TAG_FOUR_B: u8 = 0b1111_0000u8;
static MAX_ONE_B: u32 = 0x80u32;
static MAX_TWO_B: u32 = 0x800u32;
static MAX_THREE_B: u32 = 0x10000u32;
/*
Lu Uppercase_Letter an uppercase letter
Ll Lowercase_Letter a lowercase letter
Lt Titlecase_Letter a digraphic character, with first part uppercase
Lm Modifier_Letter a modifier letter
Lo Other_Letter other letters, including syllables and ideographs
Mn Nonspacing_Mark a nonspacing combining mark (zero advance width)
Mc Spacing_Mark a spacing combining mark (positive advance width)
Me Enclosing_Mark an enclosing combining mark
Nd Decimal_Number a decimal digit
Nl Letter_Number a letterlike numeric character
No Other_Number a numeric character of other type
Pc Connector_Punctuation a connecting punctuation mark, like a tie
Pd Dash_Punctuation a dash or hyphen punctuation mark
Ps Open_Punctuation an opening punctuation mark (of a pair)
Pe Close_Punctuation a closing punctuation mark (of a pair)
Pi Initial_Punctuation an initial quotation mark
Pf Final_Punctuation a final quotation mark
Po Other_Punctuation a punctuation mark of other type
Sm Math_Symbol a symbol of primarily mathematical use
Sc Currency_Symbol a currency sign
Sk Modifier_Symbol a non-letterlike modifier symbol
So Other_Symbol a symbol of other type
Zs Space_Separator a space character (of various non-zero widths)
Zl Line_Separator U+2028 LINE SEPARATOR only
Zp Paragraph_Separator U+2029 PARAGRAPH SEPARATOR only
Cc Control a C0 or C1 control code
Cf Format a format control character
Cs Surrogate a surrogate code point
Co Private_Use a private-use character
Cn Unassigned a reserved unassigned code point or a noncharacter
*/
/// The highest valid code point
pub const MAX: char = '\U0010ffff';
/// Converts from `u32` to a `char`
#[inline]
pub fn from_u32(i: u32) -> Option<char> {
// catch out-of-bounds and surrogates
if (i > MAX as u32) || (i >= 0xD800 && i <= 0xDFFF) {
None
} else {
Some(unsafe { transmute(i) })
}
}
///
/// Checks if a `char` parses as a numeric digit in the given radix
///
/// Compared to `is_digit()`, this function only recognizes the
/// characters `0-9`, `a-z` and `A-Z`.
///
/// # Return value
///
/// Returns `true` if `c` is a valid digit under `radix`, and `false`
/// otherwise.
///
/// # Failure
///
/// Fails if given a `radix` > 36.
///
/// # Note
///
/// This just wraps `to_digit()`.
///
#[inline]
pub fn is_digit_radix(c: char, radix: uint) -> bool {
match to_digit(c, radix) {
Some(_) => true,
None => false,
}
}
///
/// Converts a `char` to the corresponding digit
///
/// # Return value
///
/// If `c` is between '0' and '9', the corresponding value
/// between 0 and 9. If `c` is 'a' or 'A', 10. If `c` is
/// 'b' or 'B', 11, etc. Returns none if the `char` does not
/// refer to a digit in the given radix.
///
/// # Failure
///
/// Fails if given a `radix` outside the range `[0..36]`.
///
#[inline]
pub fn to_digit(c: char, radix: uint) -> Option<uint> {
if radix > 36 {
panic!("to_digit: radix is too high (maximum 36)");
}
let val = match c {
'0' ... '9' => c as uint - ('0' as uint),
'a' ... 'z' => c as uint + 10u - ('a' as uint),
'A' ... 'Z' => c as uint + 10u - ('A' as uint),
_ => return None,
};
if val < radix { Some(val) }
else { None }
}
///
/// Converts a number to the character representing it
///
/// # Return value
///
/// Returns `Some(char)` if `num` represents one digit under `radix`,
/// using one character of `0-9` or `a-z`, or `None` if it doesn't.
///
/// # Failure
///
/// Fails if given an `radix` > 36.
///
#[inline]
pub fn from_digit(num: uint, radix: uint) -> Option<char> {
if radix > 36 {
panic!("from_digit: radix is to high (maximum 36)");
}
if num < radix {
unsafe {
if num < 10 {
Some(transmute(('0' as uint + num) as u32))
} else {
Some(transmute(('a' as uint + num - 10u) as u32))
}
}
} else {
None
}
}
///
/// Returns the hexadecimal Unicode escape of a `char`
///
/// The rules are as follows:
///
/// - chars in [0,0xff] get 2-digit escapes: `\\xNN`
/// - chars in [0x100,0xffff] get 4-digit escapes: `\\uNNNN`
/// - chars above 0x10000 get 8-digit escapes: `\\UNNNNNNNN`
///
pub fn escape_unicode(c: char, f: |char|) {
// avoid calling str::to_str_radix because we don't really need to allocate
// here.
f('\\');
let pad = match () {
_ if c <= '\x7f' => { f('x'); 2 }
_ if c <= '\uffff' => { f('u'); 4 }
_ => { f('U'); 8 }
};
for offset in range_step::<i32>(4 * (pad - 1), -1, -4) {
let offset = offset as uint;
unsafe {
match ((c as i32) >> offset) & 0xf {
i @ 0 ... 9 => { f(transmute('0' as i32 + i)); }
i => { f(transmute('a' as i32 + (i - 10))); }
}
}
}
}
///
/// Returns a 'default' ASCII and C++11-like literal escape of a `char`
///
/// The default is chosen with a bias toward producing literals that are
/// legal in a variety of languages, including C++11 and similar C-family
/// languages. The exact rules are:
///
/// - Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively.
/// - Single-quote, double-quote and backslash chars are backslash-escaped.
/// - Any other chars in the range [0x20,0x7e] are not escaped.
/// - Any other chars are given hex Unicode escapes; see `escape_unicode`.
///
pub fn escape_default(c: char, f: |char|) {
match c {
'\t' => { f('\\'); f('t'); }
'\r' => { f('\\'); f('r'); }
'\n' => { f('\\'); f('n'); }
'\\' => { f('\\'); f('\\'); }
'\'' => { f('\\'); f('\''); }
'"' => { f('\\'); f('"'); }
'\x20' ... '\x7e' => { f(c); }
_ => c.escape_unicode(f),
}
}
/// Returns the amount of bytes this `char` would need if encoded in UTF-8
#[inline]
pub fn len_utf8_bytes(c: char) -> uint {
let code = c as u32;
match () {
_ if code < MAX_ONE_B => 1u,
_ if code < MAX_TWO_B => 2u,
_ if code < MAX_THREE_B => 3u,
_ => 4u,
}
}
/// Basic `char` manipulations.
pub trait Char {
/// Checks if a `char` parses as a numeric digit in the given radix.
///
/// Compared to `is_digit()`, this function only recognizes the characters
/// `0-9`, `a-z` and `A-Z`.
///
/// # Return value
///
/// Returns `true` if `c` is a valid digit under `radix`, and `false`
/// otherwise.
///
/// # Failure
///
/// Fails if given a radix > 36.
fn is_digit_radix(&self, radix: uint) -> bool;
/// Converts a character to the corresponding digit.
///
/// # Return value
///
/// If `c` is between '0' and '9', the corresponding value between 0 and
/// 9. If `c` is 'a' or 'A', 10. If `c` is 'b' or 'B', 11, etc. Returns
/// none if the character does not refer to a digit in the given radix.
///
/// # Failure
///
/// Fails if given a radix outside the range [0..36].
fn to_digit(&self, radix: uint) -> Option<uint>;
/// Converts a number to the character representing it.
///
/// # Return value
///
/// Returns `Some(char)` if `num` represents one digit under `radix`,
/// using one character of `0-9` or `a-z`, or `None` if it doesn't.
///
/// # Failure
///
/// Fails if given a radix > 36.
fn from_digit(num: uint, radix: uint) -> Option<Self>;
/// Returns the hexadecimal Unicode escape of a character.
///
/// The rules are as follows:
///
/// * Characters in [0,0xff] get 2-digit escapes: `\\xNN`
/// * Characters in [0x100,0xffff] get 4-digit escapes: `\\uNNNN`.
/// * Characters above 0x10000 get 8-digit escapes: `\\UNNNNNNNN`.
fn escape_unicode(&self, f: |char|);
/// Returns a 'default' ASCII and C++11-like literal escape of a
/// character.
///
/// The default is chosen with a bias toward producing literals that are
/// legal in a variety of languages, including C++11 and similar C-family
/// languages. The exact rules are:
///
/// * Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively.
/// * Single-quote, double-quote and backslash chars are backslash-
/// escaped.
/// * Any other chars in the range [0x20,0x7e] are not escaped.
/// * Any other chars are given hex Unicode escapes; see `escape_unicode`.
fn escape_default(&self, f: |char|);
/// Returns the amount of bytes this character would need if encoded in
/// UTF-8.
fn len_utf8_bytes(&self) -> uint;
/// Encodes this character as UTF-8 into the provided byte buffer,
/// and then returns the number of bytes written.
///
/// If the buffer is not large enough, nothing will be written into it
/// and a `None` will be returned.
fn encode_utf8(&self, dst: &mut [u8]) -> Option<uint>;
/// Encodes this character as UTF-16 into the provided `u16` buffer,
/// and then returns the number of `u16`s written.
///
/// If the buffer is not large enough, nothing will be written into it
/// and a `None` will be returned.
fn encode_utf16(&self, dst: &mut [u16]) -> Option<uint>;
}
impl Char for char {
fn is_digit_radix(&self, radix: uint) -> bool { is_digit_radix(*self, radix) }
fn to_digit(&self, radix: uint) -> Option<uint> { to_digit(*self, radix) }
fn from_digit(num: uint, radix: uint) -> Option<char> |
fn escape_unicode(&self, f: |char|) { escape_unicode(*self, f) }
fn escape_default(&self, f: |char|) { escape_default(*self, f) }
#[inline]
fn len_utf8_bytes(&self) -> uint { len_utf8_bytes(*self) }
#[inline]
fn encode_utf8<'a>(&self, dst: &'a mut [u8]) -> Option<uint> {
// Marked #[inline] to allow llvm optimizing it away
let code = *self as u32;
if code < MAX_ONE_B && dst.len() >= 1 {
dst[0] = code as u8;
Some(1)
} else if code < MAX_TWO_B && dst.len() >= 2 {
dst[0] = (code >> 6u & 0x1F_u32) as u8 | TAG_TWO_B;
dst[1] = (code & 0x3F_u32) as u8 | TAG_CONT;
Some(2)
} else if code < MAX_THREE_B && dst.len() >= 3 {
dst[0] = (code >> 12u & 0x0F_u32) as u8 | TAG_THREE_B;
dst[1] = (code >> 6u & 0x3F_u32) as u8 | TAG_CONT;
dst[2] = (code & 0x3F_u32) as u8 | TAG_CONT;
Some(3)
} else if dst.len() >= 4 {
dst[0] = (code >> 18u & 0x07_u32) as u8 | TAG_FOUR_B;
dst[1] = (code >> 12u & 0x3F_u32) as u8 | TAG_CONT;
dst[2] = (code >> 6u & 0x3F_u32) as u8 | TAG_CONT;
dst[3] = (code & 0x3F_u32) as u8 | TAG_CONT;
Some(4)
} else {
None
}
}
#[inline]
fn encode_utf16(&self, dst: &mut [u16]) -> Option<uint> {
// Marked #[inline] to allow llvm optimizing it away
let mut ch = *self as u32;
if (ch & 0xFFFF_u32) == ch && dst.len() >= 1 {
// The BMP falls through (assuming non-surrogate, as it should)
dst[0] = ch as u16;
Some(1)
} else if dst.len() >= 2 {
// Supplementary planes break into surrogates.
ch -= 0x1_0000_u32;
dst[0] = 0xD800_u16 | ((ch >> 10) as u16);
dst[1] = 0xDC00_u16 | ((ch as u16) & 0x3FF_u16);
Some(2)
} else {
None
}
}
}
| { from_digit(num, radix) } |
constants.rs | pub(crate) const HANGEUL_OFFSET: u32 = 0xAC00;
pub(crate) const SYLLABLE_START: u32 = 0xAC00;
pub(crate) const SYLLABLE_END: u32 = 0xD7A3;
pub(crate) const JUNGSEONG_COUNT: u32 = 21;
pub(crate) const JONGSEONG_COUNT: u32 = 28;
// normal | pub(crate) const CHOSEONG_START: u32 = 0x1100;
// pub(crate) const CHOSEONG_END: u32 = 0x1112;
pub(crate) const JUNGSEONG_START: u32 = 0x1161;
// pub(crate) const JUNGSEONG_END: u32 = 0x1175;
pub(crate) const JONGSEONG_START: u32 = 0x11A8;
// pub(crate) const JONGSEONG_END: u32 = 0x11C2;
// compat
pub(crate) const COMPAT_JAMO_START: u32 = COMPAT_CHOSEONG_START;
pub(crate) const COMPAT_JAMO_END: u32 = COMPAT_JONGSEONG_END;
pub(crate) const COMPAT_CHOSEONG_START: u32 = 0x3131;
// pub(crate) const COMPAT_CHOSEONG_END: u32 = 0x314E;
// pub(crate) const COMPAT_JUNGSEONG_START: u32 = 0x314F;
// pub(crate) const COMPAT_JUNGSEONG_END: u32 = 0x3163;
// pub(crate) const COMPAT_JONGSEONG_START: u32 = 0x3165;
pub(crate) const COMPAT_JONGSEONG_END: u32 = 0x318E; | pub(crate) const JAMO_START: u32 = 0x1100;
pub(crate) const JAMO_END: u32 = 0x11ff;
|
__init__.py | # Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
#
# 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. | # |
command-collection.test.ts | import { CommandCollection } from '../command-collection';
const MockCommands = () => ({
standard: {
name: 'standard',
execute: jest.fn()
},
hasAlias: {
name: 'hasAlias',
aliases: ['hasAl'], | });
describe('CommandCollection', () => {
let mockCommands: ReturnType<typeof MockCommands>;
beforeEach(() => {
mockCommands = MockCommands();
});
describe('getCommand', () => {
it('gets a command by its name', () => {
const commands = new CommandCollection([mockCommands.standard]);
const command = commands.getCommand('standard');
expect(command).toEqual(mockCommands.standard);
});
it('gets a command by alias', () => {
const commands = new CommandCollection([mockCommands.hasAlias]);
const command = commands.getCommand('hasAl');
expect(command).toEqual(mockCommands.hasAlias);
});
});
}); | execute: jest.fn()
} |
serializers.py | from rest_framework import serializers
from .models import Skill, Task, Days
class SkillSerializer(serializers.ModelSerializer):
class Meta:
model = Skill
fields = ('name', 'user')
class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Task
fields = ('name', 'completion_time', 'skill')
class | (serializers.ModelSerializer):
class Meta:
model = Days
fields = ('monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', 'user')
| DaysSerializer |
ident.rs | use span::Span;
macro_attr_many! {
/// An identifier: `channels`, `SendMessageAction`, `X`, etc..
#[cfg_derive!(Clone, Debug)]
pub struct Ident {
span: Span,
string: String,
}
}
impl Ident {
/// Create a new `Ident` with the given `span` and the given `string` if
/// the string is a valid TL language identifier.
pub fn new(span: Span, string: &str) -> Option<Ident> {
if is_valid_ident(string) {
Some(Ident {
span,
string: string.to_owned(),
})
} else {
None
}
}
/// Create a new `Ident` with the given `span` and the given `string`
/// without checking the string.
///
/// # Safety
///
/// The string must be a valid TL language identifier.
///
/// If conditions are not met, it is a violation of safety guarantees.
pub unsafe fn new_unchecked(span: Span, string: &str) -> Ident {
Ident {
span,
string: string.to_owned(),
}
}
/// Extract a string view into this `Ident`.
pub fn as_str(&self) -> &str {
&self.string
}
/// Return true if the first character of this `Ident` is lowercase, and
/// false otherwise.
pub fn is_lowercase(&self) -> bool {
match self.string.chars().next() {
Some(c) => c.is_lowercase(),
None => unreachable!("There must be at least one char for any `Ident`"),
}
}
/// Return true if the first character of this `Ident` is uppercase, and
/// false otherwise.
pub fn is_uppercase(&self) -> bool {
match self.string.chars().next() {
Some(c) => c.is_uppercase(),
None => unreachable!("There must be at least one char for any `Ident`"),
}
}
}
#[cfg(feature = "eq-impls")]
mod eq_impls {
use super::*;
impl Eq for Ident {}
impl PartialEq for Ident {
fn eq(&self, other: &Ident) -> bool {
self.string == other.string
}
}
}
#[cfg(feature = "hash-impls")]
mod hash_impls {
use std::hash::{Hash, Hasher};
use super::*;
impl Hash for Ident {
fn hash<H: Hasher>(&self, state: &mut H) {
self.string.hash(state)
}
}
}
mod spanned {
use super::*;
use span::Span;
use spanned::Spanned;
use spanned::private::Sealed;
impl Sealed for Ident {}
impl Spanned for Ident {
fn span(&self) -> Span {
self.span
}
}
}
#[cfg(feature = "parsing")]
mod parsing {
use super::*;
use cursor::Cursor;
use synom::Synom;
use synom::private::Sealed;
impl Sealed for Ident {}
impl Synom for Ident {
named!(parse_cursor(Cursor) -> Ident, do_parse!(
ident_str_cursor: take_while!(is_ident_char) >>
ident_str: verify!(value!(ident_str_cursor.to_str()), is_valid_ident) >>
(Ident {
span: ident_str_cursor.span(),
string: ident_str.to_owned(),
})
));
}
}
#[cfg(feature = "printing")]
mod printing {
use std::fmt;
use super::*;
use print::Print;
use print::private::Sealed;
impl Sealed for Ident {}
impl Print for Ident {
fn print(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&self.string, f)
}
}
}
// A valid identifier char must be either of:
// * uppercase Latin letter
// * lowercase Latin letter
// * decimal digit
// * underscore
fn is_ident_char(c: char) -> bool {
match c {
'A' ... 'Z' |
'a' ... 'z' |
'0' ... '9' |
'_' => true,
_ => false,
}
}
// A valid identifier beginning char must be either of:
// * uppercase Latin letter
// * lowercase Latin letter
fn is_ident_beginning_char(c: char) -> bool {
match c {
'A' ... 'Z' |
'a' ... 'z' => true,
_ => false,
}
}
// A valid identifier must:
// + be non-empty
// + begin with either an uppercase or a lowercase Latin letter
// + contain an uppercase or a lowercase Latin letter, a decimal digit or an underscore in other
// positions
fn is_valid_ident(s: &str) -> bool {
let mut chars = s.chars();
match chars.next() {
Some(c) => is_ident_beginning_char(c) && chars.all(is_ident_char),
None => false,
}
}
#[cfg(test)]
mod tests {
#[cfg(feature = "eq-impls")]
use super::*;
#[cfg(feature = "eq-impls")]
use utils::tests::test_span_permutations;
#[cfg(all(feature = "eq-impls", feature = "hash-impls"))]
use utils::tests::get_hasher_state;
#[cfg(feature = "eq-impls")]
fn test_ident_span_permutations<FT, FA1, FA2>(
test_eq: FT,
assert_when_eq: FA1,
assert_when_ne: FA2,
)
where
FT: Fn(&Ident, &Ident) -> bool,
FA1: Fn(&Ident, &Ident),
FA2: Fn(&Ident, &Ident),
|
#[cfg(feature = "eq-impls")]
#[test]
fn eq_does_not_depend_on_span() {
test_ident_span_permutations(
|x, y| x.string == y.string,
|x, y| any_debug_assert_eq!(x, y),
|x, y| any_debug_assert_ne!(x, y),
);
}
#[cfg(all(feature = "eq-impls", feature = "hash-impls"))]
#[test]
fn eq_hash_property() {
test_ident_span_permutations(
|x, y| x == y,
|x, y| any_debug_assert_eq!(get_hasher_state(x), get_hasher_state(y)),
|x, y| any_debug_assert_ne!(get_hasher_state(x), get_hasher_state(y)),
);
}
}
| {
let idents = ["B", "j", "x_z", "EasyHaricotPlantInformedFacetItemPlant", "r2d2"];
assert!(idents.iter().all(|ident| is_valid_ident(ident)));
for ident1 in &idents {
for ident2 in &idents {
test_span_permutations(
|span1| Ident { span: span1, string: (*ident1).to_owned() },
|span2| Ident { span: span2, string: (*ident2).to_owned() },
&test_eq,
&assert_when_eq,
&assert_when_ne,
);
}
}
} |
prepare_pgmodel.py | #!/usr/bin/env python
from pandas import *
from numpy import *
from djeval import *
import csv, code
import pickle as pickle
from sklearn.externals import joblib
NUM_GAMES=50000
def shell():
vars = globals()
vars.update(locals())
shell = code.InteractiveConsole(vars)
shell.interact()
msg("Hi! Reading eheaders")
eheaders_filename = '/data/eheaders.p'
eheaders_file = open(eheaders_filename, 'r')
eheaders = pickle.load(eheaders_file)
elos = eheaders['elos']
result = eheaders['result']
checkmate = eheaders['checkmate']
openings = eheaders['openings']
ocount = eheaders['opening_count']
msg("Hi! Reading crunched movescores from %s" % sys.argv[1])
crunched_path = sys.argv[1]
crunched_df = read_csv(crunched_path, sep=',', engine='c', index_col=['gamenum', 'side'])
do_gb = False
if do_gb:
msg("Hi! Reading GB scores from %s" % sys.argv[2])
gb_path = sys.argv[2]
gb_df = read_csv(gb_path, sep=',', engine='c', index_col=['gamenum'])
msg("Hi! Reading depthstats")
depthstats_path = '/data/depthstats.csv'
columns = [
'gamenum',
'side',
'mean_depth',
'mean_seldepth',
'mean_depths_agreeing_ratio',
'mean_deepest_agree_ratio',
'pct_sanemoves',
'gamelength',
'mean_num_bestmoves',
'mean_num_bestmove_changes',
'mean_bestmove_depths_agreeing',
'mean_deepest_change',
'mean_deepest_change_ratio',
]
depthstats_df = read_csv(depthstats_path, sep=' ', engine='c', header=None, names=columns, index_col=False)
depthstats_df = depthstats_df.set_index(['gamenum', 'side'])
# we have the gamelength column in another df, drop it here to avoid conflicts
depthstats_df.drop('gamelength', axis=1, inplace=True)
do_material = True
if do_material:
msg("Hi! Reading material")
material_path = '/data/material.csv'
columns = [
'gamenum',
'material_break_0',
'material_break_1',
'material_break_2',
'material_break_3',
'material_break_4',
| 'mean_acwsa',
'mean_acwsa_0',
'mean_acwsa_1',
'mean_acwsa_2',
'mean_acwsa_3',
'mean_acwsa_4',
'mean_acwsa_5',
'mean_acwsa_6',
'mean_acwsa_7',
'mean_acwsa_8',
'mean_acwsa_9',
]
material_df = read_csv(material_path, sep=' ', engine='c', header=None, names=columns, index_col=False)
material_df = material_df.set_index(['gamenum'])
material_df = material_df.reindex(list(range(1, NUM_GAMES+1)))
material_df = material_df.fillna(material_df.mean())
msg("Reading ELOscored data")
eloscored_cols = [
'gamenum',
'final_elo',
'final_ply',
'final_num_games',
'final_elo_stdev',
'elopath_min',
'elopath_max',
]
eloscored_df = read_csv('/data/data.pgn.eloscored21', sep=',', engine='c', header=None, names=eloscored_cols, index_col=False)
eloscored_df = eloscored_df.set_index(['gamenum'])
msg("Reading ELOscored data 4")
eloscored4_cols = [
'gamenum',
'final_elo',
'final_ply',
'final_num_games',
'final_elo_stdev',
]
eloscored4_cols[1:] = [x + '_elo4' for x in eloscored4_cols[1:]]
eloscored4_df = read_csv('/data/data.pgn.eloscored4', sep=',', engine='c', header=None, names=eloscored4_cols, index_col=False)
eloscored4_df = eloscored4_df.set_index(['gamenum'])
msg("Reading ELOscored data 10")
eloscored10_cols = [
'gamenum',
'final_elo',
'final_ply',
'final_num_games',
'final_elo_stdev',
]
eloscored10_cols[1:] = [x + '_elo10' for x in eloscored10_cols[1:]]
eloscored10_df = read_csv('/data/data.pgn.eloscored10', sep=',', engine='c', header=None, names=eloscored10_cols, index_col=False)
eloscored10_df = eloscored10_df.set_index(['gamenum'])
do_movemodel=True
if do_movemodel:
msg("Hi! Reading moveaggs")
move_aggs = joblib.load('/data/move_aggs.p')
move_aggs.fillna(move_aggs.mean(), inplace=True)
move_aggs = move_aggs[['mean', 'median', '25', '10', 'min', 'max', 'stdev']]
msg("Hi! Reading wmoveaggs")
wmove_aggs = joblib.load('/data/wmove_aggs.p')
wmove_aggs.fillna(wmove_aggs.mean(), inplace=True)
wmove_aggs.rename(columns={'elo_pred': 'moveelo_weighted'}, inplace=True)
wmove_aggs = wmove_aggs['moveelo_weighted']
do_elochunk = False
if do_elochunk:
ch_agg_df = joblib.load('/data/chunk_aggs.p')
ch_agg_df.index = ch_agg_df.index.droplevel('elo')
ch_agg_df.columns = ['elochunk_' + x for x in ch_agg_df.columns]
msg("Hi! Setting up playergame rows")
if do_elochunk:
elorange_cols = list(ch_agg_df.columns.values)
msg("elorange cols are %s" % elorange_cols)
msg('Preparing ELO df')
elo_rows = [[x[0][0], x[0][1], x[1]] for x in list(elos.items())]
elo_df = DataFrame(elo_rows, columns=['gamenum','side','elo'])
elo_df.set_index(['gamenum','side'], inplace=True)
msg('Joining DFs')
supplemental_dfs = [depthstats_df, elo_df, crunched_df]
if do_movemodel:
supplemental_dfs.extend([move_aggs, wmove_aggs])
if do_elochunk:
supplemental_dfs.append(ch_agg_df)
mega_df = concat(supplemental_dfs, axis=1)
if do_material:
mega_df = mega_df.join(material_df, how='outer')
mega_df = mega_df.join(eloscored_df, how='outer')
mega_df = mega_df.join(eloscored4_df, how='outer')
mega_df = mega_df.join(eloscored10_df, how='outer')
if do_gb:
mega_df = mega_df.join(gb_df, how='outer')
yy_df = mega_df
msg("hi, columns are %s" % yy_df.columns)
# TODO confirm that all columns are there
def opening_feature(opening):
if ocount[opening] < 20:
return 'rare'
if ocount[opening] < 200:
return 'uncommon'
return opening
msg("Hi! Computing additional features")
yy_df['opening_feature'] = [opening_feature(openings[x]) for x in yy_df.index.get_level_values('gamenum')]
yy_df['opening_count'] = [ocount[openings[x]] for x in yy_df.index.get_level_values('gamenum')]
yy_df['any_grit'] = (yy_df['grit'] > 0)
yy_df['major_grit'] = (yy_df['grit'] > 5)
yy_df['nmerror'] = log((-1 * yy_df['meanerror']).clip(1,60)).clip(1,4) - 2.53
yy_df['premature_quit'] = (yy_df['gameoutcome'] == -1) & (yy_df['my_final_equity'] > -100)
yy_df['drawn_game'] = (yy_df['gameoutcome'] == 0)
yy_df['ended_by_checkmate'] = yy_df['won_by_checkmate'] | yy_df['lost_by_checkmate']
yy_df['noblunders'] = (yy_df['blunderrate'] == 0)
yy_df['final_equity'] = yy_df['my_final_equity'].abs().clip(0,300)
yy_df['early_lead'] = yy_df['early_lead'].clip(0,100)
yy_df['mean_depth_clipped'] = yy_df['mean_depth'].clip(0,25)
yy_df['gamelength_clipped'] = yy_df['gamelength'].clip(20,200)
# prepare opponent_df with selected info about opponent
opponent_columns = ['meanerror', 'blunderrate', 'perfectrate', 'grit', 'meanecho', 'mate_created', 'mate_destroyed', 'q_error_one', 'q_error_two', 'stdeverror', 'elo', 'any_grit', 'noblunders', 'nmerror', 'mean_depths_agreeing_ratio', 'mean_deepest_agree_ratio', 'pct_sanemoves']
if do_elochunk:
opponent_columns.extend(elorange_cols)
opponent_df = yy_df[opponent_columns]
opponent_df = opponent_df.reset_index()
opponent_df['side'] = opponent_df['side'] * -1
opponent_df.set_index(['gamenum', 'side'], inplace=True)
opponent_df.columns = ['opponent_' + x for x in opponent_df.columns]
yy_df = concat([yy_df, opponent_df], axis=1)
# more derived columns that use opponent comparisons
yy_df['elo_advantage'] = (yy_df['elo'] - yy_df['opponent_elo']).clip(-500, 500)
yy_df['max_nmerror'] = yy_df[['nmerror', 'opponent_nmerror']].max(axis=1)
yy_df['min_nmerror'] = yy_df[['nmerror', 'opponent_nmerror']].min(axis=1)
yy_df['max_meanecho'] = yy_df[['meanecho', 'opponent_meanecho']].max(axis=1)
yy_df['elo_avg'] = (yy_df['elo'] + yy_df['opponent_elo'])/2.0
yy_df['elo_advantage'] = (yy_df['elo'] - yy_df['opponent_elo'])
yy_df['winner_elo_advantage'] = yy_df['elo_advantage'] * yy_df['gameoutcome']
msg("Hi! Computing dummy variables")
categorical_features = ['opening_feature']
dummies = get_dummies(yy_df[categorical_features]).astype(np.int8)
yy_df = yy_df.join(dummies)
# fill in missing values
msg("Hi! Filling in missing values")
full_index = pandas.MultiIndex.from_product([list(range(1,NUM_GAMES + 1)), [1,-1]], names=['gamenum', 'side'])
yy_df = yy_df.reindex(full_index)
yy_elo = yy_df['elo'].copy(True)
yy_df.fillna(yy_df.mean(numeric_only=True), inplace=True)
yy_df.fillna(False, inplace=True)
yy_df['elo'] = yy_elo
# stupid patch for some stupid opening feature that got assigned to False by fillna ?!!?!?!?
yy_df.loc[yy_df['opening_feature'] == False,'opening_feature'] = 'rare'
msg("Hi! Writing yy_df to disk")
yy_df.to_pickle(sys.argv[3])
msg("Column counts are:")
counts = yy_df.count(axis=0)
print(counts) | 'opening_length',
'midgame_length',
'endgame_length',
|
flags.py | '''
Several testcases around <Flags> and <Flag>.
'''
import sys
sys.path.append("c:/peach")
from Peach.Generators.dictionary import *
from Peach.Generators.static import *
import unittest
import utils
import struct
def suite():
suite = unittest.TestSuite()
suite.addTest(FlagsInputTestCase())
suite.addTest(FlagsOutputTestCase())
#suite.addTest(Flags1TestCase())
#suite.addTest(Flags2TestCase())
#suite.addTest(Flags3TestCase())
#suite.addTest(Flags4TestCase())
#suite.addTest(Flags5TestCase())
#suite.addTest(Flags6TestCase())
suite.addTest(Flags7TestCase())
suite.addTest(Flags8TestCase())
return suite
class FlagsInputTestCase(utils.PeachSendAndRecvTestCase):
def runTest(self):
# Test
gen = Flags2(None, 8, [ [0, 1, Static(1)], [1, 2, Static(2)], [3, 2, Static(3)], [5, 3, Static(4)] ])
value = struct.pack("B", int(str(gen.getValue())))
self.peachUtils.SetSendAndReceiveData(value)
self.peachUtils.RunPeachXml("flagsInput.xml")
ret = str(self.peachUtils.GetListenerData())
assert ret == '4', 'flagsInput.xml failed, instead [%s]' % repr(ret)
class FlagsOutputTestCase(utils.PeachTcpTestCase):
def runTest(self):
# Test
|
#class Flags1TestCase(utils.PeachTcpTestCase):
#
# def runTest(self):
# # Test
#
# self.peachUtils.RunPeachXml("flags1.xml")
# ret = struct.unpack("B", str(self.peachUtils.GetListenerData()))[0]
#
# assert ret == 163, 'flags1.xml failed, instead [%s]' % repr(ret)
#
#class Flags2TestCase(utils.PeachTcpTestCase):
#
# def runTest(self):
# # Test
#
# self.peachUtils.RunPeachXml("flags2.xml")
# ret = struct.unpack("B", str(self.peachUtils.GetListenerData()))[0]
#
# assert ret == 131, 'flags2.xml failed, instead [%s]' % repr(ret)
#
#class Flags3TestCase(utils.PeachTcpTestCase):
#
# def runTest(self):
# # Test
#
# self.peachUtils.RunPeachXml("flags3.xml")
# ret = struct.unpack("!H", str(self.peachUtils.GetListenerData()))[0]
#
# assert ret == 65411, 'flags3.xml failed, instead [%s]' % repr(ret)
#
#class Flags4TestCase(utils.PeachTcpTestCase):
#
# def runTest(self):
# # Test
#
# self.peachUtils.RunPeachXml("flags4.xml")
# ret = struct.unpack("L", str(self.peachUtils.GetListenerData()))[0]
#
# assert ret == 2214560767, 'flags4.xml failed, instead [%s]' % repr(ret)
#
#class Flags5TestCase(utils.PeachTcpTestCase):
#
# def runTest(self):
# # Test
#
# self.peachUtils.RunPeachXml("flags5.xml")
# ret = struct.unpack("L", str(self.peachUtils.GetListenerData()))[0]
#
# assert ret == 33554432, 'flags5.xml failed, instead [%s]' % repr(ret)
#
#class Flags6TestCase(utils.PeachTcpTestCase):
#
# def runTest(self):
# # Test
#
# self.peachUtils.RunPeachXml("flags6.xml")
# ret = struct.unpack("B", str(self.peachUtils.GetListenerData()))[0]
#
# assert ret == 2, 'flags6.xml failed, instead [%s]' % repr(ret)
class Flags7TestCase(utils.PeachTcpTestCase):
def runTest(self):
# Test
self.peachUtils.RunPeachXml("flags7.xml")
ret = self.peachUtils.GetListenerData()
assert ret == "\x28\x00\x28\x05\x8e\x01", 'flags7.xml failed, instead [%s]' % repr(ret)
class Flags8TestCase(utils.PeachTcpTestCase):
def runTest(self):
# Test
self.peachUtils.RunPeachXml("flags8.xml")
ret = self.peachUtils.GetListenerData()
assert ret == "\x0a\x00\x0a\x50\x63\x10", 'flags8.xml failed, instead [%s]' % repr(ret)
if __name__ == "__main__":
unittest.main()
# end
| gen = Flags2(None, 8, [ [0, 1, Static(1)], [1, 2, Static(2)], [3, 2, Static(3)], [5, 3, Static(4)] ])
value = struct.pack("B", int(str(gen.getValue())))
self.peachUtils.RunPeachXml("flagsOutput.xml")
ret = struct.unpack("B", str(self.peachUtils.GetListenerData()))[0]
assert ret == 157, 'flagsOutput.xml failed, instead [%s]' % repr(ret) |
testutils.go | /*
Copyright 2018 The Kubernetes 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 collectors
import (
"bytes"
"fmt"
"reflect"
"sort"
"strings"
"github.com/prometheus/client_golang/prometheus"
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/common/expfmt"
)
// GatherAndCompare retrieves all metrics exposed by a collector and compares it
// to an expected output in the Prometheus text exposition format.
// metricNames allows only comparing the given metrics. All are compared if it's nil.
func GatherAndCompare(c prometheus.Collector, expected string, metricNames []string, reg prometheus.Gatherer) error {
expected = removeUnusedWhitespace(expected)
metrics, err := reg.Gather()
if err != nil {
return fmt.Errorf("gathering metrics failed: %s", err)
}
if metricNames != nil {
metrics = filterMetrics(metrics, metricNames)
}
var tp expfmt.TextParser
expectedMetrics, err := tp.TextToMetricFamilies(bytes.NewReader([]byte(expected)))
if err != nil {
return fmt.Errorf("parsing expected metrics failed: %s", err)
}
if !reflect.DeepEqual(metrics, normalizeMetricFamilies(expectedMetrics)) {
// Encode the gathered output to the readbale text format for comparison.
var buf1 bytes.Buffer
enc := expfmt.NewEncoder(&buf1, expfmt.FmtText)
for _, mf := range metrics {
if err := enc.Encode(mf); err != nil {
return fmt.Errorf("encoding result failed: %s", err)
}
}
// Encode normalized expected metrics again to generate them in the same ordering
// the registry does to spot differences more easily.
var buf2 bytes.Buffer
enc = expfmt.NewEncoder(&buf2, expfmt.FmtText)
for _, mf := range normalizeMetricFamilies(expectedMetrics) {
if err := enc.Encode(mf); err != nil {
return fmt.Errorf("encoding result failed: %s", err)
}
}
if buf2.String() == buf1.String() {
return nil
}
return fmt.Errorf(`
metric output does not match expectation; want:
'%s'
got:
'%s'
`, buf2.String(), buf1.String())
}
return nil
}
func filterMetrics(metrics []*dto.MetricFamily, names []string) []*dto.MetricFamily {
var filtered []*dto.MetricFamily
for _, m := range metrics {
drop := true
for _, name := range names {
if m.GetName() == name {
drop = false
break
}
}
if !drop {
filtered = append(filtered, m)
}
}
return filtered
}
func removeUnusedWhitespace(s string) string {
var (
trimmedLine string
trimmedLines []string
lines = strings.Split(s, "\n")
)
for _, l := range lines {
trimmedLine = strings.TrimSpace(l)
if len(trimmedLine) > 0 {
trimmedLines = append(trimmedLines, trimmedLine)
}
}
// The Prometheus metrics representation parser expects an empty line at the
// end otherwise fails with an unexpected EOF error.
return strings.Join(trimmedLines, "\n") + "\n"
}
// The below sorting code is copied form the Prometheus client library modulo the added
// label pair sorting.
// https://github.com/prometheus/client_golang/blob/ea6e1db4cb8127eeb0b6954f7320363e5451820f/prometheus/registry.go#L642-L684
// labelPairSorter implements sort.Interface. It is used to sort a slice of
// dto.LabelPair pointers.
type labelPairSorter []*dto.LabelPair
func (s labelPairSorter) Len() int {
return len(s)
}
func (s labelPairSorter) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s labelPairSorter) Less(i, j int) bool {
return s[i].GetName() < s[j].GetName()
}
// metricSorter is a sortable slice of *dto.Metric.
type metricSorter []*dto.Metric
func (s metricSorter) Len() int {
return len(s)
}
func (s metricSorter) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s metricSorter) Less(i, j int) bool {
sort.Sort(labelPairSorter(s[i].Label))
sort.Sort(labelPairSorter(s[j].Label))
if len(s[i].Label) != len(s[j].Label) {
return len(s[i].Label) < len(s[j].Label)
}
for n, lp := range s[i].Label {
vi := lp.GetValue()
vj := s[j].Label[n].GetValue()
if vi != vj {
return vi < vj
}
}
if s[i].TimestampMs == nil {
return false
}
if s[j].TimestampMs == nil {
return true
}
return s[i].GetTimestampMs() < s[j].GetTimestampMs()
}
// normalizeMetricFamilies returns a MetricFamily slice with empty
// MetricFamilies pruned and the remaining MetricFamilies sorted by name within
// the slice, with the contained Metrics sorted within each MetricFamily.
func normalizeMetricFamilies(metricFamiliesByName map[string]*dto.MetricFamily) []*dto.MetricFamily {
for _, mf := range metricFamiliesByName {
sort.Sort(metricSorter(mf.Metric))
} | for name, mf := range metricFamiliesByName {
if len(mf.Metric) > 0 {
names = append(names, name)
}
}
sort.Strings(names)
result := make([]*dto.MetricFamily, 0, len(names))
for _, name := range names {
result = append(result, metricFamiliesByName[name])
}
return result
} | names := make([]string, 0, len(metricFamiliesByName)) |
398-random-pick-index.go | package main
import "math/rand"
type Solution struct {
indexes map[int][]int
}
func Constructor(nums []int) Solution |
func (this *Solution) Pick(target int) int {
idx := rand.Intn(len(this.indexes[target]))
return this.indexes[target][idx]
}
/**
* Your Solution object will be instantiated and called as such:
* obj := Constructor(nums);
* param_1 := obj.Pick(target);
*/
| {
indexes := make(map[int][]int)
for i, n := range nums {
indexes[n] = append(indexes[n], i)
}
return Solution{indexes: indexes}
} |
payment_intent.rs | use crate::config::{Client, Response};
use crate::ids::{CustomerId, PaymentIntentId};
use crate::params::{Expand, Expandable, List, Metadata, Object, RangeQuery, Timestamp};
use crate::resources::{
Account, Application, Charge, Currency, Customer, Invoice, PaymentIntentOffSession,
PaymentMethod, PaymentSource, Review, Shipping, TransferDataParams,
};
use crate::TransferDataUpdateParams;
use serde_derive::{Deserialize, Serialize};
/// The resource representing a Stripe "PaymentIntent".
///
/// For more details see [https://stripe.com/docs/api/payment_intents/object](https://stripe.com/docs/api/payment_intents/object).
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PaymentIntent {
/// Unique identifier for the object.
pub id: PaymentIntentId,
/// Amount intended to be collected by this PaymentIntent.
pub amount: i64,
/// Amount that can be captured from this PaymentIntent.
#[serde(skip_serializing_if = "Option::is_none")]
pub amount_capturable: Option<i64>,
/// Amount that was collected by this PaymentIntent.
#[serde(skip_serializing_if = "Option::is_none")]
pub amount_received: Option<i64>,
/// ID of the Connect application that created the PaymentIntent.
#[serde(skip_serializing_if = "Option::is_none")]
pub application: Option<Expandable<Application>>,
/// The amount of the application fee (if any) for the resulting payment.
///
/// See the PaymentIntents [use case for connected accounts](https://stripe.com/docs/payments/payment-intents/use-cases#connected-accounts) for details.
#[serde(skip_serializing_if = "Option::is_none")]
pub application_fee_amount: Option<i64>,
/// Populated when `status` is `canceled`, this is the time at which the PaymentIntent was canceled.
///
/// Measured in seconds since the Unix epoch.
#[serde(skip_serializing_if = "Option::is_none")]
pub canceled_at: Option<Timestamp>,
/// Reason for cancellation of this PaymentIntent, either user-provided (`duplicate`, `fraudulent`, `requested_by_customer`, or `abandoned`) or generated by Stripe internally (`failed_invoice`, `void_invoice`, or `automatic`).
#[serde(skip_serializing_if = "Option::is_none")]
pub cancellation_reason: Option<PaymentIntentCancellationReason>,
/// Capture method of this PaymentIntent, one of `automatic` or `manual`.
pub capture_method: PaymentIntentCaptureMethod,
/// Charges that were created by this PaymentIntent, if any.
#[serde(default)]
pub charges: List<Charge>,
/// The client secret of this PaymentIntent.
///
/// Used for client-side retrieval using a publishable key.
/// Please refer to our [automatic confirmation quickstart guide](https://stripe.com/docs/payments/payment-intents/quickstart#automatic-confirmation-flow) to learn about how `client_secret` should be handled.
#[serde(skip_serializing_if = "Option::is_none")]
pub client_secret: Option<String>,
/// Confirmation method of this PaymentIntent, one of `manual` or `automatic`.
pub confirmation_method: PaymentIntentConfirmationMethod,
/// Time at which the object was created.
///
/// Measured in seconds since the Unix epoch.
pub created: Timestamp,
/// Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase.
///
/// Must be a [supported currency](https://stripe.com/docs/currencies).
pub currency: Currency,
/// ID of the Customer this PaymentIntent is for if one exists.
#[serde(skip_serializing_if = "Option::is_none")]
pub customer: Option<Expandable<Customer>>,
/// An arbitrary string attached to the object.
///
/// Often useful for displaying to users.
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// ID of the invoice that created this PaymentIntent, if it exists.
#[serde(skip_serializing_if = "Option::is_none")]
pub invoice: Option<Expandable<Invoice>>,
/// The payment error encountered in the previous PaymentIntent confirmation.
#[serde(skip_serializing_if = "Option::is_none")]
pub last_payment_error: Option<PaymentError>,
/// Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode.
pub livemode: bool,
/// Set of key-value pairs that you can attach to an object.
///
/// This can be useful for storing additional information about the object in a structured format.
/// For more information, see the [documentation](https://stripe.com/docs/payments/payment-intents/creating-payment-intents#storing-information-in-metadata).
#[serde(default)]
pub metadata: Metadata,
/// If present, this property tells you what actions you need to take in order for your customer to fulfill a payment using the provided source.
#[serde(skip_serializing_if = "Option::is_none")]
pub next_action: Option<PaymentIntentNextAction>,
/// The account (if any) for which the funds of the PaymentIntent are intended.
///
/// See the PaymentIntents [use case for connected accounts](https://stripe.com/docs/payments/payment-intents/use-cases#connected-accounts) for details.
#[serde(skip_serializing_if = "Option::is_none")]
pub on_behalf_of: Option<Expandable<Account>>,
/// ID of the payment method used in this PaymentIntent.
#[serde(skip_serializing_if = "Option::is_none")]
pub payment_method: Option<Expandable<PaymentMethod>>,
/// The list of payment method types (e.g.
///
/// card) that this PaymentIntent is allowed to use.
pub payment_method_types: Vec<String>,
/// Email address that the receipt for the resulting payment will be sent to.
#[serde(skip_serializing_if = "Option::is_none")]
pub receipt_email: Option<String>,
/// ID of the review associated with this PaymentIntent, if any.
#[serde(skip_serializing_if = "Option::is_none")]
pub review: Option<Expandable<Review>>,
/// Shipping information for this PaymentIntent.
#[serde(skip_serializing_if = "Option::is_none")]
pub shipping: Option<Shipping>,
/// ID of the source used in this PaymentIntent.
#[serde(skip_serializing_if = "Option::is_none")]
pub source: Option<Expandable<PaymentSource>>,
/// Used in payment flows that collect payment details and charge later when the customer is not available to complete additional required steps for the payment.
///
/// Setting this parameter indicates that this payment attempt is happening while the customer is not in your checkout flow.
/// Use `recurring` for payments made on a recurring basis (for example, subscriptions) and `one_off` for all other off-session payments.
pub off_session: Option<PaymentIntentOffSession>,
/// Extra information about a PaymentIntent.
///
/// This will appear on your customer's statement when this PaymentIntent succeeds in creating a charge.
#[serde(skip_serializing_if = "Option::is_none")]
pub statement_descriptor: Option<String>,
/// Status of this PaymentIntent, one of `requires_payment_method`, `requires_confirmation`, `requires_action`, `processing`, `requires_capture`, `canceled`, or `succeeded`.
///
/// Read more about each PaymentIntent [status](https://stripe.com/docs/payments/payment-intents/status).
pub status: PaymentIntentStatus,
/// The data with which to automatically create a Transfer when the payment is finalized.
///
/// See the PaymentIntents [use case for connected accounts](https://stripe.com/docs/payments/payment-intents/use-cases#connected-accounts) for details.
#[serde(skip_serializing_if = "Option::is_none")]
pub transfer_data: Option<TransferData>,
/// A string that identifies the resulting payment as part of a group.
///
/// See the PaymentIntents [use case for connected accounts](https://stripe.com/docs/payments/payment-intents/use-cases#connected-accounts) for details.
#[serde(skip_serializing_if = "Option::is_none")]
pub transfer_group: Option<String>,
}
impl PaymentIntent {
/// Creates a new payment_intent.
///
/// For more details see [https://stripe.com/docs/api/payment_intents/create](https://stripe.com/docs/api/payment_intents/create).
pub fn create(client: &Client, params: CreatePaymentIntent<'_>) -> Response<PaymentIntent> {
client.post_form("/payment_intents", params)
}
/// Retrieves the details of a payment_intent.
///
/// For more details see [https://stripe.com/docs/api/payment_intents/retrieve](https://stripe.com/docs/api/payment_intents/retrieve).
pub fn retrieve(client: &Client, payment_intent_id: &str) -> Response<PaymentIntent> {
client.get(&format!("/payment_intents/{}", payment_intent_id))
}
/// Updates a payment_intent's properties.
///
/// For more details see [https://stripe.com/docs/api/payment_intents/update](https://stripe.com/docs/api/payment_intents/update).
pub fn update(
client: &Client,
payment_intent_id: &str,
params: PaymentIntentUpdateParams<'_>,
) -> Response<PaymentIntent> {
client.post_form(&format!("/payment_intents/{}", payment_intent_id), params)
}
/// Confirm that customer intends to pay with current or provided source. Upon confirmation, the PaymentIntent will attempt to initiate a payment.
///
/// For more details see [https://stripe.com/docs/api/payment_intents/confirm](https://stripe.com/docs/api/payment_intents/confirm).
pub fn confirm(
client: &Client,
payment_intent_id: &str,
params: PaymentIntentConfirmParams<'_>,
) -> Response<PaymentIntent> {
client.post_form(&format!("/payment_intents/{}/confirm", payment_intent_id), params)
}
/// Capture the funds of an existing uncaptured PaymentIntent where required_action="requires_capture".
///
/// For more details see [https://stripe.com/docs/api/payment_intents/capture](https://stripe.com/docs/api/payment_intents/capture).
pub fn capture(
client: &Client,
payment_intent_id: &str,
params: CapturePaymentIntent,
) -> Response<PaymentIntent> {
client.post_form(&format!("/payment_intents/{}/capture", payment_intent_id), params)
}
/// A PaymentIntent object can be canceled when it is in one of these statuses: requires_source, requires_capture, requires_confirmation, requires_source_action.
///
/// For more details see [https://stripe.com/docs/api/payment_intents/cancel](https://stripe.com/docs/api/payment_intents/cancel).
pub fn cancel(
client: &Client,
payment_intent_id: &str,
params: CancelPaymentIntent,
) -> Response<PaymentIntent> {
client.post_form(&format!("/payment_intents/{}/cancel", payment_intent_id), params)
}
/// List all payment_intents.
///
/// For more details see [https://stripe.com/docs/api/payment_intents/list](https://stripe.com/docs/api/payment_intents/list).
pub fn list(client: &Client, params: ListPaymentIntents) -> Response<List<PaymentIntent>> {
client.get_query("/payment_intents", ¶ms)
}
}
impl Object for PaymentIntent {
type Id = PaymentIntentId;
fn id(&self) -> Self::Id {
self.id.clone()
}
fn object(&self) -> &'static str {
"payment_intent"
}
}
/// The resource representing a Stripe PaymentError object.
///
/// For more details see [https://stripe.com/docs/api/payment_intents/object#payment_intent_object-last_payment_error](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-last_payment_error).
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PaymentError {
#[serde(rename = "type")]
pub payment_error_type: PaymentErrorType,
pub charge: Option<String>,
pub code: Option<String>,
pub decline_code: Option<String>,
pub doc_url: Option<String>,
pub message: Option<String>,
pub param: Option<String>,
pub source: Option<Expandable<PaymentSource>>,
}
/// The resource representing a Stripe PaymentErrorType object.
///
/// For more details see [https://stripe.com/docs/api/payment_intents/object#payment_intent_object-last_payment_error-type](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-last_payment_error-type).
#[derive(Deserialize, Serialize, PartialEq, Debug, Clone, Eq)]
pub enum PaymentErrorType {
#[serde(rename = "api_error")]
Api,
#[serde(rename = "api_connection_error")]
Connection,
#[serde(rename = "authentication_error")]
Authentication,
#[serde(rename = "card_error")]
Card,
#[serde(rename = "idempotency_error")]
Idempotency,
#[serde(rename = "invalid_request_error")]
InvalidRequest,
#[serde(rename = "rate_limit_error")]
RateLimit,
/// A variant not yet supported by the library.
/// It is an error to send `Other` as part of a request.
#[serde(other, skip_serializing)]
Other,
}
// TODO: This might be moved to `PaymentSourceType` if we determine
// that all of the variants are _always_ the same.
//
// In that case this can be replaced with a deprecated type alias.
/// Represents the way a `PaymentIntent` needs to be fulfilled.
#[derive(Deserialize, Serialize, PartialEq, Debug, Clone, Eq)]
#[serde(rename_all = "snake_case")]
pub enum PaymentIntentMethodType {
/// This `PaymentIntent` needs to be fulfilled through credit card payment.
Card,
/// This `PaymentIntent` needs to be fulfilled through an
/// [iDeal](https://stripe.com/docs/payments/ideal) payment.
Ideal,
/// This `PaymentIntent` needs to be fulfilled through a
/// [Sepa Direct Debit](https://stripe.com/docs/payments/sepa-debit) payment.
SepaDebit,
}
/// The resource representing a Stripe CaptureMethod object.
///
/// For more details see [https://stripe.com/docs/api/payment_intents/object#payment_intent_object-capture_method](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-capture_method).
#[derive(Deserialize, Serialize, PartialEq, Debug, Clone, Eq)]
#[serde(rename_all = "snake_case")]
pub enum CaptureMethod {
Automatic,
Manual,
/// A variant not yet supported by the library.
/// It is an error to send `Other` as part of a request.
#[serde(other, skip_serializing)]
Other,
}
/// The resource representing a Stripe ConfirmationMethod object.
///
/// For more details see [https://stripe.com/docs/api/payment_intents/object#payment_intent_object-confirmation_method](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-confirmation_method).
#[derive(Deserialize, Serialize, PartialEq, Debug, Clone, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ConfirmationMethod {
Secret,
Publishable,
/// A variant not yet supported by the library.
/// It is an error to send `Other` as part of a request.
#[serde(other, skip_serializing)]
Other,
}
#[derive(Deserialize, Serialize, PartialEq, Debug, Clone, Eq)]
#[serde(rename_all = "snake_case")]
pub enum PaymentIntentNextActionType {
RedirectToUrl,
UseStripeSdk,
/// A variant not yet supported by the library.
/// It is an error to send `Other` as part of a request.
#[serde(other, skip_serializing)]
Other,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PaymentIntentNextAction {
/// Type of the next action to perform, one of `redirect_to_url` or `use_stripe_sdk`.
#[serde(rename = "type")]
pub type_: PaymentIntentNextActionType,
#[serde(skip_serializing_if = "Option::is_none")]
pub redirect_to_url: Option<PaymentIntentNextActionRedirectToUrl>,
/// When confirming a PaymentIntent with Stripe.js, Stripe.js depends on the contents of this dictionary to invoke authentication flows.
///
/// The shape of the contents is subject to change and is only intended to be used by Stripe.js.
#[serde(skip_serializing_if = "Option::is_none")]
pub use_stripe_sdk: Option<serde_json::Value>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PaymentIntentNextActionRedirectToUrl {
/// If the customer does not exit their browser while authenticating, they will be redirected to this specified URL after completion.
#[serde(skip_serializing_if = "Option::is_none")]
pub return_url: Option<String>,
/// The URL you must redirect your customer to in order to authenticate the payment.
#[serde(skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct TransferData {
/// The account (if any) the payment will be attributed to for tax
/// reporting, and where funds from the payment will be transferred to upon
/// payment success.
pub destination: Expandable<Account>,
}
/// The set of parameters that can be used when creating a payment_intent object.
///
/// For more details see [https://stripe.com/docs/api/payment_intents/create](https://stripe.com/docs/api/payment_intents/create)
#[derive(Clone, Debug, Default, Serialize)]
pub struct CreatePaymentIntent<'a> {
/// The list of payment types (e.g. card) that this PaymentIntent is allowed to use.
pub payment_method_types: Vec<PaymentIntentMethodType>,
pub amount: u64,
pub currency: Currency,
pub payment_method: Option<&'a str>,
pub confirmation_method: Option<PaymentIntentConfirmationMethod>,
#[serde(skip_serializing_if = "Option::is_none")]
pub application_fee_amount: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub capture_method: Option<PaymentIntentCaptureMethod>,
/// Attempt to confirm this PaymentIntent on source attachment.
#[serde(skip_serializing_if = "Option::is_none")]
pub confirm: Option<bool>, // TODO: Is this the correct type?
#[serde(skip_serializing_if = "Option::is_none")]
pub customer: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<Metadata>,
#[serde(skip_serializing_if = "Option::is_none")]
pub on_behalf_of: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub receipt_email: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub return_url: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub save_source_to_customer: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub shipping: Option<Shipping>,
#[serde(skip_serializing_if = "Option::is_none")]
pub source: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub statement_descriptor: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub transfer_data: Option<TransferDataParams>,
#[serde(skip_serializing_if = "Option::is_none")]
pub transfer_group: Option<&'a str>,
}
impl<'a> CreatePaymentIntent<'a> {
pub fn new(amount: u64, currency: Currency) -> Self {
CreatePaymentIntent {
payment_method_types: Default::default(),
amount,
currency,
payment_method: Default::default(),
confirmation_method: Default::default(),
application_fee_amount: Default::default(),
capture_method: Default::default(),
confirm: Default::default(),
customer: Default::default(),
description: Default::default(),
metadata: Default::default(),
on_behalf_of: Default::default(),
receipt_email: Default::default(),
return_url: Default::default(),
save_source_to_customer: Default::default(),
shipping: Default::default(),
source: Default::default(),
statement_descriptor: Default::default(),
transfer_data: Default::default(),
transfer_group: Default::default(),
}
}
}
/// The set of parameters that can be used when updating a payment_intent object.
///
/// For more details see [https://stripe.com/docs/api/payment_intents/update](https://stripe.com/docs/api/payment_intents/update)
#[derive(Clone, Debug, Default, Serialize)]
pub struct PaymentIntentUpdateParams<'a> {
#[serde(skip_serializing_if = "Option::is_none")]
pub amount: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub application_fee_amount: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub currency: Option<Currency>,
#[serde(skip_serializing_if = "Option::is_none")]
pub customer: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<Metadata>,
#[serde(skip_serializing_if = "Option::is_none")]
pub receipt_email: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub save_source_to_customer: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub shipping: Option<Shipping>,
#[serde(skip_serializing_if = "Option::is_none")]
pub source: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub transfer_group: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub transfer_data: Option<TransferDataUpdateParams>,
}
/// The set of parameters that can be used when confirming a payment_intent object.
///
/// For more details see [https://stripe.com/docs/api/payment_intents/confirm](https://stripe.com/docs/api/payment_intents/confirm)
#[derive(Clone, Debug, Default, Serialize)]
pub struct PaymentIntentConfirmParams<'a> {
#[serde(skip_serializing_if = "Option::is_none")]
pub receipt_email: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub return_url: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub save_source_to_customer: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub shipping: Option<Shipping>,
#[serde(skip_serializing_if = "Option::is_none")]
pub source: Option<&'a str>,
}
/// The set of parameters that can be used when capturing a payment_intent object.
///
/// For more details see [https://stripe.com/docs/api/payment_intents/capture](https://stripe.com/docs/api/payment_intents/capture)
#[derive(Clone, Debug, Default, Serialize)]
pub struct CapturePaymentIntent {
#[serde(skip_serializing_if = "Option::is_none")]
pub amount_to_capture: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub application_fee_amount: Option<u64>,
}
/// The set of parameters that can be used when canceling a payment_intent object.
///
/// For more details see [https://stripe.com/docs/api/payment_intents/cancel](https://stripe.com/docs/api/payment_intents/cancel)
#[derive(Clone, Debug, Default, Serialize)]
pub struct CancelPaymentIntent {
#[serde(skip_serializing_if = "Option::is_none")]
pub cancellation_reason: Option<PaymentIntentCancellationReason>,
}
/// The parameters for `PaymentIntent::list`.
#[derive(Clone, Debug, Serialize)]
pub struct ListPaymentIntents<'a> {
/// A filter on the list, based on the object `created` field.
///
/// The value can be a string with an integer Unix timestamp, or it can be a dictionary with a number of different query options.
#[serde(skip_serializing_if = "Option::is_none")]
pub created: Option<RangeQuery<Timestamp>>,
/// Only return PaymentIntents for the customer specified by this customer ID.
#[serde(skip_serializing_if = "Option::is_none")]
pub customer: Option<CustomerId>,
/// A cursor for use in pagination.
///
/// `ending_before` is an object ID that defines your place in the list.
/// For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list.
#[serde(skip_serializing_if = "Option::is_none")]
pub ending_before: Option<&'a PaymentIntentId>,
/// Specifies which fields in the response should be expanded.
#[serde(skip_serializing_if = "Expand::is_empty")]
pub expand: &'a [&'a str],
/// A limit on the number of objects to be returned.
///
/// Limit can range between 1 and 100, and the default is 10.
#[serde(skip_serializing_if = "Option::is_none")]
pub limit: Option<u64>,
/// A cursor for use in pagination.
///
/// `starting_after` is an object ID that defines your place in the list.
/// For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list.
#[serde(skip_serializing_if = "Option::is_none")]
pub starting_after: Option<&'a PaymentIntentId>,
}
/// An enum representing the possible values of an `PaymentIntent`'s `cancellation_reason` field.
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum PaymentIntentCancellationReason {
Abandoned,
Automatic,
Duplicate,
FailedInvoice,
Fraudulent,
RequestedByCustomer,
VoidInvoice,
}
/// An enum representing the possible values of an `PaymentIntent`'s `capture_method` field.
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum | {
Automatic,
Manual,
}
/// An enum representing the possible values of an `PaymentIntent`'s `confirmation_method` field.
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum PaymentIntentConfirmationMethod {
Automatic,
Manual,
}
/// An enum representing the possible values of an `PaymentIntent`'s `status` field.
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum PaymentIntentStatus {
Canceled,
Processing,
RequiresAction,
RequiresCapture,
RequiresConfirmation,
RequiresPaymentMethod,
RequiresSource,
Succeeded,
}
| PaymentIntentCaptureMethod |
EM_and_MD_answers_wc3.py | #!/usr/local/bin/python
#############################################################
# Simple MD of Lennard Jones charged or uncharged particles #
# Alexandre Bonvin, Aalt Jan van Dijk, Utrecht University #
# Updated to a singular script with a modern look by Douwe #
# Schulte, Utrecht University (2022) #
# #
# Adapted from a script from Patrick Fuchs, Uni. Paris VI #
#############################################################
##################
# Import modules #
##################
from math import sqrt,log,sin,cos
from random import random,seed
from enum import Enum
from tkinter import Tk, Canvas, DoubleVar, StringVar
from tkinter.ttk import Label, Button, Style, Frame, Notebook, Entry
import sys
#####################
# Define parameters #
#####################
nAtoms = 20 # Number of atoms
Radius = 25.0 # Beware that Radius must be in a good range (according to nAtoms)
# In order to be able to place all atoms
Mass = 10.0 # Atom mass
Rmin = 2.24 * Radius # Distance at which Rmin is minimal
BoxDim = [500,500] # Box dimension
Atom_Coord = [] # List of the form : [nAtoms][2]
Epsilon = 2 * Radius # Well depth
Dielec = 1.0 # Dielectric constant
qat = 2 * Radius # Atom absolute charge
frac_neg = 0.5 # Fraction negative charges
OverlapFr = 0.0 # Fraction of overlap allowed
CutOff = 250 # Non-bonded cutoff
CutOffSquare = CutOff**2 # Precalculated square
speed = 5 # Canvas update speed
cstboltz = 0.00198722 # Boltzmann's constant in kcal/mol/K
cstboltz = 1000*cstboltz/4.18 # In kJ/mol/K
Seed = 42 # Random number seed
# Steepest Descent parameters
drinit = 1.00 # dr from EM
drmin = 0.00001 # Minimum dr value to step EM
drmax = 5.00 # Maximum dr
alpha = 1.05 # Scaling factor for dr if Enew < Eold
beta = 0.90 # Scaling factor for dr if Enew > Eold
deltaE = 0.001 # Energy difference threshold to stop EM
normFmin = 0.001 # Minimum force norm to step EM
# Verlet parameters
Temperature = 300.0 # Temperature in K
timestep = 5.0E-3 # MD time step
# Set specific behaviour for practical session 4
CalculateEnergyPeriodic = True # Practical #4 part 1
ShowOtherEnergyCutoffResults = False # Practical #4 part 2
# Additional program specific parameters
Minimizers = Enum("Minimisers", "SteepestDescent Verlet")
Minimizer = Minimizers.Verlet
drstep = drinit
Iterations = 0
canvas_event = None
Color = []
ATOM = []
##############################
# Steepest descent minimizer #
##############################
def steepest_descent(atom_coord,drstep,forces):
"""
This function gets as input parameters:
- atom_coord, a vector containing the x and y position and the charge of the i atoms
- drstep, the displacement for the minimizer
- force, a vector containing the x and y components of the force on the atoms
The function returns a list array (vector containing the new positions)
Implement in the following loop over all atoms the using the steepest descent algorithm
A few hints:
- powers in python are given by **, e.g.: x to the square is x**2
- squared root x: sqrt(x)
- avoid dividing by zero
"""
new_positions=[]
# 1) First calculate the norm of the total force vector
normf = 0.0
for force in forces:
normf=normf+force[0]**2.0+force[1]**2.0
normf=sqrt(normf)
if normf < 0: return atom_coord, normf
# 2) Then move the particles
for (coord, force) in zip(atom_coord, forces):
r0x=coord[0] # Coordinates
r0y=coord[1]
# Insert below the lines defining the new coordinates based on the old ones + forces + drstep.
#
# Forces are contained in force[0] for the x force component and force[1] for the y force.
# The step size for the move is given by drstep.
#
# ====>>>>>
sx=force[0]/normf
sy=force[1]/normf
r0xnew=r0x+drstep*sx
r0ynew=r0y+drstep*sy
# <<<<<====
new_positions.append([r0xnew,r0ynew,coord[2]])
return new_positions,normf
#####################
# Verlet integrator #
#####################
def verlet(atom_coord,forces,dtstep,old_atom_coord,mass):
"""
This function gets as input parameters:
- `atom_coord`, a vector containing the x and y position and the charge of the i atoms
- `old_atom_coord`, a vector containing the x and y positions from the previous MD step
- `forces`, a vector containing the x and y components of the force on the atoms
- `dtstep`, the integration time step
The function returns a list containing the new positions.
Implement in the following loop between the arrows the Verlet MD algorithm.
A few hints:
- Powers in python are given by **, e.g.: x to the square is `x**2`
- Squared root x: `sqrt(x)`
- Indents are important in python
"""
new_positions=[]
for coord,old_coord,force in zip(atom_coord, old_atom_coord, forces):
r0x=coord[0] # Coordinates
r0y=coord[1]
old_r0x=old_coord[0] # Old coordinates
old_r0y=old_coord[1]
# Insert below the lines defining the new x and y positions based on the old ones + forces + mass + dtstep.
#
# Forces are contained in force[0] for the x force component and force[1] for the y force.
# The step size for the move is given by dtstep.
#
# ====>>>>>
new_r0x = 2*r0x - old_r0x + force[0]/mass * dtstep**2
new_r0y = 2*r0y - old_r0y + force[1]/mass * dtstep**2
# <<<<<====
new_positions.append([new_r0x,new_r0y,coord[2]])
return new_positions
def verlet_step1(atom_coord,velocity,forces,dtstep,mass):
"""The first step for Verlet"""
global Ene,EneLJ,EneCoul,ELJ2,ELJ4
new_positions=[]
for coord, vel, force in zip(atom_coord, velocity, forces):
r0x=coord[0]+dtstep*vel[0]+0.5*dtstep**2*force[0]/mass
r0y=coord[1]+dtstep*vel[1]+0.5*dtstep**2*force[1]/mass
new_positions.append([r0x,r0y,coord[2]])
Ene,EneLJ,EneCoul,ELJ2,ELJ4 = calculate_energy(Atom_Coord,Epsilon,Rmin,Dielec,CutOffSquare,BoxDim)
return new_positions
def calculate_velocities(old_atom_coord,atom_coord,dtstep):
"""Calculate velocities based on old and new positions"""
velocities=[]
for coord, old_coord in zip(atom_coord, old_atom_coord):
v0x=(coord[0]-old_coord[0])/(2*dtstep)
v0y=(coord[1]-old_coord[1])/(2*dtstep)
velocities.append([v0x,v0y])
return velocities
##########################
# Move particles with MD #
##########################
def simulate():
"""Execute the simulation"""
global Atom_Coord,Radius,Mass,BoxDim,Epsilon,Rmin,CutOffSquare,Iterations,Ene,Old_Atom_Coord
global Velocity,timestep,report_var_total,report_var_subenergies, drstep, Ene_prev
global Color,report_var_time,Dielec,root,atom_canvas,speed,canvas_event
Force = calculate_force(Atom_Coord,Epsilon,Rmin,Dielec,CutOffSquare,BoxDim)
tmp=Atom_Coord
if Minimizer == Minimizers.SteepestDescent:
if Iterations == 0: Ene_prev=Ene
Atom_Coord, normF=steepest_descent(Atom_Coord,drstep,Force)
if Minimizer == Minimizers.Verlet:
if Iterations == 0:
Old_Atom_Coord=Atom_Coord
Atom_Coord=verlet_step1(Atom_Coord,Velocity,Force,timestep,Mass)
Atom_Coord=verlet(Atom_Coord,Force,timestep,Old_Atom_Coord,Mass)
Velocity=calculate_velocities(Old_Atom_Coord,Atom_Coord,timestep)
Old_Atom_Coord=tmp
Ene,EneLJ,EneCoul,ELJ2,ELJ4 = calculate_energy(Atom_Coord,Epsilon,Rmin,Dielec,CutOffSquare,BoxDim)
Kin,temperature=calculate_temperature(Velocity,nAtoms,cstboltz,Mass)
# Update drstep
if Minimizer == Minimizers.SteepestDescent:
if Ene < Ene_prev:
drstep = min(drmax, drstep * alpha)
else:
drstep = drstep * beta
# Update top labels
report_var_time.set("Step: %d Time: %8.3f" % (Iterations,float(Iterations)*timestep))
report_var_total.set("Etot: %6.1f Ekin: %6.1f Epot: %6.1f" % (Ene+Kin,Kin,Ene))
if ShowOtherEnergyCutoffResults:
report_var_subenergies.set("Elj: %6.2f Elj2: %6.2f Elj4: %6.2f Ecoul: %6.1f Temp: %6.1f" % (EneLJ,ELJ2,ELJ4,EneCoul,temperature))
else:
report_var_subenergies.set("Elj: %6.1f Ecoul: %6.1f Temp: %6.1f" % (EneLJ,EneCoul,temperature))
# Apply boundary conditions
for coord, old_coord in zip(Atom_Coord, Old_Atom_Coord):
for i in range(2): # i=0 -> case x coordinate ; i=1 -> case y coordinate
if coord[i] < 0:
coord[i] += BoxDim[i]
old_coord[i] += BoxDim[i]
if coord[i] > BoxDim[i]:
coord[i] -= BoxDim[i]
old_coord[i] -= BoxDim[i]
# Draw new canvas coordinates
for atom, coord in zip(ATOM, Atom_Coord):
x, y = coord[0], coord[1]
atom_canvas.coords(atom, x + Radius, y + Radius, x - Radius, y - Radius)
# Print to terminal window
if Iterations % 20 == 0:
if ShowOtherEnergyCutoffResults:
print("Step: %4d Time: %8.3f Etot: %6.1f Ekin: %6.1f Epot: %6.1f Elj: %6.1f Elj2: %6.1f Elj4: %6.1f Ecoul: %6.1f Temp: %6.1f" % (Iterations,float(Iterations)*timestep,Ene+Kin,Kin,Ene,EneLJ,ELJ2,ELJ4,EneCoul,temperature))
else:
print("Step: %4d Time: %8.3f Etot: %6.1f Ekin: %6.1f Epot: %6.1f Elj: %6.1f Ecoul: %6.1f Temp: %6.1f" % (Iterations,float(Iterations)*timestep,Ene+Kin,Kin,Ene,EneLJ,EneCoul,temperature))
# Stopping conditions
if Minimizer == Minimizers.SteepestDescent and (abs(Ene - Ene_prev) < deltaE or drstep < drmin or normF < normFmin):
print("STOPPING... deltaE <",deltaE,", or drstep <",drmin,", or normF <",normFmin)
outtext="Step: %4d Epot: %6.1f Elj: %6.1f Ecoul: %6.1f deltaE: %10.6f <normF>: %8.6f dr: %8.6f" % (Iterations,Ene,EneLJ,EneCoul,Ene - Ene_prev,normF,drstep)
print(outtext)
elif temperature > 1000000:
print("The system is exploding !!!")
print("Step: %4d Time: %8.3f" % (Iterations,float(Iterations)*timestep))
print("Etot: %6.1f Ekin: %6.1f Epot: %6.1f" % (Ene+Kin,Kin,Ene))
print("Elj: %6.1f Ecoul: %6.1f Temp: %6.1f" % (EneLJ,EneCoul,temperature))
print("Emergency stop")
else:
Ene_prev=Ene
Iterations=Iterations+1
canvas_event=atom_canvas.after(speed,simulate)
####################
# Energy functions #
####################
# Calculate Lennard Jones from the squared distance
def LJ2(r2, epsilon, sigma6):
# Uncomment the following lines to get a more obvious mathematical implementation
# r = sqrt(r2)
# sigma = sigma6**(1/6)
# return epsilon*((sigma/r)**12 - (sigma/r)**6)
# The following implementation is significantly faster so this is the default
Z = (1/r2)**3 * sigma6
return epsilon * Z * (Z-1)
# Classical Coulomb from the squared distance
def Coulomb2(r,dielec,qa,qb):
return qa*qb/(dielec*sqrt(r))
# Calculate energy Evdw + Ecoulomb (used squared distance)
def calculate_energy(coord,epsilon,rmin,dielec,cutoffsquare,boxdim,elec=1):
global CalculateEnergyPeriodic
cutoff2=2.0*rmin; cutoff2sq=cutoff2**2
cutoff4=4.0*rmin; cutoff4sq=cutoff4**2
Ene = 0.0; distsquare = 0
ELJ = 0.0; ECoul=0.0
ELJ2 = 0.0; ELJ4 = 0.0
rmin_exp6 = rmin**6
# Doubly nested loop over all particle pairs
for i in range(len(coord)-1):
for j in range(i+1,len(coord)):
# Calculate the squared atomic distance
distsquare = 0
for k in range(2):
tmp = coord[j][k] - coord[i][k]
# Chooses the nearest image
if CalculateEnergyPeriodic:
halfbox = boxdim[k]/2
tmp = tmp - SignR(halfbox,tmp-halfbox) - SignR(halfbox,tmp+halfbox)
distsquare += tmp**2
# Compute vdw and Coulomb energy
if distsquare < cutoffsquare:
qa = coord[i][2]
qb = coord[j][2]
vdw = LJ2(distsquare, epsilon, rmin_exp6)
Ene += vdw
ELJ += vdw
if elec:
CC = Coulomb2(distsquare,dielec,qa,qb)
Ene+=CC
ECoul+=CC
if distsquare < cutoff4sq:
ELJ4 += vdw
if distsquare < cutoff2sq:
ELJ2 += vdw
return Ene,ELJ,ECoul,ELJ2,ELJ4
# Calculate kinetic energy and temperature
def calculate_temperature(vel,nat,k,mass):
v2=0.0
for velocity in vel:
v2=v2+velocity[0]**2+velocity[1]**2
nkt=0.5*mass*v2 # Kinetic energy equals 0.5*m*v**2
kin=v2*0.5*mass
temp=nkt/(nat*k) # N*k*T=Kinetic Energy
return kin,temp
###################
# Force functions #
###################
# Force LJ (use squared distance)
def calculate_lennard_jones(distsquare, epsilon, rmin_exp6,xi):
rij=sqrt(distsquare)
Z = (1/distsquare)**3 * rmin_exp6
dedz=epsilon*(2*Z-1)
dzdr=rmin_exp6*(-6.0/rij**(7.0))
drdx=xi/rij
return dedz*dzdr*drdx
# Force Coulomb (use squared distance)
def calculate_coulomb(distsquare,dielec,qa,qb,xi):
|
# Calculate force from Evdw + Ecoulomb (uses squared distance)
def calculate_force(coord,epsilon,rmin,dielec,cutoffsquare,boxdim):
Force=[] ; distsquare = 0
rmin_exp6 = rmin**6
# Doubly nested loop over all particle pairs
for i in range(len(coord)):
tmpforce=[0.0,0.0]
for j in range(len(coord)):
if not i==j:
# Calculate the squared atomic distance
distsquare = 0
for k in range(2):
tmp = coord[j][k] - coord[i][k]
# Chooses the nearest image
halfbox = boxdim[k]/2
tmp = tmp - SignR(halfbox,tmp-halfbox) - SignR(halfbox,tmp+halfbox)
distsquare += tmp**2
# Compute vdw force
if distsquare < cutoffsquare:
qa = coord[i][2]
qb = coord[j][2]
for k in range(2):
tmp = coord[j][k] - coord[i][k]
ff = calculate_lennard_jones(distsquare, epsilon, rmin_exp6,tmp)
ff += calculate_coulomb(distsquare,dielec,qa,qb,tmp)
tmpforce[k]+=ff
Force.append(tmpforce)
return Force
###################
# Other functions #
###################
# Normal Distance
def dist(A,B):
return sqrt((A[0]-B[0])**2+(A[1]-B[1])**2)
# Change sign
def SignR(a,b):
if b > 0:
return a
else:
return -a
# Color particules based on charge
def charge_color(charge,qat):
if charge == qat:
return "white"
else:
return "#333333"
##################
# Initialization #
##################
# Generate random coordinates
def InitConf(n,dim,radius,qat,frac_neg):
global Seed
seed(Seed)
print("Initializing box, please wait...", end='')
tmp_coord = []
ntrial = 0
i = 1
# Fix first atom
x = random()*(dim[0]-2*radius)+radius
y = random()*(dim[1]-2*radius)+radius
nneg = int(float(n) * frac_neg)
charge = -qat
if nneg == 0: charge = qat
tmp_coord.append([x,y,charge])
for negative in [-1, 1]:
while negative == -1 and i < nneg or negative == 1 and i < n:
x = random()*(dim[0]-2*radius)+radius
y = random()*(dim[1]-2*radius)+radius
# Check wether the new particle overlaps with an existing one
OVERLAP = False
for j in range(i):
if dist(tmp_coord[j],[x,y]) < (1-OverlapFr)*2*radius:
OVERLAP = True
if not OVERLAP:
tmp_coord.append([x,y,negative * qat])
i += 1
ntrial = ntrial + 1
if ntrial > 100000:
print('error')
print("Initialisation failed")
print("==> Reduce radius or number of atoms")
sys.exit()
print("done")
return tmp_coord
# Generate random charges
def InitCharge(n,qat,frac_neg):
global Atom_Coord
print("Initializing charges, please wait...", end='')
i = 0
nneg = int(float(n) * frac_neg)
charge = -qat
if nneg == 0: charge = qat
Atom_Coord[i][2]=charge
i += 1
while i < nneg:
Atom_Coord[i][2]=-qat
i += 1
while i < n:
Atom_Coord[i][2]=qat
i += 1
print("done")
# Generates initial velocities according to Maxwell distribution
def InitVel(n,temperature,cstboltz,mass):
global Seed
seed(Seed)
stdev=sqrt(cstboltz*temperature/mass)
print("Initializing velocities, please wait...", end='')
tmp_vel=[]
for i in range(n):
# Generate random numbers according to Gaussian:
r1=random()
r2=random()
x1=sqrt(-2.0*log(r1))*cos(r2)*stdev
x2=sqrt(-2.0*log(r1))*sin(0.5*r2)*stdev
tmp_vel.append([x1,x2])
# Remove overall motion
vxt=0.0
vyt=0.0
for item in tmp_vel:
vxt+=item[0]
vyt+=item[1]
for item in tmp_vel:
item[0] -= vxt/float(n)
item[1] -= vyt/float(n)
# Scaling factor is used to get temperature exactly equal to desired temperature
kin,tt=calculate_temperature(tmp_vel,n,cstboltz,mass)
scaling=sqrt(temperature/tt)
vel=[]
for item in tmp_vel:
vx=item[0]*scaling
vy=item[1]*scaling
vel.append([vx,vy])
print("done")
return vel
########################################
# Various functions for input + layout #
########################################
# Setup system
def set_up_atoms(repack=1):
global Iterations,Velocity,Temperature,Mass,cstboltz,atom_canvas,ATOM,Atom_Coord,Color
ATOM = []
if repack==1:
Atom_Coord = InitConf(nAtoms,BoxDim,Radius,qat,frac_neg)
Color = []
for i in range(nAtoms):
Color.append(charge_color(Atom_Coord[i][2],qat))
Velocity=InitVel(nAtoms,Temperature,cstboltz,Mass)
if repack==2:
InitCharge(nAtoms,qat,frac_neg)
Color = []
for i in range(nAtoms):
Color.append(charge_color(Atom_Coord[i][2],qat))
for (color, atom) in zip(Color, Atom_Coord):
x, y = atom[0], atom[1]
ATOM.append(atom_canvas.create_oval(x + Radius,y + Radius,x - Radius,y - Radius,fill=color))
update_energy()
# Set number of particles
def set_r(event):
global nAtoms
nAtoms=int(r.get())
update_canvas()
# Set atom Radius
def set_size(event):
global Radius,Rmin
Radius=int(size.get())
Rmin = 2 * Radius
update_canvas()
# Set epsilon for Lennard-Jones
def set_vdw1(event):
global Epsilon
Epsilon=int(vdw1.get())
update_canvas(0)
# Set sigma for Lennard-Jones
def set_vdw2(event):
global Rmin
Rmin=int(vdw2.get())
update_canvas(0)
# Set charge fraction
def set_frac(event):
global frac_neg
frac_neg=float(frac.get())
update_canvas(2)
# Set particle charge
def set_q(event):
global qat
qat=float(q.get())
update_canvas(2)
# Set dielectric constant
def set_diel(event):
global Dielec
Dielec=float(diel.get())
update_canvas(0)
# Set Temperature
def set_temp(event):
global Temperature
Temperature=float(temp.get())
update_canvas(0)
def set_tstep(event):
global timestep,Velocity,nAtoms,Temperature,cstboltz,Mass
timestep=float(tstep.get())
update_canvas(0)
Velocity=InitVel(nAtoms,Temperature,cstboltz,Mass)
# Set minimum Force norm difference for stop condition
def set_dFmin(event):
global normFmin
normFmin=float(Fmin.get())
update_canvas(0)
# Set minimum Energy difference for stop condition
def set_deltaE(event):
global deltaE
deltaE=float(Emin.get())
update_canvas(0)
# Set initial displacement for minimizer
def set_dxstep(event):
global drinit
drinit=float(dxstep.get())
update_canvas(0)
# Set alpha factor for increasing dr
def set_alpha(event):
global alpha
alpha=float(alphafactor.get())
update_canvas(0)
# Set beta factor for decreasing dr
def set_beta(event):
global beta
beta=float(betafactor.get())
update_canvas(0)
# Update energy
def update_energy():
global Atom_Coord,BoxDim,Epsilon,Rmin,CutOffSquare,Iterations,Ene
global Dielec,Velocity,Mass,cstboltz
Ene,EneLJ,EneCoul,ELJ2,ELJ4 = calculate_energy(Atom_Coord,Epsilon,Rmin,Dielec,CutOffSquare,BoxDim)
Kin,temperature=calculate_temperature(Velocity,nAtoms,cstboltz,Mass)
report_var_time.set("Step: %d Time: %8.3f" % (Iterations,float(Iterations)*timestep))
report_var_total.set("Etot: %6.1f Ekin: %6.1f Epot: %6.1f" % (Ene+Kin,Kin,Ene))
if ShowOtherEnergyCutoffResults:
report_var_subenergies.set("Elj: %6.2f Elj2: %6.2f Elj4: %6.2f Ecoul: %6.1f Temp: %6.1f" % (EneLJ,ELJ2,ELJ4,EneCoul,temperature))
else:
report_var_subenergies.set("Elj: %6.1f Ecoul: %6.1f Temp: %6.1f" % (EneLJ,EneCoul,temperature))
def update_canvas(repack=1):
global Iterations, atom_canvas, Atom_Coord, ATOM, Color
atom_canvas.delete("all")
set_up_atoms(repack)
update_energy()
Iterations = 0
################
# MAIN PROGRAM #
################
def die():
sys.exit()
def select_minimizer(*args):
global Minimizer, minimizer_selector
reset()
if minimizer_selector.index('current') == 0: # First tab is Steepest Descent
Minimizer = Minimizers.SteepestDescent
selected_method_text.set("Active method: Steepest Descent")
else:
Minimizer = Minimizers.Verlet
selected_method_text.set("Active method: Verlet")
def start():
global canvas_event
if canvas_event==None:
simulate()
def stop():
global canvas_event
if canvas_event != None: atom_canvas.after_cancel(canvas_event)
canvas_event = None
update_canvas(0)
def reset():
global canvas_event
if canvas_event != None: atom_canvas.after_cancel(canvas_event)
canvas_event = None
update_canvas()
root = Tk()
root.winfo_toplevel().title("MolMod Practical")
root.bind("<Escape>", die)
root.bind('<Control-c>', die)
top=Frame(root)
top.pack(side='top')
title=Frame(top)
title.pack(side='top')
labels=Frame(top)
labels.pack(side='top')
buttons=Frame(top)
buttons.pack(side='bottom')
atom_canvas=Canvas(root, width=BoxDim[0], height=BoxDim[1],bg="#ccddff")
atom_canvas.pack()
minimizer_selector=Notebook(root)
minimizer_selector.pack(side='bottom')
steepest_descent_pack=Frame(minimizer_selector)
steepest_descent_pack.pack(side='top')
verlet_pack=Frame(minimizer_selector)
verlet_pack.pack(side='top')
Style().configure("Notebook", foreground="black")
minimizer_selector.add(steepest_descent_pack, text="Steepest Descent")
minimizer_selector.add(verlet_pack, text="Verlet")
minimizer_selector.bind("<<NotebookTabChanged>>", select_minimizer)
minimizer_selector.select(1)
selected_method=Frame(root)
selected_method.pack(side='bottom')
low2=Frame(root)
low2.pack(side='bottom')
low1=Frame(root)
low1.pack(side='bottom')
r=DoubleVar()
size=DoubleVar()
vdw1=DoubleVar()
vdw2=DoubleVar()
frac=DoubleVar()
diel=DoubleVar()
q=DoubleVar()
temp=DoubleVar()
tstep=DoubleVar()
Emin=DoubleVar()
Fmin=DoubleVar()
alphafactor=DoubleVar()
betafactor=DoubleVar()
q=DoubleVar()
temp=DoubleVar()
dxstep=DoubleVar()
# Create an entry with a label
def create_entry(pack, text, var, bound_var, callback):
Label(pack,text=text + " =").pack(side='left')
var.set(bound_var)
tstep_entry=Entry(pack,width=6,textvariable=var)
tstep_entry.pack(side='left')
tstep_entry.bind('<Return>', callback)
tstep_entry.bind('<FocusOut>', callback)
# Set up the general parameters
create_entry(low1, "Atoms", r, nAtoms, set_r)
create_entry(low1, "VDW radius", size, Radius, set_size)
create_entry(low1, "VDW ε", vdw1, Epsilon, set_vdw1)
create_entry(low1, "VDW σ", vdw2, Rmin, set_vdw2)
create_entry(low2, "Coulomb param: fraction negative", frac, frac_neg, set_frac)
create_entry(low2, "Charge", q, qat, set_q)
create_entry(low2, "Dielec", diel, Dielec, set_diel)
# Steepest Descent Paramaters
create_entry(steepest_descent_pack, "DeltaE threshold", Emin, deltaE, set_deltaE)
create_entry(steepest_descent_pack, "dFmin", Fmin, normFmin, set_dFmin)
create_entry(steepest_descent_pack, "dr init", dxstep, drinit, set_dxstep)
create_entry(steepest_descent_pack, "α", alphafactor, alpha, set_alpha)
create_entry(steepest_descent_pack, "β", betafactor, beta, set_beta)
# Verlet Parameters
create_entry(verlet_pack, "T (K)", temp, Temperature, set_temp)
create_entry(verlet_pack, "Timestep", tstep, timestep, set_tstep)
# Set up title
Label(title,text="EM & MD",foreground='blue',font='times 18 bold').pack(side='left')
# Set up reporting labels
report_var_time = StringVar()
Label(labels,textvariable=report_var_time).pack(side='top')
report_var_total = StringVar()
Label(labels,textvariable=report_var_total).pack(side='top')
report_var_subenergies = StringVar()
Label(labels,textvariable=report_var_subenergies).pack(side='top')
selected_method_text = StringVar()
Label(selected_method,textvariable=selected_method_text).pack(side='top')
# Set up buttons
Style().configure("TButton", padding=1, relief="flat")
Style().configure("Start.TButton", foreground='blue')
Style().configure("Stop.TButton", foreground='red')
Style().configure("Reset.TButton", foreground='green')
Button(buttons,text='Start',command=start,style="Start.TButton").pack(side='left',fill='x')
Button(buttons,text='Stop',command=stop,style="Stop.TButton").pack(side='left')
Button(buttons,text='Reset',command=reset,style="Reset.TButton").pack(side='left')
# Set up the positions of the atoms and start the simulation
set_up_atoms()
print("Click on 'Start' to go ahead")
print("Use <ESC> or 'X' to quit")
root.mainloop()
| rij=sqrt(distsquare)
dedr=-1.0*(qa*qb/dielec)*(1/distsquare)
drdx=xi/rij
return dedr*drdx |
messaging_test.go | // Copyright 2018 Google Inc. 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 messaging
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
"time"
"golang.org/x/net/context"
"firebase.google.com/go/internal"
"google.golang.org/api/option"
)
const testMessageID = "projects/test-project/messages/msg_id"
var (
testMessagingConfig = &internal.MessagingConfig{
ProjectID: "test-project",
Opts: []option.ClientOption{
option.WithTokenSource(&internal.MockTokenSource{AccessToken: "test-token"}),
},
}
ttlWithNanos = time.Duration(1500) * time.Millisecond
ttl = time.Duration(10) * time.Second
invalidTTL = time.Duration(-10) * time.Second
badge = 42
badgeZero = 0
timestampMillis = int64(12345)
)
var validMessages = []struct {
name string
req *Message
want map[string]interface{}
}{
{
name: "TokenOnly",
req: &Message{Token: "test-token"},
want: map[string]interface{}{"token": "test-token"},
},
{
name: "TopicOnly",
req: &Message{Topic: "test-topic"},
want: map[string]interface{}{"topic": "test-topic"},
},
{
name: "PrefixedTopicOnly",
req: &Message{Topic: "/topics/test-topic"},
want: map[string]interface{}{"topic": "test-topic"},
},
{
name: "ConditionOnly",
req: &Message{Condition: "test-condition"},
want: map[string]interface{}{"condition": "test-condition"},
},
{
name: "DataMessage",
req: &Message{
Data: map[string]string{
"k1": "v1",
"k2": "v2",
},
Topic: "test-topic",
},
want: map[string]interface{}{
"data": map[string]interface{}{
"k1": "v1",
"k2": "v2",
},
"topic": "test-topic",
},
},
{
name: "NotificationMessage",
req: &Message{
Notification: &Notification{
Title: "t",
Body: "b",
},
Topic: "test-topic",
},
want: map[string]interface{}{
"notification": map[string]interface{}{
"title": "t",
"body": "b",
},
"topic": "test-topic",
},
},
{
name: "AndroidDataMessage",
req: &Message{
Android: &AndroidConfig{
CollapseKey: "ck",
Data: map[string]string{
"k1": "v1",
"k2": "v2",
},
Priority: "normal",
TTL: &ttl,
},
Topic: "test-topic",
},
want: map[string]interface{}{
"android": map[string]interface{}{
"collapse_key": "ck",
"data": map[string]interface{}{
"k1": "v1",
"k2": "v2",
},
"priority": "normal",
"ttl": "10s",
},
"topic": "test-topic",
},
},
{
name: "AndroidNotificationMessage",
req: &Message{
Android: &AndroidConfig{
RestrictedPackageName: "rpn",
Notification: &AndroidNotification{
Title: "t",
Body: "b",
Color: "#112233",
Sound: "s",
TitleLocKey: "tlk",
TitleLocArgs: []string{"t1", "t2"},
BodyLocKey: "blk",
BodyLocArgs: []string{"b1", "b2"},
},
TTL: &ttlWithNanos,
},
Topic: "test-topic",
},
want: map[string]interface{}{
"android": map[string]interface{}{
"restricted_package_name": "rpn",
"notification": map[string]interface{}{
"title": "t",
"body": "b",
"color": "#112233",
"sound": "s",
"title_loc_key": "tlk",
"title_loc_args": []interface{}{"t1", "t2"},
"body_loc_key": "blk",
"body_loc_args": []interface{}{"b1", "b2"},
},
"ttl": "1.500000000s",
},
"topic": "test-topic",
},
},
{
name: "AndroidNoTTL",
req: &Message{
Android: &AndroidConfig{
Priority: "high",
},
Topic: "test-topic",
},
want: map[string]interface{}{
"android": map[string]interface{}{
"priority": "high",
},
"topic": "test-topic",
},
},
{
name: "WebpushMessage",
req: &Message{
Webpush: &WebpushConfig{
Headers: map[string]string{
"h1": "v1",
"h2": "v2",
},
Data: map[string]string{
"k1": "v1",
"k2": "v2",
},
Notification: &WebpushNotification{
Title: "title",
Body: "body",
Icon: "icon",
Actions: []*WebpushNotificationAction{
{
Action: "a1",
Title: "a1-title",
},
{
Action: "a2",
Title: "a2-title",
Icon: "a2-icon",
},
},
Badge: "badge",
Data: "data",
Image: "image",
Language: "lang",
Renotify: true,
RequireInteraction: true,
Silent: true,
Tag: "tag",
TimestampMillis: ×tampMillis,
Vibrate: []int{100, 200, 100},
CustomData: map[string]interface{}{"k1": "v1", "k2": "v2"},
},
},
Topic: "test-topic",
},
want: map[string]interface{}{
"webpush": map[string]interface{}{
"headers": map[string]interface{}{"h1": "v1", "h2": "v2"},
"data": map[string]interface{}{"k1": "v1", "k2": "v2"},
"notification": map[string]interface{}{
"title": "title",
"body": "body",
"icon": "icon",
"actions": []interface{}{
map[string]interface{}{"action": "a1", "title": "a1-title"},
map[string]interface{}{"action": "a2", "title": "a2-title", "icon": "a2-icon"},
},
"badge": "badge",
"data": "data",
"image": "image",
"lang": "lang",
"renotify": true,
"requireInteraction": true,
"silent": true,
"tag": "tag",
"timestamp": float64(12345),
"vibrate": []interface{}{float64(100), float64(200), float64(100)},
"k1": "v1",
"k2": "v2",
},
},
"topic": "test-topic",
},
},
{
name: "APNSHeadersOnly",
req: &Message{
APNS: &APNSConfig{
Headers: map[string]string{
"h1": "v1",
"h2": "v2",
},
},
Topic: "test-topic",
},
want: map[string]interface{}{
"apns": map[string]interface{}{
"headers": map[string]interface{}{"h1": "v1", "h2": "v2"},
},
"topic": "test-topic",
},
},
{
name: "APNSAlertString",
req: &Message{
APNS: &APNSConfig{
Headers: map[string]string{
"h1": "v1",
"h2": "v2",
},
Payload: &APNSPayload{
Aps: &Aps{
AlertString: "a",
Badge: &badge,
Category: "c",
Sound: "s",
ThreadID: "t",
ContentAvailable: true,
MutableContent: true,
},
CustomData: map[string]interface{}{
"k1": "v1",
"k2": true,
},
},
},
Topic: "test-topic",
},
want: map[string]interface{}{
"apns": map[string]interface{}{
"headers": map[string]interface{}{"h1": "v1", "h2": "v2"},
"payload": map[string]interface{}{
"aps": map[string]interface{}{
"alert": "a",
"badge": float64(badge),
"category": "c",
"sound": "s",
"thread-id": "t",
"content-available": float64(1),
"mutable-content": float64(1),
},
"k1": "v1",
"k2": true,
},
},
"topic": "test-topic",
},
},
{
name: "APNSBadgeZero",
req: &Message{
APNS: &APNSConfig{
Payload: &APNSPayload{
Aps: &Aps{
Badge: &badgeZero,
Category: "c",
Sound: "s",
ThreadID: "t",
ContentAvailable: true,
MutableContent: true,
CustomData: map[string]interface{}{"k1": "v1", "k2": 1},
},
},
},
Topic: "test-topic",
},
want: map[string]interface{}{
"apns": map[string]interface{}{
"payload": map[string]interface{}{
"aps": map[string]interface{}{
"badge": float64(badgeZero),
"category": "c",
"sound": "s",
"thread-id": "t",
"content-available": float64(1),
"mutable-content": float64(1),
"k1": "v1",
"k2": float64(1),
},
},
},
"topic": "test-topic",
},
},
{
name: "APNSAlertObject",
req: &Message{
APNS: &APNSConfig{
Payload: &APNSPayload{
Aps: &Aps{
Alert: &ApsAlert{
Title: "t",
Body: "b",
TitleLocKey: "tlk",
TitleLocArgs: []string{"t1", "t2"},
LocKey: "blk",
LocArgs: []string{"b1", "b2"},
ActionLocKey: "alk",
LaunchImage: "li",
},
},
},
},
Topic: "test-topic",
},
want: map[string]interface{}{
"apns": map[string]interface{}{
"payload": map[string]interface{}{
"aps": map[string]interface{}{
"alert": map[string]interface{}{
"title": "t",
"body": "b",
"title-loc-key": "tlk",
"title-loc-args": []interface{}{"t1", "t2"},
"loc-key": "blk",
"loc-args": []interface{}{"b1", "b2"},
"action-loc-key": "alk",
"launch-image": "li",
},
},
},
},
"topic": "test-topic",
},
},
}
var invalidMessages = []struct {
name string
req *Message
want string
}{
{
name: "NilMessage",
req: nil,
want: "message must not be nil",
},
{
name: "NoTargets",
req: &Message{},
want: "exactly one of token, topic or condition must be specified",
},
{
name: "MultipleTargets",
req: &Message{
Token: "token",
Topic: "topic",
},
want: "exactly one of token, topic or condition must be specified",
},
{
name: "InvalidPrefixedTopicName",
req: &Message{
Topic: "/topics/",
},
want: "malformed topic name",
},
{
name: "InvalidTopicName",
req: &Message{
Topic: "foo*bar",
},
want: "malformed topic name",
},
{
name: "InvalidAndroidTTL",
req: &Message{
Android: &AndroidConfig{
TTL: &invalidTTL,
},
Topic: "topic",
},
want: "ttl duration must not be negative",
},
{
name: "InvalidAndroidPriority",
req: &Message{
Android: &AndroidConfig{
Priority: "not normal",
},
Topic: "topic",
},
want: "priority must be 'normal' or 'high'",
},
{
name: "InvalidAndroidColor1",
req: &Message{
Android: &AndroidConfig{
Notification: &AndroidNotification{
Color: "112233",
},
},
Topic: "topic",
},
want: "color must be in the #RRGGBB form",
},
{
name: "InvalidAndroidColor2",
req: &Message{
Android: &AndroidConfig{
Notification: &AndroidNotification{
Color: "#112233X",
},
},
Topic: "topic",
},
want: "color must be in the #RRGGBB form",
},
{
name: "InvalidAndroidTitleLocArgs",
req: &Message{
Android: &AndroidConfig{
Notification: &AndroidNotification{
TitleLocArgs: []string{"a1"},
},
},
Topic: "topic",
},
want: "titleLocKey is required when specifying titleLocArgs",
},
{
name: "InvalidAndroidBodyLocArgs",
req: &Message{
Android: &AndroidConfig{
Notification: &AndroidNotification{
BodyLocArgs: []string{"a1"},
},
},
Topic: "topic",
},
want: "bodyLocKey is required when specifying bodyLocArgs",
},
{
name: "APNSMultipleAlerts",
req: &Message{
APNS: &APNSConfig{
Payload: &APNSPayload{
Aps: &Aps{
Alert: &ApsAlert{},
AlertString: "alert",
},
},
},
Topic: "topic",
},
want: "multiple alert specifications",
},
{
name: "APNSMultipleFieldSpecifications",
req: &Message{
APNS: &APNSConfig{
Payload: &APNSPayload{
Aps: &Aps{
Category: "category",
CustomData: map[string]interface{}{"category": "category"},
},
},
},
Topic: "topic",
},
want: `multiple specifications for the key "category"`,
},
{
name: "InvalidAPNSTitleLocArgs",
req: &Message{
APNS: &APNSConfig{
Payload: &APNSPayload{
Aps: &Aps{
Alert: &ApsAlert{
TitleLocArgs: []string{"a1"},
},
},
},
},
Topic: "topic",
},
want: "titleLocKey is required when specifying titleLocArgs",
},
{
name: "InvalidAPNSLocArgs",
req: &Message{
APNS: &APNSConfig{
Payload: &APNSPayload{
Aps: &Aps{
Alert: &ApsAlert{
LocArgs: []string{"a1"},
},
},
},
},
Topic: "topic",
},
want: "locKey is required when specifying locArgs",
},
{
name: "InvalidWebpushNotificationDirection",
req: &Message{
Webpush: &WebpushConfig{
Notification: &WebpushNotification{
Direction: "invalid",
},
},
Topic: "topic",
},
want: "direction must be 'ltr', 'rtl' or 'auto'",
},
{
name: "WebpushNotificationMultipleFieldSpecifications",
req: &Message{
Webpush: &WebpushConfig{
Notification: &WebpushNotification{
Direction: "ltr",
CustomData: map[string]interface{}{"dir": "rtl"},
},
},
Topic: "topic",
},
want: `multiple specifications for the key "dir"`,
},
}
var invalidTopicMgtArgs = []struct {
name string
tokens []string
topic string
want string
}{
{
name: "NoTokensAndTopic",
want: "no tokens specified",
},
{
name: "NoTopic",
tokens: []string{"token1"},
want: "topic name not specified",
},
{
name: "InvalidTopicName",
tokens: []string{"token1"},
topic: "foo*bar",
want: "invalid topic name: \"foo*bar\"",
},
{
name: "TooManyTokens",
tokens: strings.Split("a"+strings.Repeat(",a", 1000), ","),
topic: "topic",
want: "tokens list must not contain more than 1000 items",
},
{
name: "EmptyToken",
tokens: []string{"foo", ""},
topic: "topic",
want: "tokens list must not contain empty strings",
},
}
func TestNoProjectID(t *testing.T) {
client, err := NewClient(context.Background(), &internal.MessagingConfig{})
if client != nil || err == nil {
t.Errorf("NewClient() = (%v, %v); want = (nil, error)", client, err)
}
}
func TestSend(t *testing.T) {
var tr *http.Request
var b []byte
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tr = r
b, _ = ioutil.ReadAll(r.Body)
w.Header().Set("Content-Type", "application/json")
w.Write([]byte("{ \"name\":\"" + testMessageID + "\" }"))
}))
defer ts.Close()
ctx := context.Background()
client, err := NewClient(ctx, testMessagingConfig)
if err != nil {
t.Fatal(err)
}
client.fcmEndpoint = ts.URL
for _, tc := range validMessages {
name, err := client.Send(ctx, tc.req)
if name != testMessageID || err != nil {
t.Errorf("Send(%s) = (%q, %v); want = (%q, nil)", tc.name, name, err, testMessageID)
}
checkFCMRequest(t, b, tr, tc.want, false)
}
}
func TestSendDryRun(t *testing.T) {
var tr *http.Request
var b []byte
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tr = r
b, _ = ioutil.ReadAll(r.Body)
w.Header().Set("Content-Type", "application/json")
w.Write([]byte("{ \"name\":\"" + testMessageID + "\" }"))
}))
defer ts.Close()
ctx := context.Background()
client, err := NewClient(ctx, testMessagingConfig)
if err != nil {
t.Fatal(err)
}
client.fcmEndpoint = ts.URL
for _, tc := range validMessages {
name, err := client.SendDryRun(ctx, tc.req)
if name != testMessageID || err != nil {
t.Errorf("SendDryRun(%s) = (%q, %v); want = (%q, nil)", tc.name, name, err, testMessageID)
}
checkFCMRequest(t, b, tr, tc.want, true)
}
}
func TestSendError(t *testing.T) {
var resp string
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(resp))
}))
defer ts.Close()
ctx := context.Background()
client, err := NewClient(ctx, testMessagingConfig)
if err != nil {
t.Fatal(err)
}
client.fcmEndpoint = ts.URL
cases := []struct {
resp, want string
check func(error) bool
}{
{
resp: "{}",
want: "http error status: 500; reason: server responded with an unknown error; response: {}",
check: IsUnknown,
},
{
resp: "{\"error\": {\"status\": \"INVALID_ARGUMENT\", \"message\": \"test error\"}}",
want: "http error status: 500; reason: request contains an invalid argument; code: invalid-argument; details: test error",
check: IsInvalidArgument,
},
{
resp: "{\"error\": {\"status\": \"NOT_FOUND\", \"message\": \"test error\"}}",
want: "http error status: 500; reason: app instance has been unregistered; code: registration-token-not-registered; " +
"details: test error",
check: IsRegistrationTokenNotRegistered,
},
{
resp: "{\"error\": {\"status\": \"QUOTA_EXCEEDED\", \"message\": \"test error\"}}",
want: "http error status: 500; reason: messaging service quota exceeded; code: message-rate-exceeded; " +
"details: test error",
check: IsMessageRateExceeded,
},
{
resp: "{\"error\": {\"status\": \"UNAVAILABLE\", \"message\": \"test error\"}}",
want: "http error status: 500; reason: backend servers are temporarily unavailable; code: server-unavailable; " +
"details: test error",
check: IsServerUnavailable,
},
{
resp: "{\"error\": {\"status\": \"INTERNAL\", \"message\": \"test error\"}}",
want: "http error status: 500; reason: backend servers encountered an unknown internl error; code: internal-error; " +
"details: test error",
check: IsInternal,
},
{
resp: "{\"error\": {\"status\": \"APNS_AUTH_ERROR\", \"message\": \"test error\"}}",
want: "http error status: 500; reason: apns certificate or auth key was invalid; code: invalid-apns-credentials; " +
"details: test error",
check: IsInvalidAPNSCredentials,
},
{
resp: "{\"error\": {\"status\": \"SENDER_ID_MISMATCH\", \"message\": \"test error\"}}",
want: "http error status: 500; reason: sender id does not match regisration token; code: mismatched-credential; " +
"details: test error",
check: IsMismatchedCredential,
},
{
resp: `{"error": {"status": "INVALID_ARGUMENT", "message": "test error", "details": [` +
`{"@type": "type.googleapis.com/google.firebase.fcm.v1.FcmErrorCode", "errorCode": "UNREGISTERED"}]}}`,
want: "http error status: 500; reason: app instance has been unregistered; code: registration-token-not-registered; " +
"details: test error",
check: IsRegistrationTokenNotRegistered,
},
{
resp: "not json",
want: "http error status: 500; reason: server responded with an unknown error; response: not json",
check: IsUnknown,
},
}
for _, tc := range cases {
resp = tc.resp
name, err := client.Send(ctx, &Message{Topic: "topic"})
if err == nil || err.Error() != tc.want || !tc.check(err) {
t.Errorf("Send() = (%q, %v); want = (%q, %q)", name, err, "", tc.want)
}
}
}
func TestInvalidMessage(t *testing.T) {
ctx := context.Background()
client, err := NewClient(ctx, testMessagingConfig)
if err != nil {
t.Fatal(err)
}
for _, tc := range invalidMessages {
name, err := client.Send(ctx, tc.req)
if err == nil || err.Error() != tc.want {
t.Errorf("Send(%s) = (%q, %v); want = (%q, %q)", tc.name, name, err, "", tc.want)
}
}
}
func TestSubscribe(t *testing.T) {
var tr *http.Request
var b []byte
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tr = r
b, _ = ioutil.ReadAll(r.Body)
w.Header().Set("Content-Type", "application/json")
w.Write([]byte("{\"results\": [{}, {\"error\": \"error_reason\"}]}"))
}))
defer ts.Close()
ctx := context.Background()
client, err := NewClient(ctx, testMessagingConfig)
if err != nil {
t.Fatal(err)
}
client.iidEndpoint = ts.URL
resp, err := client.SubscribeToTopic(ctx, []string{"id1", "id2"}, "test-topic")
if err != nil {
t.Fatal(err)
}
checkIIDRequest(t, b, tr, iidSubscribe)
checkTopicMgtResponse(t, resp)
}
func TestInvalidSubscribe(t *testing.T) {
ctx := context.Background()
client, err := NewClient(ctx, testMessagingConfig)
if err != nil {
t.Fatal(err)
}
for _, tc := range invalidTopicMgtArgs {
name, err := client.SubscribeToTopic(ctx, tc.tokens, tc.topic)
if err == nil || err.Error() != tc.want {
t.Errorf("SubscribeToTopic(%s) = (%q, %v); want = (%q, %q)", tc.name, name, err, "", tc.want)
}
}
}
func TestUnsubscribe(t *testing.T) {
var tr *http.Request
var b []byte
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tr = r
b, _ = ioutil.ReadAll(r.Body)
w.Header().Set("Content-Type", "application/json")
w.Write([]byte("{\"results\": [{}, {\"error\": \"error_reason\"}]}"))
}))
defer ts.Close()
ctx := context.Background()
client, err := NewClient(ctx, testMessagingConfig)
if err != nil {
t.Fatal(err)
}
client.iidEndpoint = ts.URL
resp, err := client.UnsubscribeFromTopic(ctx, []string{"id1", "id2"}, "test-topic")
if err != nil {
t.Fatal(err)
}
checkIIDRequest(t, b, tr, iidUnsubscribe)
checkTopicMgtResponse(t, resp)
}
func TestInvalidUnsubscribe(t *testing.T) {
ctx := context.Background()
client, err := NewClient(ctx, testMessagingConfig)
if err != nil {
t.Fatal(err)
}
for _, tc := range invalidTopicMgtArgs {
name, err := client.UnsubscribeFromTopic(ctx, tc.tokens, tc.topic)
if err == nil || err.Error() != tc.want {
t.Errorf("UnsubscribeFromTopic(%s) = (%q, %v); want = (%q, %q)", tc.name, name, err, "", tc.want)
}
}
}
func TestTopicManagementError(t *testing.T) {
var resp string
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(resp))
}))
defer ts.Close()
ctx := context.Background()
client, err := NewClient(ctx, testMessagingConfig)
if err != nil {
t.Fatal(err)
}
client.iidEndpoint = ts.URL
cases := []struct {
resp, want string
check func(error) bool
}{
{
resp: "{}",
want: "http error status: 500; reason: client encountered an unknown error; response: {}",
check: IsUnknown,
},
{
resp: "{\"error\": \"INVALID_ARGUMENT\"}",
want: "http error status: 500; reason: request contains an invalid argument; code: invalid-argument",
check: IsInvalidArgument,
},
{
resp: "{\"error\": \"TOO_MANY_TOPICS\"}",
want: "http error status: 500; reason: client exceeded the number of allowed topics; code: too-many-topics",
check: IsTooManyTopics,
},
{
resp: "not json",
want: "http error status: 500; reason: client encountered an unknown error; response: not json",
check: IsUnknown,
},
}
for _, tc := range cases {
resp = tc.resp
tmr, err := client.SubscribeToTopic(ctx, []string{"id1"}, "topic")
if err == nil || err.Error() != tc.want || !tc.check(err) {
t.Errorf("SubscribeToTopic() = (%q, %v); want = (%q, %q)", tmr, err, "", tc.want) | resp = tc.resp
tmr, err := client.UnsubscribeFromTopic(ctx, []string{"id1"}, "topic")
if err == nil || err.Error() != tc.want {
t.Errorf("UnsubscribeFromTopic() = (%q, %v); want = (%q, %q)", tmr, err, "", tc.want)
}
}
}
func checkFCMRequest(t *testing.T, b []byte, tr *http.Request, want map[string]interface{}, dryRun bool) {
var parsed map[string]interface{}
if err := json.Unmarshal(b, &parsed); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(parsed["message"], want) {
t.Errorf("Body = %#v; want = %#v", parsed["message"], want)
}
validate, ok := parsed["validate_only"]
if dryRun {
if !ok || validate != true {
t.Errorf("ValidateOnly = %v; want = true", validate)
}
} else if ok {
t.Errorf("ValidateOnly = %v; want none", validate)
}
if tr.Method != http.MethodPost {
t.Errorf("Method = %q; want = %q", tr.Method, http.MethodPost)
}
if tr.URL.Path != "/projects/test-project/messages:send" {
t.Errorf("Path = %q; want = %q", tr.URL.Path, "/projects/test-project/messages:send")
}
if h := tr.Header.Get("Authorization"); h != "Bearer test-token" {
t.Errorf("Authorization = %q; want = %q", h, "Bearer test-token")
}
}
func checkIIDRequest(t *testing.T, b []byte, tr *http.Request, op string) {
var parsed map[string]interface{}
if err := json.Unmarshal(b, &parsed); err != nil {
t.Fatal(err)
}
want := map[string]interface{}{
"to": "/topics/test-topic",
"registration_tokens": []interface{}{"id1", "id2"},
}
if !reflect.DeepEqual(parsed, want) {
t.Errorf("Body = %#v; want = %#v", parsed, want)
}
if tr.Method != http.MethodPost {
t.Errorf("Method = %q; want = %q", tr.Method, http.MethodPost)
}
wantOp := "/" + op
if tr.URL.Path != wantOp {
t.Errorf("Path = %q; want = %q", tr.URL.Path, wantOp)
}
if h := tr.Header.Get("Authorization"); h != "Bearer test-token" {
t.Errorf("Authorization = %q; want = %q", h, "Bearer test-token")
}
}
func checkTopicMgtResponse(t *testing.T, resp *TopicManagementResponse) {
if resp.SuccessCount != 1 {
t.Errorf("SuccessCount = %d; want = %d", resp.SuccessCount, 1)
}
if resp.FailureCount != 1 {
t.Errorf("FailureCount = %d; want = %d", resp.FailureCount, 1)
}
if len(resp.Errors) != 1 {
t.Fatalf("Errors = %d; want = %d", len(resp.Errors), 1)
}
e := resp.Errors[0]
if e.Index != 1 {
t.Errorf("ErrorInfo.Index = %d; want = %d", e.Index, 1)
}
if e.Reason != "unknown-error" {
t.Errorf("ErrorInfo.Reason = %s; want = %s", e.Reason, "unknown-error")
}
} | }
}
for _, tc := range cases { |
base.py | from bos_consensus.util import LoggingMixin
class | (Exception):
pass
class StopReceiveBallot(Exception):
pass
class BaseBlockchainMiddleware(LoggingMixin):
blockchain = None
def __init__(self, blockchain):
self.blockchain = blockchain
super(BaseBlockchainMiddleware, self).__init__()
self.set_logging('middleware', node=self.blockchain.consensus.node.name)
def received_ballot(self, ballot):
pass
def finished_ballot(self, ballot):
pass
| NoFurtherBlockchainMiddlewares |
usePrinter.ts | import { useState, useEffect, useRef } from 'react';
import { Nullable } from '../../utils/helpers';
import { printer, PrintableItem, PrinterResponse, createPrinterTask } from '../../API/printer';
type PrinterReturnType = ReturnType<typeof usePrinter>;
const defaultState: PrinterResponse = {
state: [],
remainingLines: null,
printedLines: [],
wordFullyPrinted: true,
newLine: true,
};
type IntervalID = ReturnType<typeof setTimeout>;
type ResolveCallback = Nullable<(value: unknown) => void>;
interface PrinterConfig {
printerSpeed: number;
charactersPerTick: number;
}
interface PrinterProps extends PrinterConfig {
afterPrintCallback: () => void;
}
function usePrinter({ printerSpeed, charactersPerTick, afterPrintCallback }: PrinterProps) {
const [isPrinting, setIsPrinting] = useState(false);
const [activeTimeout, setActiveTimeout] = useState<IntervalID | null>(null);
const [printerResponse, setPrinterResponse] = useState<PrinterResponse>(defaultState);
const resolveRef = useRef<ResolveCallback>(null);
const clearTimeoutState = () => {
if (activeTimeout) {
clearTimeout(activeTimeout);
setActiveTimeout(null);
}
};
const clearResolver = () => {
if (resolveRef.current) {
resolveRef.current(true);
resolveRef.current = null;
}
};
const nextPrint = () => {
const { remainingLines, printedLines, wordFullyPrinted, newLine, state } = printerResponse;
if (!remainingLines) return;
const resp = printer({
remainingLines,
printedLines: newLine ? [] : printedLines,
wordFullyPrinted,
newLine,
state,
charactersToPrint: charactersPerTick,
});
setPrinterResponse(resp);
setActiveTimeout(null);
};
const startPrint = async (line: PrintableItem) => {
const resp = printer({
remainingLines: line,
printedLines: [],
state: printerResponse.state,
wordFullyPrinted: true,
newLine: true,
charactersToPrint: charactersPerTick,
});
setIsPrinting(true);
setPrinterResponse(resp);
return new Promise((resolve) => {
resolveRef.current = resolve;
});
};
const stopPrint = () => {
setIsPrinting(false);
clearTimeout();
clearResolver();
};
const clear = () => {
setPrinterResponse(defaultState);
};
useEffect(() => {
const shouldStopPrint = isPrinting && !printerResponse.remainingLines;
const shouldPrint = isPrinting && !activeTimeout;
const shouldClearTimeout = !isPrinting && activeTimeout;
if (shouldStopPrint) {
stopPrint(); | } else if (shouldPrint) {
setActiveTimeout(createPrinterTask(nextPrint, printerSpeed));
afterPrintCallback();
} else if (shouldClearTimeout) {
clearTimeoutState();
}
return () => {};
// disabled due to inner structure: nextSlide only matters when activeTimeout or isLoading updated
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isPrinting, activeTimeout]);
useEffect(
() => () => {
clearTimeoutState();
clearResolver();
},
// disabled due to inner structure: should be equal to "onBeforeUnmount"
// eslint-disable-next-line react-hooks/exhaustive-deps
[],
);
return {
state: printerResponse.state,
handlers: {
startPrint,
clear,
},
};
}
export type { PrinterReturnType, PrinterConfig, PrinterProps };
export { usePrinter }; | afterPrintCallback(); |
main.rs | // Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to include inner attributes from a common source.
#![cfg_attr(
feature = "cargo-clippy",
deny(
clippy,
default_trait_access,
expl_impl_clone_on_copy,
if_not_else,
needless_continue,
single_match_else,
unseparated_literal_suffix,
used_underscore_binding
)
)]
// It is often more clear to show that nothing is being moved.
#![cfg_attr(feature = "cargo-clippy", allow(match_ref_pats))]
// Subjective style.
#![cfg_attr(
feature = "cargo-clippy",
allow(len_without_is_empty, redundant_field_names)
)]
// Default isn't as big a deal as people seem to think it is.
#![cfg_attr(
feature = "cargo-clippy",
allow(new_without_default, new_without_default_derive)
)]
// Arc<Mutex> can be more clear than needing to grok Orderings:
#![cfg_attr(feature = "cargo-clippy", allow(mutex_atomic))]
extern crate rand;
extern crate ui;
use std::thread;
use std::time::Duration;
use rand::Rng;
use ui::EngineDisplay;
// N.B. This is purely a demo/testing bin target for exercising the library.
fn main() {
let mut display = EngineDisplay::for_stdout(0);
display.start();
let worker_ids = vec![
"pool worker 1".to_string(),
"pool worker 2".to_string(),
"pool worker 3".to_string(),
"pool worker 4".to_string(),
"pool worker 5".to_string(),
"pool worker 6".to_string(),
"pool worker 7".to_string(),
"pool worker 8".to_string(),
];
let random_verbs = vec![
"some printable result for".to_string(),
"failed to get a".to_string(),
];
let random_log_levels = vec!["INFO".to_string(), "WARN".to_string(), "DEBUG".to_string()];
let random_products = vec!(
"PathGlobs".to_string(),
"FileContents xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxzzzzzzzzzzzzzzzzzzzzzzzzz".to_string(),
"Snapshot".to_string(),
"DirectoryDigest".to_string(),
"SourcesField".to_string(),
"BundlesField".to_string(),
"HydratedField".to_string(),
"File".to_string(),
"Dir".to_string(),
"Link".to_string()
);
let mut done = false;
let mut counter: u64 = 0;
for worker_id in worker_ids.clone() {
display.add_worker(worker_id);
display.render();
thread::sleep(Duration::from_millis(63));
}
display.render();
thread::sleep(Duration::from_secs(1));
while !done {
display.render_and_sleep();
gen_display_work(
&mut display,
counter,
&random_products,
&worker_ids,
&random_verbs,
&random_log_levels,
);
if counter > 300 {
done = true;
} else {
counter += 1;
}
}
display.finish();
}
fn gen_display_work(
display: &mut EngineDisplay,
counter: u64,
type_selection: &[String],
worker_ids: &[String],
verb_selection: &[String],
log_level_selection: &[String],
) | {
let mut rng = rand::thread_rng();
for worker_id in worker_ids {
let random_product = rng.choose(&type_selection).unwrap();
let random_subject = rng.choose(&type_selection).unwrap();
display.update(
worker_id.to_string(),
format!("computing {} for {}(...)", random_product, random_subject),
);
}
if counter > 50 && counter % 2 == 0 {
let random_log_level = rng.choose(&log_level_selection).unwrap();
let random_verb = rng.choose(&verb_selection).unwrap();
let random_product_2 = rng.choose(&type_selection).unwrap();
display.log(format!(
"{}] {} {}",
random_log_level, random_verb, random_product_2
));
}
} |
|
transform_groupby_partial_test.rs | // Copyright 2020-2021 The Datafuse Authors.
//
// SPDX-License-Identifier: Apache-2.0.
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_transform_partial_groupby() -> anyhow::Result<()> {
use std::sync::Arc;
use common_planners::*;
use common_planners::{self};
use futures::TryStreamExt;
use pretty_assertions::assert_eq;
use crate::pipelines::processors::*;
use crate::pipelines::transforms::*;
let ctx = crate::tests::try_create_context()?;
let test_source = crate::tests::NumberTestData::create(ctx.clone());
// sum(number), avg(number)
let aggr_exprs = vec![sum(col("number")), avg(col("number"))];
let group_exprs = vec![col("number")];
let aggr_partial = PlanBuilder::create(test_source.number_schema_for_test()?)
.aggregate_partial(&aggr_exprs, &group_exprs)?
.build()?;
// Pipeline.
let mut pipeline = Pipeline::create(ctx.clone());
let source = test_source.number_source_transform_for_test(5)?;
let source_schema = test_source.number_schema_for_test()?;
pipeline.add_source(Arc::new(source))?;
pipeline.add_simple_transform(|| {
Ok(Box::new(GroupByPartialTransform::create(
aggr_partial.schema(),
source_schema.clone(),
aggr_exprs.clone(),
group_exprs.clone(),
)))
})?;
pipeline.merge_processor()?;
// Result.
let stream = pipeline.execute().await?;
let result = stream.try_collect::<Vec<_>>().await?;
let block = &result[0];
assert_eq!(block.num_columns(), 4);
// SELECT SUM(number), AVG(number), number ... GROUP BY number;
let expected = vec![
"+---------------------------+-----------------------------------------------------+---------------------------+------------------+",
"| sum(number) | avg(number) | _group_keys | _group_by_key |",
"+---------------------------+-----------------------------------------------------+---------------------------+------------------+",
"| {\"Struct\":[{\"UInt64\":0}]} | {\"Struct\":[{\"Struct\":[{\"UInt64\":0},{\"UInt64\":1}]}]} | {\"Struct\":[{\"UInt64\":0}]} | 0000000000000000 |",
"| {\"Struct\":[{\"UInt64\":1}]} | {\"Struct\":[{\"Struct\":[{\"UInt64\":1},{\"UInt64\":1}]}]} | {\"Struct\":[{\"UInt64\":1}]} | 0100000000000000 |",
"| {\"Struct\":[{\"UInt64\":2}]} | {\"Struct\":[{\"Struct\":[{\"UInt64\":2},{\"UInt64\":1}]}]} | {\"Struct\":[{\"UInt64\":2}]} | 0200000000000000 |",
"| {\"Struct\":[{\"UInt64\":3}]} | {\"Struct\":[{\"Struct\":[{\"UInt64\":3},{\"UInt64\":1}]}]} | {\"Struct\":[{\"UInt64\":3}]} | 0300000000000000 |",
"| {\"Struct\":[{\"UInt64\":4}]} | {\"Struct\":[{\"Struct\":[{\"UInt64\":4},{\"UInt64\":1}]}]} | {\"Struct\":[{\"UInt64\":4}]} | 0400000000000000 |",
"+---------------------------+-----------------------------------------------------+---------------------------+------------------+", | ];
common_datablocks::assert_blocks_sorted_eq(expected, result.as_slice());
Ok(())
} | |
index.js | "use strict";
const stringUtils = require("ember-cli-string-utils");
const useTestFrameworkDetector = require("../test-framework-detector");
module.exports = useTestFrameworkDetector({
description: "Generates a mixin unit test.",
locals: function(options) {
let projectName = options.inRepoAddon
? options.inRepoAddon
: options.project.name();
let dasherizedModulePrefix = options.inRepoAddon
? projectName
: stringUtils.dasherize(options.project.config().modulePrefix);
return { | }
}); | dasherizedModulePrefix,
projectName,
friendlyTestName: ["Unit", "Mixin", options.entity.name].join(" | ")
}; |
team.pb.go | // Copyright 2020-2021 Buf Technologies, 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.
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.27.1
// protoc v3.17.3
// source: buf/alpha/registry/v1alpha1/team.proto
package registryv1alpha1
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
timestamppb "google.golang.org/protobuf/types/known/timestamppb"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type Team struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// primary key, unique, immutable
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
// immutable
CreateTime *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty"`
// mutable
UpdateTime *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=update_time,json=updateTime,proto3" json:"update_time,omitempty"`
// unique, mutable
Name string `protobuf:"bytes,4,opt,name=name,proto3" json:"name,omitempty"`
// foreign key, immutable
OrganizationId string `protobuf:"bytes,5,opt,name=organization_id,json=organizationId,proto3" json:"organization_id,omitempty"`
}
func (x *Team) Reset() {
*x = Team{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *Team) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Team) ProtoMessage() {}
func (x *Team) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Team.ProtoReflect.Descriptor instead.
func (*Team) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{0}
}
func (x *Team) GetId() string {
if x != nil {
return x.Id
}
return ""
}
func (x *Team) GetCreateTime() *timestamppb.Timestamp {
if x != nil {
return x.CreateTime
}
return nil
}
func (x *Team) GetUpdateTime() *timestamppb.Timestamp {
if x != nil {
return x.UpdateTime
}
return nil
}
func (x *Team) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *Team) GetOrganizationId() string {
if x != nil {
return x.OrganizationId
}
return ""
}
type GetTeamRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
}
func (x *GetTeamRequest) Reset() {
*x = GetTeamRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *GetTeamRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GetTeamRequest) ProtoMessage() {}
func (x *GetTeamRequest) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GetTeamRequest.ProtoReflect.Descriptor instead.
func (*GetTeamRequest) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{1}
}
func (x *GetTeamRequest) GetId() string {
if x != nil {
return x.Id
}
return ""
}
type GetTeamResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Team *Team `protobuf:"bytes,1,opt,name=team,proto3" json:"team,omitempty"`
}
func (x *GetTeamResponse) Reset() {
*x = GetTeamResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *GetTeamResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GetTeamResponse) ProtoMessage() {}
func (x *GetTeamResponse) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[2]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GetTeamResponse.ProtoReflect.Descriptor instead.
func (*GetTeamResponse) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{2}
}
func (x *GetTeamResponse) GetTeam() *Team {
if x != nil {
return x.Team
}
return nil
}
type GetTeamByNameRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
OrganizationName string `protobuf:"bytes,2,opt,name=organization_name,json=organizationName,proto3" json:"organization_name,omitempty"`
}
func (x *GetTeamByNameRequest) Reset() {
*x = GetTeamByNameRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *GetTeamByNameRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GetTeamByNameRequest) ProtoMessage() {}
func (x *GetTeamByNameRequest) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[3]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GetTeamByNameRequest.ProtoReflect.Descriptor instead.
func (*GetTeamByNameRequest) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{3}
}
func (x *GetTeamByNameRequest) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *GetTeamByNameRequest) GetOrganizationName() string {
if x != nil {
return x.OrganizationName
}
return ""
}
type GetTeamByNameResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Team *Team `protobuf:"bytes,1,opt,name=team,proto3" json:"team,omitempty"`
}
func (x *GetTeamByNameResponse) Reset() {
*x = GetTeamByNameResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[4]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *GetTeamByNameResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GetTeamByNameResponse) ProtoMessage() {}
func (x *GetTeamByNameResponse) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[4]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GetTeamByNameResponse.ProtoReflect.Descriptor instead.
func (*GetTeamByNameResponse) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{4}
}
func (x *GetTeamByNameResponse) GetTeam() *Team {
if x != nil {
return x.Team
}
return nil
}
type ListOrganizationTeamsRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// The ID of the organization whose teams should be listed.
OrganizationId string `protobuf:"bytes,1,opt,name=organization_id,json=organizationId,proto3" json:"organization_id,omitempty"`
PageSize uint32 `protobuf:"varint,2,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"`
// The first page is returned if this is empty.
PageToken string `protobuf:"bytes,3,opt,name=page_token,json=pageToken,proto3" json:"page_token,omitempty"`
Reverse bool `protobuf:"varint,4,opt,name=reverse,proto3" json:"reverse,omitempty"`
}
func (x *ListOrganizationTeamsRequest) Reset() {
*x = ListOrganizationTeamsRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[5]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *ListOrganizationTeamsRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ListOrganizationTeamsRequest) ProtoMessage() {}
func (x *ListOrganizationTeamsRequest) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[5]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ListOrganizationTeamsRequest.ProtoReflect.Descriptor instead.
func (*ListOrganizationTeamsRequest) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{5}
}
func (x *ListOrganizationTeamsRequest) GetOrganizationId() string {
if x != nil {
return x.OrganizationId
}
return ""
}
func (x *ListOrganizationTeamsRequest) GetPageSize() uint32 {
if x != nil {
return x.PageSize
}
return 0
}
func (x *ListOrganizationTeamsRequest) GetPageToken() string {
if x != nil {
return x.PageToken
}
return ""
}
func (x *ListOrganizationTeamsRequest) GetReverse() bool {
if x != nil {
return x.Reverse
}
return false
}
type ListOrganizationTeamsResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Teams []*Team `protobuf:"bytes,1,rep,name=teams,proto3" json:"teams,omitempty"`
// There are no more pages if this is empty.
NextPageToken string `protobuf:"bytes,2,opt,name=next_page_token,json=nextPageToken,proto3" json:"next_page_token,omitempty"`
}
func (x *ListOrganizationTeamsResponse) Reset() {
*x = ListOrganizationTeamsResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[6]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *ListOrganizationTeamsResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ListOrganizationTeamsResponse) ProtoMessage() {}
func (x *ListOrganizationTeamsResponse) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[6]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ListOrganizationTeamsResponse.ProtoReflect.Descriptor instead.
func (*ListOrganizationTeamsResponse) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{6}
}
func (x *ListOrganizationTeamsResponse) GetTeams() []*Team {
if x != nil {
return x.Teams
}
return nil
}
func (x *ListOrganizationTeamsResponse) GetNextPageToken() string {
if x != nil {
return x.NextPageToken
}
return ""
}
type CreateTeamRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// Must be unique within organization.
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
OrganizationId string `protobuf:"bytes,2,opt,name=organization_id,json=organizationId,proto3" json:"organization_id,omitempty"`
}
func (x *CreateTeamRequest) Reset() {
*x = CreateTeamRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[7]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *CreateTeamRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*CreateTeamRequest) ProtoMessage() {}
func (x *CreateTeamRequest) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[7]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil |
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use CreateTeamRequest.ProtoReflect.Descriptor instead.
func (*CreateTeamRequest) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{7}
}
func (x *CreateTeamRequest) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *CreateTeamRequest) GetOrganizationId() string {
if x != nil {
return x.OrganizationId
}
return ""
}
type CreateTeamResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Team *Team `protobuf:"bytes,1,opt,name=team,proto3" json:"team,omitempty"`
}
func (x *CreateTeamResponse) Reset() {
*x = CreateTeamResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[8]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *CreateTeamResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*CreateTeamResponse) ProtoMessage() {}
func (x *CreateTeamResponse) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[8]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use CreateTeamResponse.ProtoReflect.Descriptor instead.
func (*CreateTeamResponse) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{8}
}
func (x *CreateTeamResponse) GetTeam() *Team {
if x != nil {
return x.Team
}
return nil
}
type CreateTeamByNameRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
// Must be unique within organization.
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
OrganizationName string `protobuf:"bytes,2,opt,name=organization_name,json=organizationName,proto3" json:"organization_name,omitempty"`
}
func (x *CreateTeamByNameRequest) Reset() {
*x = CreateTeamByNameRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[9]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *CreateTeamByNameRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*CreateTeamByNameRequest) ProtoMessage() {}
func (x *CreateTeamByNameRequest) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[9]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use CreateTeamByNameRequest.ProtoReflect.Descriptor instead.
func (*CreateTeamByNameRequest) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{9}
}
func (x *CreateTeamByNameRequest) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *CreateTeamByNameRequest) GetOrganizationName() string {
if x != nil {
return x.OrganizationName
}
return ""
}
type CreateTeamByNameResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Team *Team `protobuf:"bytes,1,opt,name=team,proto3" json:"team,omitempty"`
}
func (x *CreateTeamByNameResponse) Reset() {
*x = CreateTeamByNameResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[10]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *CreateTeamByNameResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*CreateTeamByNameResponse) ProtoMessage() {}
func (x *CreateTeamByNameResponse) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[10]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use CreateTeamByNameResponse.ProtoReflect.Descriptor instead.
func (*CreateTeamByNameResponse) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{10}
}
func (x *CreateTeamByNameResponse) GetTeam() *Team {
if x != nil {
return x.Team
}
return nil
}
type UpdateTeamNameRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
NewName string `protobuf:"bytes,2,opt,name=new_name,json=newName,proto3" json:"new_name,omitempty"`
}
func (x *UpdateTeamNameRequest) Reset() {
*x = UpdateTeamNameRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[11]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *UpdateTeamNameRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*UpdateTeamNameRequest) ProtoMessage() {}
func (x *UpdateTeamNameRequest) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[11]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use UpdateTeamNameRequest.ProtoReflect.Descriptor instead.
func (*UpdateTeamNameRequest) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{11}
}
func (x *UpdateTeamNameRequest) GetId() string {
if x != nil {
return x.Id
}
return ""
}
func (x *UpdateTeamNameRequest) GetNewName() string {
if x != nil {
return x.NewName
}
return ""
}
type UpdateTeamNameResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Team *Team `protobuf:"bytes,1,opt,name=team,proto3" json:"team,omitempty"`
}
func (x *UpdateTeamNameResponse) Reset() {
*x = UpdateTeamNameResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[12]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *UpdateTeamNameResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*UpdateTeamNameResponse) ProtoMessage() {}
func (x *UpdateTeamNameResponse) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[12]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use UpdateTeamNameResponse.ProtoReflect.Descriptor instead.
func (*UpdateTeamNameResponse) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{12}
}
func (x *UpdateTeamNameResponse) GetTeam() *Team {
if x != nil {
return x.Team
}
return nil
}
type AddUserToTeamRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
UserId string `protobuf:"bytes,2,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"`
}
func (x *AddUserToTeamRequest) Reset() {
*x = AddUserToTeamRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[13]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *AddUserToTeamRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AddUserToTeamRequest) ProtoMessage() {}
func (x *AddUserToTeamRequest) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[13]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AddUserToTeamRequest.ProtoReflect.Descriptor instead.
func (*AddUserToTeamRequest) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{13}
}
func (x *AddUserToTeamRequest) GetId() string {
if x != nil {
return x.Id
}
return ""
}
func (x *AddUserToTeamRequest) GetUserId() string {
if x != nil {
return x.UserId
}
return ""
}
type AddUserToTeamResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *AddUserToTeamResponse) Reset() {
*x = AddUserToTeamResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[14]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *AddUserToTeamResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AddUserToTeamResponse) ProtoMessage() {}
func (x *AddUserToTeamResponse) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[14]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AddUserToTeamResponse.ProtoReflect.Descriptor instead.
func (*AddUserToTeamResponse) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{14}
}
type AddUserToTeamByNameRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
UserName string `protobuf:"bytes,2,opt,name=user_name,json=userName,proto3" json:"user_name,omitempty"`
OrganizationName string `protobuf:"bytes,3,opt,name=organization_name,json=organizationName,proto3" json:"organization_name,omitempty"`
}
func (x *AddUserToTeamByNameRequest) Reset() {
*x = AddUserToTeamByNameRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[15]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *AddUserToTeamByNameRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AddUserToTeamByNameRequest) ProtoMessage() {}
func (x *AddUserToTeamByNameRequest) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[15]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AddUserToTeamByNameRequest.ProtoReflect.Descriptor instead.
func (*AddUserToTeamByNameRequest) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{15}
}
func (x *AddUserToTeamByNameRequest) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *AddUserToTeamByNameRequest) GetUserName() string {
if x != nil {
return x.UserName
}
return ""
}
func (x *AddUserToTeamByNameRequest) GetOrganizationName() string {
if x != nil {
return x.OrganizationName
}
return ""
}
type AddUserToTeamByNameResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *AddUserToTeamByNameResponse) Reset() {
*x = AddUserToTeamByNameResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[16]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *AddUserToTeamByNameResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AddUserToTeamByNameResponse) ProtoMessage() {}
func (x *AddUserToTeamByNameResponse) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[16]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AddUserToTeamByNameResponse.ProtoReflect.Descriptor instead.
func (*AddUserToTeamByNameResponse) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{16}
}
type RemoveUserFromTeamRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
UserId string `protobuf:"bytes,2,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"`
}
func (x *RemoveUserFromTeamRequest) Reset() {
*x = RemoveUserFromTeamRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[17]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *RemoveUserFromTeamRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RemoveUserFromTeamRequest) ProtoMessage() {}
func (x *RemoveUserFromTeamRequest) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[17]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RemoveUserFromTeamRequest.ProtoReflect.Descriptor instead.
func (*RemoveUserFromTeamRequest) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{17}
}
func (x *RemoveUserFromTeamRequest) GetId() string {
if x != nil {
return x.Id
}
return ""
}
func (x *RemoveUserFromTeamRequest) GetUserId() string {
if x != nil {
return x.UserId
}
return ""
}
type RemoveUserFromTeamResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *RemoveUserFromTeamResponse) Reset() {
*x = RemoveUserFromTeamResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[18]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *RemoveUserFromTeamResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RemoveUserFromTeamResponse) ProtoMessage() {}
func (x *RemoveUserFromTeamResponse) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[18]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RemoveUserFromTeamResponse.ProtoReflect.Descriptor instead.
func (*RemoveUserFromTeamResponse) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{18}
}
type RemoveUserFromTeamByNameRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
UserName string `protobuf:"bytes,2,opt,name=user_name,json=userName,proto3" json:"user_name,omitempty"`
OrganizationName string `protobuf:"bytes,3,opt,name=organization_name,json=organizationName,proto3" json:"organization_name,omitempty"`
}
func (x *RemoveUserFromTeamByNameRequest) Reset() {
*x = RemoveUserFromTeamByNameRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[19]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *RemoveUserFromTeamByNameRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RemoveUserFromTeamByNameRequest) ProtoMessage() {}
func (x *RemoveUserFromTeamByNameRequest) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[19]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RemoveUserFromTeamByNameRequest.ProtoReflect.Descriptor instead.
func (*RemoveUserFromTeamByNameRequest) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{19}
}
func (x *RemoveUserFromTeamByNameRequest) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *RemoveUserFromTeamByNameRequest) GetUserName() string {
if x != nil {
return x.UserName
}
return ""
}
func (x *RemoveUserFromTeamByNameRequest) GetOrganizationName() string {
if x != nil {
return x.OrganizationName
}
return ""
}
type RemoveUserFromTeamByNameResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *RemoveUserFromTeamByNameResponse) Reset() {
*x = RemoveUserFromTeamByNameResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[20]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *RemoveUserFromTeamByNameResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RemoveUserFromTeamByNameResponse) ProtoMessage() {}
func (x *RemoveUserFromTeamByNameResponse) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[20]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RemoveUserFromTeamByNameResponse.ProtoReflect.Descriptor instead.
func (*RemoveUserFromTeamByNameResponse) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{20}
}
type DeleteTeamRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
}
func (x *DeleteTeamRequest) Reset() {
*x = DeleteTeamRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[21]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *DeleteTeamRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*DeleteTeamRequest) ProtoMessage() {}
func (x *DeleteTeamRequest) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[21]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use DeleteTeamRequest.ProtoReflect.Descriptor instead.
func (*DeleteTeamRequest) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{21}
}
func (x *DeleteTeamRequest) GetId() string {
if x != nil {
return x.Id
}
return ""
}
type DeleteTeamResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *DeleteTeamResponse) Reset() {
*x = DeleteTeamResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[22]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *DeleteTeamResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*DeleteTeamResponse) ProtoMessage() {}
func (x *DeleteTeamResponse) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[22]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use DeleteTeamResponse.ProtoReflect.Descriptor instead.
func (*DeleteTeamResponse) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{22}
}
type DeleteTeamByNameRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
OrganizationName string `protobuf:"bytes,2,opt,name=organization_name,json=organizationName,proto3" json:"organization_name,omitempty"`
}
func (x *DeleteTeamByNameRequest) Reset() {
*x = DeleteTeamByNameRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[23]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *DeleteTeamByNameRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*DeleteTeamByNameRequest) ProtoMessage() {}
func (x *DeleteTeamByNameRequest) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[23]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use DeleteTeamByNameRequest.ProtoReflect.Descriptor instead.
func (*DeleteTeamByNameRequest) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{23}
}
func (x *DeleteTeamByNameRequest) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *DeleteTeamByNameRequest) GetOrganizationName() string {
if x != nil {
return x.OrganizationName
}
return ""
}
type DeleteTeamByNameResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *DeleteTeamByNameResponse) Reset() {
*x = DeleteTeamByNameResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[24]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *DeleteTeamByNameResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*DeleteTeamByNameResponse) ProtoMessage() {}
func (x *DeleteTeamByNameResponse) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[24]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use DeleteTeamByNameResponse.ProtoReflect.Descriptor instead.
func (*DeleteTeamByNameResponse) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{24}
}
type AddTeamOrganizationScopeRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
OrganizationScope OrganizationScope `protobuf:"varint,2,opt,name=organization_scope,json=organizationScope,proto3,enum=buf.alpha.registry.v1alpha1.OrganizationScope" json:"organization_scope,omitempty"`
}
func (x *AddTeamOrganizationScopeRequest) Reset() {
*x = AddTeamOrganizationScopeRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[25]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *AddTeamOrganizationScopeRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AddTeamOrganizationScopeRequest) ProtoMessage() {}
func (x *AddTeamOrganizationScopeRequest) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[25]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AddTeamOrganizationScopeRequest.ProtoReflect.Descriptor instead.
func (*AddTeamOrganizationScopeRequest) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{25}
}
func (x *AddTeamOrganizationScopeRequest) GetId() string {
if x != nil {
return x.Id
}
return ""
}
func (x *AddTeamOrganizationScopeRequest) GetOrganizationScope() OrganizationScope {
if x != nil {
return x.OrganizationScope
}
return OrganizationScope_ORGANIZATION_SCOPE_UNSPECIFIED
}
type AddTeamOrganizationScopeResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *AddTeamOrganizationScopeResponse) Reset() {
*x = AddTeamOrganizationScopeResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[26]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *AddTeamOrganizationScopeResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AddTeamOrganizationScopeResponse) ProtoMessage() {}
func (x *AddTeamOrganizationScopeResponse) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[26]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AddTeamOrganizationScopeResponse.ProtoReflect.Descriptor instead.
func (*AddTeamOrganizationScopeResponse) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{26}
}
type AddTeamOrganizationScopeByNameRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
OrganizationName string `protobuf:"bytes,2,opt,name=organization_name,json=organizationName,proto3" json:"organization_name,omitempty"`
OrganizationScope OrganizationScope `protobuf:"varint,3,opt,name=organization_scope,json=organizationScope,proto3,enum=buf.alpha.registry.v1alpha1.OrganizationScope" json:"organization_scope,omitempty"`
}
func (x *AddTeamOrganizationScopeByNameRequest) Reset() {
*x = AddTeamOrganizationScopeByNameRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[27]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *AddTeamOrganizationScopeByNameRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AddTeamOrganizationScopeByNameRequest) ProtoMessage() {}
func (x *AddTeamOrganizationScopeByNameRequest) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[27]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AddTeamOrganizationScopeByNameRequest.ProtoReflect.Descriptor instead.
func (*AddTeamOrganizationScopeByNameRequest) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{27}
}
func (x *AddTeamOrganizationScopeByNameRequest) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *AddTeamOrganizationScopeByNameRequest) GetOrganizationName() string {
if x != nil {
return x.OrganizationName
}
return ""
}
func (x *AddTeamOrganizationScopeByNameRequest) GetOrganizationScope() OrganizationScope {
if x != nil {
return x.OrganizationScope
}
return OrganizationScope_ORGANIZATION_SCOPE_UNSPECIFIED
}
type AddTeamOrganizationScopeByNameResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *AddTeamOrganizationScopeByNameResponse) Reset() {
*x = AddTeamOrganizationScopeByNameResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[28]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *AddTeamOrganizationScopeByNameResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AddTeamOrganizationScopeByNameResponse) ProtoMessage() {}
func (x *AddTeamOrganizationScopeByNameResponse) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[28]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AddTeamOrganizationScopeByNameResponse.ProtoReflect.Descriptor instead.
func (*AddTeamOrganizationScopeByNameResponse) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{28}
}
type RemoveTeamOrganizationScopeRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
OrganizationScope OrganizationScope `protobuf:"varint,2,opt,name=organization_scope,json=organizationScope,proto3,enum=buf.alpha.registry.v1alpha1.OrganizationScope" json:"organization_scope,omitempty"`
}
func (x *RemoveTeamOrganizationScopeRequest) Reset() {
*x = RemoveTeamOrganizationScopeRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[29]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *RemoveTeamOrganizationScopeRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RemoveTeamOrganizationScopeRequest) ProtoMessage() {}
func (x *RemoveTeamOrganizationScopeRequest) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[29]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RemoveTeamOrganizationScopeRequest.ProtoReflect.Descriptor instead.
func (*RemoveTeamOrganizationScopeRequest) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{29}
}
func (x *RemoveTeamOrganizationScopeRequest) GetId() string {
if x != nil {
return x.Id
}
return ""
}
func (x *RemoveTeamOrganizationScopeRequest) GetOrganizationScope() OrganizationScope {
if x != nil {
return x.OrganizationScope
}
return OrganizationScope_ORGANIZATION_SCOPE_UNSPECIFIED
}
type RemoveTeamOrganizationScopeResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *RemoveTeamOrganizationScopeResponse) Reset() {
*x = RemoveTeamOrganizationScopeResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[30]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *RemoveTeamOrganizationScopeResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RemoveTeamOrganizationScopeResponse) ProtoMessage() {}
func (x *RemoveTeamOrganizationScopeResponse) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[30]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RemoveTeamOrganizationScopeResponse.ProtoReflect.Descriptor instead.
func (*RemoveTeamOrganizationScopeResponse) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{30}
}
type RemoveTeamOrganizationScopeByNameRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
OrganizationName string `protobuf:"bytes,2,opt,name=organization_name,json=organizationName,proto3" json:"organization_name,omitempty"`
OrganizationScope OrganizationScope `protobuf:"varint,3,opt,name=organization_scope,json=organizationScope,proto3,enum=buf.alpha.registry.v1alpha1.OrganizationScope" json:"organization_scope,omitempty"`
}
func (x *RemoveTeamOrganizationScopeByNameRequest) Reset() {
*x = RemoveTeamOrganizationScopeByNameRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[31]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *RemoveTeamOrganizationScopeByNameRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RemoveTeamOrganizationScopeByNameRequest) ProtoMessage() {}
func (x *RemoveTeamOrganizationScopeByNameRequest) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[31]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RemoveTeamOrganizationScopeByNameRequest.ProtoReflect.Descriptor instead.
func (*RemoveTeamOrganizationScopeByNameRequest) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{31}
}
func (x *RemoveTeamOrganizationScopeByNameRequest) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *RemoveTeamOrganizationScopeByNameRequest) GetOrganizationName() string {
if x != nil {
return x.OrganizationName
}
return ""
}
func (x *RemoveTeamOrganizationScopeByNameRequest) GetOrganizationScope() OrganizationScope {
if x != nil {
return x.OrganizationScope
}
return OrganizationScope_ORGANIZATION_SCOPE_UNSPECIFIED
}
type RemoveTeamOrganizationScopeByNameResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *RemoveTeamOrganizationScopeByNameResponse) Reset() {
*x = RemoveTeamOrganizationScopeByNameResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[32]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *RemoveTeamOrganizationScopeByNameResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RemoveTeamOrganizationScopeByNameResponse) ProtoMessage() {}
func (x *RemoveTeamOrganizationScopeByNameResponse) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[32]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RemoveTeamOrganizationScopeByNameResponse.ProtoReflect.Descriptor instead.
func (*RemoveTeamOrganizationScopeByNameResponse) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{32}
}
type AddTeamBaseRepositoryScopeRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
RepositoryScope RepositoryScope `protobuf:"varint,2,opt,name=repository_scope,json=repositoryScope,proto3,enum=buf.alpha.registry.v1alpha1.RepositoryScope" json:"repository_scope,omitempty"`
}
func (x *AddTeamBaseRepositoryScopeRequest) Reset() {
*x = AddTeamBaseRepositoryScopeRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[33]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *AddTeamBaseRepositoryScopeRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AddTeamBaseRepositoryScopeRequest) ProtoMessage() {}
func (x *AddTeamBaseRepositoryScopeRequest) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[33]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AddTeamBaseRepositoryScopeRequest.ProtoReflect.Descriptor instead.
func (*AddTeamBaseRepositoryScopeRequest) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{33}
}
func (x *AddTeamBaseRepositoryScopeRequest) GetId() string {
if x != nil {
return x.Id
}
return ""
}
func (x *AddTeamBaseRepositoryScopeRequest) GetRepositoryScope() RepositoryScope {
if x != nil {
return x.RepositoryScope
}
return RepositoryScope_REPOSITORY_SCOPE_UNSPECIFIED
}
type AddTeamBaseRepositoryScopeResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *AddTeamBaseRepositoryScopeResponse) Reset() {
*x = AddTeamBaseRepositoryScopeResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[34]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *AddTeamBaseRepositoryScopeResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AddTeamBaseRepositoryScopeResponse) ProtoMessage() {}
func (x *AddTeamBaseRepositoryScopeResponse) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[34]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AddTeamBaseRepositoryScopeResponse.ProtoReflect.Descriptor instead.
func (*AddTeamBaseRepositoryScopeResponse) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{34}
}
type AddTeamBaseRepositoryScopeByNameRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
OrganizationName string `protobuf:"bytes,2,opt,name=organization_name,json=organizationName,proto3" json:"organization_name,omitempty"`
RepositoryScope RepositoryScope `protobuf:"varint,3,opt,name=repository_scope,json=repositoryScope,proto3,enum=buf.alpha.registry.v1alpha1.RepositoryScope" json:"repository_scope,omitempty"`
}
func (x *AddTeamBaseRepositoryScopeByNameRequest) Reset() {
*x = AddTeamBaseRepositoryScopeByNameRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[35]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *AddTeamBaseRepositoryScopeByNameRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AddTeamBaseRepositoryScopeByNameRequest) ProtoMessage() {}
func (x *AddTeamBaseRepositoryScopeByNameRequest) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[35]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AddTeamBaseRepositoryScopeByNameRequest.ProtoReflect.Descriptor instead.
func (*AddTeamBaseRepositoryScopeByNameRequest) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{35}
}
func (x *AddTeamBaseRepositoryScopeByNameRequest) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *AddTeamBaseRepositoryScopeByNameRequest) GetOrganizationName() string {
if x != nil {
return x.OrganizationName
}
return ""
}
func (x *AddTeamBaseRepositoryScopeByNameRequest) GetRepositoryScope() RepositoryScope {
if x != nil {
return x.RepositoryScope
}
return RepositoryScope_REPOSITORY_SCOPE_UNSPECIFIED
}
type AddTeamBaseRepositoryScopeByNameResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *AddTeamBaseRepositoryScopeByNameResponse) Reset() {
*x = AddTeamBaseRepositoryScopeByNameResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[36]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *AddTeamBaseRepositoryScopeByNameResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AddTeamBaseRepositoryScopeByNameResponse) ProtoMessage() {}
func (x *AddTeamBaseRepositoryScopeByNameResponse) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[36]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AddTeamBaseRepositoryScopeByNameResponse.ProtoReflect.Descriptor instead.
func (*AddTeamBaseRepositoryScopeByNameResponse) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{36}
}
type RemoveTeamBaseRepositoryScopeRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
RepositoryScope RepositoryScope `protobuf:"varint,2,opt,name=repository_scope,json=repositoryScope,proto3,enum=buf.alpha.registry.v1alpha1.RepositoryScope" json:"repository_scope,omitempty"`
}
func (x *RemoveTeamBaseRepositoryScopeRequest) Reset() {
*x = RemoveTeamBaseRepositoryScopeRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[37]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *RemoveTeamBaseRepositoryScopeRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RemoveTeamBaseRepositoryScopeRequest) ProtoMessage() {}
func (x *RemoveTeamBaseRepositoryScopeRequest) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[37]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RemoveTeamBaseRepositoryScopeRequest.ProtoReflect.Descriptor instead.
func (*RemoveTeamBaseRepositoryScopeRequest) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{37}
}
func (x *RemoveTeamBaseRepositoryScopeRequest) GetId() string {
if x != nil {
return x.Id
}
return ""
}
func (x *RemoveTeamBaseRepositoryScopeRequest) GetRepositoryScope() RepositoryScope {
if x != nil {
return x.RepositoryScope
}
return RepositoryScope_REPOSITORY_SCOPE_UNSPECIFIED
}
type RemoveTeamBaseRepositoryScopeResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *RemoveTeamBaseRepositoryScopeResponse) Reset() {
*x = RemoveTeamBaseRepositoryScopeResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[38]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *RemoveTeamBaseRepositoryScopeResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RemoveTeamBaseRepositoryScopeResponse) ProtoMessage() {}
func (x *RemoveTeamBaseRepositoryScopeResponse) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[38]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RemoveTeamBaseRepositoryScopeResponse.ProtoReflect.Descriptor instead.
func (*RemoveTeamBaseRepositoryScopeResponse) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{38}
}
type RemoveTeamBaseRepositoryScopeByNameRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
OrganizationName string `protobuf:"bytes,2,opt,name=organization_name,json=organizationName,proto3" json:"organization_name,omitempty"`
RepositoryScope RepositoryScope `protobuf:"varint,3,opt,name=repository_scope,json=repositoryScope,proto3,enum=buf.alpha.registry.v1alpha1.RepositoryScope" json:"repository_scope,omitempty"`
}
func (x *RemoveTeamBaseRepositoryScopeByNameRequest) Reset() {
*x = RemoveTeamBaseRepositoryScopeByNameRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[39]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *RemoveTeamBaseRepositoryScopeByNameRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RemoveTeamBaseRepositoryScopeByNameRequest) ProtoMessage() {}
func (x *RemoveTeamBaseRepositoryScopeByNameRequest) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[39]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RemoveTeamBaseRepositoryScopeByNameRequest.ProtoReflect.Descriptor instead.
func (*RemoveTeamBaseRepositoryScopeByNameRequest) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{39}
}
func (x *RemoveTeamBaseRepositoryScopeByNameRequest) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *RemoveTeamBaseRepositoryScopeByNameRequest) GetOrganizationName() string {
if x != nil {
return x.OrganizationName
}
return ""
}
func (x *RemoveTeamBaseRepositoryScopeByNameRequest) GetRepositoryScope() RepositoryScope {
if x != nil {
return x.RepositoryScope
}
return RepositoryScope_REPOSITORY_SCOPE_UNSPECIFIED
}
type RemoveTeamBaseRepositoryScopeByNameResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *RemoveTeamBaseRepositoryScopeByNameResponse) Reset() {
*x = RemoveTeamBaseRepositoryScopeByNameResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[40]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *RemoveTeamBaseRepositoryScopeByNameResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RemoveTeamBaseRepositoryScopeByNameResponse) ProtoMessage() {}
func (x *RemoveTeamBaseRepositoryScopeByNameResponse) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[40]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RemoveTeamBaseRepositoryScopeByNameResponse.ProtoReflect.Descriptor instead.
func (*RemoveTeamBaseRepositoryScopeByNameResponse) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{40}
}
type AddTeamRepositoryScopeRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
RepositoryId string `protobuf:"bytes,2,opt,name=repository_id,json=repositoryId,proto3" json:"repository_id,omitempty"`
RepositoryScope RepositoryScope `protobuf:"varint,3,opt,name=repository_scope,json=repositoryScope,proto3,enum=buf.alpha.registry.v1alpha1.RepositoryScope" json:"repository_scope,omitempty"`
}
func (x *AddTeamRepositoryScopeRequest) Reset() {
*x = AddTeamRepositoryScopeRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[41]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *AddTeamRepositoryScopeRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AddTeamRepositoryScopeRequest) ProtoMessage() {}
func (x *AddTeamRepositoryScopeRequest) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[41]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AddTeamRepositoryScopeRequest.ProtoReflect.Descriptor instead.
func (*AddTeamRepositoryScopeRequest) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{41}
}
func (x *AddTeamRepositoryScopeRequest) GetId() string {
if x != nil {
return x.Id
}
return ""
}
func (x *AddTeamRepositoryScopeRequest) GetRepositoryId() string {
if x != nil {
return x.RepositoryId
}
return ""
}
func (x *AddTeamRepositoryScopeRequest) GetRepositoryScope() RepositoryScope {
if x != nil {
return x.RepositoryScope
}
return RepositoryScope_REPOSITORY_SCOPE_UNSPECIFIED
}
type AddTeamRepositoryScopeResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *AddTeamRepositoryScopeResponse) Reset() {
*x = AddTeamRepositoryScopeResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[42]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *AddTeamRepositoryScopeResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AddTeamRepositoryScopeResponse) ProtoMessage() {}
func (x *AddTeamRepositoryScopeResponse) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[42]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AddTeamRepositoryScopeResponse.ProtoReflect.Descriptor instead.
func (*AddTeamRepositoryScopeResponse) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{42}
}
type AddTeamRepositoryScopeByNameRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
OrganizationName string `protobuf:"bytes,2,opt,name=organization_name,json=organizationName,proto3" json:"organization_name,omitempty"`
RepositoryName string `protobuf:"bytes,3,opt,name=repository_name,json=repositoryName,proto3" json:"repository_name,omitempty"`
RepositoryScope RepositoryScope `protobuf:"varint,4,opt,name=repository_scope,json=repositoryScope,proto3,enum=buf.alpha.registry.v1alpha1.RepositoryScope" json:"repository_scope,omitempty"`
}
func (x *AddTeamRepositoryScopeByNameRequest) Reset() {
*x = AddTeamRepositoryScopeByNameRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[43]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *AddTeamRepositoryScopeByNameRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AddTeamRepositoryScopeByNameRequest) ProtoMessage() {}
func (x *AddTeamRepositoryScopeByNameRequest) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[43]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AddTeamRepositoryScopeByNameRequest.ProtoReflect.Descriptor instead.
func (*AddTeamRepositoryScopeByNameRequest) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{43}
}
func (x *AddTeamRepositoryScopeByNameRequest) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *AddTeamRepositoryScopeByNameRequest) GetOrganizationName() string {
if x != nil {
return x.OrganizationName
}
return ""
}
func (x *AddTeamRepositoryScopeByNameRequest) GetRepositoryName() string {
if x != nil {
return x.RepositoryName
}
return ""
}
func (x *AddTeamRepositoryScopeByNameRequest) GetRepositoryScope() RepositoryScope {
if x != nil {
return x.RepositoryScope
}
return RepositoryScope_REPOSITORY_SCOPE_UNSPECIFIED
}
type AddTeamRepositoryScopeByNameResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *AddTeamRepositoryScopeByNameResponse) Reset() {
*x = AddTeamRepositoryScopeByNameResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[44]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *AddTeamRepositoryScopeByNameResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AddTeamRepositoryScopeByNameResponse) ProtoMessage() {}
func (x *AddTeamRepositoryScopeByNameResponse) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[44]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AddTeamRepositoryScopeByNameResponse.ProtoReflect.Descriptor instead.
func (*AddTeamRepositoryScopeByNameResponse) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{44}
}
type RemoveTeamRepositoryScopeRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
RepositoryId string `protobuf:"bytes,2,opt,name=repository_id,json=repositoryId,proto3" json:"repository_id,omitempty"`
RepositoryScope RepositoryScope `protobuf:"varint,3,opt,name=repository_scope,json=repositoryScope,proto3,enum=buf.alpha.registry.v1alpha1.RepositoryScope" json:"repository_scope,omitempty"`
}
func (x *RemoveTeamRepositoryScopeRequest) Reset() {
*x = RemoveTeamRepositoryScopeRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[45]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *RemoveTeamRepositoryScopeRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RemoveTeamRepositoryScopeRequest) ProtoMessage() {}
func (x *RemoveTeamRepositoryScopeRequest) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[45]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RemoveTeamRepositoryScopeRequest.ProtoReflect.Descriptor instead.
func (*RemoveTeamRepositoryScopeRequest) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{45}
}
func (x *RemoveTeamRepositoryScopeRequest) GetId() string {
if x != nil {
return x.Id
}
return ""
}
func (x *RemoveTeamRepositoryScopeRequest) GetRepositoryId() string {
if x != nil {
return x.RepositoryId
}
return ""
}
func (x *RemoveTeamRepositoryScopeRequest) GetRepositoryScope() RepositoryScope {
if x != nil {
return x.RepositoryScope
}
return RepositoryScope_REPOSITORY_SCOPE_UNSPECIFIED
}
type RemoveTeamRepositoryScopeResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *RemoveTeamRepositoryScopeResponse) Reset() {
*x = RemoveTeamRepositoryScopeResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[46]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *RemoveTeamRepositoryScopeResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RemoveTeamRepositoryScopeResponse) ProtoMessage() {}
func (x *RemoveTeamRepositoryScopeResponse) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[46]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RemoveTeamRepositoryScopeResponse.ProtoReflect.Descriptor instead.
func (*RemoveTeamRepositoryScopeResponse) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{46}
}
type RemoveTeamRepositoryScopeByNameRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
OrganizationName string `protobuf:"bytes,2,opt,name=organization_name,json=organizationName,proto3" json:"organization_name,omitempty"`
RepositoryName string `protobuf:"bytes,3,opt,name=repository_name,json=repositoryName,proto3" json:"repository_name,omitempty"`
RepositoryScope RepositoryScope `protobuf:"varint,4,opt,name=repository_scope,json=repositoryScope,proto3,enum=buf.alpha.registry.v1alpha1.RepositoryScope" json:"repository_scope,omitempty"`
}
func (x *RemoveTeamRepositoryScopeByNameRequest) Reset() {
*x = RemoveTeamRepositoryScopeByNameRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[47]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *RemoveTeamRepositoryScopeByNameRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RemoveTeamRepositoryScopeByNameRequest) ProtoMessage() {}
func (x *RemoveTeamRepositoryScopeByNameRequest) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[47]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RemoveTeamRepositoryScopeByNameRequest.ProtoReflect.Descriptor instead.
func (*RemoveTeamRepositoryScopeByNameRequest) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{47}
}
func (x *RemoveTeamRepositoryScopeByNameRequest) GetName() string {
if x != nil {
return x.Name
}
return ""
}
func (x *RemoveTeamRepositoryScopeByNameRequest) GetOrganizationName() string {
if x != nil {
return x.OrganizationName
}
return ""
}
func (x *RemoveTeamRepositoryScopeByNameRequest) GetRepositoryName() string {
if x != nil {
return x.RepositoryName
}
return ""
}
func (x *RemoveTeamRepositoryScopeByNameRequest) GetRepositoryScope() RepositoryScope {
if x != nil {
return x.RepositoryScope
}
return RepositoryScope_REPOSITORY_SCOPE_UNSPECIFIED
}
type RemoveTeamRepositoryScopeByNameResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *RemoveTeamRepositoryScopeByNameResponse) Reset() {
*x = RemoveTeamRepositoryScopeByNameResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[48]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *RemoveTeamRepositoryScopeByNameResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RemoveTeamRepositoryScopeByNameResponse) ProtoMessage() {}
func (x *RemoveTeamRepositoryScopeByNameResponse) ProtoReflect() protoreflect.Message {
mi := &file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[48]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RemoveTeamRepositoryScopeByNameResponse.ProtoReflect.Descriptor instead.
func (*RemoveTeamRepositoryScopeByNameResponse) Descriptor() ([]byte, []int) {
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP(), []int{48}
}
var File_buf_alpha_registry_v1alpha1_team_proto protoreflect.FileDescriptor
var file_buf_alpha_registry_v1alpha1_team_proto_rawDesc = []byte{
0x0a, 0x26, 0x62, 0x75, 0x66, 0x2f, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2f, 0x72, 0x65, 0x67, 0x69,
0x73, 0x74, 0x72, 0x79, 0x2f, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2f, 0x74, 0x65,
0x61, 0x6d, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x1b, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c,
0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61,
0x6c, 0x70, 0x68, 0x61, 0x31, 0x1a, 0x27, 0x62, 0x75, 0x66, 0x2f, 0x61, 0x6c, 0x70, 0x68, 0x61,
0x2f, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2f, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68,
0x61, 0x31, 0x2f, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1f,
0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f,
0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22,
0xcd, 0x01, 0x0a, 0x04, 0x54, 0x65, 0x61, 0x6d, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01,
0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, 0x3b, 0x0a, 0x0b, 0x63, 0x72, 0x65, 0x61,
0x74, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e,
0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e,
0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x0a, 0x63, 0x72, 0x65, 0x61, 0x74,
0x65, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x3b, 0x0a, 0x0b, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x5f,
0x74, 0x69, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f,
0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d,
0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x0a, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x54, 0x69,
0x6d, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09,
0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x27, 0x0a, 0x0f, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69,
0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52,
0x0e, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x64, 0x22,
0x20, 0x0a, 0x0e, 0x47, 0x65, 0x74, 0x54, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73,
0x74, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69,
0x64, 0x22, 0x48, 0x0a, 0x0f, 0x47, 0x65, 0x74, 0x54, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x73, 0x70,
0x6f, 0x6e, 0x73, 0x65, 0x12, 0x35, 0x0a, 0x04, 0x74, 0x65, 0x61, 0x6d, 0x18, 0x01, 0x20, 0x01,
0x28, 0x0b, 0x32, 0x21, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72,
0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31,
0x2e, 0x54, 0x65, 0x61, 0x6d, 0x52, 0x04, 0x74, 0x65, 0x61, 0x6d, 0x22, 0x57, 0x0a, 0x14, 0x47,
0x65, 0x74, 0x54, 0x65, 0x61, 0x6d, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75,
0x65, 0x73, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28,
0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x2b, 0x0a, 0x11, 0x6f, 0x72, 0x67, 0x61, 0x6e,
0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01,
0x28, 0x09, 0x52, 0x10, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e,
0x4e, 0x61, 0x6d, 0x65, 0x22, 0x4e, 0x0a, 0x15, 0x47, 0x65, 0x74, 0x54, 0x65, 0x61, 0x6d, 0x42,
0x79, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x35, 0x0a,
0x04, 0x74, 0x65, 0x61, 0x6d, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x21, 0x2e, 0x62, 0x75,
0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79,
0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x54, 0x65, 0x61, 0x6d, 0x52, 0x04,
0x74, 0x65, 0x61, 0x6d, 0x22, 0x9d, 0x01, 0x0a, 0x1c, 0x4c, 0x69, 0x73, 0x74, 0x4f, 0x72, 0x67,
0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x54, 0x65, 0x61, 0x6d, 0x73, 0x52, 0x65,
0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x27, 0x0a, 0x0f, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a,
0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0e,
0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x64, 0x12, 0x1b,
0x0a, 0x09, 0x70, 0x61, 0x67, 0x65, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28,
0x0d, 0x52, 0x08, 0x70, 0x61, 0x67, 0x65, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x70,
0x61, 0x67, 0x65, 0x5f, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52,
0x09, 0x70, 0x61, 0x67, 0x65, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x12, 0x18, 0x0a, 0x07, 0x72, 0x65,
0x76, 0x65, 0x72, 0x73, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, 0x72, 0x65, 0x76,
0x65, 0x72, 0x73, 0x65, 0x22, 0x80, 0x01, 0x0a, 0x1d, 0x4c, 0x69, 0x73, 0x74, 0x4f, 0x72, 0x67,
0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x54, 0x65, 0x61, 0x6d, 0x73, 0x52, 0x65,
0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x37, 0x0a, 0x05, 0x74, 0x65, 0x61, 0x6d, 0x73, 0x18,
0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x21, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68,
0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70,
0x68, 0x61, 0x31, 0x2e, 0x54, 0x65, 0x61, 0x6d, 0x52, 0x05, 0x74, 0x65, 0x61, 0x6d, 0x73, 0x12,
0x26, 0x0a, 0x0f, 0x6e, 0x65, 0x78, 0x74, 0x5f, 0x70, 0x61, 0x67, 0x65, 0x5f, 0x74, 0x6f, 0x6b,
0x65, 0x6e, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x6e, 0x65, 0x78, 0x74, 0x50, 0x61,
0x67, 0x65, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x22, 0x50, 0x0a, 0x11, 0x43, 0x72, 0x65, 0x61, 0x74,
0x65, 0x54, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x12, 0x0a, 0x04,
0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65,
0x12, 0x27, 0x0a, 0x0f, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e,
0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0e, 0x6f, 0x72, 0x67, 0x61, 0x6e,
0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x64, 0x22, 0x4b, 0x0a, 0x12, 0x43, 0x72, 0x65,
0x61, 0x74, 0x65, 0x54, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12,
0x35, 0x0a, 0x04, 0x74, 0x65, 0x61, 0x6d, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x21, 0x2e,
0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74,
0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x54, 0x65, 0x61, 0x6d,
0x52, 0x04, 0x74, 0x65, 0x61, 0x6d, 0x22, 0x5a, 0x0a, 0x17, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65,
0x54, 0x65, 0x61, 0x6d, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73,
0x74, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52,
0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x2b, 0x0a, 0x11, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a,
0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09,
0x52, 0x10, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x4e, 0x61,
0x6d, 0x65, 0x22, 0x51, 0x0a, 0x18, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x54, 0x65, 0x61, 0x6d,
0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x35,
0x0a, 0x04, 0x74, 0x65, 0x61, 0x6d, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x21, 0x2e, 0x62,
0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72,
0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x54, 0x65, 0x61, 0x6d, 0x52,
0x04, 0x74, 0x65, 0x61, 0x6d, 0x22, 0x42, 0x0a, 0x15, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x54,
0x65, 0x61, 0x6d, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x0e,
0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, 0x19,
0x0a, 0x08, 0x6e, 0x65, 0x77, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09,
0x52, 0x07, 0x6e, 0x65, 0x77, 0x4e, 0x61, 0x6d, 0x65, 0x22, 0x4f, 0x0a, 0x16, 0x55, 0x70, 0x64,
0x61, 0x74, 0x65, 0x54, 0x65, 0x61, 0x6d, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f,
0x6e, 0x73, 0x65, 0x12, 0x35, 0x0a, 0x04, 0x74, 0x65, 0x61, 0x6d, 0x18, 0x01, 0x20, 0x01, 0x28,
0x0b, 0x32, 0x21, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65,
0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e,
0x54, 0x65, 0x61, 0x6d, 0x52, 0x04, 0x74, 0x65, 0x61, 0x6d, 0x22, 0x3f, 0x0a, 0x14, 0x41, 0x64,
0x64, 0x55, 0x73, 0x65, 0x72, 0x54, 0x6f, 0x54, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x71, 0x75, 0x65,
0x73, 0x74, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02,
0x69, 0x64, 0x12, 0x17, 0x0a, 0x07, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20,
0x01, 0x28, 0x09, 0x52, 0x06, 0x75, 0x73, 0x65, 0x72, 0x49, 0x64, 0x22, 0x17, 0x0a, 0x15, 0x41,
0x64, 0x64, 0x55, 0x73, 0x65, 0x72, 0x54, 0x6f, 0x54, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x73, 0x70,
0x6f, 0x6e, 0x73, 0x65, 0x22, 0x7a, 0x0a, 0x1a, 0x41, 0x64, 0x64, 0x55, 0x73, 0x65, 0x72, 0x54,
0x6f, 0x54, 0x65, 0x61, 0x6d, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65,
0x73, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09,
0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x1b, 0x0a, 0x09, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x6e,
0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x75, 0x73, 0x65, 0x72, 0x4e,
0x61, 0x6d, 0x65, 0x12, 0x2b, 0x0a, 0x11, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74,
0x69, 0x6f, 0x6e, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x10,
0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x4e, 0x61, 0x6d, 0x65,
0x22, 0x1d, 0x0a, 0x1b, 0x41, 0x64, 0x64, 0x55, 0x73, 0x65, 0x72, 0x54, 0x6f, 0x54, 0x65, 0x61,
0x6d, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22,
0x44, 0x0a, 0x19, 0x52, 0x65, 0x6d, 0x6f, 0x76, 0x65, 0x55, 0x73, 0x65, 0x72, 0x46, 0x72, 0x6f,
0x6d, 0x54, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x0e, 0x0a, 0x02,
0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, 0x17, 0x0a, 0x07,
0x75, 0x73, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x75,
0x73, 0x65, 0x72, 0x49, 0x64, 0x22, 0x1c, 0x0a, 0x1a, 0x52, 0x65, 0x6d, 0x6f, 0x76, 0x65, 0x55,
0x73, 0x65, 0x72, 0x46, 0x72, 0x6f, 0x6d, 0x54, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x73, 0x70, 0x6f,
0x6e, 0x73, 0x65, 0x22, 0x7f, 0x0a, 0x1f, 0x52, 0x65, 0x6d, 0x6f, 0x76, 0x65, 0x55, 0x73, 0x65,
0x72, 0x46, 0x72, 0x6f, 0x6d, 0x54, 0x65, 0x61, 0x6d, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x52,
0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01,
0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x1b, 0x0a, 0x09, 0x75, 0x73,
0x65, 0x72, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x75,
0x73, 0x65, 0x72, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x2b, 0x0a, 0x11, 0x6f, 0x72, 0x67, 0x61, 0x6e,
0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01,
0x28, 0x09, 0x52, 0x10, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e,
0x4e, 0x61, 0x6d, 0x65, 0x22, 0x22, 0x0a, 0x20, 0x52, 0x65, 0x6d, 0x6f, 0x76, 0x65, 0x55, 0x73,
0x65, 0x72, 0x46, 0x72, 0x6f, 0x6d, 0x54, 0x65, 0x61, 0x6d, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65,
0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x23, 0x0a, 0x11, 0x44, 0x65, 0x6c, 0x65,
0x74, 0x65, 0x54, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x0e, 0x0a,
0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x22, 0x14, 0x0a,
0x12, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x54, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x73, 0x70, 0x6f,
0x6e, 0x73, 0x65, 0x22, 0x5a, 0x0a, 0x17, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x54, 0x65, 0x61,
0x6d, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x12,
0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61,
0x6d, 0x65, 0x12, 0x2b, 0x0a, 0x11, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69,
0x6f, 0x6e, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x10, 0x6f,
0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x4e, 0x61, 0x6d, 0x65, 0x22,
0x1a, 0x0a, 0x18, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x54, 0x65, 0x61, 0x6d, 0x42, 0x79, 0x4e,
0x61, 0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x90, 0x01, 0x0a, 0x1f,
0x41, 0x64, 0x64, 0x54, 0x65, 0x61, 0x6d, 0x4f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74,
0x69, 0x6f, 0x6e, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12,
0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12,
0x5d, 0x0a, 0x12, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f,
0x73, 0x63, 0x6f, 0x70, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x2e, 0x2e, 0x62, 0x75,
0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79,
0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x4f, 0x72, 0x67, 0x61, 0x6e, 0x69,
0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x52, 0x11, 0x6f, 0x72, 0x67,
0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x22, 0x22,
0x0a, 0x20, 0x41, 0x64, 0x64, 0x54, 0x65, 0x61, 0x6d, 0x4f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a,
0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e,
0x73, 0x65, 0x22, 0xc7, 0x01, 0x0a, 0x25, 0x41, 0x64, 0x64, 0x54, 0x65, 0x61, 0x6d, 0x4f, 0x72,
0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x42,
0x79, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x12, 0x0a, 0x04,
0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65,
0x12, 0x2b, 0x0a, 0x11, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e,
0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x10, 0x6f, 0x72, 0x67,
0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x5d, 0x0a,
0x12, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x73, 0x63,
0x6f, 0x70, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x2e, 0x2e, 0x62, 0x75, 0x66, 0x2e,
0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76,
0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x4f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61,
0x74, 0x69, 0x6f, 0x6e, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x52, 0x11, 0x6f, 0x72, 0x67, 0x61, 0x6e,
0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x22, 0x28, 0x0a, 0x26,
0x41, 0x64, 0x64, 0x54, 0x65, 0x61, 0x6d, 0x4f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74,
0x69, 0x6f, 0x6e, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65,
0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x93, 0x01, 0x0a, 0x22, 0x52, 0x65, 0x6d, 0x6f, 0x76,
0x65, 0x54, 0x65, 0x61, 0x6d, 0x4f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f,
0x6e, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x0e, 0x0a,
0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, 0x5d, 0x0a,
0x12, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x73, 0x63,
0x6f, 0x70, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x2e, 0x2e, 0x62, 0x75, 0x66, 0x2e,
0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76,
0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x4f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61,
0x74, 0x69, 0x6f, 0x6e, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x52, 0x11, 0x6f, 0x72, 0x67, 0x61, 0x6e,
0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x22, 0x25, 0x0a, 0x23,
0x52, 0x65, 0x6d, 0x6f, 0x76, 0x65, 0x54, 0x65, 0x61, 0x6d, 0x4f, 0x72, 0x67, 0x61, 0x6e, 0x69,
0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f,
0x6e, 0x73, 0x65, 0x22, 0xca, 0x01, 0x0a, 0x28, 0x52, 0x65, 0x6d, 0x6f, 0x76, 0x65, 0x54, 0x65,
0x61, 0x6d, 0x4f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x63,
0x6f, 0x70, 0x65, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74,
0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04,
0x6e, 0x61, 0x6d, 0x65, 0x12, 0x2b, 0x0a, 0x11, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61,
0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52,
0x10, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x4e, 0x61, 0x6d,
0x65, 0x12, 0x5d, 0x0a, 0x12, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f,
0x6e, 0x5f, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x2e, 0x2e,
0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74,
0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x4f, 0x72, 0x67, 0x61,
0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x52, 0x11, 0x6f,
0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x63, 0x6f, 0x70, 0x65,
0x22, 0x2b, 0x0a, 0x29, 0x52, 0x65, 0x6d, 0x6f, 0x76, 0x65, 0x54, 0x65, 0x61, 0x6d, 0x4f, 0x72,
0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x42,
0x79, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x8c, 0x01,
0x0a, 0x21, 0x41, 0x64, 0x64, 0x54, 0x65, 0x61, 0x6d, 0x42, 0x61, 0x73, 0x65, 0x52, 0x65, 0x70,
0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x52, 0x65, 0x71, 0x75,
0x65, 0x73, 0x74, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52,
0x02, 0x69, 0x64, 0x12, 0x57, 0x0a, 0x10, 0x72, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72,
0x79, 0x5f, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x2c, 0x2e,
0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74,
0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x52, 0x65, 0x70, 0x6f,
0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x52, 0x0f, 0x72, 0x65, 0x70,
0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x22, 0x24, 0x0a, 0x22,
0x41, 0x64, 0x64, 0x54, 0x65, 0x61, 0x6d, 0x42, 0x61, 0x73, 0x65, 0x52, 0x65, 0x70, 0x6f, 0x73,
0x69, 0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e,
0x73, 0x65, 0x22, 0xc3, 0x01, 0x0a, 0x27, 0x41, 0x64, 0x64, 0x54, 0x65, 0x61, 0x6d, 0x42, 0x61,
0x73, 0x65, 0x52, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70,
0x65, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x12,
0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61,
0x6d, 0x65, 0x12, 0x2b, 0x0a, 0x11, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69,
0x6f, 0x6e, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x10, 0x6f,
0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x4e, 0x61, 0x6d, 0x65, 0x12,
0x57, 0x0a, 0x10, 0x72, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x5f, 0x73, 0x63,
0x6f, 0x70, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x2c, 0x2e, 0x62, 0x75, 0x66, 0x2e,
0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76,
0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x52, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f,
0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x52, 0x0f, 0x72, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74,
0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x22, 0x2a, 0x0a, 0x28, 0x41, 0x64, 0x64, 0x54,
0x65, 0x61, 0x6d, 0x42, 0x61, 0x73, 0x65, 0x52, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72,
0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x73, 0x70,
0x6f, 0x6e, 0x73, 0x65, 0x22, 0x8f, 0x01, 0x0a, 0x24, 0x52, 0x65, 0x6d, 0x6f, 0x76, 0x65, 0x54,
0x65, 0x61, 0x6d, 0x42, 0x61, 0x73, 0x65, 0x52, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72,
0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x0e, 0x0a,
0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, 0x57, 0x0a,
0x10, 0x72, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x5f, 0x73, 0x63, 0x6f, 0x70,
0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x2c, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c,
0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61,
0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x52, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79,
0x53, 0x63, 0x6f, 0x70, 0x65, 0x52, 0x0f, 0x72, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72,
0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x22, 0x27, 0x0a, 0x25, 0x52, 0x65, 0x6d, 0x6f, 0x76, 0x65,
0x54, 0x65, 0x61, 0x6d, 0x42, 0x61, 0x73, 0x65, 0x52, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f,
0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22,
0xc6, 0x01, 0x0a, 0x2a, 0x52, 0x65, 0x6d, 0x6f, 0x76, 0x65, 0x54, 0x65, 0x61, 0x6d, 0x42, 0x61,
0x73, 0x65, 0x52, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70,
0x65, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x12,
0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61,
0x6d, 0x65, 0x12, 0x2b, 0x0a, 0x11, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69,
0x6f, 0x6e, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x10, 0x6f,
0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x4e, 0x61, 0x6d, 0x65, 0x12,
0x57, 0x0a, 0x10, 0x72, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x5f, 0x73, 0x63,
0x6f, 0x70, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x2c, 0x2e, 0x62, 0x75, 0x66, 0x2e,
0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76,
0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x52, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f,
0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x52, 0x0f, 0x72, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74,
0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x22, 0x2d, 0x0a, 0x2b, 0x52, 0x65, 0x6d, 0x6f,
0x76, 0x65, 0x54, 0x65, 0x61, 0x6d, 0x42, 0x61, 0x73, 0x65, 0x52, 0x65, 0x70, 0x6f, 0x73, 0x69,
0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x52,
0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0xad, 0x01, 0x0a, 0x1d, 0x41, 0x64, 0x64, 0x54,
0x65, 0x61, 0x6d, 0x52, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f,
0x70, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18,
0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, 0x23, 0x0a, 0x0d, 0x72, 0x65, 0x70,
0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09,
0x52, 0x0c, 0x72, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x49, 0x64, 0x12, 0x57,
0x0a, 0x10, 0x72, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x5f, 0x73, 0x63, 0x6f,
0x70, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x2c, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61,
0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31,
0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x52, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72,
0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x52, 0x0f, 0x72, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f,
0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x22, 0x20, 0x0a, 0x1e, 0x41, 0x64, 0x64, 0x54, 0x65,
0x61, 0x6d, 0x52, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70,
0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0xe8, 0x01, 0x0a, 0x23, 0x41, 0x64,
0x64, 0x54, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x53,
0x63, 0x6f, 0x70, 0x65, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73,
0x74, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52,
0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x2b, 0x0a, 0x11, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a,
0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09,
0x52, 0x10, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x4e, 0x61,
0x6d, 0x65, 0x12, 0x27, 0x0a, 0x0f, 0x72, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79,
0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0e, 0x72, 0x65, 0x70,
0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x57, 0x0a, 0x10, 0x72,
0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x5f, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x18,
0x04, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x2c, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68,
0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70,
0x68, 0x61, 0x31, 0x2e, 0x52, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x53, 0x63,
0x6f, 0x70, 0x65, 0x52, 0x0f, 0x72, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x53,
0x63, 0x6f, 0x70, 0x65, 0x22, 0x26, 0x0a, 0x24, 0x41, 0x64, 0x64, 0x54, 0x65, 0x61, 0x6d, 0x52,
0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x42, 0x79,
0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0xb0, 0x01, 0x0a,
0x20, 0x52, 0x65, 0x6d, 0x6f, 0x76, 0x65, 0x54, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x70, 0x6f, 0x73,
0x69, 0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73,
0x74, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69,
0x64, 0x12, 0x23, 0x0a, 0x0d, 0x72, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x5f,
0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x72, 0x65, 0x70, 0x6f, 0x73, 0x69,
0x74, 0x6f, 0x72, 0x79, 0x49, 0x64, 0x12, 0x57, 0x0a, 0x10, 0x72, 0x65, 0x70, 0x6f, 0x73, 0x69,
0x74, 0x6f, 0x72, 0x79, 0x5f, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0e,
0x32, 0x2c, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67,
0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x52,
0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x52, 0x0f,
0x72, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x22,
0x23, 0x0a, 0x21, 0x52, 0x65, 0x6d, 0x6f, 0x76, 0x65, 0x54, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x70,
0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x52, 0x65, 0x73, 0x70,
0x6f, 0x6e, 0x73, 0x65, 0x22, 0xeb, 0x01, 0x0a, 0x26, 0x52, 0x65, 0x6d, 0x6f, 0x76, 0x65, 0x54,
0x65, 0x61, 0x6d, 0x52, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f,
0x70, 0x65, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12,
0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e,
0x61, 0x6d, 0x65, 0x12, 0x2b, 0x0a, 0x11, 0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74,
0x69, 0x6f, 0x6e, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x10,
0x6f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x4e, 0x61, 0x6d, 0x65,
0x12, 0x27, 0x0a, 0x0f, 0x72, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x5f, 0x6e,
0x61, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0e, 0x72, 0x65, 0x70, 0x6f, 0x73,
0x69, 0x74, 0x6f, 0x72, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x57, 0x0a, 0x10, 0x72, 0x65, 0x70,
0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x5f, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x18, 0x04, 0x20,
0x01, 0x28, 0x0e, 0x32, 0x2c, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e,
0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61,
0x31, 0x2e, 0x52, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70,
0x65, 0x52, 0x0f, 0x72, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f,
0x70, 0x65, 0x22, 0x29, 0x0a, 0x27, 0x52, 0x65, 0x6d, 0x6f, 0x76, 0x65, 0x54, 0x65, 0x61, 0x6d,
0x52, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x42,
0x79, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x32, 0xd6, 0x1b,
0x0a, 0x0b, 0x54, 0x65, 0x61, 0x6d, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x64, 0x0a,
0x07, 0x47, 0x65, 0x74, 0x54, 0x65, 0x61, 0x6d, 0x12, 0x2b, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61,
0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31,
0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x47, 0x65, 0x74, 0x54, 0x65, 0x61, 0x6d, 0x52, 0x65,
0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2c, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68,
0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70,
0x68, 0x61, 0x31, 0x2e, 0x47, 0x65, 0x74, 0x54, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x73, 0x70, 0x6f,
0x6e, 0x73, 0x65, 0x12, 0x76, 0x0a, 0x0d, 0x47, 0x65, 0x74, 0x54, 0x65, 0x61, 0x6d, 0x42, 0x79,
0x4e, 0x61, 0x6d, 0x65, 0x12, 0x31, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61,
0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68,
0x61, 0x31, 0x2e, 0x47, 0x65, 0x74, 0x54, 0x65, 0x61, 0x6d, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65,
0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x32, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c,
0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61,
0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x47, 0x65, 0x74, 0x54, 0x65, 0x61, 0x6d, 0x42, 0x79, 0x4e,
0x61, 0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x8e, 0x01, 0x0a, 0x15,
0x4c, 0x69, 0x73, 0x74, 0x4f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e,
0x54, 0x65, 0x61, 0x6d, 0x73, 0x12, 0x39, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68,
0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70,
0x68, 0x61, 0x31, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x4f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61,
0x74, 0x69, 0x6f, 0x6e, 0x54, 0x65, 0x61, 0x6d, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74,
0x1a, 0x3a, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67,
0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x4c,
0x69, 0x73, 0x74, 0x4f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x54,
0x65, 0x61, 0x6d, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x6d, 0x0a, 0x0a,
0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x54, 0x65, 0x61, 0x6d, 0x12, 0x2e, 0x2e, 0x62, 0x75, 0x66,
0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e,
0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x54,
0x65, 0x61, 0x6d, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2f, 0x2e, 0x62, 0x75, 0x66,
0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e,
0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x54,
0x65, 0x61, 0x6d, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x7f, 0x0a, 0x10, 0x43,
0x72, 0x65, 0x61, 0x74, 0x65, 0x54, 0x65, 0x61, 0x6d, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x12,
0x34, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69,
0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x43, 0x72,
0x65, 0x61, 0x74, 0x65, 0x54, 0x65, 0x61, 0x6d, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65,
0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x35, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68,
0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70,
0x68, 0x61, 0x31, 0x2e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x54, 0x65, 0x61, 0x6d, 0x42, 0x79,
0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x79, 0x0a, 0x0e,
0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x54, 0x65, 0x61, 0x6d, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x32,
0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73,
0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x55, 0x70, 0x64,
0x61, 0x74, 0x65, 0x54, 0x65, 0x61, 0x6d, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65,
0x73, 0x74, 0x1a, 0x33, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72,
0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31,
0x2e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x54, 0x65, 0x61, 0x6d, 0x4e, 0x61, 0x6d, 0x65, 0x52,
0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x76, 0x0a, 0x0d, 0x41, 0x64, 0x64, 0x55, 0x73,
0x65, 0x72, 0x54, 0x6f, 0x54, 0x65, 0x61, 0x6d, 0x12, 0x31, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61,
0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31,
0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x41, 0x64, 0x64, 0x55, 0x73, 0x65, 0x72, 0x54, 0x6f,
0x54, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x32, 0x2e, 0x62, 0x75,
0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79,
0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x41, 0x64, 0x64, 0x55, 0x73, 0x65,
0x72, 0x54, 0x6f, 0x54, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12,
0x88, 0x01, 0x0a, 0x13, 0x41, 0x64, 0x64, 0x55, 0x73, 0x65, 0x72, 0x54, 0x6f, 0x54, 0x65, 0x61,
0x6d, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x37, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c,
0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61,
0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x41, 0x64, 0x64, 0x55, 0x73, 0x65, 0x72, 0x54, 0x6f, 0x54,
0x65, 0x61, 0x6d, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74,
0x1a, 0x38, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67,
0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x41,
0x64, 0x64, 0x55, 0x73, 0x65, 0x72, 0x54, 0x6f, 0x54, 0x65, 0x61, 0x6d, 0x42, 0x79, 0x4e, 0x61,
0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x85, 0x01, 0x0a, 0x12, 0x52,
0x65, 0x6d, 0x6f, 0x76, 0x65, 0x55, 0x73, 0x65, 0x72, 0x46, 0x72, 0x6f, 0x6d, 0x54, 0x65, 0x61,
0x6d, 0x12, 0x36, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65,
0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e,
0x52, 0x65, 0x6d, 0x6f, 0x76, 0x65, 0x55, 0x73, 0x65, 0x72, 0x46, 0x72, 0x6f, 0x6d, 0x54, 0x65,
0x61, 0x6d, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x37, 0x2e, 0x62, 0x75, 0x66, 0x2e,
0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76,
0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x52, 0x65, 0x6d, 0x6f, 0x76, 0x65, 0x55, 0x73,
0x65, 0x72, 0x46, 0x72, 0x6f, 0x6d, 0x54, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e,
0x73, 0x65, 0x12, 0x97, 0x01, 0x0a, 0x18, 0x52, 0x65, 0x6d, 0x6f, 0x76, 0x65, 0x55, 0x73, 0x65,
0x72, 0x46, 0x72, 0x6f, 0x6d, 0x54, 0x65, 0x61, 0x6d, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x12,
0x3c, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69,
0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x52, 0x65,
0x6d, 0x6f, 0x76, 0x65, 0x55, 0x73, 0x65, 0x72, 0x46, 0x72, 0x6f, 0x6d, 0x54, 0x65, 0x61, 0x6d,
0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x3d, 0x2e,
0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74,
0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x52, 0x65, 0x6d, 0x6f,
0x76, 0x65, 0x55, 0x73, 0x65, 0x72, 0x46, 0x72, 0x6f, 0x6d, 0x54, 0x65, 0x61, 0x6d, 0x42, 0x79,
0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x6d, 0x0a, 0x0a,
0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x54, 0x65, 0x61, 0x6d, 0x12, 0x2e, 0x2e, 0x62, 0x75, 0x66,
0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e,
0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x54,
0x65, 0x61, 0x6d, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x2f, 0x2e, 0x62, 0x75, 0x66,
0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e,
0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x54,
0x65, 0x61, 0x6d, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x7f, 0x0a, 0x10, 0x44,
0x65, 0x6c, 0x65, 0x74, 0x65, 0x54, 0x65, 0x61, 0x6d, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x12,
0x34, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69,
0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x44, 0x65,
0x6c, 0x65, 0x74, 0x65, 0x54, 0x65, 0x61, 0x6d, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65,
0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x35, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68,
0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70,
0x68, 0x61, 0x31, 0x2e, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x54, 0x65, 0x61, 0x6d, 0x42, 0x79,
0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x97, 0x01, 0x0a,
0x18, 0x41, 0x64, 0x64, 0x54, 0x65, 0x61, 0x6d, 0x4f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61,
0x74, 0x69, 0x6f, 0x6e, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x12, 0x3c, 0x2e, 0x62, 0x75, 0x66, 0x2e,
0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76,
0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x41, 0x64, 0x64, 0x54, 0x65, 0x61, 0x6d, 0x4f,
0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x63, 0x6f, 0x70, 0x65,
0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x3d, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c,
0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61,
0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x41, 0x64, 0x64, 0x54, 0x65, 0x61, 0x6d, 0x4f, 0x72, 0x67,
0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x52, 0x65,
0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0xa9, 0x01, 0x0a, 0x1e, 0x41, 0x64, 0x64, 0x54, 0x65,
0x61, 0x6d, 0x4f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x63,
0x6f, 0x70, 0x65, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x42, 0x2e, 0x62, 0x75, 0x66, 0x2e,
0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76,
0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x41, 0x64, 0x64, 0x54, 0x65, 0x61, 0x6d, 0x4f,
0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x63, 0x6f, 0x70, 0x65,
0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x43, 0x2e,
0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74,
0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x41, 0x64, 0x64, 0x54,
0x65, 0x61, 0x6d, 0x4f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53,
0x63, 0x6f, 0x70, 0x65, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e,
0x73, 0x65, 0x12, 0xa0, 0x01, 0x0a, 0x1b, 0x52, 0x65, 0x6d, 0x6f, 0x76, 0x65, 0x54, 0x65, 0x61,
0x6d, 0x4f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x63, 0x6f,
0x70, 0x65, 0x12, 0x3f, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72,
0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31,
0x2e, 0x52, 0x65, 0x6d, 0x6f, 0x76, 0x65, 0x54, 0x65, 0x61, 0x6d, 0x4f, 0x72, 0x67, 0x61, 0x6e,
0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x52, 0x65, 0x71, 0x75,
0x65, 0x73, 0x74, 0x1a, 0x40, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e,
0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61,
0x31, 0x2e, 0x52, 0x65, 0x6d, 0x6f, 0x76, 0x65, 0x54, 0x65, 0x61, 0x6d, 0x4f, 0x72, 0x67, 0x61,
0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x52, 0x65, 0x73,
0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0xb2, 0x01, 0x0a, 0x21, 0x52, 0x65, 0x6d, 0x6f, 0x76, 0x65,
0x54, 0x65, 0x61, 0x6d, 0x4f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e,
0x53, 0x63, 0x6f, 0x70, 0x65, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x45, 0x2e, 0x62, 0x75,
0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79,
0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x52, 0x65, 0x6d, 0x6f, 0x76, 0x65,
0x54, 0x65, 0x61, 0x6d, 0x4f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e,
0x53, 0x63, 0x6f, 0x70, 0x65, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65,
0x73, 0x74, 0x1a, 0x46, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72,
0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31,
0x2e, 0x52, 0x65, 0x6d, 0x6f, 0x76, 0x65, 0x54, 0x65, 0x61, 0x6d, 0x4f, 0x72, 0x67, 0x61, 0x6e,
0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x42, 0x79, 0x4e, 0x61,
0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x9d, 0x01, 0x0a, 0x1a, 0x41,
0x64, 0x64, 0x54, 0x65, 0x61, 0x6d, 0x42, 0x61, 0x73, 0x65, 0x52, 0x65, 0x70, 0x6f, 0x73, 0x69,
0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x12, 0x3e, 0x2e, 0x62, 0x75, 0x66, 0x2e,
0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76,
0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x41, 0x64, 0x64, 0x54, 0x65, 0x61, 0x6d, 0x42,
0x61, 0x73, 0x65, 0x52, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f,
0x70, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x3f, 0x2e, 0x62, 0x75, 0x66, 0x2e,
0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76,
0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x41, 0x64, 0x64, 0x54, 0x65, 0x61, 0x6d, 0x42,
0x61, 0x73, 0x65, 0x52, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f,
0x70, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0xaf, 0x01, 0x0a, 0x20, 0x41,
0x64, 0x64, 0x54, 0x65, 0x61, 0x6d, 0x42, 0x61, 0x73, 0x65, 0x52, 0x65, 0x70, 0x6f, 0x73, 0x69,
0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x12,
0x44, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69,
0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x41, 0x64,
0x64, 0x54, 0x65, 0x61, 0x6d, 0x42, 0x61, 0x73, 0x65, 0x52, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74,
0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65,
0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x45, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68,
0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70,
0x68, 0x61, 0x31, 0x2e, 0x41, 0x64, 0x64, 0x54, 0x65, 0x61, 0x6d, 0x42, 0x61, 0x73, 0x65, 0x52,
0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x42, 0x79,
0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0xa6, 0x01, 0x0a,
0x1d, 0x52, 0x65, 0x6d, 0x6f, 0x76, 0x65, 0x54, 0x65, 0x61, 0x6d, 0x42, 0x61, 0x73, 0x65, 0x52,
0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x12, 0x41,
0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73,
0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x52, 0x65, 0x6d,
0x6f, 0x76, 0x65, 0x54, 0x65, 0x61, 0x6d, 0x42, 0x61, 0x73, 0x65, 0x52, 0x65, 0x70, 0x6f, 0x73,
0x69, 0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73,
0x74, 0x1a, 0x42, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65,
0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e,
0x52, 0x65, 0x6d, 0x6f, 0x76, 0x65, 0x54, 0x65, 0x61, 0x6d, 0x42, 0x61, 0x73, 0x65, 0x52, 0x65,
0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x52, 0x65, 0x73,
0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0xb8, 0x01, 0x0a, 0x23, 0x52, 0x65, 0x6d, 0x6f, 0x76, 0x65,
0x54, 0x65, 0x61, 0x6d, 0x42, 0x61, 0x73, 0x65, 0x52, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f,
0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x47, 0x2e,
0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74,
0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x52, 0x65, 0x6d, 0x6f,
0x76, 0x65, 0x54, 0x65, 0x61, 0x6d, 0x42, 0x61, 0x73, 0x65, 0x52, 0x65, 0x70, 0x6f, 0x73, 0x69,
0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x52,
0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x48, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70,
0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c,
0x70, 0x68, 0x61, 0x31, 0x2e, 0x52, 0x65, 0x6d, 0x6f, 0x76, 0x65, 0x54, 0x65, 0x61, 0x6d, 0x42,
0x61, 0x73, 0x65, 0x52, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f,
0x70, 0x65, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65,
0x12, 0x91, 0x01, 0x0a, 0x16, 0x41, 0x64, 0x64, 0x54, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x70, 0x6f,
0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x12, 0x3a, 0x2e, 0x62, 0x75,
0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79,
0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x41, 0x64, 0x64, 0x54, 0x65, 0x61,
0x6d, 0x52, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65,
0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x3b, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c,
0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61,
0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x41, 0x64, 0x64, 0x54, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x70,
0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x52, 0x65, 0x73, 0x70,
0x6f, 0x6e, 0x73, 0x65, 0x12, 0xa3, 0x01, 0x0a, 0x1c, 0x41, 0x64, 0x64, 0x54, 0x65, 0x61, 0x6d,
0x52, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x42,
0x79, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x40, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68,
0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70,
0x68, 0x61, 0x31, 0x2e, 0x41, 0x64, 0x64, 0x54, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x70, 0x6f, 0x73,
0x69, 0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65,
0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x41, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c,
0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61,
0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x41, 0x64, 0x64, 0x54, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x70,
0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x42, 0x79, 0x4e, 0x61,
0x6d, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x9a, 0x01, 0x0a, 0x19, 0x52,
0x65, 0x6d, 0x6f, 0x76, 0x65, 0x54, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74,
0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x12, 0x3d, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61,
0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31,
0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x52, 0x65, 0x6d, 0x6f, 0x76, 0x65, 0x54, 0x65, 0x61,
0x6d, 0x52, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65,
0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x3e, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c,
0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61,
0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x52, 0x65, 0x6d, 0x6f, 0x76, 0x65, 0x54, 0x65, 0x61, 0x6d,
0x52, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x52,
0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0xac, 0x01, 0x0a, 0x1f, 0x52, 0x65, 0x6d, 0x6f,
0x76, 0x65, 0x54, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79,
0x53, 0x63, 0x6f, 0x70, 0x65, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x43, 0x2e, 0x62, 0x75,
0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79,
0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x52, 0x65, 0x6d, 0x6f, 0x76, 0x65,
0x54, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x6f, 0x72, 0x79, 0x53, 0x63,
0x6f, 0x70, 0x65, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74,
0x1a, 0x44, 0x2e, 0x62, 0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67,
0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x2e, 0x52,
0x65, 0x6d, 0x6f, 0x76, 0x65, 0x54, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x70, 0x6f, 0x73, 0x69, 0x74,
0x6f, 0x72, 0x79, 0x53, 0x63, 0x6f, 0x70, 0x65, 0x42, 0x79, 0x4e, 0x61, 0x6d, 0x65, 0x52, 0x65,
0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x96, 0x02, 0x0a, 0x1f, 0x63, 0x6f, 0x6d, 0x2e, 0x62,
0x75, 0x66, 0x2e, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2e, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72,
0x79, 0x2e, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x42, 0x09, 0x54, 0x65, 0x61, 0x6d,
0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x59, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e,
0x63, 0x6f, 0x6d, 0x2f, 0x62, 0x75, 0x66, 0x62, 0x75, 0x69, 0x6c, 0x64, 0x2f, 0x62, 0x75, 0x66,
0x2f, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, 0x2f, 0x67, 0x65, 0x6e, 0x2f, 0x70, 0x72, 0x6f,
0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x2f, 0x62, 0x75, 0x66, 0x2f, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x2f,
0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2f, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61,
0x31, 0x3b, 0x72, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x76, 0x31, 0x61, 0x6c, 0x70, 0x68,
0x61, 0x31, 0xa2, 0x02, 0x03, 0x42, 0x41, 0x52, 0xaa, 0x02, 0x1b, 0x42, 0x75, 0x66, 0x2e, 0x41,
0x6c, 0x70, 0x68, 0x61, 0x2e, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x2e, 0x56, 0x31,
0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0xca, 0x02, 0x1b, 0x42, 0x75, 0x66, 0x5c, 0x41, 0x6c, 0x70,
0x68, 0x61, 0x5c, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x5c, 0x56, 0x31, 0x61, 0x6c,
0x70, 0x68, 0x61, 0x31, 0xe2, 0x02, 0x27, 0x42, 0x75, 0x66, 0x5c, 0x41, 0x6c, 0x70, 0x68, 0x61,
0x5c, 0x52, 0x65, 0x67, 0x69, 0x73, 0x74, 0x72, 0x79, 0x5c, 0x56, 0x31, 0x61, 0x6c, 0x70, 0x68,
0x61, 0x31, 0x5c, 0x47, 0x50, 0x42, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0xea, 0x02,
0x1e, 0x42, 0x75, 0x66, 0x3a, 0x3a, 0x41, 0x6c, 0x70, 0x68, 0x61, 0x3a, 0x3a, 0x52, 0x65, 0x67,
0x69, 0x73, 0x74, 0x72, 0x79, 0x3a, 0x3a, 0x56, 0x31, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x31, 0x62,
0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_buf_alpha_registry_v1alpha1_team_proto_rawDescOnce sync.Once
file_buf_alpha_registry_v1alpha1_team_proto_rawDescData = file_buf_alpha_registry_v1alpha1_team_proto_rawDesc
)
func file_buf_alpha_registry_v1alpha1_team_proto_rawDescGZIP() []byte {
file_buf_alpha_registry_v1alpha1_team_proto_rawDescOnce.Do(func() {
file_buf_alpha_registry_v1alpha1_team_proto_rawDescData = protoimpl.X.CompressGZIP(file_buf_alpha_registry_v1alpha1_team_proto_rawDescData)
})
return file_buf_alpha_registry_v1alpha1_team_proto_rawDescData
}
var file_buf_alpha_registry_v1alpha1_team_proto_msgTypes = make([]protoimpl.MessageInfo, 49)
var file_buf_alpha_registry_v1alpha1_team_proto_goTypes = []interface{}{
(*Team)(nil), // 0: buf.alpha.registry.v1alpha1.Team
(*GetTeamRequest)(nil), // 1: buf.alpha.registry.v1alpha1.GetTeamRequest
(*GetTeamResponse)(nil), // 2: buf.alpha.registry.v1alpha1.GetTeamResponse
(*GetTeamByNameRequest)(nil), // 3: buf.alpha.registry.v1alpha1.GetTeamByNameRequest
(*GetTeamByNameResponse)(nil), // 4: buf.alpha.registry.v1alpha1.GetTeamByNameResponse
(*ListOrganizationTeamsRequest)(nil), // 5: buf.alpha.registry.v1alpha1.ListOrganizationTeamsRequest
(*ListOrganizationTeamsResponse)(nil), // 6: buf.alpha.registry.v1alpha1.ListOrganizationTeamsResponse
(*CreateTeamRequest)(nil), // 7: buf.alpha.registry.v1alpha1.CreateTeamRequest
(*CreateTeamResponse)(nil), // 8: buf.alpha.registry.v1alpha1.CreateTeamResponse
(*CreateTeamByNameRequest)(nil), // 9: buf.alpha.registry.v1alpha1.CreateTeamByNameRequest
(*CreateTeamByNameResponse)(nil), // 10: buf.alpha.registry.v1alpha1.CreateTeamByNameResponse
(*UpdateTeamNameRequest)(nil), // 11: buf.alpha.registry.v1alpha1.UpdateTeamNameRequest
(*UpdateTeamNameResponse)(nil), // 12: buf.alpha.registry.v1alpha1.UpdateTeamNameResponse
(*AddUserToTeamRequest)(nil), // 13: buf.alpha.registry.v1alpha1.AddUserToTeamRequest
(*AddUserToTeamResponse)(nil), // 14: buf.alpha.registry.v1alpha1.AddUserToTeamResponse
(*AddUserToTeamByNameRequest)(nil), // 15: buf.alpha.registry.v1alpha1.AddUserToTeamByNameRequest
(*AddUserToTeamByNameResponse)(nil), // 16: buf.alpha.registry.v1alpha1.AddUserToTeamByNameResponse
(*RemoveUserFromTeamRequest)(nil), // 17: buf.alpha.registry.v1alpha1.RemoveUserFromTeamRequest
(*RemoveUserFromTeamResponse)(nil), // 18: buf.alpha.registry.v1alpha1.RemoveUserFromTeamResponse
(*RemoveUserFromTeamByNameRequest)(nil), // 19: buf.alpha.registry.v1alpha1.RemoveUserFromTeamByNameRequest
(*RemoveUserFromTeamByNameResponse)(nil), // 20: buf.alpha.registry.v1alpha1.RemoveUserFromTeamByNameResponse
(*DeleteTeamRequest)(nil), // 21: buf.alpha.registry.v1alpha1.DeleteTeamRequest
(*DeleteTeamResponse)(nil), // 22: buf.alpha.registry.v1alpha1.DeleteTeamResponse
(*DeleteTeamByNameRequest)(nil), // 23: buf.alpha.registry.v1alpha1.DeleteTeamByNameRequest
(*DeleteTeamByNameResponse)(nil), // 24: buf.alpha.registry.v1alpha1.DeleteTeamByNameResponse
(*AddTeamOrganizationScopeRequest)(nil), // 25: buf.alpha.registry.v1alpha1.AddTeamOrganizationScopeRequest
(*AddTeamOrganizationScopeResponse)(nil), // 26: buf.alpha.registry.v1alpha1.AddTeamOrganizationScopeResponse
(*AddTeamOrganizationScopeByNameRequest)(nil), // 27: buf.alpha.registry.v1alpha1.AddTeamOrganizationScopeByNameRequest
(*AddTeamOrganizationScopeByNameResponse)(nil), // 28: buf.alpha.registry.v1alpha1.AddTeamOrganizationScopeByNameResponse
(*RemoveTeamOrganizationScopeRequest)(nil), // 29: buf.alpha.registry.v1alpha1.RemoveTeamOrganizationScopeRequest
(*RemoveTeamOrganizationScopeResponse)(nil), // 30: buf.alpha.registry.v1alpha1.RemoveTeamOrganizationScopeResponse
(*RemoveTeamOrganizationScopeByNameRequest)(nil), // 31: buf.alpha.registry.v1alpha1.RemoveTeamOrganizationScopeByNameRequest
(*RemoveTeamOrganizationScopeByNameResponse)(nil), // 32: buf.alpha.registry.v1alpha1.RemoveTeamOrganizationScopeByNameResponse
(*AddTeamBaseRepositoryScopeRequest)(nil), // 33: buf.alpha.registry.v1alpha1.AddTeamBaseRepositoryScopeRequest
(*AddTeamBaseRepositoryScopeResponse)(nil), // 34: buf.alpha.registry.v1alpha1.AddTeamBaseRepositoryScopeResponse
(*AddTeamBaseRepositoryScopeByNameRequest)(nil), // 35: buf.alpha.registry.v1alpha1.AddTeamBaseRepositoryScopeByNameRequest
(*AddTeamBaseRepositoryScopeByNameResponse)(nil), // 36: buf.alpha.registry.v1alpha1.AddTeamBaseRepositoryScopeByNameResponse
(*RemoveTeamBaseRepositoryScopeRequest)(nil), // 37: buf.alpha.registry.v1alpha1.RemoveTeamBaseRepositoryScopeRequest
(*RemoveTeamBaseRepositoryScopeResponse)(nil), // 38: buf.alpha.registry.v1alpha1.RemoveTeamBaseRepositoryScopeResponse
(*RemoveTeamBaseRepositoryScopeByNameRequest)(nil), // 39: buf.alpha.registry.v1alpha1.RemoveTeamBaseRepositoryScopeByNameRequest
(*RemoveTeamBaseRepositoryScopeByNameResponse)(nil), // 40: buf.alpha.registry.v1alpha1.RemoveTeamBaseRepositoryScopeByNameResponse
(*AddTeamRepositoryScopeRequest)(nil), // 41: buf.alpha.registry.v1alpha1.AddTeamRepositoryScopeRequest
(*AddTeamRepositoryScopeResponse)(nil), // 42: buf.alpha.registry.v1alpha1.AddTeamRepositoryScopeResponse
(*AddTeamRepositoryScopeByNameRequest)(nil), // 43: buf.alpha.registry.v1alpha1.AddTeamRepositoryScopeByNameRequest
(*AddTeamRepositoryScopeByNameResponse)(nil), // 44: buf.alpha.registry.v1alpha1.AddTeamRepositoryScopeByNameResponse
(*RemoveTeamRepositoryScopeRequest)(nil), // 45: buf.alpha.registry.v1alpha1.RemoveTeamRepositoryScopeRequest
(*RemoveTeamRepositoryScopeResponse)(nil), // 46: buf.alpha.registry.v1alpha1.RemoveTeamRepositoryScopeResponse
(*RemoveTeamRepositoryScopeByNameRequest)(nil), // 47: buf.alpha.registry.v1alpha1.RemoveTeamRepositoryScopeByNameRequest
(*RemoveTeamRepositoryScopeByNameResponse)(nil), // 48: buf.alpha.registry.v1alpha1.RemoveTeamRepositoryScopeByNameResponse
(*timestamppb.Timestamp)(nil), // 49: google.protobuf.Timestamp
(OrganizationScope)(0), // 50: buf.alpha.registry.v1alpha1.OrganizationScope
(RepositoryScope)(0), // 51: buf.alpha.registry.v1alpha1.RepositoryScope
}
var file_buf_alpha_registry_v1alpha1_team_proto_depIdxs = []int32{
49, // 0: buf.alpha.registry.v1alpha1.Team.create_time:type_name -> google.protobuf.Timestamp
49, // 1: buf.alpha.registry.v1alpha1.Team.update_time:type_name -> google.protobuf.Timestamp
0, // 2: buf.alpha.registry.v1alpha1.GetTeamResponse.team:type_name -> buf.alpha.registry.v1alpha1.Team
0, // 3: buf.alpha.registry.v1alpha1.GetTeamByNameResponse.team:type_name -> buf.alpha.registry.v1alpha1.Team
0, // 4: buf.alpha.registry.v1alpha1.ListOrganizationTeamsResponse.teams:type_name -> buf.alpha.registry.v1alpha1.Team
0, // 5: buf.alpha.registry.v1alpha1.CreateTeamResponse.team:type_name -> buf.alpha.registry.v1alpha1.Team
0, // 6: buf.alpha.registry.v1alpha1.CreateTeamByNameResponse.team:type_name -> buf.alpha.registry.v1alpha1.Team
0, // 7: buf.alpha.registry.v1alpha1.UpdateTeamNameResponse.team:type_name -> buf.alpha.registry.v1alpha1.Team
50, // 8: buf.alpha.registry.v1alpha1.AddTeamOrganizationScopeRequest.organization_scope:type_name -> buf.alpha.registry.v1alpha1.OrganizationScope
50, // 9: buf.alpha.registry.v1alpha1.AddTeamOrganizationScopeByNameRequest.organization_scope:type_name -> buf.alpha.registry.v1alpha1.OrganizationScope
50, // 10: buf.alpha.registry.v1alpha1.RemoveTeamOrganizationScopeRequest.organization_scope:type_name -> buf.alpha.registry.v1alpha1.OrganizationScope
50, // 11: buf.alpha.registry.v1alpha1.RemoveTeamOrganizationScopeByNameRequest.organization_scope:type_name -> buf.alpha.registry.v1alpha1.OrganizationScope
51, // 12: buf.alpha.registry.v1alpha1.AddTeamBaseRepositoryScopeRequest.repository_scope:type_name -> buf.alpha.registry.v1alpha1.RepositoryScope
51, // 13: buf.alpha.registry.v1alpha1.AddTeamBaseRepositoryScopeByNameRequest.repository_scope:type_name -> buf.alpha.registry.v1alpha1.RepositoryScope
51, // 14: buf.alpha.registry.v1alpha1.RemoveTeamBaseRepositoryScopeRequest.repository_scope:type_name -> buf.alpha.registry.v1alpha1.RepositoryScope
51, // 15: buf.alpha.registry.v1alpha1.RemoveTeamBaseRepositoryScopeByNameRequest.repository_scope:type_name -> buf.alpha.registry.v1alpha1.RepositoryScope
51, // 16: buf.alpha.registry.v1alpha1.AddTeamRepositoryScopeRequest.repository_scope:type_name -> buf.alpha.registry.v1alpha1.RepositoryScope
51, // 17: buf.alpha.registry.v1alpha1.AddTeamRepositoryScopeByNameRequest.repository_scope:type_name -> buf.alpha.registry.v1alpha1.RepositoryScope
51, // 18: buf.alpha.registry.v1alpha1.RemoveTeamRepositoryScopeRequest.repository_scope:type_name -> buf.alpha.registry.v1alpha1.RepositoryScope
51, // 19: buf.alpha.registry.v1alpha1.RemoveTeamRepositoryScopeByNameRequest.repository_scope:type_name -> buf.alpha.registry.v1alpha1.RepositoryScope
1, // 20: buf.alpha.registry.v1alpha1.TeamService.GetTeam:input_type -> buf.alpha.registry.v1alpha1.GetTeamRequest
3, // 21: buf.alpha.registry.v1alpha1.TeamService.GetTeamByName:input_type -> buf.alpha.registry.v1alpha1.GetTeamByNameRequest
5, // 22: buf.alpha.registry.v1alpha1.TeamService.ListOrganizationTeams:input_type -> buf.alpha.registry.v1alpha1.ListOrganizationTeamsRequest
7, // 23: buf.alpha.registry.v1alpha1.TeamService.CreateTeam:input_type -> buf.alpha.registry.v1alpha1.CreateTeamRequest
9, // 24: buf.alpha.registry.v1alpha1.TeamService.CreateTeamByName:input_type -> buf.alpha.registry.v1alpha1.CreateTeamByNameRequest
11, // 25: buf.alpha.registry.v1alpha1.TeamService.UpdateTeamName:input_type -> buf.alpha.registry.v1alpha1.UpdateTeamNameRequest
13, // 26: buf.alpha.registry.v1alpha1.TeamService.AddUserToTeam:input_type -> buf.alpha.registry.v1alpha1.AddUserToTeamRequest
15, // 27: buf.alpha.registry.v1alpha1.TeamService.AddUserToTeamByName:input_type -> buf.alpha.registry.v1alpha1.AddUserToTeamByNameRequest
17, // 28: buf.alpha.registry.v1alpha1.TeamService.RemoveUserFromTeam:input_type -> buf.alpha.registry.v1alpha1.RemoveUserFromTeamRequest
19, // 29: buf.alpha.registry.v1alpha1.TeamService.RemoveUserFromTeamByName:input_type -> buf.alpha.registry.v1alpha1.RemoveUserFromTeamByNameRequest
21, // 30: buf.alpha.registry.v1alpha1.TeamService.DeleteTeam:input_type -> buf.alpha.registry.v1alpha1.DeleteTeamRequest
23, // 31: buf.alpha.registry.v1alpha1.TeamService.DeleteTeamByName:input_type -> buf.alpha.registry.v1alpha1.DeleteTeamByNameRequest
25, // 32: buf.alpha.registry.v1alpha1.TeamService.AddTeamOrganizationScope:input_type -> buf.alpha.registry.v1alpha1.AddTeamOrganizationScopeRequest
27, // 33: buf.alpha.registry.v1alpha1.TeamService.AddTeamOrganizationScopeByName:input_type -> buf.alpha.registry.v1alpha1.AddTeamOrganizationScopeByNameRequest
29, // 34: buf.alpha.registry.v1alpha1.TeamService.RemoveTeamOrganizationScope:input_type -> buf.alpha.registry.v1alpha1.RemoveTeamOrganizationScopeRequest
31, // 35: buf.alpha.registry.v1alpha1.TeamService.RemoveTeamOrganizationScopeByName:input_type -> buf.alpha.registry.v1alpha1.RemoveTeamOrganizationScopeByNameRequest
33, // 36: buf.alpha.registry.v1alpha1.TeamService.AddTeamBaseRepositoryScope:input_type -> buf.alpha.registry.v1alpha1.AddTeamBaseRepositoryScopeRequest
35, // 37: buf.alpha.registry.v1alpha1.TeamService.AddTeamBaseRepositoryScopeByName:input_type -> buf.alpha.registry.v1alpha1.AddTeamBaseRepositoryScopeByNameRequest
37, // 38: buf.alpha.registry.v1alpha1.TeamService.RemoveTeamBaseRepositoryScope:input_type -> buf.alpha.registry.v1alpha1.RemoveTeamBaseRepositoryScopeRequest
39, // 39: buf.alpha.registry.v1alpha1.TeamService.RemoveTeamBaseRepositoryScopeByName:input_type -> buf.alpha.registry.v1alpha1.RemoveTeamBaseRepositoryScopeByNameRequest
41, // 40: buf.alpha.registry.v1alpha1.TeamService.AddTeamRepositoryScope:input_type -> buf.alpha.registry.v1alpha1.AddTeamRepositoryScopeRequest
43, // 41: buf.alpha.registry.v1alpha1.TeamService.AddTeamRepositoryScopeByName:input_type -> buf.alpha.registry.v1alpha1.AddTeamRepositoryScopeByNameRequest
45, // 42: buf.alpha.registry.v1alpha1.TeamService.RemoveTeamRepositoryScope:input_type -> buf.alpha.registry.v1alpha1.RemoveTeamRepositoryScopeRequest
47, // 43: buf.alpha.registry.v1alpha1.TeamService.RemoveTeamRepositoryScopeByName:input_type -> buf.alpha.registry.v1alpha1.RemoveTeamRepositoryScopeByNameRequest
2, // 44: buf.alpha.registry.v1alpha1.TeamService.GetTeam:output_type -> buf.alpha.registry.v1alpha1.GetTeamResponse
4, // 45: buf.alpha.registry.v1alpha1.TeamService.GetTeamByName:output_type -> buf.alpha.registry.v1alpha1.GetTeamByNameResponse
6, // 46: buf.alpha.registry.v1alpha1.TeamService.ListOrganizationTeams:output_type -> buf.alpha.registry.v1alpha1.ListOrganizationTeamsResponse
8, // 47: buf.alpha.registry.v1alpha1.TeamService.CreateTeam:output_type -> buf.alpha.registry.v1alpha1.CreateTeamResponse
10, // 48: buf.alpha.registry.v1alpha1.TeamService.CreateTeamByName:output_type -> buf.alpha.registry.v1alpha1.CreateTeamByNameResponse
12, // 49: buf.alpha.registry.v1alpha1.TeamService.UpdateTeamName:output_type -> buf.alpha.registry.v1alpha1.UpdateTeamNameResponse
14, // 50: buf.alpha.registry.v1alpha1.TeamService.AddUserToTeam:output_type -> buf.alpha.registry.v1alpha1.AddUserToTeamResponse
16, // 51: buf.alpha.registry.v1alpha1.TeamService.AddUserToTeamByName:output_type -> buf.alpha.registry.v1alpha1.AddUserToTeamByNameResponse
18, // 52: buf.alpha.registry.v1alpha1.TeamService.RemoveUserFromTeam:output_type -> buf.alpha.registry.v1alpha1.RemoveUserFromTeamResponse
20, // 53: buf.alpha.registry.v1alpha1.TeamService.RemoveUserFromTeamByName:output_type -> buf.alpha.registry.v1alpha1.RemoveUserFromTeamByNameResponse
22, // 54: buf.alpha.registry.v1alpha1.TeamService.DeleteTeam:output_type -> buf.alpha.registry.v1alpha1.DeleteTeamResponse
24, // 55: buf.alpha.registry.v1alpha1.TeamService.DeleteTeamByName:output_type -> buf.alpha.registry.v1alpha1.DeleteTeamByNameResponse
26, // 56: buf.alpha.registry.v1alpha1.TeamService.AddTeamOrganizationScope:output_type -> buf.alpha.registry.v1alpha1.AddTeamOrganizationScopeResponse
28, // 57: buf.alpha.registry.v1alpha1.TeamService.AddTeamOrganizationScopeByName:output_type -> buf.alpha.registry.v1alpha1.AddTeamOrganizationScopeByNameResponse
30, // 58: buf.alpha.registry.v1alpha1.TeamService.RemoveTeamOrganizationScope:output_type -> buf.alpha.registry.v1alpha1.RemoveTeamOrganizationScopeResponse
32, // 59: buf.alpha.registry.v1alpha1.TeamService.RemoveTeamOrganizationScopeByName:output_type -> buf.alpha.registry.v1alpha1.RemoveTeamOrganizationScopeByNameResponse
34, // 60: buf.alpha.registry.v1alpha1.TeamService.AddTeamBaseRepositoryScope:output_type -> buf.alpha.registry.v1alpha1.AddTeamBaseRepositoryScopeResponse
36, // 61: buf.alpha.registry.v1alpha1.TeamService.AddTeamBaseRepositoryScopeByName:output_type -> buf.alpha.registry.v1alpha1.AddTeamBaseRepositoryScopeByNameResponse
38, // 62: buf.alpha.registry.v1alpha1.TeamService.RemoveTeamBaseRepositoryScope:output_type -> buf.alpha.registry.v1alpha1.RemoveTeamBaseRepositoryScopeResponse
40, // 63: buf.alpha.registry.v1alpha1.TeamService.RemoveTeamBaseRepositoryScopeByName:output_type -> buf.alpha.registry.v1alpha1.RemoveTeamBaseRepositoryScopeByNameResponse
42, // 64: buf.alpha.registry.v1alpha1.TeamService.AddTeamRepositoryScope:output_type -> buf.alpha.registry.v1alpha1.AddTeamRepositoryScopeResponse
44, // 65: buf.alpha.registry.v1alpha1.TeamService.AddTeamRepositoryScopeByName:output_type -> buf.alpha.registry.v1alpha1.AddTeamRepositoryScopeByNameResponse
46, // 66: buf.alpha.registry.v1alpha1.TeamService.RemoveTeamRepositoryScope:output_type -> buf.alpha.registry.v1alpha1.RemoveTeamRepositoryScopeResponse
48, // 67: buf.alpha.registry.v1alpha1.TeamService.RemoveTeamRepositoryScopeByName:output_type -> buf.alpha.registry.v1alpha1.RemoveTeamRepositoryScopeByNameResponse
44, // [44:68] is the sub-list for method output_type
20, // [20:44] is the sub-list for method input_type
20, // [20:20] is the sub-list for extension type_name
20, // [20:20] is the sub-list for extension extendee
0, // [0:20] is the sub-list for field type_name
}
func init() { file_buf_alpha_registry_v1alpha1_team_proto_init() }
func file_buf_alpha_registry_v1alpha1_team_proto_init() {
if File_buf_alpha_registry_v1alpha1_team_proto != nil {
return
}
file_buf_alpha_registry_v1alpha1_scope_proto_init()
if !protoimpl.UnsafeEnabled {
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*Team); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*GetTeamRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*GetTeamResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*GetTeamByNameRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*GetTeamByNameResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*ListOrganizationTeamsRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*ListOrganizationTeamsResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*CreateTeamRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*CreateTeamResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[9].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*CreateTeamByNameRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[10].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*CreateTeamByNameResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[11].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*UpdateTeamNameRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[12].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*UpdateTeamNameResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[13].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*AddUserToTeamRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[14].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*AddUserToTeamResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[15].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*AddUserToTeamByNameRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[16].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*AddUserToTeamByNameResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[17].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*RemoveUserFromTeamRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[18].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*RemoveUserFromTeamResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[19].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*RemoveUserFromTeamByNameRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[20].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*RemoveUserFromTeamByNameResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[21].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*DeleteTeamRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[22].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*DeleteTeamResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[23].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*DeleteTeamByNameRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[24].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*DeleteTeamByNameResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[25].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*AddTeamOrganizationScopeRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[26].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*AddTeamOrganizationScopeResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[27].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*AddTeamOrganizationScopeByNameRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[28].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*AddTeamOrganizationScopeByNameResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[29].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*RemoveTeamOrganizationScopeRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[30].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*RemoveTeamOrganizationScopeResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[31].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*RemoveTeamOrganizationScopeByNameRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[32].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*RemoveTeamOrganizationScopeByNameResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[33].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*AddTeamBaseRepositoryScopeRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[34].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*AddTeamBaseRepositoryScopeResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[35].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*AddTeamBaseRepositoryScopeByNameRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[36].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*AddTeamBaseRepositoryScopeByNameResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[37].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*RemoveTeamBaseRepositoryScopeRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[38].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*RemoveTeamBaseRepositoryScopeResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[39].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*RemoveTeamBaseRepositoryScopeByNameRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[40].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*RemoveTeamBaseRepositoryScopeByNameResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[41].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*AddTeamRepositoryScopeRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[42].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*AddTeamRepositoryScopeResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[43].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*AddTeamRepositoryScopeByNameRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[44].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*AddTeamRepositoryScopeByNameResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[45].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*RemoveTeamRepositoryScopeRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[46].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*RemoveTeamRepositoryScopeResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[47].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*RemoveTeamRepositoryScopeByNameRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_buf_alpha_registry_v1alpha1_team_proto_msgTypes[48].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*RemoveTeamRepositoryScopeByNameResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_buf_alpha_registry_v1alpha1_team_proto_rawDesc,
NumEnums: 0,
NumMessages: 49,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_buf_alpha_registry_v1alpha1_team_proto_goTypes,
DependencyIndexes: file_buf_alpha_registry_v1alpha1_team_proto_depIdxs,
MessageInfos: file_buf_alpha_registry_v1alpha1_team_proto_msgTypes,
}.Build()
File_buf_alpha_registry_v1alpha1_team_proto = out.File
file_buf_alpha_registry_v1alpha1_team_proto_rawDesc = nil
file_buf_alpha_registry_v1alpha1_team_proto_goTypes = nil
file_buf_alpha_registry_v1alpha1_team_proto_depIdxs = nil
}
| {
ms.StoreMessageInfo(mi)
} |
util.go | /*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package blockledger
import (
"github.com/golang/protobuf/proto"
cb "github.com/mcc-github/blockchain-protos-go/common"
ab "github.com/mcc-github/blockchain-protos-go/orderer"
"github.com/mcc-github/blockchain/protoutil"
)
var closedChan chan struct{}
func init() {
closedChan = make(chan struct{})
close(closedChan)
}
type NotFoundErrorIterator struct{}
func (nfei *NotFoundErrorIterator) Next() (*cb.Block, cb.Status) {
return nil, cb.Status_NOT_FOUND
}
func (nfei *NotFoundErrorIterator) ReadyChan() <-chan struct{} {
return closedChan
}
func (nfei *NotFoundErrorIterator) Close() {}
func CreateNextBlock(rl Reader, messages []*cb.Envelope) *cb.Block |
func GetBlock(rl Reader, index uint64) *cb.Block {
iterator, _ := rl.Iterator(&ab.SeekPosition{
Type: &ab.SeekPosition_Specified{
Specified: &ab.SeekSpecified{Number: index},
},
})
if iterator == nil {
return nil
}
defer iterator.Close()
block, status := iterator.Next()
if status != cb.Status_SUCCESS {
return nil
}
return block
}
| {
var nextBlockNumber uint64
var previousBlockHash []byte
if rl.Height() > 0 {
it, _ := rl.Iterator(&ab.SeekPosition{
Type: &ab.SeekPosition_Newest{
Newest: &ab.SeekNewest{},
},
})
block, status := it.Next()
if status != cb.Status_SUCCESS {
panic("Error seeking to newest block for chain with non-zero height")
}
nextBlockNumber = block.Header.Number + 1
previousBlockHash = protoutil.BlockHeaderHash(block.Header)
}
data := &cb.BlockData{
Data: make([][]byte, len(messages)),
}
var err error
for i, msg := range messages {
data.Data[i], err = proto.Marshal(msg)
if err != nil {
panic(err)
}
}
block := protoutil.NewBlock(nextBlockNumber, previousBlockHash)
block.Header.DataHash = protoutil.BlockDataHash(data)
block.Data = data
return block
} |
labels.go | /*
Kubernetes labels and annotations used in Linkerd's control plane and data plane
Kubernetes configs.
*/
package k8s
import (
"fmt"
"github.com/linkerd/linkerd2/pkg/version"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
)
const (
/*
* Labels
*/
// Prefix is the prefix common to all labels and annotations injected by Linkerd
Prefix = "linkerd.io"
// LinkerdExtensionLabel is a label that helps identifying the namespace
// that contain a Linkerd Extension
LinkerdExtensionLabel = Prefix + "/extension"
// ControllerComponentLabel identifies this object as a component of Linkerd's
// control plane (e.g. web, controller).
ControllerComponentLabel = Prefix + "/control-plane-component"
// ExtensionAPIServerAuthenticationConfigMapName is the name of the ConfigMap where
// authentication data for extension API servers is placed.
ExtensionAPIServerAuthenticationConfigMapName = "extension-apiserver-authentication"
// ExtensionAPIServerAuthenticationRequestHeaderClientCAFileKey is the key that
// contains the value of the "--requestheader-client-ca-file" flag.
ExtensionAPIServerAuthenticationRequestHeaderClientCAFileKey = "requestheader-client-ca-file"
// RequireIDHeader signals to the proxy that a certain identity should be expected
// of the remote peer
RequireIDHeader = "l5d-require-id"
// ControllerNSLabel is injected into mesh-enabled apps, identifying the
// namespace of the Linkerd control plane.
ControllerNSLabel = Prefix + "/control-plane-ns"
// ProxyDeploymentLabel is injected into mesh-enabled apps, identifying the
// deployment that this proxy belongs to.
ProxyDeploymentLabel = Prefix + "/proxy-deployment"
// ProxyReplicationControllerLabel is injected into mesh-enabled apps,
// identifying the ReplicationController that this proxy belongs to.
ProxyReplicationControllerLabel = Prefix + "/proxy-replicationcontroller"
// ProxyReplicaSetLabel is injected into mesh-enabled apps, identifying the
// ReplicaSet that this proxy belongs to.
ProxyReplicaSetLabel = Prefix + "/proxy-replicaset"
// ProxyJobLabel is injected into mesh-enabled apps, identifying the Job that
// this proxy belongs to.
ProxyJobLabel = Prefix + "/proxy-job"
// ProxyDaemonSetLabel is injected into mesh-enabled apps, identifying the
// DaemonSet that this proxy belongs to.
ProxyDaemonSetLabel = Prefix + "/proxy-daemonset"
// ProxyStatefulSetLabel is injected into mesh-enabled apps, identifying the
// StatefulSet that this proxy belongs to.
ProxyStatefulSetLabel = Prefix + "/proxy-statefulset"
// ProxyCronJobLabel is injected into mesh-enabled apps, identifying the
// CronJob that this proxy belongs to.
ProxyCronJobLabel = Prefix + "/proxy-cronjob"
// WorkloadNamespaceLabel is injected into mesh-enabled apps, identifying the
// Namespace that this proxy belongs to.
WorkloadNamespaceLabel = Prefix + "/workload-ns"
// Enabled is used by annotations whose valid values include "enabled".
Enabled = "enabled"
// Disabled is used by annotations whose valid values include "disabled".
Disabled = "disabled"
/*
* Annotations
*/
// CreatedByAnnotation indicates the source of the injected data plane
// (e.g. linkerd/cli v2.0.0).
CreatedByAnnotation = Prefix + "/created-by"
// ProxyVersionAnnotation indicates the version of the injected data plane
// (e.g. v0.1.3).
ProxyVersionAnnotation = Prefix + "/proxy-version"
// ProxyInjectAnnotation controls whether or not a pod should be injected
// when set on a pod spec. When set on a namespace spec, it applies to all
// pods in the namespace. Supported values are Enabled or Disabled
ProxyInjectAnnotation = Prefix + "/inject"
// ProxyInjectEnabled is assigned to the ProxyInjectAnnotation annotation to
// enable injection for a pod or namespace.
ProxyInjectEnabled = Enabled
// ProxyInjectIngress is assigned to the ProxyInjectAnnotation annotation to
// enable injection in ingress mode for a pod.
ProxyInjectIngress = "ingress"
// ProxyInjectDisabled is assigned to the ProxyInjectAnnotation annotation to
// disable injection for a pod or namespace.
ProxyInjectDisabled = Disabled
// IdentityModeAnnotation controls how a pod participates
// in service identity.
IdentityModeAnnotation = Prefix + "/identity-mode"
/*
* Proxy config annotations
*/
// ProxyConfigAnnotationsPrefix is the prefix of all config-related annotations
ProxyConfigAnnotationsPrefix = "config.linkerd.io"
// ProxyConfigAnnotationsPrefixAlpha is the prefix of newly released config-related annotations
ProxyConfigAnnotationsPrefixAlpha = "config.alpha.linkerd.io"
// ProxyImageAnnotation can be used to override the proxyImage config.
ProxyImageAnnotation = ProxyConfigAnnotationsPrefix + "/proxy-image"
// ProxyImagePullPolicyAnnotation can be used to override the
// proxyImagePullPolicy and proxyInitImagePullPolicy configs.
ProxyImagePullPolicyAnnotation = ProxyConfigAnnotationsPrefix + "/image-pull-policy"
// ProxyInitImageAnnotation can be used to override the proxyInitImage
// config.
ProxyInitImageAnnotation = ProxyConfigAnnotationsPrefix + "/init-image"
// ProxyInitImageVersionAnnotation can be used to override the proxy-init image version
ProxyInitImageVersionAnnotation = ProxyConfigAnnotationsPrefix + "/init-image-version"
// DebugImageAnnotation can be used to override the debugImage config.
DebugImageAnnotation = ProxyConfigAnnotationsPrefix + "/debug-image"
// DebugImageVersionAnnotation can be used to override the debugImageVersion config.
DebugImageVersionAnnotation = ProxyConfigAnnotationsPrefix + "/debug-image-version"
// DebugImagePullPolicyAnnotation can be used to override the debugImagePullPolicy config.
DebugImagePullPolicyAnnotation = ProxyConfigAnnotationsPrefix + "/debug-image-pull-policy"
// ProxyControlPortAnnotation can be used to override the controlPort config.
ProxyControlPortAnnotation = ProxyConfigAnnotationsPrefix + "/control-port"
// ProxyIgnoreInboundPortsAnnotation can be used to override the
// ignoreInboundPorts config.
ProxyIgnoreInboundPortsAnnotation = ProxyConfigAnnotationsPrefix + "/skip-inbound-ports"
// ProxyOpaquePortsAnnotation can be used to override the opaquePorts
// config.
ProxyOpaquePortsAnnotation = ProxyConfigAnnotationsPrefix + "/opaque-ports"
// ProxyIgnoreOutboundPortsAnnotation can be used to override the
// ignoreOutboundPorts config.
ProxyIgnoreOutboundPortsAnnotation = ProxyConfigAnnotationsPrefix + "/skip-outbound-ports"
// ProxySkipSubnetsAnnotation can be used to override the skipSubnets config
ProxySkipSubnetsAnnotation = ProxyConfigAnnotationsPrefix + "/skip-subnets"
// ProxyInboundPortAnnotation can be used to override the inboundPort config.
ProxyInboundPortAnnotation = ProxyConfigAnnotationsPrefix + "/inbound-port"
// ProxyAdminPortAnnotation can be used to override the adminPort config.
ProxyAdminPortAnnotation = ProxyConfigAnnotationsPrefix + "/admin-port"
// ProxyOutboundPortAnnotation can be used to override the outboundPort
// config.
ProxyOutboundPortAnnotation = ProxyConfigAnnotationsPrefix + "/outbound-port"
// ProxyPodInboundPortsAnnotation can be used to set a comma-separated
// list of (non-proxy) container ports exposed by the pod spec. Useful
// when other mutating webhooks inject sidecar containers after the
// proxy injector has run.
ProxyPodInboundPortsAnnotation = ProxyConfigAnnotationsPrefix + "/pod-inbound-ports"
// ProxyCPURequestAnnotation can be used to override the requestCPU config.
ProxyCPURequestAnnotation = ProxyConfigAnnotationsPrefix + "/proxy-cpu-request"
// ProxyMemoryRequestAnnotation can be used to override the
// requestMemoryConfig.
ProxyMemoryRequestAnnotation = ProxyConfigAnnotationsPrefix + "/proxy-memory-request"
// ProxyEphemeralStorageRequestAnnotation can be used to override the requestEphemeralStorage config.
ProxyEphemeralStorageRequestAnnotation = ProxyConfigAnnotationsPrefix + "/proxy-ephemeral-storage-request"
// ProxyCPULimitAnnotation can be used to override the limitCPU config.
ProxyCPULimitAnnotation = ProxyConfigAnnotationsPrefix + "/proxy-cpu-limit"
// ProxyMemoryLimitAnnotation can be used to override the limitMemory config.
ProxyMemoryLimitAnnotation = ProxyConfigAnnotationsPrefix + "/proxy-memory-limit"
// ProxyEphemeralStorageLimitAnnotation can be used to override the limitEphemeralStorage config.
ProxyEphemeralStorageLimitAnnotation = ProxyConfigAnnotationsPrefix + "/proxy-ephemeral-storage-limit"
// ProxyUIDAnnotation can be used to override the UID config.
ProxyUIDAnnotation = ProxyConfigAnnotationsPrefix + "/proxy-uid"
// ProxyLogLevelAnnotation can be used to override the log level config.
ProxyLogLevelAnnotation = ProxyConfigAnnotationsPrefix + "/proxy-log-level"
// ProxyLogFormatAnnotation can be used to override the log format config.
ProxyLogFormatAnnotation = ProxyConfigAnnotationsPrefix + "/proxy-log-format"
// ProxyEnableExternalProfilesAnnotation can be used to override the
// disableExternalProfilesAnnotation config.
ProxyEnableExternalProfilesAnnotation = ProxyConfigAnnotationsPrefix + "/enable-external-profiles"
// ProxyVersionOverrideAnnotation can be used to override the proxy version config.
ProxyVersionOverrideAnnotation = ProxyConfigAnnotationsPrefix + "/proxy-version"
// ProxyRequireIdentityOnInboundPortsAnnotation can be used to configure the proxy
// to always require identity on inbound ports
ProxyRequireIdentityOnInboundPortsAnnotation = ProxyConfigAnnotationsPrefix + "/proxy-require-identity-inbound-ports"
// ProxyOutboundConnectTimeout can be used to configure the outbound TCP connection
// timeout in the proxy
ProxyOutboundConnectTimeout = ProxyConfigAnnotationsPrefix + "/proxy-outbound-connect-timeout"
// ProxyInboundConnectTimeout can be used to configure the inbound TCP connection
// timeout in the proxy
ProxyInboundConnectTimeout = ProxyConfigAnnotationsPrefix + "/proxy-inbound-connect-timeout"
// ProxyEnableGatewayAnnotation can be used to configure the proxy
// to operate as a gateway, routing requests that target the inbound router.
ProxyEnableGatewayAnnotation = ProxyConfigAnnotationsPrefix + "/enable-gateway"
// ProxyDisableIdentityAnnotation can be used to disable identity on the injected proxy.
ProxyDisableIdentityAnnotation = ProxyConfigAnnotationsPrefix + "/disable-identity"
// ProxyEnableDebugAnnotation is set to true if the debug container is
// injected.
ProxyEnableDebugAnnotation = ProxyConfigAnnotationsPrefix + "/enable-debug-sidecar"
// CloseWaitTimeoutAnnotation configures nf_conntrack_tcp_timeout_close_wait.
CloseWaitTimeoutAnnotation = ProxyConfigAnnotationsPrefix + "/close-wait-timeout"
// ProxyWaitBeforeExitSecondsAnnotation makes the proxy container to wait for the given period before exiting
// after the Pod entered the Terminating state. Must be smaller than terminationGracePeriodSeconds
// configured for the Pod
ProxyWaitBeforeExitSecondsAnnotation = ProxyConfigAnnotationsPrefixAlpha + "/proxy-wait-before-exit-seconds"
// ProxyAwait can be used to force the application to wait for the proxy
// to be ready.
ProxyAwait = ProxyConfigAnnotationsPrefix + "/proxy-await"
// ProxyDefaultInboundPolicyAnnotation is used to configure the default
// inbound policy of the proxy
ProxyDefaultInboundPolicyAnnotation = ProxyConfigAnnotationsPrefix + "/default-inbound-policy"
// IdentityModeDefault is assigned to IdentityModeAnnotation to
// use the control plane's default identity scheme.
IdentityModeDefault = "default"
// IdentityModeDisabled is assigned to IdentityModeAnnotation to
// disable the proxy from participating in automatic identity.
IdentityModeDisabled = Disabled
// AllUnauthenticated allows all unathenticated connections.
AllUnauthenticated = "all-unauthenticated"
// AllAuthenticated allows all authenticated connections.
AllAuthenticated = "all-authenticated"
// ClusterUnauthenticated allows all unauthenticated connections from
// within the cluster.
ClusterUnauthenticated = "cluster-unauthenticated"
// ClusterAuthenticated allows all authenticated connections from within
// the cluster.
ClusterAuthenticated = "cluster-authenticated"
// Deny denies all connections.
Deny = "deny"
/*
* Component Names
*/
// ConfigConfigMapName is the name of the ConfigMap containing the linkerd controller configuration.
ConfigConfigMapName = "linkerd-config"
// DebugContainerName is the name of the default linkerd debug container
DebugContainerName = "linkerd-debug"
// DebugSidecarImage is the image name of the default linkerd debug container
DebugSidecarImage = "cr.l5d.io/linkerd/debug"
// InitContainerName is the name assigned to the injected init container.
InitContainerName = "linkerd-init"
// InitXtablesLockVolumeMountName is the name of the volumeMount used by proxy-init
// to handle iptables-legacy
InitXtablesLockVolumeMountName = "linkerd-proxy-init-xtables-lock"
// LinkerdTokenVolumeMountName is the name of the volumeMount used for
// the serviceAccount token
LinkerdTokenVolumeMountName = "linkerd-identity-token"
// ProxyContainerName is the name assigned to the injected proxy container.
ProxyContainerName = "linkerd-proxy"
// IdentityEndEntityVolumeName is the name assigned the temporary end-entity
// volume mounted into each proxy to store identity credentials.
IdentityEndEntityVolumeName = "linkerd-identity-end-entity"
// IdentityIssuerSecretName is the name of the Secret that stores issuer credentials.
IdentityIssuerSecretName = "linkerd-identity-issuer"
// IdentityIssuerSchemeLinkerd is the issuer secret scheme used by linkerd
IdentityIssuerSchemeLinkerd = "linkerd.io/tls"
// IdentityIssuerKeyName is the issuer's private key file.
IdentityIssuerKeyName = "key.pem"
// IdentityIssuerCrtName is the issuer's certificate file.
IdentityIssuerCrtName = "crt.pem"
// IdentityIssuerTrustAnchorsNameExternal is the issuer's certificate file (when using cert-manager).
IdentityIssuerTrustAnchorsNameExternal = "ca.crt"
// ProxyPortName is the name of the Linkerd Proxy's proxy port.
ProxyPortName = "linkerd-proxy"
// ProxyAdminPortName is the name of the Linkerd Proxy's metrics port.
ProxyAdminPortName = "linkerd-admin"
// ProxyInjectorWebhookServiceName is the name of the mutating webhook service
ProxyInjectorWebhookServiceName = "linkerd-proxy-injector"
// ProxyInjectorWebhookConfigName is the name of the mutating webhook configuration
ProxyInjectorWebhookConfigName = ProxyInjectorWebhookServiceName + "-webhook-config"
// SPValidatorWebhookServiceName is the name of the validating webhook service
SPValidatorWebhookServiceName = "linkerd-sp-validator"
// SPValidatorWebhookConfigName is the name of the validating webhook configuration
SPValidatorWebhookConfigName = SPValidatorWebhookServiceName + "-webhook-config"
// PolicyValidatorWebhookConfigName is the name of the validating webhook configuration
PolicyValidatorWebhookConfigName = "linkerd-policy-validator-webhook-config"
// AdmissionWebhookLabel indicates whether admission webhooks are enabled for a namespace
AdmissionWebhookLabel = ProxyConfigAnnotationsPrefix + "/admission-webhooks"
/*
* Mount paths
*/
// MountPathBase is the base directory of the mount path.
MountPathBase = "/var/run/linkerd"
// MountPathTrustRootsBase is the base directory of the trust roots.
MountPathTrustRootsBase = MountPathBase + "/identity/trust-roots"
// MountPathTrustRootsPEM is the path at which the trust bundle is mounted.
MountPathTrustRootsPEM = MountPathTrustRootsBase + "/ca-bundle.crt"
// MountPathServiceAccount is the default path where Kubernetes stores
// the service account token
MountPathServiceAccount = "/var/run/secrets/kubernetes.io/serviceaccount"
// MountPathValuesConfig is the path at which the values config file is mounted.
MountPathValuesConfig = MountPathBase + "/config/values"
// MountPathTLSBase is the path at which the TLS cert and key PEM files are mounted
MountPathTLSBase = MountPathBase + "/tls"
// MountPathTLSKeyPEM is the path at which the TLS key PEM file is mounted.
MountPathTLSKeyPEM = MountPathTLSBase + "/tls.key"
// MountPathTLSCrtPEM is the path at which the TLS cert PEM file is mounted.
MountPathTLSCrtPEM = MountPathTLSBase + "/tls.crt"
/*
* Service mirror constants
*/
// SvcMirrorPrefix is the prefix common to all labels and annotations
// and types used by the service mirror component
SvcMirrorPrefix = "mirror.linkerd.io"
// MirrorSecretType is the type of secret that is supposed to contain
// the access information for remote clusters.
MirrorSecretType = SvcMirrorPrefix + "/remote-kubeconfig"
// DefaultExportedServiceSelector is the default label selector for exported
// services.
DefaultExportedServiceSelector = SvcMirrorPrefix + "/exported"
// MirroredResourceLabel indicates that this resource is the result
// of a mirroring operation (can be a namespace or a service)
MirroredResourceLabel = SvcMirrorPrefix + "/mirrored-service"
// MirroredGatewayLabel indicates that this is a mirrored gateway
MirroredGatewayLabel = SvcMirrorPrefix + "/mirrored-gateway"
// MirroredHeadlessSvcNameLabel indicates the root headless service for
// mirrored headless hosts.
MirroredHeadlessSvcNameLabel = SvcMirrorPrefix + "/headless-mirror-svc-name"
// RemoteClusterNameLabel put on a local mirrored service, it
// allows us to associate a mirrored service with a remote cluster
RemoteClusterNameLabel = SvcMirrorPrefix + "/cluster-name"
// RemoteResourceVersionAnnotation is the last observed remote resource
// version of a mirrored resource. Useful when doing updates
RemoteResourceVersionAnnotation = SvcMirrorPrefix + "/remote-resource-version"
// RemoteServiceFqName is the fully qualified name of the mirrored service
// on the remote cluster
RemoteServiceFqName = SvcMirrorPrefix + "/remote-svc-fq-name"
// RemoteGatewayIdentity follows the same kind of logic as RemoteGatewayNameLabel
RemoteGatewayIdentity = SvcMirrorPrefix + "/remote-gateway-identity"
// GatewayIdentity can be found on the remote gateway service
GatewayIdentity = SvcMirrorPrefix + "/gateway-identity"
// GatewayProbePeriod the interval at which the health of the gateway should be probed
GatewayProbePeriod = SvcMirrorPrefix + "/probe-period"
// GatewayProbePath the path at which the health of the gateway should be probed
GatewayProbePath = SvcMirrorPrefix + "/probe-path"
// ConfigKeyName is the key in the secret that stores the kubeconfig needed to connect
// to a remote cluster
ConfigKeyName = "kubeconfig"
// GatewayPortName is the name of the incoming port of the gateway
GatewayPortName = "mc-gateway"
// ProbePortName is the name of the probe port of the gateway
ProbePortName = "mc-probe"
)
// CreatedByAnnotationValue returns the value associated with
// CreatedByAnnotation.
func CreatedByAnnotationValue() string {
return fmt.Sprintf("linkerd/cli %s", version.Version)
}
// GetServiceAccountAndNS returns the pod's serviceaccount and namespace.
func GetServiceAccountAndNS(pod *corev1.Pod) (sa string, ns string) {
sa = pod.Spec.ServiceAccountName
if sa == "" {
sa = "default"
}
ns = pod.GetNamespace()
if ns == "" |
return
}
// GetPodLabels returns the set of prometheus owner labels for a given pod
func GetPodLabels(ownerKind, ownerName string, pod *corev1.Pod) map[string]string {
labels := map[string]string{"pod": pod.Name}
l5dLabel := KindToL5DLabel(ownerKind)
labels[l5dLabel] = ownerName
labels["serviceaccount"], _ = GetServiceAccountAndNS(pod)
if controllerNS := pod.Labels[ControllerNSLabel]; controllerNS != "" {
labels["control_plane_ns"] = controllerNS
}
if pth := pod.Labels[appsv1.DefaultDeploymentUniqueLabelKey]; pth != "" {
labels["pod_template_hash"] = pth
}
return labels
}
// IsMeshed returns whether a given Pod is in a given controller's service mesh.
func IsMeshed(pod *corev1.Pod, controllerNS string) bool {
return pod.Labels[ControllerNSLabel] == controllerNS
}
| {
ns = "default"
} |
zz_generated.deepcopy.go | // +build !ignore_autogenerated
/*
Copyright 2020 The Kubernetes 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.
*/
// Code generated by controller-gen. DO NOT EDIT.
package v1alpha3
import (
"k8s.io/api/core/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
"sigs.k8s.io/cluster-api/errors"
)
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PacketCluster) DeepCopyInto(out *PacketCluster) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
out.Spec = in.Spec
out.Status = in.Status
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PacketCluster.
func (in *PacketCluster) DeepCopy() *PacketCluster {
if in == nil {
return nil
}
out := new(PacketCluster)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *PacketCluster) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PacketClusterList) DeepCopyInto(out *PacketClusterList) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]PacketCluster, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PacketClusterList.
func (in *PacketClusterList) DeepCopy() *PacketClusterList {
if in == nil {
return nil
}
out := new(PacketClusterList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *PacketClusterList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PacketClusterSpec) DeepCopyInto(out *PacketClusterSpec) {
*out = *in
out.ControlPlaneEndpoint = in.ControlPlaneEndpoint
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PacketClusterSpec.
func (in *PacketClusterSpec) DeepCopy() *PacketClusterSpec {
if in == nil {
return nil
}
out := new(PacketClusterSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PacketClusterStatus) DeepCopyInto(out *PacketClusterStatus) {
*out = *in
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PacketClusterStatus.
func (in *PacketClusterStatus) DeepCopy() *PacketClusterStatus {
if in == nil {
return nil
}
out := new(PacketClusterStatus)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PacketMachine) DeepCopyInto(out *PacketMachine) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
in.Status.DeepCopyInto(&out.Status)
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PacketMachine.
func (in *PacketMachine) DeepCopy() *PacketMachine {
if in == nil {
return nil
}
out := new(PacketMachine)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *PacketMachine) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil |
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PacketMachineList) DeepCopyInto(out *PacketMachineList) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]PacketMachine, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PacketMachineList.
func (in *PacketMachineList) DeepCopy() *PacketMachineList {
if in == nil {
return nil
}
out := new(PacketMachineList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *PacketMachineList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PacketMachineSpec) DeepCopyInto(out *PacketMachineSpec) {
*out = *in
if in.SshKeys != nil {
in, out := &in.SshKeys, &out.SshKeys
*out = make([]string, len(*in))
copy(*out, *in)
}
if in.ProviderID != nil {
in, out := &in.ProviderID, &out.ProviderID
*out = new(string)
**out = **in
}
if in.Tags != nil {
in, out := &in.Tags, &out.Tags
*out = make(Tags, len(*in))
copy(*out, *in)
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PacketMachineSpec.
func (in *PacketMachineSpec) DeepCopy() *PacketMachineSpec {
if in == nil {
return nil
}
out := new(PacketMachineSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PacketMachineStatus) DeepCopyInto(out *PacketMachineStatus) {
*out = *in
if in.Addresses != nil {
in, out := &in.Addresses, &out.Addresses
*out = make([]v1.NodeAddress, len(*in))
copy(*out, *in)
}
if in.InstanceStatus != nil {
in, out := &in.InstanceStatus, &out.InstanceStatus
*out = new(PacketResourceStatus)
**out = **in
}
if in.ErrorReason != nil {
in, out := &in.ErrorReason, &out.ErrorReason
*out = new(errors.MachineStatusError)
**out = **in
}
if in.ErrorMessage != nil {
in, out := &in.ErrorMessage, &out.ErrorMessage
*out = new(string)
**out = **in
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PacketMachineStatus.
func (in *PacketMachineStatus) DeepCopy() *PacketMachineStatus {
if in == nil {
return nil
}
out := new(PacketMachineStatus)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PacketMachineTemplate) DeepCopyInto(out *PacketMachineTemplate) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PacketMachineTemplate.
func (in *PacketMachineTemplate) DeepCopy() *PacketMachineTemplate {
if in == nil {
return nil
}
out := new(PacketMachineTemplate)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *PacketMachineTemplate) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PacketMachineTemplateList) DeepCopyInto(out *PacketMachineTemplateList) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]PacketMachineTemplate, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PacketMachineTemplateList.
func (in *PacketMachineTemplateList) DeepCopy() *PacketMachineTemplateList {
if in == nil {
return nil
}
out := new(PacketMachineTemplateList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *PacketMachineTemplateList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PacketMachineTemplateResource) DeepCopyInto(out *PacketMachineTemplateResource) {
*out = *in
in.Spec.DeepCopyInto(&out.Spec)
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PacketMachineTemplateResource.
func (in *PacketMachineTemplateResource) DeepCopy() *PacketMachineTemplateResource {
if in == nil {
return nil
}
out := new(PacketMachineTemplateResource)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PacketMachineTemplateSpec) DeepCopyInto(out *PacketMachineTemplateSpec) {
*out = *in
in.Template.DeepCopyInto(&out.Template)
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PacketMachineTemplateSpec.
func (in *PacketMachineTemplateSpec) DeepCopy() *PacketMachineTemplateSpec {
if in == nil {
return nil
}
out := new(PacketMachineTemplateSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in Tags) DeepCopyInto(out *Tags) {
{
in := &in
*out = make(Tags, len(*in))
copy(*out, *in)
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Tags.
func (in Tags) DeepCopy() Tags {
if in == nil {
return nil
}
out := new(Tags)
in.DeepCopyInto(out)
return *out
}
| {
return c
} |
run.go | // Copyright 2020 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0
package solo
import (
"fmt"
"github.com/iotaledger/goshimmer/dapps/waspconn/packages/waspconn"
"github.com/iotaledger/wasp/packages/coretypes"
"github.com/iotaledger/wasp/packages/hashing"
"github.com/iotaledger/wasp/packages/kv/dict"
"github.com/iotaledger/wasp/packages/sctransaction"
"github.com/iotaledger/wasp/packages/state"
"github.com/iotaledger/wasp/packages/vm"
"github.com/iotaledger/wasp/packages/vm/runvm"
"github.com/stretchr/testify/require"
"strings"
"sync"
)
func (ch *Chain) runBatch(batch []vm.RequestRefWithFreeTokens, trace string) (dict.Dict, error) {
ch.Log.Debugf("runBatch ('%s')", trace)
ch.runVMMutex.Lock()
defer ch.runVMMutex.Unlock()
// solidify arguments
for _, reqRef := range batch {
if ok, err := reqRef.RequestSection().SolidifyArgs(ch.Env.registry); err != nil || !ok {
return nil, fmt.Errorf("solo inconsistency: failed to solidify request args")
}
}
task := &vm.VMTask{
Processors: ch.proc,
ChainID: ch.ChainID,
Color: ch.ChainColor,
Entropy: hashing.RandomHash(nil),
ValidatorFeeTarget: ch.ValidatorFeeTarget,
Balances: waspconn.OutputsToBalances(ch.Env.utxoDB.GetAddressOutputs(ch.ChainAddress)),
Requests: batch,
Timestamp: ch.Env.LogicalTime().UnixNano(),
VirtualState: ch.State.Clone(),
Log: ch.Log,
}
var err error
var wg sync.WaitGroup
var callRes dict.Dict
var callErr error
task.OnFinish = func(callResult dict.Dict, callError error, err error) {
require.NoError(ch.Env.T, err)
callRes = callResult
callErr = callError
wg.Done()
}
wg.Add(1)
err = runvm.RunComputationsAsync(task)
require.NoError(ch.Env.T, err)
wg.Wait()
task.ResultTransaction.Sign(ch.ChainSigScheme)
ch.settleStateTransition(task.VirtualState, task.ResultBlock, task.ResultTransaction)
return callRes, callErr
}
func (ch *Chain) settleStateTransition(newState state.VirtualState, block state.Block, stateTx *sctransaction.Transaction) {
err := ch.Env.utxoDB.AddTransaction(stateTx.Transaction)
require.NoError(ch.Env.T, err)
err = newState.ApplyBlock(block)
require.NoError(ch.Env.T, err)
err = newState.CommitToDb(block)
require.NoError(ch.Env.T, err)
prevBlockIndex := ch.StateTx.MustState().BlockIndex()
ch.StateTx = stateTx
ch.State = newState
ch.Log.Infof("state transition #%d --> #%d. Requests in the block: %d. Posted: %d",
prevBlockIndex, ch.State.BlockIndex(), len(block.RequestIDs()), len(ch.StateTx.Requests()))
ch.Log.Debugf("Batch processed: %s", batchShortStr(block.RequestIDs()))
ch.Env.ClockStep()
// dispatch requests among chains
ch.Env.glbMutex.Lock()
defer ch.Env.glbMutex.Unlock()
reqRefByChain := make(map[coretypes.ChainID][]sctransaction.RequestRef)
for i, rsect := range ch.StateTx.Requests() {
chid := rsect.Target().ChainID()
_, ok := reqRefByChain[chid]
if !ok {
reqRefByChain[chid] = make([]sctransaction.RequestRef, 0)
}
reqRefByChain[chid] = append(reqRefByChain[chid], sctransaction.RequestRef{
Tx: stateTx,
Index: uint16(i),
})
}
for chid, reqs := range reqRefByChain {
chain, ok := ch.Env.chains[chid]
if !ok {
ch.Log.Infof("dispatching requests. Unknown chain: %s", chid.String())
continue
}
chain.chPosted.Add(len(reqs))
for _, reqRef := range reqs {
chain.chInRequest <- reqRef
}
}
}
func | (reqIds []*coretypes.RequestID) string {
ret := make([]string, len(reqIds))
for i, r := range reqIds {
ret[i] = r.Short()
}
return fmt.Sprintf("[%s]", strings.Join(ret, ","))
}
| batchShortStr |
main.go | // Copyright 2022 Google LLC
//
// 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 cloud.google.com/go/internal/gapicgen/gensnippets. DO NOT EDIT.
// [START compute_v1_generated_Projects_MoveInstance_sync]
package main
import (
"context"
compute "cloud.google.com/go/compute/apiv1"
computepb "google.golang.org/genproto/googleapis/cloud/compute/v1"
)
func | () {
ctx := context.Background()
c, err := compute.NewProjectsRESTClient(ctx)
if err != nil {
// TODO: Handle error.
}
defer c.Close()
req := &computepb.MoveInstanceProjectRequest{
// TODO: Fill request struct fields.
// See https://pkg.go.dev/google.golang.org/genproto/googleapis/cloud/compute/v1#MoveInstanceProjectRequest.
}
resp, err := c.MoveInstance(ctx, req)
if err != nil {
// TODO: Handle error.
}
// TODO: Use resp.
_ = resp
}
// [END compute_v1_generated_Projects_MoveInstance_sync]
| main |
employee.go | package controllers
import (
"fmt"
"github.com/labstack/echo"
"net/http"
"qure/models"
)
func | (c echo.Context) error {
requested_id := c.Param("id")
result := models.GetEmployeeDB(requested_id)
return c.JSON(http.StatusOK, result)
}
func GetEmployees(c echo.Context) error {
result := models.GetEmployeesDB()
// println("foo")
return c.JSON(http.StatusOK, result)
}
func PostEmployee(c echo.Context) error {
emp := models.Employee{}
if err := c.Bind(&emp); err != nil {
return err
}
result := models.InsertEmployeeDB(emp)
return c.JSON(http.StatusCreated, result)
}
func DeleteEmployee(c echo.Context) error {
requested_id := c.Param("id")
fmt.Println(requested_id)
_ = models.DeleteEmployeeDB(requested_id)
return c.JSON(http.StatusOK, "Deleted")
} | GetEmployee |
skpaint_overview.rs | use crate::{resources, DrawingDriver};
use skia_safe::{
corner_path_effect, dash_path_effect, discrete_path_effect, gradient_shader,
line_2d_path_effect, paint, path_1d_path_effect, path_2d_path_effect, perlin_noise_shader,
scalar, table_color_filter, AutoCanvasRestore, BlendMode, BlurStyle, Canvas, Color,
ColorFilters, Font, MaskFilter, Matrix, Paint, Path, PathEffect, Point, Rect, Shaders,
TextBlob, TileMode, Typeface,
};
use std::path;
pub fn draw<Driver: DrawingDriver>(path: &path::Path) {
let path = &path.join("SkPaint-Overview");
Driver::draw_image_256(path, "01-three-paints", draw_three_paints);
Driver::draw_image_256(path, "02-fill-and-stroke", draw_fill_and_stroke);
Driver::draw_image_256(path, "03-gradient", draw_gradient);
Driver::draw_image((576, 640), path, "04-transfer-modes", draw_transfer_modes);
Driver::draw_image_256(path, "05-bitmap-shader", draw_bitmap_shader);
Driver::draw_image_256(
path,
"06-radial-gradient-shader",
draw_radial_gradient_shader,
);
Driver::draw_image_256(
path,
"07-two-point-conical-shader",
draw_two_point_conical_shader,
);
Driver::draw_image_256(path, "08-sweep-gradient-shader", draw_sweep_gradient_shader);
Driver::draw_image_256(
path,
"09-fractal-perlin-noise-shader",
draw_fractal_perlin_noise_shader,
);
Driver::draw_image_256(
path,
"10-turbulence-perlin-noise-shader",
draw_turbulence_perlin_noise_shader,
);
Driver::draw_image_256(path, "11-compose-shader", draw_compose_shader);
Driver::draw_image_256(path, "12-mask-filter", draw_mask_filter);
Driver::draw_image((256, 128), path, "13-color-filter", draw_color_filter);
Driver::draw_image_256(path, "14-table-color-filter", draw_color_table_color_filter);
Driver::draw_image_256(path, "15-path-2d-effect", draw_path_2d_effect);
Driver::draw_image_256(path, "16-line-2d-effect", draw_line_2d_effect);
Driver::draw_image_256(path, "17-path-1d-effect", draw_path_1d_effect);
Driver::draw_image_256(path, "18-corner-path-effect", draw_corner_path_effect);
Driver::draw_image_256(path, "19-dash-path-effect", draw_dash_path_effect);
Driver::draw_image_256(path, "20-discrete-path-effect", draw_discrete_path_effect);
Driver::draw_image_256(path, "21-compose-path-effect", draw_compose_path_effect);
Driver::draw_image_256(path, "22-sum-path-effect", draw_sum_path_effect);
}
fn draw_three_paints(canvas: &mut Canvas) {
let (paint1, paint2, paint3) = (
&mut Paint::default(),
&mut Paint::default(),
&mut Paint::default(),
);
paint1
.set_anti_alias(true)
.set_color(Color::from_rgb(255, 0, 0))
.set_style(paint::Style::Fill);
paint2
.set_anti_alias(true)
.set_color(Color::from_rgb(0, 136, 0))
.set_style(paint::Style::Stroke)
.set_stroke_width(3.0);
paint3
.set_anti_alias(true)
.set_color(Color::from_rgb(136, 136, 136));
let blob1 = TextBlob::from_str(
"Skia!",
&Font::from_typeface_with_params(Typeface::default(), 64.0, 1.0, 0.0),
)
.unwrap();
let blob2 = TextBlob::from_str(
"Skia!",
&Font::from_typeface_with_params(Typeface::default(), 64.0, 1.5, 0.0),
)
.unwrap();
canvas
.clear(Color::WHITE)
.draw_text_blob(&blob1, (20.0, 64.0), paint1)
.draw_text_blob(&blob1, (20.0, 144.0), paint2)
.draw_text_blob(&blob2, (20.0, 224.0), paint3);
}
fn draw_fill_and_stroke(canvas: &mut Canvas) {
let fill_paint = &mut Paint::default();
let stroke_paint = &mut Paint::default();
stroke_paint
.set_style(paint::Style::Stroke)
.set_stroke_width(3.0);
canvas
.draw_rect(Rect::from_point_and_size((10, 10), (60, 20)), fill_paint)
.draw_rect(Rect::from_point_and_size((80, 10), (60, 20)), stroke_paint);
stroke_paint.set_stroke_width(5.0);
canvas.draw_oval(Rect::from_point_and_size((150, 10), (60, 20)), stroke_paint);
let blob = TextBlob::from_str("SKIA", &Font::from_typeface(Typeface::default(), 80.0)).unwrap();
fill_paint.set_color(Color::from_argb(0xFF, 0xFF, 0x00, 0x00));
canvas.draw_text_blob(&blob, (20, 120), fill_paint);
fill_paint.set_color(Color::from_argb(0xFF, 0x00, 0x00, 0xFF));
canvas.draw_text_blob(&blob, (20, 220), fill_paint);
}
fn draw_gradient(canvas: &mut Canvas) {
let points: (Point, Point) = ((0.0, 0.0).into(), (256.0, 256.0).into());
let colors = [Color::BLUE, Color::YELLOW];
let paint = &mut Paint::default();
paint.set_shader(gradient_shader::linear(
points,
colors.as_ref(),
None,
TileMode::Clamp,
None,
None,
));
canvas.draw_paint(paint);
}
fn draw_transfer_modes(canvas: &mut Canvas) {
fn draw_str(c: &mut Canvas, text: &str, x: scalar, y: scalar, font: &Font, paint: &Paint) {
c.draw_text_blob(TextBlob::from_str(text, font).unwrap(), (x, y), paint);
}
let modes = [
BlendMode::Clear,
BlendMode::Src,
BlendMode::Dst,
BlendMode::SrcOver,
BlendMode::DstOver,
BlendMode::SrcIn,
BlendMode::DstIn,
BlendMode::SrcOut,
BlendMode::DstOut,
BlendMode::SrcATop,
BlendMode::DstATop,
BlendMode::Xor,
BlendMode::Plus,
BlendMode::Modulate,
BlendMode::Screen,
BlendMode::Overlay,
BlendMode::Darken,
BlendMode::Lighten,
BlendMode::ColorDodge,
BlendMode::ColorBurn,
BlendMode::HardLight,
BlendMode::SoftLight,
BlendMode::Difference,
BlendMode::Exclusion,
BlendMode::Multiply,
BlendMode::Hue,
BlendMode::Saturation,
BlendMode::Color,
BlendMode::Luminosity,
];
let rect = Rect::from_size((64.0, 64.0));
let (stroke, src, dst) = (
&mut Paint::default(),
&mut Paint::default(),
&mut Paint::default(),
);
stroke.set_style(paint::Style::Stroke);
let font = &Font::from_typeface(Typeface::default(), 24.0);
let src_points: (Point, Point) = ((0.0, 0.0).into(), (64.0, 0.0).into());
let src_colors = [Color::MAGENTA & 0x00_FF_FF_FF, Color::MAGENTA];
src.set_shader(gradient_shader::linear(
src_points,
src_colors.as_ref(),
None,
TileMode::Clamp,
None,
None,
));
let dst_points: (Point, Point) = ((0.0, 0.0).into(), (0.0, 64.0).into());
let dst_colors = [Color::CYAN & 0x00_FF_FF_FF, Color::CYAN];
dst.set_shader(gradient_shader::linear(
dst_points,
dst_colors.as_ref(),
None,
TileMode::Clamp,
None,
None,
));
canvas.clear(Color::WHITE);
let n = modes.len();
let k = (n - 1) / 3 + 1;
assert_eq!(k * 64, 640); // tall enough
for (i, mode) in modes.iter().enumerate() {
let canvas = &mut AutoCanvasRestore::guard(canvas, true);
canvas.translate((192.0 * (i / k) as scalar, 64.0 * (i % k) as scalar));
let desc = mode.name();
draw_str(canvas, desc, 68.0, 30.0, font, &Paint::default());
canvas
.clip_rect(Rect::from_size((64.0, 64.0)), None, None)
.draw_color(Color::LIGHT_GRAY, BlendMode::default())
.save_layer(&Default::default());
canvas.clear(Color::TRANSPARENT).draw_paint(dst);
src.set_blend_mode(*mode);
canvas.draw_paint(src).draw_rect(rect, stroke);
}
}
fn draw_bitmap_shader(canvas: &mut Canvas) {
let image = resources::color_wheel();
canvas.clear(Color::WHITE);
let mut matrix = Matrix::default();
matrix.set_scale((0.75, 0.75), None).pre_rotate(30.0, None);
let paint = &mut Paint::default();
paint.set_shader(image.to_shader((TileMode::Repeat, TileMode::Repeat), &matrix));
canvas.draw_paint(paint);
}
fn draw_radial_gradient_shader(canvas: &mut Canvas) {
let colors = [Color::BLUE, Color::YELLOW];
let mut paint = Paint::default();
paint.set_shader(gradient_shader::radial(
(128.0, 128.0),
180.0,
colors.as_ref(),
None,
TileMode::Clamp,
None,
None,
));
canvas.draw_paint(&paint);
}
fn draw_two_point_conical_shader(canvas: &mut Canvas) {
let colors = [Color::BLUE, Color::YELLOW];
let paint = &mut Paint::default();
paint.set_shader(gradient_shader::two_point_conical(
(128.0, 128.0),
128.0,
(128.0, 16.0),
16.0,
colors.as_ref(),
None,
TileMode::Clamp,
None,
None,
));
canvas.draw_paint(&paint);
}
fn draw_sweep_gradient_shader(canvas: &mut Canvas) {
let colors = [Color::CYAN, Color::MAGENTA, Color::YELLOW, Color::CYAN];
let paint = &mut Paint::default();
paint.set_shader(gradient_shader::sweep(
(128.0, 128.0),
colors.as_ref(),
None,
TileMode::default(),
None,
None,
None,
));
canvas.draw_paint(paint);
}
fn draw_fractal_perlin_noise_shader(canvas: &mut Canvas) {
canvas.clear(Color::WHITE);
let paint = &mut Paint::default();
paint.set_shader(perlin_noise_shader::fractal_noise(
(0.05, 0.05),
4,
0.0,
None,
));
canvas.draw_paint(paint);
}
fn draw_turbulence_perlin_noise_shader(canvas: &mut Canvas) {
canvas.clear(Color::WHITE);
let paint = &mut Paint::default();
paint.set_shader(perlin_noise_shader::turbulence((0.05, 0.05), 4, 0.0, None));
canvas.draw_paint(paint);
}
fn draw_compose_shader(canvas: &mut Canvas) {
let colors = [Color::BLUE, Color::YELLOW];
let paint = &mut Paint::default();
paint.set_shader(Shaders::blend(
BlendMode::Difference,
gradient_shader::radial(
(128.0, 128.0),
180.0,
colors.as_ref(),
None,
TileMode::Clamp,
None,
None,
)
.unwrap(),
perlin_noise_shader::turbulence((0.025, 0.025), 2, 0.0, None).unwrap(),
None,
));
canvas.draw_paint(paint);
}
fn draw_mask_filter(canvas: &mut Canvas) {
// TODO: make BlendMode optional in draw_color.
canvas.draw_color(
Color::from_argb(0xFF, 0xFF, 0xFF, 0xFF),
BlendMode::default(),
);
let paint = &mut Paint::default();
paint.set_mask_filter(MaskFilter::blur(BlurStyle::Normal, 5.0, None));
let blob =
TextBlob::from_str("Skia", &Font::from_typeface(Typeface::default(), 120.0)).unwrap();
canvas.draw_text_blob(blob, (0, 160), paint);
}
fn draw_color_filter(c: &mut Canvas) {
fn | (c: &mut Canvas, (x, y): (scalar, scalar), color_matrix: &[scalar; 20]) {
let paint = &mut Paint::default();
paint.set_color_filter(ColorFilters::matrix_row_major(color_matrix));
let image = &resources::mandrill();
c.draw_image(image, (x, y), Some(paint));
}
c.scale((0.25, 0.25));
let color_matrix_1 = [
0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
1.0, 0.0,
];
f(c, (0.0, 0.0), &color_matrix_1);
let grayscale = [
0.21, 0.72, 0.07, 0.0, 0.0, 0.21, 0.72, 0.07, 0.0, 0.0, 0.21, 0.72, 0.07, 0.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
];
f(c, (512.0, 0.0), &grayscale);
}
fn draw_color_table_color_filter(canvas: &mut Canvas) {
let image = resources::mandrill();
canvas.scale((0.5, 0.5));
let ct = &mut [0u8; 256];
for (i, v) in ct.iter_mut().enumerate() {
let x = (i as i32 - 96) * 255 / 64;
*v = x.max(0).min(255) as _;
}
let mut paint = Paint::default();
paint.set_color_filter(table_color_filter::from_argb(
None,
Some(ct),
Some(ct),
Some(ct),
));
canvas.draw_image(&image, (0, 0), Some(&paint));
}
fn draw_path_2d_effect(canvas: &mut Canvas) {
let scale = 10.0;
let path = &mut Path::default();
let pts: [i8; 28] = [
2, 2, 1, 3, 0, 3, 2, 1, 3, 1, 4, 0, 4, 1, 5, 1, 4, 2, 4, 3, 2, 5, 2, 4, 3, 3, 2, 3,
];
path.move_to((2.0 * scale, 3.0 * scale));
for i in (0..pts.len()).step_by(2) {
path.line_to((
scalar::from(pts[i]) * scale,
scalar::from(pts[i + 1]) * scale,
));
}
path.close();
let matrix = &Matrix::new_scale((4.0 * scale, 4.0 * scale));
let paint = &mut Paint::default();
paint
.set_path_effect(path_2d_path_effect::new(matrix, path))
.set_anti_alias(true);
canvas.clear(Color::WHITE);
let bounds = Rect::new(-4.0 * scale, -4.0 * scale, 256.0, 256.0);
canvas.draw_rect(bounds, paint);
}
fn draw_line_2d_effect(canvas: &mut Canvas) {
let paint = &mut Paint::default();
let lattice = &mut Matrix::default();
lattice.set_scale((8.0, 8.0), None).pre_rotate(30.0, None);
paint
.set_path_effect(line_2d_path_effect::new(0.0, lattice))
.set_anti_alias(true);
let bounds = Rect::from_size((256, 256)).with_outset((8.0, 8.0));
canvas.clear(Color::WHITE);
canvas.draw_rect(bounds, paint);
}
fn draw_path_1d_effect(canvas: &mut Canvas) {
let paint = &mut Paint::default();
let path = &mut Path::default();
path.add_oval(Rect::from_size((16.0, 6.0)), None);
paint
.set_path_effect(path_1d_path_effect::new(
path,
32.0,
0.0,
path_1d_path_effect::Style::Rotate,
))
.set_anti_alias(true);
canvas.clear(Color::WHITE);
canvas.draw_circle((128.0, 128.0), 122.0, paint);
}
fn star() -> Path {
const R: scalar = 115.2;
const C: scalar = 128.0;
let mut path = Path::default();
path.move_to((C + R, C));
for i in 1..8 {
#[allow(clippy::excessive_precision)]
let a = 2.692_793_7 * i as scalar;
path.line_to((C + R * a.cos(), C + R * a.sin()));
}
path.close();
path
}
fn draw_corner_path_effect(canvas: &mut Canvas) {
let paint = &mut Paint::default();
paint
.set_path_effect(corner_path_effect::new(32.0))
.set_style(paint::Style::Stroke)
.set_anti_alias(true);
canvas.clear(Color::WHITE);
canvas.draw_path(&star(), paint);
}
fn draw_dash_path_effect(canvas: &mut Canvas) {
const INTERVALS: [scalar; 4] = [10.0, 5.0, 2.0, 5.0];
let paint = &mut Paint::default();
paint
.set_path_effect(dash_path_effect::new(&INTERVALS, 0.0))
.set_style(paint::Style::Stroke)
.set_stroke_width(2.0)
.set_anti_alias(true);
canvas.clear(Color::WHITE);
canvas.draw_path(&star(), paint);
}
fn draw_discrete_path_effect(canvas: &mut Canvas) {
let paint = &mut Paint::default();
paint
.set_path_effect(discrete_path_effect::new(10.0, 4.0, None))
.set_style(paint::Style::Stroke)
.set_stroke_width(2.0)
.set_anti_alias(true);
canvas.clear(Color::WHITE);
canvas.draw_path(&star(), paint);
}
fn draw_compose_path_effect(canvas: &mut Canvas) {
const INTERVALS: [scalar; 4] = [10.0, 5.0, 2.0, 5.0];
let paint = &mut Paint::default();
paint
.set_path_effect(PathEffect::compose(
dash_path_effect::new(&INTERVALS, 0.0).unwrap(),
discrete_path_effect::new(10.0, 4.0, None).unwrap(),
))
.set_style(paint::Style::Stroke)
.set_stroke_width(2.0)
.set_anti_alias(true);
canvas.clear(Color::WHITE);
canvas.draw_path(&star(), paint);
}
fn draw_sum_path_effect(canvas: &mut Canvas) {
let paint = &mut Paint::default();
paint
.set_path_effect(PathEffect::sum(
discrete_path_effect::new(10.0, 4.0, None).unwrap(),
discrete_path_effect::new(10.0, 4.0, Some(1245)).unwrap(),
))
.set_style(paint::Style::Stroke)
.set_stroke_width(2.0)
.set_anti_alias(true);
canvas.clear(Color::WHITE);
canvas.draw_path(&star(), paint);
}
| f |
tcp_socket.rs | use crate::{
arch::SpinLock,
fs::{
inode::{FileLike, PollStatus},
opened_file::OpenOptions,
},
net::{socket::SockAddr, RecvFromFlags},
user_buffer::UserBuffer,
user_buffer::{UserBufReader, UserBufWriter, UserBufferMut},
};
use crate::{
arch::SpinLockGuard,
result::{Errno, Result},
};
use alloc::{collections::BTreeSet, sync::Arc, vec::Vec};
use core::{cmp::min, convert::TryInto};
use crossbeam::atomic::AtomicCell;
use smoltcp::socket::{SocketRef, TcpSocketBuffer};
use smoltcp::wire::{IpAddress, IpEndpoint, Ipv4Address};
use super::{process_packets, SOCKETS, SOCKET_WAIT_QUEUE};
const BACKLOG_MAX: usize = 8;
static INUSE_ENDPOINTS: SpinLock<BTreeSet<u16>> = SpinLock::new(BTreeSet::new());
/// Looks for an accept'able socket in the backlog.
fn get_ready_backlog_index(
sockets: &mut smoltcp::socket::SocketSet,
backlogs: &[Arc<TcpSocket>],
) -> Option<usize> {
backlogs.iter().position(|sock| {
let smol_socket: SocketRef<'_, smoltcp::socket::TcpSocket> = sockets.get(sock.handle);
smol_socket.may_recv() || smol_socket.may_send()
})
}
pub struct TcpSocket {
handle: smoltcp::socket::SocketHandle,
local_endpoint: AtomicCell<Option<IpEndpoint>>,
backlogs: SpinLock<Vec<Arc<TcpSocket>>>,
num_backlogs: AtomicCell<usize>,
}
impl TcpSocket {
pub fn new() -> Arc<TcpSocket> {
let rx_buffer = TcpSocketBuffer::new(vec![0; 4096]);
let tx_buffer = TcpSocketBuffer::new(vec![0; 4096]);
let inner = smoltcp::socket::TcpSocket::new(rx_buffer, tx_buffer);
let handle = SOCKETS.lock().add(inner);
Arc::new(TcpSocket {
handle,
local_endpoint: AtomicCell::new(None),
backlogs: SpinLock::new(Vec::new()),
num_backlogs: AtomicCell::new(0),
})
}
fn refill_backlog_sockets(
&self,
backlogs: &mut SpinLockGuard<'_, Vec<Arc<TcpSocket>>>,
) -> Result<()> {
let local_endpoint = match self.local_endpoint.load() {
Some(local_endpoint) => local_endpoint,
None => return Err(Errno::EINVAL.into()),
};
for _ in 0..(self.num_backlogs.load() - backlogs.len()) {
let socket = TcpSocket::new();
SOCKETS
.lock()
.get::<smoltcp::socket::TcpSocket>(socket.handle)
.listen(local_endpoint)?;
backlogs.push(socket);
}
Ok(())
}
}
impl FileLike for TcpSocket {
fn | (&self, backlog: i32) -> Result<()> {
let mut backlogs = self.backlogs.lock();
let new_num_backlogs = min(backlog as usize, BACKLOG_MAX);
backlogs.truncate(new_num_backlogs);
self.num_backlogs.store(new_num_backlogs);
self.refill_backlog_sockets(&mut backlogs)
}
fn accept(&self, _options: &OpenOptions) -> Result<(Arc<dyn FileLike>, SockAddr)> {
SOCKET_WAIT_QUEUE.sleep_signalable_until(|| {
let mut sockets = SOCKETS.lock();
let mut backlogs = self.backlogs.lock();
match get_ready_backlog_index(&mut *sockets, &*backlogs) {
Some(index) => {
// Pop the client socket and add a new socket into the backlog.
let socket = backlogs.remove(index);
drop(sockets);
self.refill_backlog_sockets(&mut backlogs)?;
// Extract the remote endpoint.
let mut sockets_lock = SOCKETS.lock();
let smol_socket: SocketRef<'_, smoltcp::socket::TcpSocket> =
sockets_lock.get(socket.handle);
Ok(Some((
socket as Arc<dyn FileLike>,
smol_socket.remote_endpoint().into(),
)))
}
None => {
// No accept'able sockets.
Ok(None)
}
}
})
}
fn bind(&self, sockaddr: SockAddr) -> Result<()> {
// TODO: Reject if the endpoint is already in use -- IIUC smoltcp
// does not check that.
self.local_endpoint.store(Some(sockaddr.try_into()?));
Ok(())
}
fn getsockname(&self) -> Result<SockAddr> {
let endpoint = SOCKETS
.lock()
.get::<smoltcp::socket::TcpSocket>(self.handle)
.local_endpoint();
if endpoint.addr.is_unspecified() {
return Err(Errno::ENOTCONN.into());
}
Ok(endpoint.into())
}
fn getpeername(&self) -> Result<SockAddr> {
let endpoint = SOCKETS
.lock()
.get::<smoltcp::socket::TcpSocket>(self.handle)
.remote_endpoint();
if endpoint.addr.is_unspecified() {
return Err(Errno::ENOTCONN.into());
}
Ok(endpoint.into())
}
fn connect(&self, sockaddr: SockAddr, _options: &OpenOptions) -> Result<()> {
let remote_endpoint: IpEndpoint = sockaddr.try_into()?;
// TODO: Reject if the endpoint is already in use -- IIUC smoltcp
// does not check that.
let mut inuse_endpoints = INUSE_ENDPOINTS.lock();
let mut local_endpoint = self.local_endpoint.load().unwrap_or(IpEndpoint {
addr: IpAddress::Ipv4(Ipv4Address::UNSPECIFIED),
port: 0,
});
if local_endpoint.port == 0 {
// Assign a unused port.
// TODO: Assign a *random* port instead.
let mut port = 50000;
while inuse_endpoints.contains(&port) {
if port == u16::MAX {
return Err(Errno::EAGAIN.into());
}
port += 1;
}
local_endpoint.port = port;
}
SOCKETS
.lock()
.get::<smoltcp::socket::TcpSocket>(self.handle)
.connect(remote_endpoint, local_endpoint)?;
inuse_endpoints.insert(remote_endpoint.port);
drop(inuse_endpoints);
// Submit a SYN packet.
process_packets();
// Wait until the connection has been established.
SOCKET_WAIT_QUEUE.sleep_signalable_until(|| {
if SOCKETS
.lock()
.get::<smoltcp::socket::TcpSocket>(self.handle)
.may_send()
{
Ok(Some(()))
} else {
Ok(None)
}
})
}
fn write(&self, _offset: usize, buf: UserBuffer<'_>, _options: &OpenOptions) -> Result<usize> {
let mut total_len = 0;
let mut reader = UserBufReader::from(buf);
loop {
let copied_len = SOCKETS
.lock()
.get::<smoltcp::socket::TcpSocket>(self.handle)
.send(|dst| {
let copied_len = reader.read_bytes(dst).unwrap_or(0);
(copied_len, copied_len)
});
process_packets();
match copied_len {
Ok(0) => {
return Ok(total_len);
}
Ok(copied_len) => {
// Continue writing.
total_len += copied_len;
}
Err(err) => return Err(err.into()),
}
}
}
fn read(&self, _offset: usize, buf: UserBufferMut<'_>, options: &OpenOptions) -> Result<usize> {
let mut writer = UserBufWriter::from(buf);
SOCKET_WAIT_QUEUE.sleep_signalable_until(|| {
let copied_len = SOCKETS
.lock()
.get::<smoltcp::socket::TcpSocket>(self.handle)
.recv(|src| {
let copied_len = writer.write_bytes(src).unwrap_or(0);
(copied_len, copied_len)
});
match copied_len {
Ok(0) | Err(smoltcp::Error::Exhausted) => {
if options.nonblock {
Err(Errno::EAGAIN.into())
} else {
// The receive buffer is empty. Sleep on the wait queue...
Ok(None)
}
}
Ok(copied_len) => {
// Continue reading.
Ok(Some(copied_len))
}
// TODO: Handle FIN
Err(err) => Err(err.into()),
}
})
}
fn sendto(
&self,
buf: UserBuffer<'_>,
sockaddr: Option<SockAddr>,
options: &OpenOptions,
) -> Result<usize> {
if sockaddr.is_some() {
return Err(Errno::EINVAL.into());
}
self.write(0, buf, options)
}
fn recvfrom(
&self,
buf: UserBufferMut<'_>,
_flags: RecvFromFlags,
options: &OpenOptions,
) -> Result<(usize, SockAddr)> {
Ok((self.read(0, buf, options)?, self.getpeername()?))
}
fn poll(&self) -> Result<PollStatus> {
let mut status = PollStatus::empty();
let mut sockets = SOCKETS.lock();
if get_ready_backlog_index(&mut *sockets, &*self.backlogs.lock()).is_some() {
status |= PollStatus::POLLIN;
}
let socket = sockets.get::<smoltcp::socket::TcpSocket>(self.handle);
if socket.can_recv() {
status |= PollStatus::POLLIN;
}
if socket.can_send() {
status |= PollStatus::POLLOUT;
}
Ok(status)
}
}
| listen |
0002_auto_20160123_1454.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.db.models.deletion
class | (migrations.Migration):
dependencies = [
('froide_campaign', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='informationobject',
options={'ordering': ('ordering',)},
),
migrations.AddField(
model_name='informationobject',
name='ordering',
field=models.CharField(max_length=255, blank=True),
),
migrations.AlterField(
model_name='campaign',
name='template',
field=models.TextField(blank=True),
),
migrations.AlterField(
model_name='informationobject',
name='context',
field=models.JSONField(blank=True),
),
migrations.AlterField(
model_name='informationobject',
name='documents',
field=models.ManyToManyField(to='foirequest.FoiAttachment', blank=True),
),
migrations.AlterField(
model_name='informationobject',
name='foirequest',
field=models.ForeignKey(blank=True, to='foirequest.FoiRequest', null=True, on_delete=django.db.models.deletion.SET_NULL),
),
migrations.AlterField(
model_name='informationobject',
name='publicbody',
field=models.ForeignKey(blank=True, to='publicbody.PublicBody', null=True, on_delete=django.db.models.deletion.SET_NULL),
),
]
| Migration |
driftctl_test.go | package pkg_test
import (
"reflect"
"testing"
"github.com/r3labs/diff/v2"
"github.com/snyk/driftctl/pkg"
"github.com/snyk/driftctl/pkg/alerter"
"github.com/snyk/driftctl/pkg/analyser"
"github.com/snyk/driftctl/pkg/filter"
"github.com/snyk/driftctl/pkg/memstore"
"github.com/snyk/driftctl/pkg/output"
"github.com/snyk/driftctl/pkg/resource"
"github.com/snyk/driftctl/pkg/resource/aws"
"github.com/snyk/driftctl/pkg/resource/github"
"github.com/snyk/driftctl/pkg/terraform"
"github.com/snyk/driftctl/test"
testresource "github.com/snyk/driftctl/test/resource"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
type TestProvider struct {
Name string
Version string
}
type TestCase struct {
name string
provider *TestProvider
stateResources []*resource.Resource
remoteResources []*resource.Resource
mocks func(factory resource.ResourceFactory, repo resource.SchemaRepositoryInterface)
assert func(t *testing.T, result *test.ScanResult, err error)
assertStore func(*testing.T, memstore.Store)
options *pkg.ScanOptions
}
type TestCases []TestCase
func runTest(t *testing.T, cases TestCases) {
for _, c := range cases {
if c.provider == nil {
c.provider = &TestProvider{
Name: "aws",
Version: "3.19.0",
}
}
repo := testresource.InitFakeSchemaRepository(c.provider.Name, c.provider.Version)
aws.InitResourcesMetadata(repo)
github.InitResourcesMetadata(repo)
t.Run(c.name, func(t *testing.T) {
testAlerter := alerter.NewAlerter()
if c.stateResources == nil {
c.stateResources = []*resource.Resource{}
}
for _, res := range c.stateResources {
schema, _ := repo.GetSchema(res.ResourceType())
res.Sch = schema
}
stateSupplier := &resource.MockIaCSupplier{}
stateSupplier.On("Resources").Return(c.stateResources, nil)
stateSupplier.On("SourceCount").Return(uint(2))
if c.remoteResources == nil {
c.remoteResources = []*resource.Resource{}
}
for _, res := range c.remoteResources {
schema, _ := repo.GetSchema(res.ResourceType())
res.Sch = schema
}
remoteSupplier := &resource.MockSupplier{}
remoteSupplier.On("Resources").Return(c.remoteResources, nil)
var resourceFactory resource.ResourceFactory = terraform.NewTerraformResourceFactory(repo)
if c.mocks != nil {
resourceFactory = &terraform.MockResourceFactory{}
c.mocks(resourceFactory, repo)
}
if c.options == nil {
c.options = &pkg.ScanOptions{Deep: true}
}
scanProgress := &output.MockProgress{}
scanProgress.On("Start").Return().Once()
scanProgress.On("Stop").Return().Once()
iacProgress := &output.MockProgress{}
iacProgress.On("Start").Return().Once()
iacProgress.On("Stop").Return().Once()
testFilter := &filter.MockFilter{}
testFilter.On("IsTypeIgnored", mock.Anything).Return(false)
testFilter.On("IsResourceIgnored", mock.Anything).Return(false)
testFilter.On("IsFieldIgnored", mock.Anything, mock.Anything).Return(false)
analyzer := analyser.NewAnalyzer(testAlerter, analyser.AnalyzerOptions{Deep: c.options.Deep}, testFilter)
store := memstore.New()
driftctl := pkg.NewDriftCTL(remoteSupplier, stateSupplier, testAlerter, analyzer, resourceFactory, c.options, scanProgress, iacProgress, repo, store)
analysis, err := driftctl.Run()
c.assert(t, test.NewScanResult(t, analysis), err)
if c.assertStore != nil {
c.assertStore(t, store)
}
scanProgress.AssertExpectations(t)
})
}
}
func matchByAttributes(input, attrs map[string]interface{}) bool {
for k, v := range attrs {
if value, ok := input[k]; !ok || !reflect.DeepEqual(value, v) {
return false
}
}
return true
}
func TestDriftctlRun_BasicBehavior(t *testing.T) {
cases := TestCases{
{
name: "analysis duration is set",
stateResources: []*resource.Resource{},
remoteResources: []*resource.Resource{},
assert: func(t *testing.T, result *test.ScanResult, err error) {
result.NotZero(result.Duration)
},
assertStore: func(t *testing.T, store memstore.Store) {
assert.Equal(t, 0, store.Bucket(memstore.TelemetryBucket).Get("total_resources"))
assert.Equal(t, 0, store.Bucket(memstore.TelemetryBucket).Get("total_managed"))
assert.Equal(t, uint(0), store.Bucket(memstore.TelemetryBucket).Get("duration"))
assert.Equal(t, uint(2), store.Bucket(memstore.TelemetryBucket).Get("iac_source_count"))
},
},
{
name: "infrastructure should be in sync",
stateResources: []*resource.Resource{
&resource.Resource{},
},
remoteResources: []*resource.Resource{
&resource.Resource{},
},
assert: func(t *testing.T, result *test.ScanResult, err error) {
result.AssertInfrastructureIsInSync()
},
assertStore: func(t *testing.T, store memstore.Store) {
assert.Equal(t, 1, store.Bucket(memstore.TelemetryBucket).Get("total_resources"))
assert.Equal(t, 1, store.Bucket(memstore.TelemetryBucket).Get("total_managed"))
assert.Equal(t, uint(0), store.Bucket(memstore.TelemetryBucket).Get("duration"))
assert.Equal(t, uint(2), store.Bucket(memstore.TelemetryBucket).Get("iac_source_count"))
},
options: func(t *testing.T) *pkg.ScanOptions {
return &pkg.ScanOptions{Deep: true}
}(t),
},
{
name: "we should have deleted resource",
stateResources: []*resource.Resource{
&resource.Resource{},
},
remoteResources: []*resource.Resource{},
assert: func(t *testing.T, result *test.ScanResult, err error) {
result.AssertDeletedCount(1)
},
assertStore: func(t *testing.T, store memstore.Store) {
assert.Equal(t, 1, store.Bucket(memstore.TelemetryBucket).Get("total_resources"))
assert.Equal(t, 0, store.Bucket(memstore.TelemetryBucket).Get("total_managed"))
assert.Equal(t, uint(0), store.Bucket(memstore.TelemetryBucket).Get("duration"))
assert.Equal(t, uint(2), store.Bucket(memstore.TelemetryBucket).Get("iac_source_count"))
},
},
{
name: "we should have unmanaged resource",
stateResources: []*resource.Resource{},
remoteResources: []*resource.Resource{
&resource.Resource{},
},
assert: func(t *testing.T, result *test.ScanResult, err error) {
result.AssertUnmanagedCount(1)
},
assertStore: func(t *testing.T, store memstore.Store) {
assert.Equal(t, 1, store.Bucket(memstore.TelemetryBucket).Get("total_resources"))
assert.Equal(t, 0, store.Bucket(memstore.TelemetryBucket).Get("total_managed"))
assert.Equal(t, uint(0), store.Bucket(memstore.TelemetryBucket).Get("duration"))
},
},
{
name: "we should have changes of field update",
stateResources: []*resource.Resource{
&resource.Resource{
Id: "fake",
Type: "FakeResource",
Attrs: &resource.Attributes{
"foobar": "barfoo",
},
},
},
remoteResources: []*resource.Resource{
&resource.Resource{
Id: "fake",
Type: "FakeResource",
Attrs: &resource.Attributes{
"foobar": "foobar",
},
},
},
assert: func(t *testing.T, result *test.ScanResult, err error) {
result.AssertManagedCount(1)
result.AssertResourceHasDrift("fake", "FakeResource", analyser.Change{
Change: diff.Change{
Type: diff.UPDATE,
Path: []string{"foobar"},
From: "barfoo",
To: "foobar",
},
Computed: false,
})
},
assertStore: func(t *testing.T, store memstore.Store) {
assert.Equal(t, 1, store.Bucket(memstore.TelemetryBucket).Get("total_resources"))
assert.Equal(t, 1, store.Bucket(memstore.TelemetryBucket).Get("total_managed"))
assert.Equal(t, uint(0), store.Bucket(memstore.TelemetryBucket).Get("duration"))
assert.Equal(t, uint(2), store.Bucket(memstore.TelemetryBucket).Get("iac_source_count"))
},
},
{
name: "we should have changes on computed field",
stateResources: []*resource.Resource{
&resource.Resource{
Id: "fake",
Type: aws.AwsAmiResourceType,
Attrs: &resource.Attributes{
"arn": "barfoo",
},
},
},
remoteResources: []*resource.Resource{
&resource.Resource{
Id: "fake",
Type: aws.AwsAmiResourceType,
Attrs: &resource.Attributes{
"arn": "foobar",
},
},
},
assert: func(t *testing.T, result *test.ScanResult, err error) {
result.AssertManagedCount(1)
result.AssertResourceHasDrift("fake", aws.AwsAmiResourceType, analyser.Change{
Change: diff.Change{
Type: diff.UPDATE,
Path: []string{"arn"},
From: "barfoo",
To: "foobar",
},
Computed: true,
})
},
assertStore: func(t *testing.T, store memstore.Store) {
assert.Equal(t, 1, store.Bucket(memstore.TelemetryBucket).Get("total_resources"))
assert.Equal(t, 1, store.Bucket(memstore.TelemetryBucket).Get("total_managed"))
assert.Equal(t, uint(0), store.Bucket(memstore.TelemetryBucket).Get("duration"))
assert.Equal(t, uint(2), store.Bucket(memstore.TelemetryBucket).Get("iac_source_count"))
},
},
{
name: "we should have changes on deleted field",
stateResources: []*resource.Resource{
&resource.Resource{
Id: "fake",
Type: "FakeResource",
Attrs: &resource.Attributes{
"tags": map[string]string{
"tag1": "deleted",
},
},
},
},
remoteResources: []*resource.Resource{
&resource.Resource{
Id: "fake",
Type: "FakeResource",
Attrs: &resource.Attributes{
"tags": map[string]string{},
},
},
},
assert: func(t *testing.T, result *test.ScanResult, err error) {
result.AssertManagedCount(1)
result.AssertResourceHasDrift("fake", "FakeResource", analyser.Change{
Change: diff.Change{
Type: diff.DELETE,
Path: []string{"tags", "tag1"},
From: "deleted",
To: nil,
},
Computed: false,
})
},
assertStore: func(t *testing.T, store memstore.Store) {
assert.Equal(t, 1, store.Bucket(memstore.TelemetryBucket).Get("total_resources"))
assert.Equal(t, 1, store.Bucket(memstore.TelemetryBucket).Get("total_managed"))
assert.Equal(t, uint(0), store.Bucket(memstore.TelemetryBucket).Get("duration"))
assert.Equal(t, uint(2), store.Bucket(memstore.TelemetryBucket).Get("iac_source_count"))
},
},
{
name: "we should have changes of added field",
stateResources: []*resource.Resource{
&resource.Resource{
Id: "fake",
Type: "FakeResource",
Attrs: &resource.Attributes{
"tags": map[string]string{},
},
},
},
remoteResources: []*resource.Resource{
&resource.Resource{
Id: "fake",
Type: "FakeResource",
Attrs: &resource.Attributes{
"tags": map[string]string{
"tag1": "added",
},
},
},
},
assert: func(t *testing.T, result *test.ScanResult, err error) {
result.AssertManagedCount(1)
result.AssertResourceHasDrift("fake", "FakeResource", analyser.Change{
Change: diff.Change{
Type: diff.CREATE,
Path: []string{"tags", "tag1"},
From: nil,
To: "added",
},
Computed: false,
})
},
assertStore: func(t *testing.T, store memstore.Store) {
assert.Equal(t, 1, store.Bucket(memstore.TelemetryBucket).Get("total_resources"))
assert.Equal(t, 1, store.Bucket(memstore.TelemetryBucket).Get("total_managed"))
assert.Equal(t, uint(0), store.Bucket(memstore.TelemetryBucket).Get("duration"))
assert.Equal(t, uint(2), store.Bucket(memstore.TelemetryBucket).Get("iac_source_count"))
},
},
{
name: "we should ignore default AWS IAM role when strict mode is disabled",
mocks: func(factory resource.ResourceFactory, repo resource.SchemaRepositoryInterface) {
factory.(*terraform.MockResourceFactory).On(
"CreateAbstractResource",
aws.AwsIamPolicyAttachmentResourceType,
"role-test-1-policy-test-1",
map[string]interface{}{
"policy_arn": "policy-test-1",
"roles": []interface{}{"role-test-1"},
},
).Once().Return(&resource.Resource{
Id: "role-test-1-policy-test-1",
Type: aws.AwsIamPolicyAttachmentResourceType,
Attrs: &resource.Attributes{
"policy_arn": "policy-test-1",
"roles": []interface{}{"role-test-1"},
},
})
},
stateResources: []*resource.Resource{
&resource.Resource{
Id: "fake",
Type: "FakeResource",
Attrs: &resource.Attributes{},
},
&resource.Resource{
Id: "role-policy-test-1",
Type: aws.AwsIamPolicyResourceType,
Attrs: &resource.Attributes{
"arn": "policy-test-1",
},
},
},
remoteResources: []*resource.Resource{
&resource.Resource{
Id: "fake",
Type: "FakeResource",
Attrs: &resource.Attributes{},
},
&resource.Resource{
Id: "role-test-1",
Type: aws.AwsIamRoleResourceType,
Attrs: &resource.Attributes{
"path": "/aws-service-role/test",
},
},
&resource.Resource{
Id: "role-policy-test-1",
Type: aws.AwsIamRolePolicyResourceType,
Attrs: &resource.Attributes{
"role": "role-test-1",
},
},
&resource.Resource{
Id: "role-policy-test-1",
Type: aws.AwsIamPolicyResourceType,
Attrs: &resource.Attributes{
"arn": "policy-test-1",
},
},
&resource.Resource{
Id: "policy-attachment-test-1",
Type: aws.AwsIamPolicyAttachmentResourceType,
Attrs: &resource.Attributes{
"policy_arn": "policy-test-1",
"users": []interface{}{},
"roles": []interface{}{"role-test-1"},
},
},
&resource.Resource{
Id: "role-test-2",
Type: aws.AwsIamRoleResourceType,
Attrs: &resource.Attributes{
"path": "/not-aws-service-role/test",
},
},
},
assert: func(t *testing.T, result *test.ScanResult, err error) {
result.AssertManagedCount(2)
result.AssertUnmanagedCount(2)
result.AssertDeletedCount(0)
result.AssertDriftCountTotal(0)
},
assertStore: func(t *testing.T, store memstore.Store) {
assert.Equal(t, 4, store.Bucket(memstore.TelemetryBucket).Get("total_resources"))
assert.Equal(t, 2, store.Bucket(memstore.TelemetryBucket).Get("total_managed"))
assert.Equal(t, uint(0), store.Bucket(memstore.TelemetryBucket).Get("duration"))
assert.Equal(t, uint(2), store.Bucket(memstore.TelemetryBucket).Get("iac_source_count"))
},
options: func(t *testing.T) *pkg.ScanOptions {
return &pkg.ScanOptions{
StrictMode: false,
Deep: true,
}
}(t),
},
{
name: "we should not ignore default AWS IAM role when strict mode is enabled",
mocks: func(factory resource.ResourceFactory, repo resource.SchemaRepositoryInterface) {
factory.(*terraform.MockResourceFactory).On(
"CreateAbstractResource",
aws.AwsIamPolicyAttachmentResourceType,
"role-test-1-policy-test-1",
map[string]interface{}{
"policy_arn": "policy-test-1",
"roles": []interface{}{"role-test-1"},
},
).Once().Return(&resource.Resource{
Id: "role-test-1-policy-test-1",
Type: aws.AwsIamPolicyAttachmentResourceType,
Attrs: &resource.Attributes{
"policy_arn": "policy-test-1",
"roles": []interface{}{"role-test-1"},
},
})
},
stateResources: []*resource.Resource{
&resource.Resource{
Id: "fake",
Type: "FakeResource",
Attrs: &resource.Attributes{},
},
&resource.Resource{
Id: "policy-test-1",
Type: aws.AwsIamPolicyResourceType,
Attrs: &resource.Attributes{
"arn": "policy-test-1",
},
},
},
remoteResources: []*resource.Resource{
&resource.Resource{
Id: "fake",
Type: "FakeResource",
Attrs: &resource.Attributes{},
},
&resource.Resource{
Id: "role-test-1",
Type: aws.AwsIamRoleResourceType,
Attrs: &resource.Attributes{
"path": "/aws-service-role/test",
},
},
&resource.Resource{
Id: "role-policy-test-1",
Type: aws.AwsIamRolePolicyResourceType,
Attrs: &resource.Attributes{
"role": "role-test-1",
},
},
&resource.Resource{
Id: "policy-test-1",
Type: aws.AwsIamPolicyResourceType,
Attrs: &resource.Attributes{
"arn": "policy-test-1",
},
},
&resource.Resource{
Id: "policy-attachment-test-1",
Type: aws.AwsIamPolicyAttachmentResourceType,
Attrs: &resource.Attributes{
"policy_arn": "policy-test-1",
"users": []interface{}{},
"roles": []interface{}{"role-test-1"},
},
},
&resource.Resource{
Id: "role-test-2",
Type: aws.AwsIamRoleResourceType,
Attrs: &resource.Attributes{
"path": "/not-aws-service-role/test",
},
},
},
assert: func(t *testing.T, result *test.ScanResult, err error) {
result.AssertManagedCount(2)
result.AssertUnmanagedCount(4)
result.AssertDeletedCount(0)
result.AssertDriftCountTotal(0)
},
assertStore: func(t *testing.T, store memstore.Store) {
assert.Equal(t, 6, store.Bucket(memstore.TelemetryBucket).Get("total_resources"))
assert.Equal(t, 2, store.Bucket(memstore.TelemetryBucket).Get("total_managed"))
assert.Equal(t, uint(0), store.Bucket(memstore.TelemetryBucket).Get("duration"))
assert.Equal(t, uint(2), store.Bucket(memstore.TelemetryBucket).Get("iac_source_count"))
},
options: func(t *testing.T) *pkg.ScanOptions {
return &pkg.ScanOptions{
StrictMode: true,
Deep: true,
}
}(t),
},
{
name: "we should not ignore default AWS IAM role when strict mode is enabled and a filter is specified",
mocks: func(factory resource.ResourceFactory, repo resource.SchemaRepositoryInterface) {
factory.(*terraform.MockResourceFactory).On(
"CreateAbstractResource",
aws.AwsIamPolicyAttachmentResourceType,
"role-test-1-policy-test-1",
map[string]interface{}{
"policy_arn": "policy-test-1",
"roles": []interface{}{"role-test-1"},
},
).Once().Return(&resource.Resource{
Id: "role-test-1-policy-test-1",
Type: aws.AwsIamPolicyAttachmentResourceType,
Attrs: &resource.Attributes{
"policy_arn": "policy-test-1",
"roles": []interface{}{"role-test-1"},
},
})
},
stateResources: []*resource.Resource{
&resource.Resource{
Id: "fake",
Type: "FakeResource",
Attrs: &resource.Attributes{},
},
&resource.Resource{
Id: "policy-test-1",
Type: aws.AwsIamPolicyResourceType,
Attrs: &resource.Attributes{
"arn": "policy-test-1",
},
},
},
remoteResources: []*resource.Resource{
&resource.Resource{
Id: "fake",
Type: "FakeResource",
Attrs: &resource.Attributes{},
},
&resource.Resource{
Id: "role-test-1",
Type: aws.AwsIamRoleResourceType,
Attrs: &resource.Attributes{
"path": "/aws-service-role/test",
},
},
&resource.Resource{
Id: "role-policy-test-1",
Type: aws.AwsIamRolePolicyResourceType,
Attrs: &resource.Attributes{
"role": "role-test-1",
},
},
&resource.Resource{
Id: "policy-test-1",
Type: aws.AwsIamPolicyResourceType,
Attrs: &resource.Attributes{
"arn": "policy-test-1",
},
},
&resource.Resource{
Id: "policy-attachment-test-1",
Type: aws.AwsIamPolicyAttachmentResourceType,
Attrs: &resource.Attributes{
"policy_arn": "policy-test-1",
"users": []interface{}{},
"roles": []interface{}{"role-test-1"},
},
},
&resource.Resource{
Id: "role-test-2",
Type: aws.AwsIamRoleResourceType,
Attrs: &resource.Attributes{
"path": "/not-aws-service-role/test",
},
},
},
assert: func(t *testing.T, result *test.ScanResult, err error) {
result.AssertCoverage(0)
result.AssertInfrastructureIsNotSync()
result.AssertManagedCount(0)
result.AssertUnmanagedCount(1)
result.AssertDeletedCount(0)
result.AssertDriftCountTotal(0)
},
assertStore: func(t *testing.T, store memstore.Store) {
assert.Equal(t, 1, store.Bucket(memstore.TelemetryBucket).Get("total_resources"))
assert.Equal(t, 0, store.Bucket(memstore.TelemetryBucket).Get("total_managed"))
assert.Equal(t, uint(0), store.Bucket(memstore.TelemetryBucket).Get("duration"))
assert.Equal(t, uint(2), store.Bucket(memstore.TelemetryBucket).Get("iac_source_count"))
},
options: func(t *testing.T) *pkg.ScanOptions {
filterStr := "Id=='role-test-1'"
f, err := filter.BuildExpression(filterStr)
if err != nil {
t.Fatalf("Unable to build filter expression: %s\n%s", filterStr, err)
}
return &pkg.ScanOptions{
Filter: f,
StrictMode: true,
Deep: true,
}
}(t),
},
}
runTest(t, cases)
}
func TestDriftctlRun_BasicFilter(t *testing.T) {
cases := TestCases{
{
name: "test filtering on Type",
stateResources: []*resource.Resource{},
remoteResources: []*resource.Resource{
&resource.Resource{
Id: "res1",
Type: "not-filtered",
Attrs: &resource.Attributes{},
},
&resource.Resource{
Id: "res2",
Type: "filtered",
Attrs: &resource.Attributes{},
},
},
assert: func(t *testing.T, result *test.ScanResult, err error) {
result.AssertUnmanagedCount(1)
result.AssertResourceUnmanaged("res2", "filtered")
},
options: func(t *testing.T) *pkg.ScanOptions {
filterStr := "Type=='filtered'"
f, err := filter.BuildExpression(filterStr)
if err != nil {
t.Fatalf("Unable to build filter expression: %s\n%s", filterStr, err)
}
return &pkg.ScanOptions{Filter: f, Deep: true}
}(t),
},
{
name: "test filtering on Id",
stateResources: []*resource.Resource{},
remoteResources: []*resource.Resource{
&resource.Resource{
Id: "res1",
Type: "not-filtered",
Attrs: &resource.Attributes{},
},
&resource.Resource{
Id: "res2",
Type: "filtered",
Attrs: &resource.Attributes{},
},
},
assert: func(t *testing.T, result *test.ScanResult, err error) {
result.AssertUnmanagedCount(1)
result.AssertResourceUnmanaged("res2", "filtered")
},
options: func(t *testing.T) *pkg.ScanOptions {
filterStr := "Id=='res2'"
f, err := filter.BuildExpression(filterStr)
if err != nil {
t.Fatalf("Unable to build filter expression: %s\n%s", filterStr, err)
}
return &pkg.ScanOptions{Filter: f, Deep: true}
}(t),
},
{
name: "test filtering on attribute",
stateResources: []*resource.Resource{},
remoteResources: []*resource.Resource{
&resource.Resource{
Id: "res1",
Type: "filtered",
Attrs: &resource.Attributes{
"test_field": "value to filter on",
},
},
&resource.Resource{
Id: "res2",
Type: "not-filtered",
Attrs: &resource.Attributes{},
},
},
assert: func(t *testing.T, result *test.ScanResult, err error) {
result.AssertUnmanagedCount(1)
result.AssertResourceUnmanaged("res1", "filtered")
},
options: func(t *testing.T) *pkg.ScanOptions {
filterStr := "Attr.test_field=='value to filter on'"
f, err := filter.BuildExpression(filterStr)
if err != nil {
t.Fatalf("Unable to build filter expression: %s\n%s", filterStr, err)
}
return &pkg.ScanOptions{Filter: f, Deep: true}
}(t),
},
}
runTest(t, cases)
}
func TestDriftctlRun_Middlewares(t *testing.T) {
cases := TestCases{
{
name: "test bucket policy expander middleware",
stateResources: []*resource.Resource{
&resource.Resource{
Id: "foo",
Type: aws.AwsS3BucketResourceType,
Attrs: &resource.Attributes{
"bucket": "foo",
"policy": "{\"Id\":\"foo\"}",
},
},
},
remoteResources: []*resource.Resource{
&resource.Resource{
Id: "foo",
Type: aws.AwsS3BucketPolicyResourceType,
Attrs: &resource.Attributes{
"id": "foo",
"bucket": "foo",
"policy": "{\"Id\":\"bar\"}",
},
},
},
mocks: func(factory resource.ResourceFactory, repo resource.SchemaRepositoryInterface) {
factory.(*terraform.MockResourceFactory).On(
"CreateAbstractResource",
aws.AwsS3BucketPolicyResourceType,
"foo",
map[string]interface{}{
"id": "foo",
"bucket": "foo",
"policy": "{\"Id\":\"foo\"}",
},
).Once().Return(&resource.Resource{
Id: "foo",
Type: aws.AwsS3BucketPolicyResourceType,
Attrs: &resource.Attributes{
"id": "foo",
"bucket": "foo",
"policy": "{\"Id\":\"foo\"}",
},
Sch: getSchema(repo, aws.AwsS3BucketPolicyResourceType),
})
},
assert: func(t *testing.T, result *test.ScanResult, err error) {
result.AssertManagedCount(1)
result.AssertResourceHasDrift("foo", "aws_s3_bucket_policy", analyser.Change{
Change: diff.Change{
Type: diff.UPDATE,
Path: []string{"policy"},
From: "{\"Id\":\"foo\"}",
To: "{\"Id\":\"bar\"}",
},
Computed: false,
JsonString: true,
})
},
options: func(t *testing.T) *pkg.ScanOptions {
filterStr := "Type=='aws_s3_bucket_policy' && Attr.bucket=='foo'"
f, err := filter.BuildExpression(filterStr)
if err != nil {
t.Fatalf("Unable to build filter expression: %s\n%s", filterStr, err)
}
return &pkg.ScanOptions{Filter: f, Deep: true}
}(t),
},
{
name: "test instance block device middleware",
stateResources: []*resource.Resource{
&resource.Resource{
Id: "dummy-instance",
Type: "aws_instance",
Attrs: &resource.Attributes{
"availability_zone": "us-east-1",
"root_block_device": []interface{}{
map[string]interface{}{
"volume_id": "vol-02862d9b39045a3a4",
"volume_type": "gp2",
},
},
"ebs_block_device": []interface{}{
map[string]interface{}{
"volume_id": "vol-018c5ae89895aca4c",
"encrypted": true,
},
},
},
},
},
remoteResources: []*resource.Resource{
&resource.Resource{
Id: "vol-018c5ae89895aca4c",
Type: "aws_ebs_volume",
Attrs: &resource.Attributes{
"encrypted": false,
"multi_attach_enabled": false,
"availability_zone": "us-east-1",
},
},
&resource.Resource{
Id: "vol-02862d9b39045a3a4",
Type: "aws_ebs_volume",
Attrs: &resource.Attributes{
"type": "gp3",
"multi_attach_enabled": false,
"availability_zone": "us-east-1",
},
},
},
mocks: func(factory resource.ResourceFactory, repo resource.SchemaRepositoryInterface) {
foo := resource.Resource{
Id: "vol-018c5ae89895aca4c",
Type: "aws_ebs_volume",
Attrs: &resource.Attributes{
"encrypted": true,
"multi_attach_enabled": false,
"availability_zone": "us-east-1",
},
Sch: getSchema(repo, "aws_ebs_volume"),
}
factory.(*terraform.MockResourceFactory).On("CreateAbstractResource", "aws_ebs_volume", mock.Anything, mock.MatchedBy(func(input map[string]interface{}) bool {
return matchByAttributes(input, map[string]interface{}{
"id": "vol-018c5ae89895aca4c",
"availability_zone": "us-east-1",
"encrypted": true,
"multi_attach_enabled": false,
})
})).Times(1).Return(&foo, nil)
bar := resource.Resource{
Id: "vol-02862d9b39045a3a4",
Type: "aws_ebs_volume",
Attrs: &resource.Attributes{
"type": "gp2",
"multi_attach_enabled": false,
"availability_zone": "us-east-1",
},
Sch: getSchema(repo, "aws_ebs_volume"),
}
factory.(*terraform.MockResourceFactory).On("CreateAbstractResource", "aws_ebs_volume", mock.Anything, mock.MatchedBy(func(input map[string]interface{}) bool {
return matchByAttributes(input, map[string]interface{}{
"id": "vol-02862d9b39045a3a4",
"availability_zone": "us-east-1",
"type": "gp2",
"multi_attach_enabled": false,
})
})).Times(1).Return(&bar, nil)
},
assert: func(t *testing.T, result *test.ScanResult, err error) {
result.AssertManagedCount(2)
result.AssertResourceHasDrift("vol-02862d9b39045a3a4", "aws_ebs_volume", analyser.Change{
Change: diff.Change{
Type: diff.UPDATE,
Path: []string{"type"},
From: "gp2",
To: "gp3",
},
Computed: true,
})
result.AssertResourceHasDrift("vol-018c5ae89895aca4c", "aws_ebs_volume", analyser.Change{
Change: diff.Change{
Type: diff.UPDATE,
Path: []string{"encrypted"},
From: true,
To: false,
},
Computed: true,
})
},
options: func(t *testing.T) *pkg.ScanOptions {
filterStr := "Type=='aws_ebs_volume' && Attr.availability_zone=='us-east-1'"
f, err := filter.BuildExpression(filterStr)
if err != nil {
t.Fatalf("Unable to build filter expression: %s\n%s", filterStr, err)
}
return &pkg.ScanOptions{Filter: f, Deep: true}
}(t),
},
{
name: "test route table expander middleware",
stateResources: []*resource.Resource{
&resource.Resource{
Id: "table",
Type: "aws_route_table",
Attrs: &resource.Attributes{
"route": []interface{}{
map[string]interface{}{
"gateway_id": "igw-07b7844a8fd17a638",
"cidr_block": "0.0.0.0/0",
},
map[string]interface{}{
"gateway_id": "igw-07b7844a8fd17a638",
"cidr_block": "",
"ipv6_cidr_block": "::/0",
},
},
},
},
},
remoteResources: []*resource.Resource{
&resource.Resource{
Id: "r-table1080289494",
Type: aws.AwsRouteResourceType,
Attrs: &resource.Attributes{
"route_table_id": "table",
"origin": "CreateRoute",
"destination_cidr_block": "0.0.0.0/0",
"gateway_id": "igw-07b7844a8fd17a638",
"state": "active",
},
},
&resource.Resource{
Id: "r-table2750132062",
Type: aws.AwsRouteResourceType,
Attrs: &resource.Attributes{
"route_table_id": "table",
"origin": "CreateRoute",
"destination_ipv6_cidr_block": "::/0",
"gateway_id": "igw-07b7844a8fd17a638",
"state": "active",
},
},
},
mocks: func(factory resource.ResourceFactory, repo resource.SchemaRepositoryInterface) {
factory.(*terraform.MockResourceFactory).On("CreateAbstractResource", "aws_route", "r-table1080289494", mock.MatchedBy(func(input map[string]interface{}) bool {
return matchByAttributes(input, map[string]interface{}{
"destination_cidr_block": "0.0.0.0/0",
"gateway_id": "igw-07b7844a8fd17a638",
"origin": "CreateRoute",
"route_table_id": "table",
"state": "active",
})
})).Times(1).Return(&resource.Resource{
Id: "r-table1080289494",
Type: aws.AwsRouteResourceType,
Attrs: &resource.Attributes{
"route_table_id": "table",
"origin": "CreateRoute",
"destination_cidr_block": "0.0.0.0/0",
"gateway_id": "igw-07b7844a8fd17a638",
"state": "active",
},
}, nil)
factory.(*terraform.MockResourceFactory).On("CreateAbstractResource", "aws_route", "r-table2750132062", mock.MatchedBy(func(input map[string]interface{}) bool {
return matchByAttributes(input, map[string]interface{}{
"destination_ipv6_cidr_block": "::/0",
"gateway_id": "igw-07b7844a8fd17a638",
"origin": "CreateRoute",
"route_table_id": "table",
"state": "active",
})
})).Times(1).Return(&resource.Resource{
Id: "r-table2750132062",
Type: aws.AwsRouteResourceType,
Attrs: &resource.Attributes{
"route_table_id": "table",
"origin": "CreateRoute",
"destination_ipv6_cidr_block": "::/0",
"gateway_id": "igw-07b7844a8fd17a638",
"state": "active",
},
}, nil)
},
assert: func(t *testing.T, result *test.ScanResult, err error) {
result.AssertManagedCount(2)
result.AssertInfrastructureIsInSync()
},
options: func(t *testing.T) *pkg.ScanOptions {
filterStr := "Type=='aws_route' && Attr.gateway_id=='igw-07b7844a8fd17a638'"
f, err := filter.BuildExpression(filterStr)
if err != nil {
t.Fatalf("Unable to build filter expression: %s\n%s", filterStr, err)
}
return &pkg.ScanOptions{Filter: f, Deep: true}
}(t),
},
{
name: "test sns topic policy expander middleware",
stateResources: []*resource.Resource{
&resource.Resource{
Id: "foo",
Type: aws.AwsSnsTopicResourceType,
Attrs: &resource.Attributes{
"arn": "arn",
"id": "foo",
"policy": "{\"policy\":\"bar\"}",
},
},
},
remoteResources: []*resource.Resource{
&resource.Resource{
Id: "foo",
Type: aws.AwsSnsTopicPolicyResourceType,
Attrs: &resource.Attributes{
"id": "foo",
"arn": "arn",
"policy": "{\"policy\":\"baz\"}",
},
},
},
mocks: func(factory resource.ResourceFactory, repo resource.SchemaRepositoryInterface) {
factory.(*terraform.MockResourceFactory).On("CreateAbstractResource", "aws_sns_topic_policy", "foo", map[string]interface{}{
"id": "foo",
"arn": "arn",
"policy": "{\"policy\":\"bar\"}",
}).Times(1).Return(&resource.Resource{
Id: "foo",
Type: aws.AwsSnsTopicPolicyResourceType,
Attrs: &resource.Attributes{
"id": "foo",
"arn": "arn",
"policy": "{\"policy\":\"bar\"}",
},
Sch: getSchema(repo, aws.AwsSnsTopicPolicyResourceType),
}, nil)
},
assert: func(t *testing.T, result *test.ScanResult, err error) {
result.AssertManagedCount(1)
result.AssertResourceHasDrift("foo", "aws_sns_topic_policy", analyser.Change{
Change: diff.Change{
Type: diff.UPDATE,
Path: []string{"policy"},
From: "{\"policy\":\"bar\"}",
To: "{\"policy\":\"baz\"}",
},
Computed: false,
JsonString: true,
})
},
options: func(t *testing.T) *pkg.ScanOptions {
filterStr := "Type=='aws_sns_topic_policy' && Attr.arn=='arn'"
f, err := filter.BuildExpression(filterStr)
if err != nil {
t.Fatalf("Unable to build filter expression: %s\n%s", filterStr, err)
}
return &pkg.ScanOptions{Filter: f, Deep: true}
}(t),
},
{
name: "test sqs queue policy expander middleware",
stateResources: []*resource.Resource{
&resource.Resource{
Id: "foo",
Type: aws.AwsSqsQueueResourceType,
Attrs: &resource.Attributes{
"id": "foo",
"policy": "{\"policy\":\"bar\"}",
},
},
},
remoteResources: []*resource.Resource{
&resource.Resource{
Id: "foo",
Type: aws.AwsSqsQueuePolicyResourceType,
Attrs: &resource.Attributes{
"id": "foo",
"queue_url": "foo",
"policy": "{\"policy\":\"baz\"}",
},
},
},
mocks: func(factory resource.ResourceFactory, repo resource.SchemaRepositoryInterface) {
factory.(*terraform.MockResourceFactory).On("CreateAbstractResource", "aws_sqs_queue_policy", "foo", map[string]interface{}{
"id": "foo",
"queue_url": "foo",
"policy": "{\"policy\":\"bar\"}",
}).Times(1).Return(&resource.Resource{
Id: "foo",
Type: aws.AwsSqsQueuePolicyResourceType,
Attrs: &resource.Attributes{
"id": "foo",
"queue_url": "foo",
"policy": "{\"policy\":\"bar\"}",
},
Sch: getSchema(repo, aws.AwsSqsQueuePolicyResourceType),
}, nil)
},
assert: func(t *testing.T, result *test.ScanResult, err error) {
result.AssertManagedCount(1)
result.AssertResourceHasDrift("foo", "aws_sqs_queue_policy", analyser.Change{
Change: diff.Change{
Type: diff.UPDATE,
Path: []string{"policy"},
From: "{\"policy\":\"bar\"}",
To: "{\"policy\":\"baz\"}",
},
Computed: false,
JsonString: true,
})
},
options: func(t *testing.T) *pkg.ScanOptions {
filterStr := "Type=='aws_sqs_queue_policy' && Attr.queue_url=='foo'"
f, err := filter.BuildExpression(filterStr)
if err != nil {
t.Fatalf("Unable to build filter expression: %s\n%s", filterStr, err)
}
return &pkg.ScanOptions{Filter: f, Deep: true}
}(t),
},
{
name: "test security group rule sanitizer middleware",
stateResources: []*resource.Resource{
&resource.Resource{
Type: aws.AwsSecurityGroupRuleResourceType,
Id: "sgrule-3970541193",
Attrs: &resource.Attributes{
"id": "sgrule-3970541193",
"type": "ingress",
"security_group_id": "sg-0254c038e32f25530",
"protocol": "tcp",
"from_port": float64(0),
"to_port": float64(65535),
"self": true,
"source_security_group_id": "sg-0254c038e32f25530",
},
},
&resource.Resource{
Type: aws.AwsSecurityGroupRuleResourceType,
Id: "sgrule-845917806",
Attrs: &resource.Attributes{
"id": "sgrule-845917806",
"type": "egress",
"security_group_id": "sg-0254c038e32f25530",
"protocol": "-1",
"from_port": float64(0),
"to_port": float64(0),
"cidr_blocks": []interface{}{"0.0.0.0/0"},
"ipv6_cidr_blocks": []interface{}{"::/0"},
},
},
&resource.Resource{
Type: aws.AwsSecurityGroupRuleResourceType,
Id: "sgrule-294318973",
Attrs: &resource.Attributes{
"id": "sgrule-294318973",
"type": "ingress",
"security_group_id": "sg-0254c038e32f25530",
"protocol": "-1",
"from_port": float64(0),
"to_port": float64(0),
"cidr_blocks": []interface{}{"1.2.0.0/16", "5.6.7.0/24"},
},
},
&resource.Resource{
Type: aws.AwsSecurityGroupRuleResourceType,
Id: "sgrule-2471889226",
Attrs: &resource.Attributes{
"id": "sgrule-2471889226",
"type": "ingress",
"security_group_id": "sg-0254c038e32f25530",
"protocol": "tcp",
"from_port": float64(0),
"to_port": float64(0),
"prefix_list_ids": []interface{}{"pl-abb451c2"},
},
},
&resource.Resource{
Type: aws.AwsSecurityGroupRuleResourceType,
Id: "sgrule-3587309474",
Attrs: &resource.Attributes{
"id": "sgrule-3587309474",
"type": "ingress",
"security_group_id": "sg-0254c038e32f25530",
"protocol": "tcp",
"from_port": float64(0),
"to_port": float64(65535),
"source_security_group_id": "sg-9e0204ff",
},
},
},
remoteResources: []*resource.Resource{
&resource.Resource{
Type: aws.AwsSecurityGroupRuleResourceType,
Id: "sgrule-3970541193",
Attrs: &resource.Attributes{
"id": "sgrule-3970541193",
"type": "ingress",
"security_group_id": "sg-0254c038e32f25530",
"protocol": "tcp",
"from_port": float64(0),
"to_port": float64(65535),
"self": true,
"source_security_group_id": "sg-0254c038e32f25530",
},
},
&resource.Resource{
Type: aws.AwsSecurityGroupRuleResourceType,
Id: "sgrule-1707973622",
Attrs: &resource.Attributes{
"id": "sgrule-1707973622",
"type": "egress",
"security_group_id": "sg-0254c038e32f25530",
"protocol": "-1",
"from_port": float64(0),
"to_port": float64(0),
"cidr_blocks": []interface{}{"0.0.0.0/0"},
"ipv6_cidr_blocks": []interface{}{},
"prefix_list_ids": []interface{}{},
},
},
&resource.Resource{
Type: aws.AwsSecurityGroupRuleResourceType,
Id: "sgrule-2821752134",
Attrs: &resource.Attributes{
"id": "sgrule-2821752134",
"type": "egress",
"security_group_id": "sg-0254c038e32f25530",
"protocol": "-1",
"from_port": float64(0),
"to_port": float64(0),
"cidr_blocks": []interface{}{},
"ipv6_cidr_blocks": []interface{}{"::/0"},
"prefix_list_ids": []interface{}{},
},
},
&resource.Resource{
Type: aws.AwsSecurityGroupRuleResourceType,
Id: "sgrule-2165103420",
Attrs: &resource.Attributes{
"id": "sgrule-2165103420",
"type": "ingress",
"security_group_id": "sg-0254c038e32f25530",
"protocol": "-1",
"from_port": float64(0),
"to_port": float64(0),
"cidr_blocks": []interface{}{"5.6.7.0/24"},
"ipv6_cidr_blocks": []interface{}{},
"prefix_list_ids": []interface{}{},
},
},
&resource.Resource{
Type: aws.AwsSecurityGroupRuleResourceType,
Id: "sgrule-2582518759",
Attrs: &resource.Attributes{
"id": "sgrule-2582518759",
"type": "ingress",
"security_group_id": "sg-0254c038e32f25530",
"protocol": "-1",
"from_port": float64(0),
"to_port": float64(0),
"cidr_blocks": []interface{}{"1.2.0.0/16"},
"ipv6_cidr_blocks": []interface{}{},
"prefix_list_ids": []interface{}{},
},
},
&resource.Resource{
Type: aws.AwsSecurityGroupRuleResourceType,
Id: "sgrule-2471889226",
Attrs: &resource.Attributes{
"id": "sgrule-2471889226",
"type": "ingress",
"security_group_id": "sg-0254c038e32f25530",
"protocol": "tcp",
"from_port": float64(0),
"to_port": float64(0),
"prefix_list_ids": []interface{}{"pl-abb451c2"},
},
},
&resource.Resource{
Type: aws.AwsSecurityGroupRuleResourceType,
Id: "sgrule-3587309474",
Attrs: &resource.Attributes{
"id": "sgrule-3587309474",
"type": "ingress",
"security_group_id": "sg-0254c038e32f25530",
"protocol": "tcp",
"from_port": float64(0),
"to_port": float64(65535),
"source_security_group_id": "sg-9e0204ff",
},
},
},
mocks: func(factory resource.ResourceFactory, repo resource.SchemaRepositoryInterface) {
rule1 := resource.Resource{
Type: aws.AwsSecurityGroupRuleResourceType,
Id: "sgrule-1707973622",
Attrs: &resource.Attributes{
"id": "sgrule-1707973622",
"type": "egress",
"security_group_id": "sg-0254c038e32f25530",
"protocol": "-1",
"from_port": float64(0),
"to_port": float64(0),
"cidr_blocks": []interface{}{
"0.0.0.0/0",
},
"ipv6_cidr_blocks": []interface{}{},
"prefix_list_ids": []interface{}{},
},
}
factory.(*terraform.MockResourceFactory).On("CreateAbstractResource", "aws_security_group_rule", rule1.Id,
mock.MatchedBy(func(input map[string]interface{}) bool {
return matchByAttributes(input, map[string]interface{}{
"id": "sgrule-1707973622",
"type": "egress",
"security_group_id": "sg-0254c038e32f25530",
"protocol": "-1",
"from_port": float64(0),
"to_port": float64(0),
"cidr_blocks": []interface{}{"0.0.0.0/0"},
"ipv6_cidr_blocks": []interface{}{},
"prefix_list_ids": []interface{}{},
})
})).Times(1).Return(&rule1, nil)
rule2 := resource.Resource{
Type: aws.AwsSecurityGroupRuleResourceType,
Id: "sgrule-2821752134",
Attrs: &resource.Attributes{
"id": "sgrule-2821752134",
"type": "egress",
"security_group_id": "sg-0254c038e32f25530",
"protocol": "-1",
"from_port": float64(0),
"to_port": float64(0),
"cidr_blocks": []interface{}{},
"ipv6_cidr_blocks": []interface{}{
"::/0",
},
"prefix_list_ids": []interface{}{},
},
}
factory.(*terraform.MockResourceFactory).On("CreateAbstractResource", "aws_security_group_rule", rule2.Id,
mock.MatchedBy(func(input map[string]interface{}) bool {
return matchByAttributes(input, map[string]interface{}{
"id": "sgrule-2821752134",
"type": "egress",
"security_group_id": "sg-0254c038e32f25530",
"protocol": "-1",
"from_port": float64(0),
"to_port": float64(0),
"cidr_blocks": []interface{}{},
"ipv6_cidr_blocks": []interface{}{"::/0"},
"prefix_list_ids": []interface{}{},
})
})).Times(1).Return(&rule2, nil)
rule3 := resource.Resource{
Type: aws.AwsSecurityGroupRuleResourceType,
Id: "sgrule-2165103420",
Attrs: &resource.Attributes{
"id": "sgrule-2165103420",
"type": "ingress",
"security_group_id": "sg-0254c038e32f25530",
"protocol": "-1",
"from_port": float64(0),
"to_port": float64(0),
"cidr_blocks": []interface{}{
"5.6.7.0/24",
},
"ipv6_cidr_blocks": []interface{}{},
"prefix_list_ids": []interface{}{},
},
}
factory.(*terraform.MockResourceFactory).On("CreateAbstractResource", "aws_security_group_rule", rule3.Id,
mock.MatchedBy(func(input map[string]interface{}) bool {
return matchByAttributes(input, map[string]interface{}{
"id": "sgrule-2165103420",
"type": "ingress",
"security_group_id": "sg-0254c038e32f25530",
"protocol": "-1",
"from_port": float64(0),
"to_port": float64(0),
"cidr_blocks": []interface{}{"5.6.7.0/24"},
"ipv6_cidr_blocks": []interface{}{},
"prefix_list_ids": []interface{}{},
})
})).Times(1).Return(&rule3, nil)
rule4 := resource.Resource{
Type: aws.AwsSecurityGroupRuleResourceType,
Id: "sgrule-2582518759",
Attrs: &resource.Attributes{
"id": "sgrule-2582518759",
"type": "ingress",
"security_group_id": "sg-0254c038e32f25530",
"protocol": "-1",
"from_port": float64(0),
"to_port": float64(0),
"cidr_blocks": []interface{}{
"1.2.0.0/16",
},
"ipv6_cidr_blocks": []interface{}{},
"prefix_list_ids": []interface{}{},
},
}
factory.(*terraform.MockResourceFactory).On("CreateAbstractResource", "aws_security_group_rule", rule4.Id,
mock.MatchedBy(func(input map[string]interface{}) bool {
return matchByAttributes(input, map[string]interface{}{
"id": "sgrule-2582518759",
"type": "ingress",
"security_group_id": "sg-0254c038e32f25530",
"protocol": "-1",
"from_port": float64(0),
"to_port": float64(0),
"cidr_blocks": []interface{}{"1.2.0.0/16"},
"ipv6_cidr_blocks": []interface{}{},
"prefix_list_ids": []interface{}{},
})
})).Times(1).Return(&rule4, nil)
},
assert: func(t *testing.T, result *test.ScanResult, err error) {
result.AssertManagedCount(7)
result.AssertInfrastructureIsInSync()
},
options: func(t *testing.T) *pkg.ScanOptions {
filterStr := "Type=='aws_security_group_rule' && Attr.security_group_id=='sg-0254c038e32f25530'"
f, err := filter.BuildExpression(filterStr)
if err != nil {
t.Fatalf("Unable to build filter expression: %s\n%s", filterStr, err)
}
return &pkg.ScanOptions{Filter: f, Deep: true}
}(t),
},
{
name: "test iam_policy_attachment_transformer & iam_policy_attachment_expander middleware",
stateResources: []*resource.Resource{
&resource.Resource{
Type: aws.AwsSecurityGroupRuleResourceType,
Id: "sgrule-3970541193",
Attrs: &resource.Attributes{
"id": "sgrule-3970541193",
"type": "ingress",
"security_group_id": "sg-0254c038e32f25530",
"protocol": "tcp",
"from_port": float64(0),
"to_port": float64(65535),
"self": true,
"source_security_group_id": "sg-0254c038e32f25530",
},
},
&resource.Resource{
Id: "iduser1",
Type: aws.AwsIamUserPolicyAttachmentResourceType,
Attrs: &resource.Attributes{
"policy_arn": "policy_arn1",
"user": "user1",
},
},
&resource.Resource{
Id: "idrole1",
Type: aws.AwsIamRolePolicyAttachmentResourceType,
Attrs: &resource.Attributes{
"policy_arn": "policy_arn1",
"role": "role1",
},
},
},
remoteResources: []*resource.Resource{
&resource.Resource{
Type: aws.AwsSecurityGroupRuleResourceType,
Id: "sgrule-3970541193",
Attrs: &resource.Attributes{
"id": "sgrule-3970541193",
"type": "ingress",
"security_group_id": "sg-0254c038e32f25530",
"protocol": "tcp",
"from_port": float64(0),
"to_port": float64(65535),
"self": true,
"source_security_group_id": "sg-0254c038e32f25530",
},
},
&resource.Resource{
Id: "iduser1",
Type: aws.AwsIamUserPolicyAttachmentResourceType,
Attrs: &resource.Attributes{
"policy_arn": "policy_arn1",
"user": "user1",
},
},
&resource.Resource{
Id: "idrole1",
Type: aws.AwsIamRolePolicyAttachmentResourceType,
Attrs: &resource.Attributes{
"policy_arn": "policy_arn1",
"role": "role1",
},
},
},
mocks: func(factory resource.ResourceFactory, repo resource.SchemaRepositoryInterface) {
factory.(*terraform.MockResourceFactory).On("CreateAbstractResource", aws.AwsIamPolicyAttachmentResourceType, "iduser1", map[string]interface{}{
"id": "iduser1",
"policy_arn": "policy_arn1",
"users": []interface{}{"user1"},
"groups": []interface{}{},
"roles": []interface{}{},
}).Twice().Return(&resource.Resource{
Id: "id1",
Type: aws.AwsIamPolicyAttachmentResourceType,
Attrs: &resource.Attributes{
"id": "iduser1",
"policy_arn": "policy_arn1",
"users": []interface{}{"user1"},
"groups": []interface{}{},
"roles": []interface{}{},
},
}, nil)
factory.(*terraform.MockResourceFactory).On("CreateAbstractResource", aws.AwsIamPolicyAttachmentResourceType, "user1-policy_arn1", map[string]interface{}{
"policy_arn": "policy_arn1",
"users": []interface{}{"user1"},
}).Twice().Return(&resource.Resource{
Id: "user1-policy_arn1",
Type: aws.AwsIamPolicyAttachmentResourceType, | "policy_arn": "policy_arn1",
"users": []interface{}{"user1"},
},
}, nil)
factory.(*terraform.MockResourceFactory).On("CreateAbstractResource", aws.AwsIamPolicyAttachmentResourceType, "idrole1", map[string]interface{}{
"id": "idrole1",
"policy_arn": "policy_arn1",
"users": []interface{}{},
"groups": []interface{}{},
"roles": []interface{}{"role1"},
}).Twice().Return(&resource.Resource{
Id: "idrole1",
Type: aws.AwsIamPolicyAttachmentResourceType,
Attrs: &resource.Attributes{
"id": "idrole1",
"policy_arn": "policy_arn1",
"users": []interface{}{},
"groups": []interface{}{},
"roles": []interface{}{"role1"},
},
}, nil)
factory.(*terraform.MockResourceFactory).On("CreateAbstractResource", aws.AwsIamPolicyAttachmentResourceType, "role1-policy_arn1", map[string]interface{}{
"policy_arn": "policy_arn1",
"roles": []interface{}{"role1"},
}).Twice().Return(&resource.Resource{
Id: "role1-policy_arn1",
Type: aws.AwsIamPolicyAttachmentResourceType,
Attrs: &resource.Attributes{
"policy_arn": "policy_arn1",
"roles": []interface{}{"role1"},
},
}, nil)
},
assert: func(t *testing.T, result *test.ScanResult, err error) {
result.AssertManagedCount(2)
result.AssertInfrastructureIsInSync()
},
options: func(t *testing.T) *pkg.ScanOptions {
filterStr := "Type=='aws_iam_policy_attachment'"
f, err := filter.BuildExpression(filterStr)
if err != nil {
t.Fatalf("Unable to build filter expression: %s\n%s", filterStr, err)
}
return &pkg.ScanOptions{Filter: f, Deep: true}
}(t),
},
{
name: "test aws role managed policy expander",
stateResources: []*resource.Resource{
&resource.Resource{
Id: "role_with_managed_policy_attr",
Type: aws.AwsIamRoleResourceType,
Attrs: &resource.Attributes{
"name": "role_with_managed_policy_attr",
"managed_policy_arns": []interface{}{
"arn1",
"arn2",
},
},
},
&resource.Resource{
Id: "role_with_managed_policy_attr-arn2",
Type: aws.AwsIamPolicyAttachmentResourceType,
Attrs: &resource.Attributes{
"policy_arn": "arn2",
"roles": []interface{}{"role_with_managed_policy_attr"},
},
},
&resource.Resource{
Id: "role_with_empty_managed_policy_attribute",
Type: aws.AwsIamRoleResourceType,
Attrs: &resource.Attributes{
"managed_policy_arns": []interface{}{},
},
},
&resource.Resource{
Id: "role_without_managed_policy_attribute",
Type: aws.AwsIamRoleResourceType,
Attrs: &resource.Attributes{},
},
},
remoteResources: []*resource.Resource{
&resource.Resource{
Id: "role_with_managed_policy_attr",
Type: aws.AwsIamRoleResourceType,
Attrs: &resource.Attributes{
"name": "role_with_managed_policy_attr",
},
},
&resource.Resource{
Id: "role_with_managed_policy_attr-arn1",
Type: aws.AwsIamPolicyAttachmentResourceType,
Attrs: &resource.Attributes{
"policy_arn": "arn1",
"roles": []interface{}{"role_with_managed_policy_attr"},
},
},
&resource.Resource{
Id: "role_with_managed_policy_attr-arn2",
Type: aws.AwsIamPolicyAttachmentResourceType,
Attrs: &resource.Attributes{
"policy_arn": "arn2",
"roles": []interface{}{"role_with_managed_policy_attr"},
},
},
&resource.Resource{
Id: "role_with_empty_managed_policy_attribute",
Type: aws.AwsIamRoleResourceType,
Attrs: &resource.Attributes{},
},
&resource.Resource{
Id: "role_without_managed_policy_attribute",
Type: aws.AwsIamRoleResourceType,
Attrs: &resource.Attributes{},
},
},
assert: func(t *testing.T, result *test.ScanResult, err error) {
result.AssertInfrastructureIsInSync()
result.AssertManagedCount(5)
},
},
{
name: "test aws eip association expander middleware",
stateResources: []*resource.Resource{
&resource.Resource{
Id: "ID",
Type: "ANOTHERTYPE",
Attrs: &resource.Attributes{},
},
&resource.Resource{
Id: "associdpresentinstate",
Type: aws.AwsEipAssociationResourceType,
Attrs: &resource.Attributes{},
},
&resource.Resource{
Id: "associdpresentinstate",
Type: aws.AwsEipResourceType,
Attrs: &resource.Attributes{
"association_id": "associdpresentinstate",
},
},
&resource.Resource{
Id: "associdNOTpresentinstate",
Type: aws.AwsEipResourceType,
Attrs: &resource.Attributes{
"association_id": "associdNOTpresentinstate",
"instance": "instanceidNOTpresentinstate",
"network_interface": "networkinterface",
"private_ip": "privateip",
"public_ip": "publicip",
},
},
},
remoteResources: []*resource.Resource{
&resource.Resource{
Id: "ID",
Type: "ANOTHERTYPE",
Attrs: &resource.Attributes{},
},
&resource.Resource{
Id: "associdpresentinstate",
Type: aws.AwsEipAssociationResourceType,
Attrs: &resource.Attributes{},
},
&resource.Resource{
Id: "associdpresentinstate",
Type: aws.AwsEipResourceType,
Attrs: &resource.Attributes{
"association_id": "associdpresentinstate",
},
},
&resource.Resource{
Id: "associdNOTpresentinstate",
Type: aws.AwsEipAssociationResourceType,
Attrs: &resource.Attributes{
"allocation_id": "associdNOTpresentinstate",
"id": "associdNOTpresentinstate",
"instance_id": "instanceidNOTpresentinstate",
"network_interface_id": "networkinterface",
"private_ip_address": "privateip",
"public_ip": "publicip",
},
},
&resource.Resource{
Id: "associdNOTpresentinstate",
Type: aws.AwsEipResourceType,
Attrs: &resource.Attributes{
"association_id": "associdNOTpresentinstate",
"instance": "instanceidNOTpresentinstate",
"network_interface": "networkinterface",
"private_ip": "privateip",
"public_ip": "publicip",
},
},
},
assert: func(t *testing.T, result *test.ScanResult, err error) {
result.AssertInfrastructureIsInSync()
result.AssertManagedCount(5)
},
},
}
runTest(t, cases)
}
func getSchema(repo resource.SchemaRepositoryInterface, resourceType string) *resource.Schema {
sch, _ := repo.GetSchema(resourceType)
return sch
} | Attrs: &resource.Attributes{ |
report.py | import rkivacc
import os
import tempfile
import email.utils
import requests
import openpyxl
class RKIReport:
def | (row, map, column):
if not column in map:
return None
value = row[map[column]].value
if isinstance(value, str):
return RKIReport.__strip_stars(value)
else:
return value
def __extract_row(row, map, state = True):
data = {}
if state:
data["state"] = RKIReport.__get_column(row, map, "state")
data.update({
"vaccinations": RKIReport.__get_column(row, map, "vaccinations"),
"delta": RKIReport.__get_column(row, map, "delta"),
"vaccinations_per_capita": RKIReport.__get_column(row, map, "vaccinations_per_capita"),
"reasons": {
"age": RKIReport.__get_column(row, map, "reasons_age"),
"profession": RKIReport.__get_column(row, map, "reasons_profession"),
"medical": RKIReport.__get_column(row, map, "reasons_medical"),
"nursing_home": RKIReport.__get_column(row, map, "reasons_nursing_home")
}
})
return data
def __strip_stars(str):
while str[-1] == "*":
str = str[0:-1]
return str
def __init__(self, report_xlsx_path, modified = None):
workbook = openpyxl.load_workbook(filename = report_xlsx_path, data_only = True)
sheet = workbook.worksheets[rkivacc.WORKSHEET_INDEX]
self._states = {}
self._modified = modified
table_rows = sheet.iter_rows(min_row=rkivacc.TABLE_FIRST_ROW - 1,
max_row=rkivacc.TABLE_FIRST_ROW + rkivacc.TABLE_LENGTH - 1,
max_col=10)
header_row = next(table_rows)
known_rows = {
"RS": None,
"Bundesland": "state",
"Impfungen kumulativ": "vaccinations",
"Differenz zum Vortag": "delta",
"Impfungen pro 1.000 Einwohner": "vaccinations_per_capita",
"Indikation nach Alter": "reasons_age",
"Berufliche Indikation": "reasons_profession",
"Medizinische Indikation": "reasons_medical",
"Pflegeheim-bewohnerIn": "reasons_nursing_home",
}
map = {}
for cellIndex in range(0, len(header_row)):
value = header_row[cellIndex].value
if value is None:
continue
value = RKIReport.__strip_stars(value)
if not value in known_rows:
print("Warning: Found unknown header item '{}'. This might be bad news.".format(value))
continue
key = known_rows[value]
if key is None:
continue
map[key] = cellIndex
total_row = next(sheet.iter_rows(min_row=rkivacc.TABLE_FIRST_ROW + rkivacc.TABLE_LENGTH,
max_row=rkivacc.TABLE_FIRST_ROW + rkivacc.TABLE_LENGTH,
max_col=10))
for row in table_rows:
self._states[RKIReport.__strip_stars(row[map["state"]].value)] = RKIReport.__extract_row(row, map)
self._total = RKIReport.__extract_row(total_row, map, state = False)
def states(self):
return list(self._states.keys())
def state(self, name):
return self._states[name]
def all_states(self):
return self._states.values()
def total(self):
return self._total
def modified(self):
return self._modified
def has_per_capita(self):
return (self._total["vaccinations_per_capita"] is not None)
def calculate_per_capita(self):
if self.has_per_capita():
print("Per capita data already present! Not overwriting.")
return
for state in self.states():
if not state in rkivacc.POPULATION_STATS:
raise RuntimeError("State '{}' not in population stats!".format(state))
self._states[state]["vaccinations_per_capita"] = (self._states[state]["vaccinations"] / rkivacc.POPULATION_STATS[state]) * 1000
self._total["vaccinations_per_capita"] = (self._total["vaccinations"] / rkivacc.POPULATION_STATS["total"]) * 1000
def download(target_path):
try:
response = requests.get(rkivacc.URL)
except RequestException:
raise RuntimeError("Failed to obtain statistics from server")
if not response.ok:
raise RuntimeError("Unexpected status code from server: {}".format(response.status_code))
with open(target_path, "wb") as file:
file.write(response.content)
return email.utils.parsedate_to_datetime(response.headers['Last-Modified'])
def obtain():
temp_dir = tempfile.TemporaryDirectory()
temp_file = os.path.join(temp_dir.name, "rkiReport.xlsx")
last_modified = RKIReport.download(temp_file)
report = RKIReport(temp_file, last_modified)
temp_dir.cleanup()
return report
| __get_column |
listings.go | /*
Copyright © 2020-2021 The k3d Author(s)
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.
*/
package util
import (
"encoding/json"
"fmt"
"os"
"sort"
"strings"
"github.com/liggitt/tabwriter"
k3d "github.com/rancher/k3d/v4/pkg/types"
log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v2"
)
type NodePrinter interface {
Print(*tabwriter.Writer, *k3d.Node)
}
type NodePrinterFunc func(*tabwriter.Writer, *k3d.Node)
func (npf NodePrinterFunc) Print(writter *tabwriter.Writer, node *k3d.Node) {
npf(writter, node)
}
// PrintNodes prints a list of nodes, either as a table or as a JSON/YAML listing
func PrintNodes(nodes []*k3d.Node, outputFormat string, headers *[]string, nodePrinter NodePrinter) { |
outputFormat = strings.ToLower(outputFormat)
tabwriter := tabwriter.NewWriter(os.Stdout, 6, 4, 3, ' ', tabwriter.RememberWidths)
defer tabwriter.Flush()
if outputFormat != "json" && outputFormat != "yaml" {
if headers != nil {
_, err := fmt.Fprintf(tabwriter, "%s\n", strings.Join(*headers, "\t"))
if err != nil {
log.Fatalln("Failed to print headers")
}
}
}
sort.Slice(nodes, func(i, j int) bool {
return nodes[i].Name < nodes[j].Name
})
if outputFormat == "json" || outputFormat == "yaml" {
var b []byte
var err error
switch outputFormat {
case "json":
b, err = json.Marshal(nodes)
case "yaml":
b, err = yaml.Marshal(nodes)
}
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(b))
} else {
for _, node := range nodes {
if !(outputFormat == "json" || outputFormat == "yaml") {
nodePrinter.Print(tabwriter, node)
}
}
}
}
|
|
index.js | const generateHTML = require('./src/GenerateHTML');
const Manager = require('./lib/Manager');
const Engineer = require('./lib/Engineer');
const Intern = require('./lib/Intern');
const fs = require('fs');
const inquirer = require('inquirer');
const { validate } = require('@babel/types');
const teamArray = [];
const addManager = () => {
return inquirer.prompt([
{
type: 'input',
message: 'What is the name of the manager for this team?',
name: 'name',
validate: userInput => {
if (userInput) {
return true;
} else {
console.log("Please enter the manager's name.");
return false;
}
}
},
{
type: 'input',
message: "What is the team manager's ID number?",
name: 'id',
validate: userInput => {
if (isNaN(userInput)) {
console.log("Please enter the manger's ID number!")
return false;
} else {
return true;
}
}
},
{
type: 'input',
message: "What is the the team manager's email adress?",
name: 'email',
validate: email => {
valid = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)
if (valid) {
return true;
} else {
console.log('Please enter a valid email adress!')
return false;
}
}
},
{ | validate: userInput => {
if (isNaN(userInput)) {
console.log('Please input a valid office number!')
return false;
} else {
return true
}
}
}
])
.then(managerInput => {
const { name, id, email, officeNumber } = managerInput;
const manager = new Manager(name, id, email, officeNumber);
teamArray.push(manager);
})
};
const addEmployee = () => {
console.log(`
==============================
Adding employees to your team!
==============================
`);
return inquirer.prompt([
{
type: 'list',
message: "Please select your team members role.",
choices: ['Engineer', 'Intern'],
name: 'role',
},
{
type: 'input',
message: "What is your team member's name?",
name: 'name',
validate: userInput => {
if (userInput) {
return true
} else {
console.log("Please enter your team member's name!")
return false;
}
}
},
{
type: 'input',
message: "What is your team member's employee ID number?",
name: 'id',
validate: userInput => {
if (isNaN(userInput)) {
console.log("Please enter your team member's employee ID number!")
return false;
} else {
return true;
}
}
},
{
type: 'input',
message: "What is your team member's email adress?",
name: 'email',
validate: email => {
valid = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)
if (valid) {
return true;
} else {
console.log("Please enter a valid email adress!")
return false;
}
}
},
{
type: 'input',
when: (input) => input.role === 'Engineer',
message: "What is your engineer's github username?",
name: 'github',
validate: userInput => {
if (userInput) {
return true;
} else {
console.log("Please enter your engineer's github username!")
return false;
}
}
},
{
type: 'input',
when: (input) => input.role === 'Intern',
message: "What is the name of your intern's school?",
name: 'school',
validate: userInput => {
if (userInput) {
return true;
} else {
console.log("Please enter the name of your intern's school!")
return false;
}
}
},
{
type: 'confirm',
message: 'Would you like to add any more team members?',
name: 'confirmTeamMembers',
default: false
}
])
.then(employeeData => {
let { name, id, email, role, github, school, confirmTeamMembers } = employeeData;
let employee;
if (role === 'Engineer') {
employee = new Engineer(name, id, email, github);
} else if (role === 'Intern') {
employee = new Intern(name, id, email, school);
}
teamArray.push(employee);
if (confirmTeamMembers) {
return addEmployee(teamArray);
} else {
return teamArray;
}
})
};
const writeFile = data => {
fs.writeFile('./dist/index.html', data, err => {
if (err) {
console.error(err);
return;
} else {
console.log("Your team's profile has been successfully generated! You can find it in the 'dist' folder.")
}
})
};
addManager()
.then(addEmployee)
.then(teamArray => {
return generateHTML(teamArray);
})
.then(pageHTML => {
return writeFile(pageHTML);
})
.catch(err => {
console.error(err);
}); | type: 'input',
message: "What is the team manager's office number?",
name: 'officeNumber', |
hash_set.rs | use std::collections::HashSet;
use std::hash::BuildHasher;
use std::iter::FromIterator;
use crate::{IntoParallelIterator, ParallelDrainFull};
impl<'a, I, S> IntoParallelIterator<'a> for HashSet<I, S>
where
I: Send + 'a,
S: BuildHasher,
{
type Iter = <Vec<I> as IntoParallelIterator<'a>>::Iter;
type Item = I;
fn into_par_iter(self) -> Self::Iter {
let vec = Vec::from_iter(self);
vec.into_par_iter() |
impl<'a, I, S> IntoParallelIterator<'a> for &'a HashSet<I, S>
where
I: Send + Sync + 'a,
S: BuildHasher,
{
type Iter = <Vec<&'a I> as IntoParallelIterator<'a>>::Iter;
type Item = &'a I;
fn into_par_iter(self) -> Self::Iter {
let vec = Vec::<&'a I>::from_iter(self);
vec.into_par_iter()
}
}
impl<'a, I, S> ParallelDrainFull<'a> for &'a mut HashSet<I, S>
where
I: Send + 'a,
S: BuildHasher,
{
type Iter = <Vec<I> as IntoParallelIterator<'a>>::Iter;
type Item = I;
fn par_drain(self) -> Self::Iter {
let vec = self.drain().collect::<Vec<_>>();
vec.into_par_iter()
}
} | }
} |
challenge.go | package serve
import (
"net/http"
"time"
| "github.com/stellar/go/strkey"
supportlog "github.com/stellar/go/support/log"
"github.com/stellar/go/support/render/httpjson"
"github.com/stellar/go/txnbuild"
)
// ChallengeHandler implements the SEP-10 challenge endpoint and handles
// requests for a new challenge transaction.
type challengeHandler struct {
Logger *supportlog.Entry
ServerName string
NetworkPassphrase string
SigningKey *keypair.Full
ChallengeExpiresIn time.Duration
}
type challengeResponse struct {
Transaction string `json:"transaction"`
NetworkPassphrase string `json:"network_passphrase"`
}
func (h challengeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
account := r.URL.Query().Get("account")
if !strkey.IsValidEd25519PublicKey(account) {
badRequest.Render(w)
return
}
tx, err := txnbuild.BuildChallengeTx(
h.SigningKey.Seed(),
account,
h.ServerName,
h.NetworkPassphrase,
h.ChallengeExpiresIn,
)
if err != nil {
h.Logger.Ctx(ctx).WithStack(err).Error(err)
serverError.Render(w)
return
}
hash, err := tx.HashHex(h.NetworkPassphrase)
if err != nil {
h.Logger.Ctx(ctx).WithStack(err).Error(err)
serverError.Render(w)
return
}
l := h.Logger.Ctx(ctx).
WithField("tx", hash).
WithField("account", account)
l.Info("Generated challenge transaction for account.")
txeBase64, err := tx.Base64()
if err != nil {
h.Logger.Ctx(ctx).WithStack(err).Error(err)
serverError.Render(w)
return
}
res := challengeResponse{
Transaction: txeBase64,
NetworkPassphrase: h.NetworkPassphrase,
}
httpjson.Render(w, res, httpjson.JSON)
} | "github.com/stellar/go/keypair" |
multidimensionalarray.test1.go | package main
import "fmt"
func matrix(x, y int) [][]uint8 {
mat := make([]uint8, x*y)
rows := make([][]uint8, y) // Assuming row-based
for i := range rows {
rows[i] = mat[i*x : (i+1)*x]
}
return rows
} | t[xx][yy] = 0
}
}
return t
}
func main() {
fmt.Println("Multi-dimensional Arrays Ahoy!")
var scratch [32][32]uint8
scratch[0][5] = 4
fmt.Println(scratch)
x := 32
s2 :=matrix(x,x)
s2[0][8] = 5
fmt.Println(s2)
s2 = resetMatrix(s2,x)
fmt.Println(s2)
} |
func resetMatrix(t [][]uint8,l int) [][]uint8 {
for xx := 0; xx < l; xx++ {
for yy := 0; yy < l; yy++ { |
test_customer_status.py | # -*- coding: utf-8 -*- | from __future__ import unicode_literals
# import frappe
import unittest
class TestCustomerStatus(unittest.TestCase):
pass | # Copyright (c) 2021, libracore AG and Contributors
# See license.txt |
transaction_mosaic_supply_change.rs | /*
* Copyright 2018 ProximaX Limited. All rights reserved. | use super::{
schema_common_definition::schema_common_definition, ArrayAttribute, ScalarAttribute, Schema,
SchemaAttribute, SIZEOF_BYTE, SIZEOF_INT,
};
pub fn mosaic_supply_change_transaction_schema() -> Schema {
let mut schema_definition = schema_common_definition();
let mut mosaic_supply_change_definition: Vec<Box<dyn SchemaAttribute>> = vec![
Box::new(ArrayAttribute::new("mosaic_id", SIZEOF_INT)),
Box::new(ScalarAttribute::new("direction", SIZEOF_BYTE)),
Box::new(ArrayAttribute::new("delta", SIZEOF_INT)),
];
schema_definition.append(&mut mosaic_supply_change_definition);
Schema::new(schema_definition)
} | * Use of this source code is governed by the Apache 2.0
* license that can be found in the LICENSE file.
*/
|
dash.controllers.SegmentsController.js | import SegmentsController from '../../src/dash/controllers/SegmentsController';
import DashConstants from '../../src/dash/constants/DashConstants';
import Debug from '../../src/core/Debug';
import Settings from '../../src/core/Settings';
import EventBus from '../../src/core/EventBus';
import Events from '../../src/core/events/Events';
import Errors from '../../src/core/errors/Errors';
import ObjectsHelper from './helpers/ObjectsHelper';
import DashMetricsMock from './mocks/DashMetricsMock';
import MediaPlayerModelMock from './mocks/MediaPlayerModelMock';
import ErrorHandlerMock from './mocks/ErrorHandlerMock';
const chai = require('chai');
const expect = chai.expect;
describe('SegmentsController', function () {
// Arrange
const context = {};
const objectsHelper = new ObjectsHelper();
const baseURLController = objectsHelper.getDummyBaseURLController();
const mediaPlayerModel = new MediaPlayerModelMock();
const dashMetricsMock = new DashMetricsMock();
const errHandler = new ErrorHandlerMock();
const settings = Settings(context).getInstance();
const debug = Debug(context).getInstance({settings: settings});
const eventBus = EventBus(context).getInstance();
const segmentsController = SegmentsController(context).create({
streamInfo: {streamId: 'streamId'},
dashMetrics: dashMetricsMock,
mediaPlayerModel: mediaPlayerModel,
errHandler: errHandler,
baseURLController: baseURLController,
dashConstants: DashConstants,
debug: debug,
eventBus: eventBus,
events: Events,
errors: Errors
}, false);
segmentsController.initialize();
it('getSegmentByIndex should return null if representation type is unknown', function () {
// Act |
let s = segmentsController.getSegmentByIndex(representation, 0, 0);
// Assert
expect(s).to.be.null; // jshint ignore:line
});
it('getSegmentByTime should return null if representation type is unknown', function () {
// Act
const representation = {
'segmentInfoType': 'unknown'
};
let s = segmentsController.getSegmentByTime(representation, 0, 0);
// Assert
expect(s).to.be.null; // jshint ignore:line
});
}); | const representation = {
'segmentInfoType': 'unknown'
}; |
flags.rs | //! Command-line interface of the rustbuild build system.
//!
//! This module implements the command-line parsing of the build system which
//! has various flags to configure how it's run.
use std::env;
use std::path::PathBuf;
use std::process;
use build_helper::t;
use getopts::Options;
use crate::builder::Builder;
use crate::config::{Config, TargetSelection};
use crate::{Build, DocTests};
/// Deserialized version of all flags for this compile.
pub struct Flags {
pub verbose: usize, // number of -v args; each extra -v after the first is passed to Cargo
pub on_fail: Option<String>,
pub stage: Option<u32>,
pub keep_stage: Vec<u32>,
pub keep_stage_std: Vec<u32>,
pub host: Option<Vec<TargetSelection>>,
pub target: Option<Vec<TargetSelection>>,
pub config: Option<PathBuf>,
pub jobs: Option<u32>,
pub cmd: Subcommand,
pub incremental: bool,
pub exclude: Vec<PathBuf>,
pub rustc_error_format: Option<String>,
pub json_output: bool,
pub dry_run: bool,
// This overrides the deny-warnings configuration option,
// which passes -Dwarnings to the compiler invocations.
//
// true => deny, false => warn
pub deny_warnings: Option<bool>,
pub llvm_skip_rebuild: Option<bool>,
}
pub enum Subcommand {
Build {
paths: Vec<PathBuf>,
},
Check {
paths: Vec<PathBuf>,
},
Clippy {
paths: Vec<PathBuf>,
},
Fix {
paths: Vec<PathBuf>,
},
Format {
check: bool,
},
Doc {
paths: Vec<PathBuf>,
open: bool,
},
Test {
paths: Vec<PathBuf>,
/// Whether to automatically update stderr/stdout files
bless: bool,
compare_mode: Option<String>,
pass: Option<String>,
test_args: Vec<String>,
rustc_args: Vec<String>,
fail_fast: bool,
doc_tests: DocTests,
rustfix_coverage: bool,
},
Bench {
paths: Vec<PathBuf>,
test_args: Vec<String>,
},
Clean {
all: bool,
},
Dist {
paths: Vec<PathBuf>,
},
Install {
paths: Vec<PathBuf>,
},
Run {
paths: Vec<PathBuf>,
},
Setup {
path: String,
},
}
impl Default for Subcommand {
fn default() -> Subcommand {
Subcommand::Build { paths: vec![PathBuf::from("nowhere")] }
}
}
impl Flags {
pub fn parse(args: &[String]) -> Flags {
let mut subcommand_help = String::from(
"\
Usage: x.py <subcommand> [options] [<paths>...]
Subcommands:
build, b Compile either the compiler or libraries
check, c Compile either the compiler or libraries, using cargo check
clippy Run clippy (uses rustup/cargo-installed clippy binary)
fix Run cargo fix
fmt Run rustfmt
test, t Build and run some test suites
bench Build and run some benchmarks
doc Build documentation
clean Clean out build directories
dist Build distribution artifacts
install Install distribution artifacts
run, r Run tools contained in this repository
To learn more about a subcommand, run `./x.py <subcommand> -h`",
);
let mut opts = Options::new();
// Options common to all subcommands
opts.optflagmulti("v", "verbose", "use verbose output (-vv for very verbose)");
opts.optflag("i", "incremental", "use incremental compilation");
opts.optopt("", "config", "TOML configuration file for build", "FILE");
opts.optopt("", "build", "build target of the stage0 compiler", "BUILD");
opts.optmulti("", "host", "host targets to build", "HOST");
opts.optmulti("", "target", "target targets to build", "TARGET");
opts.optmulti("", "exclude", "build paths to exclude", "PATH");
opts.optopt("", "on-fail", "command to run on failure", "CMD");
opts.optflag("", "dry-run", "dry run; don't build anything");
opts.optopt(
"",
"stage",
"stage to build (indicates compiler to use/test, e.g., stage 0 uses the \
bootstrap compiler, stage 1 the stage 0 rustc artifacts, etc.)",
"N",
);
opts.optmulti(
"",
"keep-stage",
"stage(s) to keep without recompiling \
(pass multiple times to keep e.g., both stages 0 and 1)",
"N",
); | "stage(s) of the standard library to keep without recompiling \
(pass multiple times to keep e.g., both stages 0 and 1)",
"N",
);
opts.optopt("", "src", "path to the root of the rust checkout", "DIR");
let j_msg = format!(
"number of jobs to run in parallel; \
defaults to {} (this host's logical CPU count)",
num_cpus::get()
);
opts.optopt("j", "jobs", &j_msg, "JOBS");
opts.optflag("h", "help", "print this help message");
opts.optopt(
"",
"warnings",
"if value is deny, will deny warnings, otherwise use default",
"VALUE",
);
opts.optopt("", "error-format", "rustc error format", "FORMAT");
opts.optflag("", "json-output", "use message-format=json");
opts.optopt(
"",
"llvm-skip-rebuild",
"whether rebuilding llvm should be skipped \
a VALUE of TRUE indicates that llvm will not be rebuilt \
VALUE overrides the skip-rebuild option in config.toml.",
"VALUE",
);
// We can't use getopt to parse the options until we have completed specifying which
// options are valid, but under the current implementation, some options are conditional on
// the subcommand. Therefore we must manually identify the subcommand first, so that we can
// complete the definition of the options. Then we can use the getopt::Matches object from
// there on out.
let subcommand = args.iter().find(|&s| {
(s == "build")
|| (s == "b")
|| (s == "check")
|| (s == "c")
|| (s == "clippy")
|| (s == "fix")
|| (s == "fmt")
|| (s == "test")
|| (s == "t")
|| (s == "bench")
|| (s == "doc")
|| (s == "clean")
|| (s == "dist")
|| (s == "install")
|| (s == "run")
|| (s == "r")
|| (s == "setup")
});
let subcommand = match subcommand {
Some(s) => s,
None => {
// No or an invalid subcommand -- show the general usage and subcommand help
// An exit code will be 0 when no subcommand is given, and 1 in case of an invalid
// subcommand.
println!("{}\n", subcommand_help);
let exit_code = if args.is_empty() { 0 } else { 1 };
process::exit(exit_code);
}
};
// Some subcommands get extra options
match subcommand.as_str() {
"test" | "t" => {
opts.optflag("", "no-fail-fast", "Run all tests regardless of failure");
opts.optmulti("", "test-args", "extra arguments", "ARGS");
opts.optmulti(
"",
"rustc-args",
"extra options to pass the compiler when running tests",
"ARGS",
);
opts.optflag("", "no-doc", "do not run doc tests");
opts.optflag("", "doc", "only run doc tests");
opts.optflag("", "bless", "update all stderr/stdout files of failing ui tests");
opts.optopt(
"",
"compare-mode",
"mode describing what file the actual ui output will be compared to",
"COMPARE MODE",
);
opts.optopt(
"",
"pass",
"force {check,build,run}-pass tests to this mode.",
"check | build | run",
);
opts.optflag(
"",
"rustfix-coverage",
"enable this to generate a Rustfix coverage file, which is saved in \
`/<build_base>/rustfix_missing_coverage.txt`",
);
}
"bench" => {
opts.optmulti("", "test-args", "extra arguments", "ARGS");
}
"doc" => {
opts.optflag("", "open", "open the docs in a browser");
}
"clean" => {
opts.optflag("", "all", "clean all build artifacts");
}
"fmt" => {
opts.optflag("", "check", "check formatting instead of applying.");
}
_ => {}
};
// fn usage()
let usage = |exit_code: i32, opts: &Options, verbose: bool, subcommand_help: &str| -> ! {
let mut extra_help = String::new();
// All subcommands except `clean` can have an optional "Available paths" section
if verbose {
let config = Config::parse(&["build".to_string()]);
let build = Build::new(config);
let maybe_rules_help = Builder::get_help(&build, subcommand.as_str());
extra_help.push_str(maybe_rules_help.unwrap_or_default().as_str());
} else if !(subcommand.as_str() == "clean" || subcommand.as_str() == "fmt") {
extra_help.push_str(
format!("Run `./x.py {} -h -v` to see a list of available paths.", subcommand)
.as_str(),
);
}
println!("{}", opts.usage(subcommand_help));
if !extra_help.is_empty() {
println!("{}", extra_help);
}
process::exit(exit_code);
};
// Done specifying what options are possible, so do the getopts parsing
let matches = opts.parse(&args[..]).unwrap_or_else(|e| {
// Invalid argument/option format
println!("\n{}\n", e);
usage(1, &opts, false, &subcommand_help);
});
// Extra sanity check to make sure we didn't hit this crazy corner case:
//
// ./x.py --frobulate clean build
// ^-- option ^ ^- actual subcommand
// \_ arg to option could be mistaken as subcommand
let mut pass_sanity_check = true;
match matches.free.get(0) {
Some(check_subcommand) => {
if check_subcommand != subcommand {
pass_sanity_check = false;
}
}
None => {
pass_sanity_check = false;
}
}
if !pass_sanity_check {
println!("{}\n", subcommand_help);
println!(
"Sorry, I couldn't figure out which subcommand you were trying to specify.\n\
You may need to move some options to after the subcommand.\n"
);
process::exit(1);
}
// Extra help text for some commands
match subcommand.as_str() {
"build" | "b" => {
subcommand_help.push_str(
"\n
Arguments:
This subcommand accepts a number of paths to directories to the crates
and/or artifacts to compile. For example:
./x.py build library/core
./x.py build library/core library/proc_macro
./x.py build library/std --stage 1
If no arguments are passed then the complete artifacts for that stage are
also compiled.
./x.py build
./x.py build --stage 1
For a quick build of a usable compiler, you can pass:
./x.py build --stage 1 library/test
This will first build everything once (like `--stage 0` without further
arguments would), and then use the compiler built in stage 0 to build
library/test and its dependencies.
Once this is done, build/$ARCH/stage1 contains a usable compiler.",
);
}
"check" | "c" => {
subcommand_help.push_str(
"\n
Arguments:
This subcommand accepts a number of paths to directories to the crates
and/or artifacts to compile. For example:
./x.py check library/core
./x.py check library/core library/proc_macro
If no arguments are passed then the complete artifacts are compiled: std, test, and rustc. Note
also that since we use `cargo check`, by default this will automatically enable incremental
compilation, so there's no need to pass it separately, though it won't hurt. We also completely
ignore the stage passed, as there's no way to compile in non-stage 0 without actually building
the compiler.",
);
}
"clippy" => {
subcommand_help.push_str(
"\n
Arguments:
This subcommand accepts a number of paths to directories to the crates
and/or artifacts to run clippy against. For example:
./x.py clippy library/core
./x.py clippy library/core library/proc_macro",
);
}
"fix" => {
subcommand_help.push_str(
"\n
Arguments:
This subcommand accepts a number of paths to directories to the crates
and/or artifacts to run `cargo fix` against. For example:
./x.py fix library/core
./x.py fix library/core library/proc_macro",
);
}
"fmt" => {
subcommand_help.push_str(
"\n
Arguments:
This subcommand optionally accepts a `--check` flag which succeeds if formatting is correct and
fails if it is not. For example:
./x.py fmt
./x.py fmt --check",
);
}
"test" | "t" => {
subcommand_help.push_str(
"\n
Arguments:
This subcommand accepts a number of paths to test directories that
should be compiled and run. For example:
./x.py test src/test/ui
./x.py test library/std --test-args hash_map
./x.py test library/std --stage 0 --no-doc
./x.py test src/test/ui --bless
./x.py test src/test/ui --compare-mode nll
Note that `test src/test/* --stage N` does NOT depend on `build compiler/rustc --stage N`;
just like `build library/std --stage N` it tests the compiler produced by the previous
stage.
Execute tool tests with a tool name argument:
./x.py test tidy
If no arguments are passed then the complete artifacts for that stage are
compiled and tested.
./x.py test
./x.py test --stage 1",
);
}
"doc" => {
subcommand_help.push_str(
"\n
Arguments:
This subcommand accepts a number of paths to directories of documentation
to build. For example:
./x.py doc src/doc/book
./x.py doc src/doc/nomicon
./x.py doc src/doc/book library/std
./x.py doc library/std --open
If no arguments are passed then everything is documented:
./x.py doc
./x.py doc --stage 1",
);
}
"run" | "r" => {
subcommand_help.push_str(
"\n
Arguments:
This subcommand accepts a number of paths to tools to build and run. For
example:
./x.py run src/tools/expand-yaml-anchors
At least a tool needs to be called.",
);
}
"setup" => {
subcommand_help.push_str(
"\n
Arguments:
This subcommand accepts a 'profile' to use for builds. For example:
./x.py setup library
The profile is optional and you will be prompted interactively if it is not given.",
);
}
_ => {}
};
// Get any optional paths which occur after the subcommand
let mut paths = matches.free[1..].iter().map(|p| p.into()).collect::<Vec<PathBuf>>();
let cfg_file = env::var_os("BOOTSTRAP_CONFIG").map(PathBuf::from);
let verbose = matches.opt_present("verbose");
// User passed in -h/--help?
if matches.opt_present("help") {
usage(0, &opts, verbose, &subcommand_help);
}
let cmd = match subcommand.as_str() {
"build" | "b" => Subcommand::Build { paths },
"check" | "c" => Subcommand::Check { paths },
"clippy" => Subcommand::Clippy { paths },
"fix" => Subcommand::Fix { paths },
"test" | "t" => Subcommand::Test {
paths,
bless: matches.opt_present("bless"),
compare_mode: matches.opt_str("compare-mode"),
pass: matches.opt_str("pass"),
test_args: matches.opt_strs("test-args"),
rustc_args: matches.opt_strs("rustc-args"),
fail_fast: !matches.opt_present("no-fail-fast"),
rustfix_coverage: matches.opt_present("rustfix-coverage"),
doc_tests: if matches.opt_present("doc") {
DocTests::Only
} else if matches.opt_present("no-doc") {
DocTests::No
} else {
DocTests::Yes
},
},
"bench" => Subcommand::Bench { paths, test_args: matches.opt_strs("test-args") },
"doc" => Subcommand::Doc { paths, open: matches.opt_present("open") },
"clean" => {
if !paths.is_empty() {
println!("\nclean does not take a path argument\n");
usage(1, &opts, verbose, &subcommand_help);
}
Subcommand::Clean { all: matches.opt_present("all") }
}
"fmt" => Subcommand::Format { check: matches.opt_present("check") },
"dist" => Subcommand::Dist { paths },
"install" => Subcommand::Install { paths },
"run" | "r" => {
if paths.is_empty() {
println!("\nrun requires at least a path!\n");
usage(1, &opts, verbose, &subcommand_help);
}
Subcommand::Run { paths }
}
"setup" => {
let path = if paths.len() > 1 {
println!("\nat most one profile can be passed to setup\n");
usage(1, &opts, verbose, &subcommand_help)
} else if let Some(path) = paths.pop() {
t!(path.into_os_string().into_string().map_err(|path| format!(
"{} is not a valid UTF8 string",
path.to_string_lossy()
)))
} else {
t!(crate::setup::interactive_path())
};
Subcommand::Setup { path }
}
_ => {
usage(1, &opts, verbose, &subcommand_help);
}
};
if let Subcommand::Check { .. } = &cmd {
if matches.opt_str("stage").is_some() {
println!("--stage not supported for x.py check, always treated as stage 0");
process::exit(1);
}
if matches.opt_str("keep-stage").is_some()
|| matches.opt_str("keep-stage-std").is_some()
{
println!("--keep-stage not supported for x.py check, only one stage available");
process::exit(1);
}
}
Flags {
verbose: matches.opt_count("verbose"),
stage: matches.opt_str("stage").map(|j| j.parse().expect("`stage` should be a number")),
dry_run: matches.opt_present("dry-run"),
on_fail: matches.opt_str("on-fail"),
rustc_error_format: matches.opt_str("error-format"),
json_output: matches.opt_present("json-output"),
keep_stage: matches
.opt_strs("keep-stage")
.into_iter()
.map(|j| j.parse().expect("`keep-stage` should be a number"))
.collect(),
keep_stage_std: matches
.opt_strs("keep-stage-std")
.into_iter()
.map(|j| j.parse().expect("`keep-stage-std` should be a number"))
.collect(),
host: if matches.opt_present("host") {
Some(
split(&matches.opt_strs("host"))
.into_iter()
.map(|x| TargetSelection::from_user(&x))
.collect::<Vec<_>>(),
)
} else {
None
},
target: if matches.opt_present("target") {
Some(
split(&matches.opt_strs("target"))
.into_iter()
.map(|x| TargetSelection::from_user(&x))
.collect::<Vec<_>>(),
)
} else {
None
},
config: cfg_file,
jobs: matches.opt_str("jobs").map(|j| j.parse().expect("`jobs` should be a number")),
cmd,
incremental: matches.opt_present("incremental"),
exclude: split(&matches.opt_strs("exclude"))
.into_iter()
.map(|p| p.into())
.collect::<Vec<_>>(),
deny_warnings: parse_deny_warnings(&matches),
llvm_skip_rebuild: matches.opt_str("llvm-skip-rebuild").map(|s| s.to_lowercase()).map(
|s| s.parse::<bool>().expect("`llvm-skip-rebuild` should be either true or false"),
),
}
}
}
impl Subcommand {
pub fn test_args(&self) -> Vec<&str> {
match *self {
Subcommand::Test { ref test_args, .. } | Subcommand::Bench { ref test_args, .. } => {
test_args.iter().flat_map(|s| s.split_whitespace()).collect()
}
_ => Vec::new(),
}
}
pub fn rustc_args(&self) -> Vec<&str> {
match *self {
Subcommand::Test { ref rustc_args, .. } => {
rustc_args.iter().flat_map(|s| s.split_whitespace()).collect()
}
_ => Vec::new(),
}
}
pub fn fail_fast(&self) -> bool {
match *self {
Subcommand::Test { fail_fast, .. } => fail_fast,
_ => false,
}
}
pub fn doc_tests(&self) -> DocTests {
match *self {
Subcommand::Test { doc_tests, .. } => doc_tests,
_ => DocTests::Yes,
}
}
pub fn bless(&self) -> bool {
match *self {
Subcommand::Test { bless, .. } => bless,
_ => false,
}
}
pub fn rustfix_coverage(&self) -> bool {
match *self {
Subcommand::Test { rustfix_coverage, .. } => rustfix_coverage,
_ => false,
}
}
pub fn compare_mode(&self) -> Option<&str> {
match *self {
Subcommand::Test { ref compare_mode, .. } => compare_mode.as_ref().map(|s| &s[..]),
_ => None,
}
}
pub fn pass(&self) -> Option<&str> {
match *self {
Subcommand::Test { ref pass, .. } => pass.as_ref().map(|s| &s[..]),
_ => None,
}
}
pub fn open(&self) -> bool {
match *self {
Subcommand::Doc { open, .. } => open,
_ => false,
}
}
}
fn split(s: &[String]) -> Vec<String> {
s.iter().flat_map(|s| s.split(',')).filter(|s| !s.is_empty()).map(|s| s.to_string()).collect()
}
fn parse_deny_warnings(matches: &getopts::Matches) -> Option<bool> {
match matches.opt_str("warnings").as_deref() {
Some("deny") => Some(true),
Some("warn") => Some(false),
Some(value) => {
eprintln!(r#"invalid value for --warnings: {:?}, expected "warn" or "deny""#, value,);
process::exit(1);
}
None => None,
}
} | opts.optmulti(
"",
"keep-stage-std", |
blinkgpio24.py | import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(24, GPIO.OUT)
print "Starting to blink GPIO 24" + datetime.datetime.now().isoformat()
while True:
print "GPIO On : " + datetime.datetime.now().isoformat()
GPIO.output(24, True)
time.sleep(2)
print "GPIO Off: " + datetime.datetime.now().isoformat()
GPIO.output(24, False)
time.sleep(2) | #!/usr/bin/python
import RPi.GPIO as GPIO
import datetime |
|
build_info.py | import os
from collections import OrderedDict
from copy import copy
from conans.errors import ConanException
from conans.util.conan_v2_mode import conan_v2_behavior
DEFAULT_INCLUDE = "include"
DEFAULT_LIB = "lib"
DEFAULT_BIN = "bin"
DEFAULT_RES = "res"
DEFAULT_SHARE = "share"
DEFAULT_BUILD = ""
DEFAULT_FRAMEWORK = "Frameworks"
COMPONENT_SCOPE = "::"
class DefaultOrderedDict(OrderedDict):
def __init__(self, factory):
self.factory = factory
super(DefaultOrderedDict, self).__init__()
def __getitem__(self, key):
if key not in self.keys():
super(DefaultOrderedDict, self).__setitem__(key, self.factory())
super(DefaultOrderedDict, self).__getitem__(key).name = key
return super(DefaultOrderedDict, self).__getitem__(key)
def __copy__(self):
the_copy = DefaultOrderedDict(self.factory)
for key, value in super(DefaultOrderedDict, self).items():
the_copy[key] = value
return the_copy
class _CppInfo(object):
""" Object that stores all the necessary information to build in C/C++.
It is intended to be system independent, translation to
specific systems will be produced from this info
"""
def __init__(self):
self._name = None
self.names = {}
self.system_libs = [] # Ordered list of system libraries
self.includedirs = [] # Ordered list of include paths
self.srcdirs = [] # Ordered list of source paths
self.libdirs = [] # Directories to find libraries
self.resdirs = [] # Directories to find resources, data, etc
self.bindirs = [] # Directories to find executables and shared libs
self.builddirs = []
self.frameworks = [] # Macos .framework
self.frameworkdirs = []
self.rootpaths = []
self.libs = [] # The libs to link against
self.defines = [] # preprocessor definitions
self.cflags = [] # pure C flags
self.cxxflags = [] # C++ compilation flags
self.sharedlinkflags = [] # linker flags
self.exelinkflags = [] # linker flags
self.build_modules = []
self.filenames = {} # name of filename to create for various generators
self.rootpath = ""
self.sysroot = ""
self._build_modules_paths = None
self._include_paths = None
self._lib_paths = None
self._bin_paths = None
self._build_paths = None
self._res_paths = None
self._src_paths = None
self._framework_paths = None
self.version = None # Version of the conan package
self.description = None # Description of the conan package | # When package is editable, filter_empty=False, so empty dirs are maintained
self.filter_empty = True
def _filter_paths(self, paths):
abs_paths = [os.path.join(self.rootpath, p)
if not os.path.isabs(p) else p for p in paths]
if self.filter_empty:
return [p for p in abs_paths if os.path.isdir(p)]
else:
return abs_paths
@property
def build_modules_paths(self):
if self._build_modules_paths is None:
self._build_modules_paths = [os.path.join(self.rootpath, p) if not os.path.isabs(p)
else p for p in self.build_modules]
return self._build_modules_paths
@property
def include_paths(self):
if self._include_paths is None:
self._include_paths = self._filter_paths(self.includedirs)
return self._include_paths
@property
def lib_paths(self):
if self._lib_paths is None:
self._lib_paths = self._filter_paths(self.libdirs)
return self._lib_paths
@property
def src_paths(self):
if self._src_paths is None:
self._src_paths = self._filter_paths(self.srcdirs)
return self._src_paths
@property
def bin_paths(self):
if self._bin_paths is None:
self._bin_paths = self._filter_paths(self.bindirs)
return self._bin_paths
@property
def build_paths(self):
if self._build_paths is None:
self._build_paths = self._filter_paths(self.builddirs)
return self._build_paths
@property
def res_paths(self):
if self._res_paths is None:
self._res_paths = self._filter_paths(self.resdirs)
return self._res_paths
@property
def framework_paths(self):
if self._framework_paths is None:
self._framework_paths = self._filter_paths(self.frameworkdirs)
return self._framework_paths
@property
def name(self):
conan_v2_behavior("Use 'get_name(generator)' instead")
return self._name
@name.setter
def name(self, value):
self._name = value
def get_name(self, generator):
return self.names.get(generator, self._name)
def get_filename(self, generator):
result = self.filenames.get(generator)
if result:
return result
return self.get_name(generator)
# Compatibility for 'cppflags' (old style property to allow decoration)
def get_cppflags(self):
conan_v2_behavior("'cpp_info.cppflags' is deprecated, use 'cxxflags' instead")
return self.cxxflags
def set_cppflags(self, value):
conan_v2_behavior("'cpp_info.cppflags' is deprecated, use 'cxxflags' instead")
self.cxxflags = value
cppflags = property(get_cppflags, set_cppflags)
class Component(_CppInfo):
def __init__(self, rootpath):
super(Component, self).__init__()
self.rootpath = rootpath
self.includedirs.append(DEFAULT_INCLUDE)
self.libdirs.append(DEFAULT_LIB)
self.bindirs.append(DEFAULT_BIN)
self.resdirs.append(DEFAULT_RES)
self.builddirs.append(DEFAULT_BUILD)
self.frameworkdirs.append(DEFAULT_FRAMEWORK)
self.requires = []
class CppInfo(_CppInfo):
""" Build Information declared to be used by the CONSUMERS of a
conans. That means that consumers must use this flags and configs i order
to build properly.
Defined in user CONANFILE, directories are relative at user definition time
"""
def __init__(self, ref_name, root_folder):
super(CppInfo, self).__init__()
self._ref_name = ref_name
self._name = ref_name
self.rootpath = root_folder # the full path of the package in which the conans is found
self.includedirs.append(DEFAULT_INCLUDE)
self.libdirs.append(DEFAULT_LIB)
self.bindirs.append(DEFAULT_BIN)
self.resdirs.append(DEFAULT_RES)
self.builddirs.append(DEFAULT_BUILD)
self.frameworkdirs.append(DEFAULT_FRAMEWORK)
self.components = DefaultOrderedDict(lambda: Component(self.rootpath))
# public_deps is needed to accumulate list of deps for cmake targets
self.public_deps = []
self._configs = {}
def __str__(self):
return self._ref_name
def get_name(self, generator):
name = super(CppInfo, self).get_name(generator)
# Legacy logic for pkg_config generator
from conans.client.generators.pkg_config import PkgConfigGenerator
if generator == PkgConfigGenerator.name:
fallback = self._name.lower() if self._name != self._ref_name else self._ref_name
if PkgConfigGenerator.name not in self.names and self._name != self._name.lower():
conan_v2_behavior("Generated file and name for {gen} generator will change in"
" Conan v2 to '{name}'. Use 'self.cpp_info.names[\"{gen}\"]"
" = \"{fallback}\"' in your recipe to continue using current name."
.format(gen=PkgConfigGenerator.name, name=name, fallback=fallback))
name = self.names.get(generator, fallback)
return name
@property
def configs(self):
return self._configs
def __getattr__(self, config):
def _get_cpp_info():
result = _CppInfo()
result.filter_empty = self.filter_empty
result.rootpath = self.rootpath
result.sysroot = self.sysroot
result.includedirs.append(DEFAULT_INCLUDE)
result.libdirs.append(DEFAULT_LIB)
result.bindirs.append(DEFAULT_BIN)
result.resdirs.append(DEFAULT_RES)
result.builddirs.append(DEFAULT_BUILD)
result.frameworkdirs.append(DEFAULT_FRAMEWORK)
return result
return self._configs.setdefault(config, _get_cpp_info())
def _raise_incorrect_components_definition(self, package_name, package_requires):
# Raise if mixing components
if (self.includedirs != [DEFAULT_INCLUDE] or
self.libdirs != [DEFAULT_LIB] or
self.bindirs != [DEFAULT_BIN] or
self.resdirs != [DEFAULT_RES] or
self.builddirs != [DEFAULT_BUILD] or
self.frameworkdirs != [DEFAULT_FRAMEWORK] or
self.libs or
self.system_libs or
self.frameworks or
self.defines or
self.cflags or
self.cxxflags or
self.sharedlinkflags or
self.exelinkflags or
self.build_modules) and self.components:
raise ConanException("self.cpp_info.components cannot be used with self.cpp_info "
"global values at the same time")
if self._configs and self.components:
raise ConanException("self.cpp_info.components cannot be used with self.cpp_info configs"
" (release/debug/...) at the same time")
# Raise on component name
for comp_name, comp in self.components.items():
if comp_name == package_name:
raise ConanException("Component name cannot be the same as the package name: '%s'"
% comp_name)
if self.components:
comp_requires = set()
for comp_name, comp in self.components.items():
for comp_require in comp.requires:
if COMPONENT_SCOPE in comp_require:
comp_requires.add(
comp_require[:comp_require.find(COMPONENT_SCOPE)])
pkg_requires = [require.ref.name for require in package_requires.values()]
# Raise on components requires without package requires
for pkg_require in pkg_requires:
if pkg_require not in comp_requires:
raise ConanException("Package require '%s' not used in components requires"
% pkg_require)
# Raise on components requires requiring inexistent package requires
for comp_require in comp_requires:
if comp_require not in pkg_requires:
raise ConanException("Package require '%s' declared in components requires "
"but not defined as a recipe requirement" % comp_require)
class _BaseDepsCppInfo(_CppInfo):
def __init__(self):
super(_BaseDepsCppInfo, self).__init__()
def update(self, dep_cpp_info):
def merge_lists(seq1, seq2):
return [s for s in seq1 if s not in seq2] + seq2
self.system_libs = merge_lists(self.system_libs, dep_cpp_info.system_libs)
self.includedirs = merge_lists(self.includedirs, dep_cpp_info.include_paths)
self.srcdirs = merge_lists(self.srcdirs, dep_cpp_info.src_paths)
self.libdirs = merge_lists(self.libdirs, dep_cpp_info.lib_paths)
self.bindirs = merge_lists(self.bindirs, dep_cpp_info.bin_paths)
self.resdirs = merge_lists(self.resdirs, dep_cpp_info.res_paths)
self.builddirs = merge_lists(self.builddirs, dep_cpp_info.build_paths)
self.frameworkdirs = merge_lists(self.frameworkdirs, dep_cpp_info.framework_paths)
self.libs = merge_lists(self.libs, dep_cpp_info.libs)
self.frameworks = merge_lists(self.frameworks, dep_cpp_info.frameworks)
self.build_modules = merge_lists(self.build_modules, dep_cpp_info.build_modules_paths)
self.rootpaths.append(dep_cpp_info.rootpath)
# Note these are in reverse order
self.defines = merge_lists(dep_cpp_info.defines, self.defines)
self.cxxflags = merge_lists(dep_cpp_info.cxxflags, self.cxxflags)
self.cflags = merge_lists(dep_cpp_info.cflags, self.cflags)
self.sharedlinkflags = merge_lists(dep_cpp_info.sharedlinkflags, self.sharedlinkflags)
self.exelinkflags = merge_lists(dep_cpp_info.exelinkflags, self.exelinkflags)
if not self.sysroot:
self.sysroot = dep_cpp_info.sysroot
@property
def build_modules_paths(self):
return self.build_modules
@property
def include_paths(self):
return self.includedirs
@property
def lib_paths(self):
return self.libdirs
@property
def src_paths(self):
return self.srcdirs
@property
def bin_paths(self):
return self.bindirs
@property
def build_paths(self):
return self.builddirs
@property
def res_paths(self):
return self.resdirs
@property
def framework_paths(self):
return self.frameworkdirs
class DepCppInfo(object):
def __init__(self, cpp_info):
self._cpp_info = cpp_info
self._libs = None
self._system_libs = None
self._frameworks = None
self._defines = None
self._cxxflags = None
self._cflags = None
self._sharedlinkflags = None
self._exelinkflags = None
self._include_paths = None
self._lib_paths = None
self._bin_paths = None
self._build_paths = None
self._res_paths = None
self._src_paths = None
self._framework_paths = None
self._build_module_paths = None
self._sorted_components = None
self._check_component_requires()
def __str__(self):
return str(self._cpp_info)
def __getattr__(self, item):
try:
attr = self._cpp_info.__getattribute__(item)
except AttributeError: # item is not defined, get config (CppInfo)
attr = self._cpp_info.__getattr__(item)
return attr
@staticmethod
def _merge_lists(seq1, seq2):
return seq1 + [s for s in seq2 if s not in seq1]
def _aggregated_values(self, item):
values = getattr(self, "_%s" % item)
if values is not None:
return values
values = getattr(self._cpp_info, item)
if self._cpp_info.components:
for component in self._get_sorted_components().values():
values = self._merge_lists(values, getattr(component, item))
setattr(self, "_%s" % item, values)
return values
def _aggregated_paths(self, item):
paths = getattr(self, "_%s_paths" % item)
if paths is not None:
return paths
paths = getattr(self._cpp_info, "%s_paths" % item)
if self._cpp_info.components:
for component in self._get_sorted_components().values():
paths = self._merge_lists(paths, getattr(component, "%s_paths" % item))
setattr(self, "_%s_paths" % item, paths)
return paths
@staticmethod
def _filter_component_requires(requires):
return [r for r in requires if COMPONENT_SCOPE not in r]
def _check_component_requires(self):
for comp_name, comp in self._cpp_info.components.items():
if not all([require in self._cpp_info.components for require in
self._filter_component_requires(comp.requires)]):
raise ConanException("Component '%s' declares a missing dependency" % comp_name)
bad_requires = [r for r in comp.requires if r.startswith(COMPONENT_SCOPE)]
if bad_requires:
msg = "Leading character '%s' not allowed in %s requires: %s. Omit it to require " \
"components inside the same package." \
% (COMPONENT_SCOPE, comp_name, bad_requires)
raise ConanException(msg)
def _get_sorted_components(self):
"""
Sort Components from most dependent one first to the less dependent one last
:return: List of sorted components
"""
if not self._sorted_components:
if any([[require for require in self._filter_component_requires(comp.requires)]
for comp in self._cpp_info.components.values()]):
ordered = OrderedDict()
components = copy(self._cpp_info.components)
while len(ordered) != len(self._cpp_info.components):
# Search next element to be processed
for comp_name, comp in components.items():
# Check if component is not required and can be added to ordered
if comp_name not in [require for dep in components.values() for require in
self._filter_component_requires(dep.requires)]:
ordered[comp_name] = comp
del components[comp_name]
break
else:
raise ConanException("There is a dependency loop in "
"'self.cpp_info.components' requires")
self._sorted_components = ordered
else: # If components do not have requirements, keep them in the same order
self._sorted_components = self._cpp_info.components
return self._sorted_components
@property
def build_modules_paths(self):
return self._aggregated_paths("build_modules")
@property
def include_paths(self):
return self._aggregated_paths("include")
@property
def lib_paths(self):
return self._aggregated_paths("lib")
@property
def src_paths(self):
return self._aggregated_paths("src")
@property
def bin_paths(self):
return self._aggregated_paths("bin")
@property
def build_paths(self):
return self._aggregated_paths("build")
@property
def res_paths(self):
return self._aggregated_paths("res")
@property
def framework_paths(self):
return self._aggregated_paths("framework")
@property
def libs(self):
return self._aggregated_values("libs")
@property
def system_libs(self):
return self._aggregated_values("system_libs")
@property
def frameworks(self):
return self._aggregated_values("frameworks")
@property
def defines(self):
return self._aggregated_values("defines")
@property
def cxxflags(self):
return self._aggregated_values("cxxflags")
@property
def cflags(self):
return self._aggregated_values("cflags")
@property
def sharedlinkflags(self):
return self._aggregated_values("sharedlinkflags")
@property
def exelinkflags(self):
return self._aggregated_values("exelinkflags")
class DepsCppInfo(_BaseDepsCppInfo):
""" Build Information necessary to build a given conans. It contains the
flags, directories and options if its dependencies. The conans CONANFILE
should use these flags to pass them to the underlaying build system (Cmake, make),
so deps info is managed
"""
def __init__(self):
super(DepsCppInfo, self).__init__()
self._dependencies = OrderedDict()
self._configs = {}
def __getattr__(self, config):
return self._configs.setdefault(config, _BaseDepsCppInfo())
@property
def configs(self):
return self._configs
@property
def dependencies(self):
return self._dependencies.items()
@property
def deps(self):
return self._dependencies.keys()
def __getitem__(self, item):
return self._dependencies[item]
def add(self, pkg_name, cpp_info):
assert pkg_name == str(cpp_info), "'{}' != '{}'".format(pkg_name, cpp_info)
assert isinstance(cpp_info, (CppInfo, DepCppInfo))
self._dependencies[pkg_name] = cpp_info
super(DepsCppInfo, self).update(cpp_info)
for config, cpp_info in cpp_info.configs.items():
self._configs.setdefault(config, _BaseDepsCppInfo()).update(cpp_info) | |
main_test.go | // Copyright 2019 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 main
import (
"testing"
. "github.com/pingcap/check"
"github.com/pingcap/tidb/config"
"github.com/pingcap/tidb/sessionctx/variable"
)
var isCoverageServer = "0"
// TestRunMain is a dummy test case, which contains only the main function of tidb-server,
// and it is used to generate coverage_server.
func TestRunMain(t *testing.T) |
func TestT(t *testing.T) {
TestingT(t)
}
var _ = Suite(&testMainSuite{})
type testMainSuite struct{}
func (t *testMainSuite) TestSetGlobalVars(c *C) {
c.Assert(variable.SysVars[variable.TiDBIsolationReadEngines].Value, Equals, "tikv, tiflash, tidb")
c.Assert(variable.SysVars[variable.TIDBMemQuotaQuery].Value, Equals, "1073741824")
config.GetGlobalConfig().IsolationRead.Engines = []string{"tikv", "tidb"}
config.GetGlobalConfig().MemQuotaQuery = 9999999
setGlobalVars()
c.Assert(variable.SysVars[variable.TiDBIsolationReadEngines].Value, Equals, "tikv, tidb")
c.Assert(variable.SysVars[variable.TIDBMemQuotaQuery].Value, Equals, "9999999")
}
| {
if isCoverageServer == "1" {
main()
}
} |
tuple.go | package memdb
import (
"context"
"fmt"
"math/rand"
"time"
v0 "github.com/authzed/authzed-go/proto/authzed/api/v0"
v1 "github.com/authzed/authzed-go/proto/authzed/api/v1"
"github.com/hashicorp/go-memdb"
"github.com/jzelinskie/stringz"
"github.com/authzed/spicedb/internal/datastore"
"github.com/authzed/spicedb/pkg/tuple"
)
const (
errUnableToWriteTuples = "unable to write tuples: %w"
errUnableToDeleteTuples = "unable to delete tuples: %w"
errUnableToQueryTuples = "unable to query tuples: %w"
errRevision = "unable to find revision: %w"
errCheckRevision = "unable to check revision: %w"
)
const deletedTransactionID = ^uint64(0)
func (mds *memdbDatastore) checkPrecondition(txn *memdb.Txn, preconditions []*v1.Precondition) error {
for _, precond := range preconditions {
switch precond.Operation {
case v1.Precondition_OPERATION_MUST_NOT_MATCH, v1.Precondition_OPERATION_MUST_MATCH:
bestIter, err := iteratorForFilter(txn, precond.Filter)
if err != nil {
return err
}
filteredIter := memdb.NewFilterIterator(bestIter, relationshipFilterFilterFunc(precond.Filter))
exists := filteredIter.Next() != nil
if (precond.Operation == v1.Precondition_OPERATION_MUST_MATCH && !exists) ||
(precond.Operation == v1.Precondition_OPERATION_MUST_NOT_MATCH && exists) {
return datastore.NewPreconditionFailedErr(precond)
}
default:
return fmt.Errorf("unspecified precondition operation")
}
}
return nil
}
func (mds *memdbDatastore) WriteTuples(ctx context.Context, preconditions []*v1.Precondition, mutations []*v1.RelationshipUpdate) (datastore.Revision, error) {
txn := mds.db.Txn(true)
defer txn.Abort()
if err := mds.checkPrecondition(txn, preconditions); err != nil {
return datastore.NoRevision, fmt.Errorf(errUnableToWriteTuples, err)
}
newChangelogID, err := mds.write(ctx, txn, mutations)
if err != nil {
return datastore.NoRevision, fmt.Errorf(errUnableToWriteTuples, err)
}
txn.Commit()
return revisionFromVersion(newChangelogID), nil
}
func (mds *memdbDatastore) write(ctx context.Context, txn *memdb.Txn, mutations []*v1.RelationshipUpdate) (uint64, error) {
// Create the changelog entry
time.Sleep(mds.simulatedLatency)
newChangelogID, err := nextTupleChangelogID(txn)
if err != nil {
return 0, err
}
changes := make([]*v0.RelationTupleUpdate, 0, len(mutations))
for _, mut := range mutations {
changes = append(changes, tuple.UpdateFromRelationshipUpdate(mut))
}
newChangelogEntry := &tupleChangelog{
id: newChangelogID,
timestamp: uint64(time.Now().UnixNano()),
changes: changes,
}
if err := txn.Insert(tableChangelog, newChangelogEntry); err != nil {
return 0, err
}
// Apply the mutations
for _, mutation := range mutations {
existing, err := findRelationship(txn, mutation.Relationship)
if err != nil {
return 0, err
}
var deletedExisting tupleEntry
if existing != nil {
deletedExisting = *existing
deletedExisting.deletedTxn = newChangelogID
}
newVersion := tupleEntryFromRelationship(mutation.Relationship, newChangelogID, deletedTransactionID)
switch mutation.Operation {
case v1.RelationshipUpdate_OPERATION_CREATE:
if err := txn.Insert(tableTuple, newVersion); err != nil {
return 0, err
}
case v1.RelationshipUpdate_OPERATION_DELETE:
if existing != nil {
if err := txn.Insert(tableTuple, &deletedExisting); err != nil {
return 0, err
}
}
case v1.RelationshipUpdate_OPERATION_TOUCH:
if existing != nil {
if err := txn.Insert(tableTuple, &deletedExisting); err != nil {
return 0, err
}
}
if err := txn.Insert(tableTuple, newVersion); err != nil {
return 0, err
}
default:
return 0, fmt.Errorf("unknown tuple mutation operation type: %s", mutation.Operation)
}
}
return newChangelogID, nil
}
func (mds *memdbDatastore) DeleteRelationships(ctx context.Context, preconditions []*v1.Precondition, filter *v1.RelationshipFilter) (datastore.Revision, error) {
txn := mds.db.Txn(true)
defer txn.Abort()
if err := mds.checkPrecondition(txn, preconditions); err != nil {
return datastore.NoRevision, fmt.Errorf(errUnableToDeleteTuples, err)
}
// Create an iterator to find the relevant tuples
bestIter, err := iteratorForFilter(txn, filter)
if err != nil {
return datastore.NoRevision, fmt.Errorf(errUnableToDeleteTuples, err)
}
filteredIter := memdb.NewFilterIterator(bestIter, relationshipFilterFilterFunc(filter))
// Collect the tuples into a slice of mutations for the changelog
var mutations []*v1.RelationshipUpdate
for row := filteredIter.Next(); row != nil; row = filteredIter.Next() {
mutations = append(mutations, &v1.RelationshipUpdate{
Operation: v1.RelationshipUpdate_OPERATION_DELETE,
Relationship: row.(*tupleEntry).Relationship(),
})
}
newChangelogID, err := mds.write(ctx, txn, mutations)
if err != nil {
return datastore.NoRevision, fmt.Errorf(errUnableToDeleteTuples, err)
}
txn.Commit()
return revisionFromVersion(newChangelogID), nil
}
func (mds *memdbDatastore) QueryTuples(filter datastore.TupleQueryResourceFilter, revision datastore.Revision) datastore.TupleQuery {
return &memdbTupleQuery{
db: mds.db,
revision: revision,
simulatedLatency: mds.simulatedLatency,
resourceFilter: &v1.RelationshipFilter{
ResourceType: filter.ResourceType,
OptionalResourceId: filter.OptionalResourceID,
OptionalRelation: filter.OptionalResourceRelation,
},
}
}
func (mds *memdbDatastore) ReverseQueryTuplesFromSubject(subject *v0.ObjectAndRelation, revision datastore.Revision) datastore.ReverseTupleQuery {
return &memdbReverseTupleQuery{
db: mds.db,
revision: revision,
simulatedLatency: mds.simulatedLatency,
subNamespaceName: subject.Namespace,
subObjectID: subject.ObjectId,
subRelationName: subject.Relation,
}
}
func (mds *memdbDatastore) ReverseQueryTuplesFromSubjectRelation(subjectNamespace, subjectRelation string, revision datastore.Revision) datastore.ReverseTupleQuery {
return &memdbReverseTupleQuery{
db: mds.db,
revision: revision,
simulatedLatency: mds.simulatedLatency,
subNamespaceName: subjectNamespace,
subRelationName: subjectRelation,
}
}
func (mds *memdbDatastore) ReverseQueryTuplesFromSubjectNamespace(subjectNamespace string, revision datastore.Revision) datastore.ReverseTupleQuery {
return &memdbReverseTupleQuery{
db: mds.db,
revision: revision,
simulatedLatency: mds.simulatedLatency,
subNamespaceName: subjectNamespace,
}
}
func (mds *memdbDatastore) SyncRevision(ctx context.Context) (datastore.Revision, error) {
// Compute the current revision
txn := mds.db.Txn(false)
defer txn.Abort()
lastRaw, err := txn.Last(tableChangelog, indexID)
if err != nil {
return datastore.NoRevision, fmt.Errorf(errRevision, err)
}
if lastRaw != nil {
return revisionFromVersion(lastRaw.(*tupleChangelog).id), nil
}
return datastore.NoRevision, nil
}
func (mds *memdbDatastore) Revision(ctx context.Context) (datastore.Revision, error) {
txn := mds.db.Txn(false)
defer txn.Abort()
lowerBound := uint64(time.Now().Add(-1 * mds.revisionFuzzingTimedelta).UnixNano())
time.Sleep(mds.simulatedLatency)
iter, err := txn.LowerBound(tableChangelog, indexTimestamp, lowerBound)
if err != nil {
return datastore.NoRevision, fmt.Errorf(errRevision, err)
}
var candidates []datastore.Revision
for oneChange := iter.Next(); oneChange != nil; oneChange = iter.Next() {
candidates = append(candidates, revisionFromVersion(oneChange.(*tupleChangelog).id))
}
if len(candidates) > 0 {
return candidates[rand.Intn(len(candidates))], nil
}
return mds.SyncRevision(ctx)
}
func (mds *memdbDatastore) CheckRevision(ctx context.Context, revision datastore.Revision) error {
txn := mds.db.Txn(false)
defer txn.Abort()
// We need to know the highest possible revision
time.Sleep(mds.simulatedLatency)
lastRaw, err := txn.Last(tableChangelog, indexID)
if err != nil {
return fmt.Errorf(errCheckRevision, err)
}
if lastRaw == nil {
return datastore.NewInvalidRevisionErr(revision, datastore.CouldNotDetermineRevision)
}
highest := revisionFromVersion(lastRaw.(*tupleChangelog).id)
if revision.GreaterThan(highest) {
return datastore.NewInvalidRevisionErr(revision, datastore.RevisionInFuture)
}
lowerBound := uint64(time.Now().Add(mds.gcWindowInverted).UnixNano())
time.Sleep(mds.simulatedLatency)
iter, err := txn.LowerBound(tableChangelog, indexTimestamp, lowerBound)
if err != nil {
return fmt.Errorf(errCheckRevision, err)
}
firstValid := iter.Next()
if firstValid == nil && !revision.Equal(highest) {
return datastore.NewInvalidRevisionErr(revision, datastore.RevisionStale)
}
if firstValid != nil && revision.LessThan(revisionFromVersion(firstValid.(*tupleChangelog).id)) {
return datastore.NewInvalidRevisionErr(revision, datastore.RevisionStale)
}
return nil
}
func relationshipFilterFilterFunc(filter *v1.RelationshipFilter) func(interface{}) bool {
return func(tupleRaw interface{}) bool {
tuple := tupleRaw.(*tupleEntry)
// If it's already dead, filter it.
if tuple.deletedTxn != deletedTransactionID {
return true
}
// If it doesn't match one of the resource filters, filter it.
switch {
case filter.ResourceType != tuple.namespace:
return true
case filter.OptionalResourceId != "" && filter.OptionalResourceId != tuple.objectID:
return true
case filter.OptionalRelation != "" && filter.OptionalRelation != tuple.relation:
return true
}
// If it doesn't match one of the subject filters, filter it.
if subjectFilter := filter.OptionalSubjectFilter; subjectFilter != nil {
switch {
case subjectFilter.SubjectType != tuple.usersetNamespace:
return true
case subjectFilter.OptionalSubjectId != "" && subjectFilter.OptionalSubjectId != tuple.usersetObjectID:
return true
case subjectFilter.OptionalRelation != nil &&
stringz.DefaultEmpty(subjectFilter.OptionalRelation.Relation, datastore.Ellipsis) != tuple.usersetRelation:
return true
}
}
return false
}
}
func findRelationship(txn *memdb.Txn, toFind *v1.Relationship) (*tupleEntry, error) {
foundRaw, err := txn.First(
tableTuple,
indexLive,
toFind.Resource.ObjectType,
toFind.Resource.ObjectId,
toFind.Relation,
toFind.Subject.Object.ObjectType,
toFind.Subject.Object.ObjectId,
stringz.DefaultEmpty(toFind.Subject.OptionalRelation, datastore.Ellipsis),
deletedTransactionID,
)
if err != nil {
return nil, err
}
if foundRaw == nil {
return nil, nil
}
return foundRaw.(*tupleEntry), nil
}
func | (txn *memdb.Txn) (uint64, error) {
lastChangeRaw, err := txn.Last(tableChangelog, indexID)
if err != nil {
return 0, err
}
if lastChangeRaw == nil {
return 1, nil
}
return lastChangeRaw.(*tupleChangelog).id + 1, nil
}
| nextTupleChangelogID |
eexec_test.py | from fontTools.misc.eexec import decrypt, encrypt
def test_decrypt():
testStr = b"\0\0asdadads asds\265"
decryptedStr, R = decrypt(testStr, 12321)
assert decryptedStr == b'0d\nh\x15\xe8\xc4\xb2\x15\x1d\x108\x1a<6\xa1'
assert R == 36142
def test_encrypt():
| testStr = b'0d\nh\x15\xe8\xc4\xb2\x15\x1d\x108\x1a<6\xa1'
encryptedStr, R = encrypt(testStr, 12321)
assert encryptedStr == b"\0\0asdadads asds\265"
assert R == 36142 |
|
logger.py | """Environment wrapper class for logging episodes.
This can be used to record data from a subject playing the task. See
../../moog_demos/restore_logged_data.py for an example of how to read log files.
Note: This logger records everything about the environment, which can be a lot
of data (depending on the task). If you plan to use this at scale for recording
subjects' or agents' behavior, we recommend forking this and modifying it to
only log the data that you need to do analyses for your specific task. For
example you may not want to log the positions/velocities of static sprites
(e.g. walls), or may not want to log all the attributes of sprites every
timestep (e.g. if you know that the colors of the sprites don't change in your
task).
"""
import copy
from datetime import datetime
import json
import logging
import numpy as np
import os
import time
from moog import env_wrappers
from moog import sprite
# This is the number of numerals in filenames. Since there is one file per
# episode, you should pick _FILENAME_ZFILL large enough that the number of
# episodes in your dataset is less than 10^_FILENAME_ZFILL.
_FILENAME_ZFILL = 5
class VertexLogging():
NEVER = 'NEVER'
ALWAYS = 'ALWAYS'
WHEN_NECESSARY = 'WHEN_NECESSARY'
def _serialize(x):
"""Serialize a value x.
This is used to serialize sprite attributes, actions, and meta_state so that
they are json-writable.
Specifically, numpy arrays are not JSON serializable, so we must convert
numpy arrays to lists. This function is recursive to handle nestings inside
of lists/tuples/dictionaries.
Args:
x: Value to serialize.
Returns:
Serialized value that can be JSON dumped.
"""
if isinstance(x, np.ndarray):
return x.tolist()
elif isinstance(x, (np.float32, np.float64)):
return float(x)
elif isinstance(x, (np.int32, np.int64)):
return int(x)
elif isinstance(x, list):
return [_serialize(a) for a in x]
elif isinstance(x, tuple):
return tuple([_serialize(a) for a in x])
elif isinstance(x, dict):
return {k: _serialize(v) for k, v in x.items()}
else:
return x
class LoggingEnvironment(env_wrappers.AbstractEnvironmentWrapper):
"""Environment class for logging timesteps.
This logger produces a description of the log in 'description.txt' of
log_dir, so please refer to that for a detailed account of the structure of
the logs.
"""
def __init__(self, environment, log_dir='logs',
log_vertices='WHEN_NECESSARY'):
"""Constructor.
Args:
environment: Instance of ../moog/environment.Environment.
log_dir: String. Log directory relative to working directory.
log_vertices: String. Of the following options:
* 'NEVER'. In this case, never log sprite vertices.
* 'WHEN_NECESSARY'. In this case, log sprite vertices when a
sprite has either just appeared or just changed shape. In
this way, the vertices of a sprite can always be inferred
from the current position/angle/aspect_ratio and the
vertices that were logged for that sprite (identifiable by
its id) the last time its vertices were logged.
* 'ALWAYS'. Log vertices for all sprites every timestep.
"""
super(LoggingEnvironment, self).__init__(environment)
# Make sure log_vertices is a valid value
if not hasattr(VertexLogging, log_vertices):
raise ValueError('log_vertices is {} but must be in VertexLogging '
'values'.format(log_vertices))
self._log_vertices = log_vertices
# Set the logging directory
now_str = datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
if log_dir[0] == '/':
log_dir = os.path.join(log_dir, now_str)
else:
log_dir = os.path.join(os.getcwd(), log_dir, now_str)
os.makedirs(log_dir)
self._log_dir = log_dir
# These are the attributes that we'll log
self._attributes = list(sprite.Sprite.FACTOR_NAMES) + ['id']
# Log attribute list
attributes_filename = os.path.join(self._log_dir, 'attributes.txt')
logging.info('Logging attribute list {} to {}.'.format(
self._attributes, attributes_filename))
with open(attributes_filename, 'w') as f:
json.dump(self._attributes, f)
# Log description
self._log_description()
# Initialize self._episode_log
self._episode_count = 0
self._episode_log = []
def _log_description(self):
"""Log a description of the data to a description.txt file."""
description_filename = os.path.join(self._log_dir, 'description.txt')
logging.info('Logging description to {}.'.format(description_filename))
description = (
'Each numerical file in this directory is an episode of the task. '
'Each such file contains a json-serialized list, each element of '
'which represents an environment step in the episode. Each step is '
'a list of four elements, [[`time`, time], [`reward`, reward], '
'[`step_type`, step_type], [`action`, action], [`meta_state`, '
'meta_state`], state].'
'\n\n'
'\n\n'
'time is a timestamp of the timestep.'
'\n\n'
'\n\n'
'reward contains the value of the reward at that step.'
'\n\n'
'\n\n'
'step_type indicates the dm_env.StepType of that step, i.e. '
'whether it was first, mid, or last.'
'\n\n'
'\n\n'
'action contains the agent action for the step.'
'\n\n'
'\n\n'
'meta_state is the serialized meta_state of the environment.'
'\n\n'
'\n\n'
'state is a list, each element of which represents a layer in the '
'environment state. The layer is represented as a list [k, [], [], '
'[], ...], where k is the layer name and the subsequent elements '
'are serialized sprites. Each serialized sprite is a list of '
'attributes. See attributes.txt for the attributes contained.'
)
if self._log_vertices == VertexLogging.ALWAYS:
description += (
' Furthermore, a list of vertices is appended to the attribute '
'list for each serialized sprite.'
)
elif self._log_vertices == VertexLogging.WHEN_NECESSARY:
description += (
'\n\n'
'\n\n'
'Furthermore, a list of vertices is appended to the attribute '
'list for a serialized for the first timestep in which that '
'serialized sprite appears, or when the sprite has changed '
'shape.'
)
with open(description_filename, 'w') as f:
f.write(description)
def _serialize_sprite(self, s):
"""Serialize a sprite as a list of attributes."""
attributes = [_serialize(getattr(s, x)) for x in self._attributes]
if (self._log_vertices == VertexLogging.ALWAYS or
(self._log_vertices == VertexLogging.WHEN_NECESSARY and
s.just_set_shape)):
attributes.append(s.vertices.tolist())
s.just_set_shape = False
return attributes
def _serialized_state(self):
"""Serialized a state."""
serialized_state = [
[k, [self._serialize_sprite(s) for s in self.state[k]]]
for k in self.state
] | timestep = self._environment.step(action)
str_timestep = (
[['time', time.time()],
['reward', timestep.reward],
['step_type', timestep.step_type.value],
['action', _serialize(action)],
['meta_state', _serialize(self._environment.meta_state)],
self._serialized_state()]
)
self._episode_log.append(str_timestep)
if timestep.last():
# Write the episode to a log file
episode_count_str = str(self._episode_count).zfill(_FILENAME_ZFILL)
filename = os.path.join(self._log_dir, episode_count_str)
logging.info('Logging episode {} to {}.'.format(
self._episode_count, filename))
with open(filename, 'w') as f:
json.dump(self._episode_log, f)
self._episode_count += 1
self._episode_log = []
return timestep | return serialized_state
def step(self, action):
"""Step the environment with an action, logging timesteps.""" |
get_all_alerts.py | #!/usr/bin/python
#
# Copyright 2013 Google Inc. 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.
"""Gets all alerts available for the logged in user's account.
Tags: alerts.list
"""
__author__ = '[email protected] (Sérgio Gomes)'
import argparse
import sys
from googleapiclient import sample_tools
from oauth2client import client
def m | argv):
# Authenticate and construct service.
service, flags = sample_tools.init(
argv, 'adexchangeseller', 'v1.1', __doc__, __file__, parents=[],
scope='https://www.googleapis.com/auth/adexchange.seller.readonly')
try:
# Retrieve alerts list in pages and display data as we receive it.
request = service.alerts().list()
if request is not None:
result = request.execute()
if 'items' in result:
alerts = result['items']
for alert in alerts:
print ('Alert id "%s" with severity "%s" and type "%s" was found. '
% (alert['id'], alert['severity'], alert['type']))
else:
print 'No alerts found!'
except client.AccessTokenRefreshError:
print ('The credentials have been revoked or expired, please re-run the '
'application to re-authorize')
if __name__ == '__main__':
main(sys.argv)
| ain( |
solution.py | # -*- coding:utf-8; -*-
class SolutionV1:
def combinationSum(self, candidates, target):
# 1. 定义保存结果的组合
result = set()
# 2. 定义递归函数,i表示递归层数,但是具体含义还不知道
def helper(nums, candidates, target):
# 4. 编写递归模板
# 1) 定义递归终止条件
# 应该是从candidate选出来的数的sum=target就返回,所以这时候递归层数i应该是候选值列表。
# 修改递归参数第一个参数i为nums,表示一个候选值列表
if sum(nums) == target:
result.append(tuple(nums))
return
# 5. 那么sum(nums)>target 这时候也应该停止了,因为candidates都是正整数
if sum(nums) > target:
return
# 2) 处理当前层逻辑
# 6. 当前层逻辑处理:如果sum(nums)<target,那么下一步nums中新增元素可能是candidates中的任一元素
newNums = [nums + [i] for i in candidates]
# 3)下探递归
# 7. 递归下一层
for nums in newNums:
helper(nums, candidates, target)
# 4)清理当前层,当前层没有要清理的
# 3. 首次调用递归函数
helper([], candidates, target)
return [list(nums) for nums in result]
class Solution:
""" 递归代码优化,语言层面优化代码
"""
def combinationSum(self, candidates, target):
result = set()
def helper(nums, candidates, target):
if sum(nums) == target:
result.add(tuple(sorted(nums)))
return
if sum(nums) > target:
return
for i in candidates:
helper(nums + [i], candidates, target)
helper([], candidates, target)
return [list(nums) for nums in result]
| ||
mysql_test.go | package test
import (
"context"
"fmt"
"github.com/GofferdoXu/golang_common/lib"
"gorm.io/gorm"
"testing"
"time"
)
type Test1 struct {
Id int64 `json:"id" gorm:"primary_key"`
Name string `json:"name"`
CreatedAt time.Time `json:"created_at"`
}
func (f *Test1) Table() string {
return "test1"
}
func (f *Test1) DB() *gorm.DB {
return lib.GORMDefaultPool
}
var (
createTableSQL = "CREATE TABLE `test1` (`id` int(12) unsigned NOT NULL AUTO_INCREMENT" +
" COMMENT '自增id',`name` varchar(255) NOT NULL DEFAULT '' COMMENT '姓名'," +
"`created_at` datetime NOT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB " +
"DEFAULT CHARSET=utf8"
insertSQL = "INSERT INTO `test1` (`id`, `name`, `created_at`) VALUES (NULL, '111', '2018-08-29 11:01:43');"
dropTableSQL = "DROP TABLE `test1`"
beginSQL = "start transaction;"
commitSQL = "commit;"
rollbackSQL = "rollback;"
)
func Test_DBP | ing.T) {
SetUp()
//获取链接池
dbpool, err := lib.GetDBPool("default")
if err != nil {
t.Fatal(err)
}
//开始事务
trace := lib.NewTrace()
if _, err := lib.DBPoolLogQuery(trace, dbpool, beginSQL); err != nil {
t.Fatal(err)
}
//创建表
if _, err := lib.DBPoolLogQuery(trace, dbpool, createTableSQL); err != nil {
lib.DBPoolLogQuery(trace, dbpool, rollbackSQL)
t.Fatal(err)
}
//插入数据
if _, err := lib.DBPoolLogQuery(trace, dbpool, insertSQL); err != nil {
lib.DBPoolLogQuery(trace, dbpool, rollbackSQL)
t.Fatal(err)
}
//循环查询数据
current_id := 0
table_name := "test1"
fmt.Println("begin read table ", table_name, "")
fmt.Println("------------------------------------------------------------------------")
fmt.Printf("%6s | %6s\n", "id", "created_at")
for {
rows, err := lib.DBPoolLogQuery(trace, dbpool, "SELECT id,created_at FROM test1 WHERE id>? order by id asc", current_id)
defer rows.Close()
row_len := 0
if err != nil {
lib.DBPoolLogQuery(trace, dbpool, "rollback;")
t.Fatal(err)
}
for rows.Next() {
var create_time string
if err := rows.Scan(¤t_id, &create_time); err != nil {
lib.DBPoolLogQuery(trace, dbpool, "rollback;")
t.Fatal(err)
}
fmt.Printf("%6d | %6s\n", current_id, create_time)
row_len++
}
if row_len == 0 {
break
}
}
fmt.Println("------------------------------------------------------------------------")
fmt.Println("finish read table ", table_name, "")
//删除表
if _, err := lib.DBPoolLogQuery(trace, dbpool, dropTableSQL); err != nil {
lib.DBPoolLogQuery(trace, dbpool, rollbackSQL)
t.Fatal(err)
}
//提交事务
lib.DBPoolLogQuery(trace, dbpool, commitSQL)
TearDown()
}
func Test_GORM(t *testing.T) {
SetUp()
//获取链接池
dbpool, err := lib.GetGormPool("default")
if err != nil {
t.Fatal(err)
}
db := dbpool.Begin()
traceCtx := lib.NewTrace()
ctx := context.Background()
ctx = lib.SetTraceContext(ctx, traceCtx)
//设置trace信息
db = db.WithContext(ctx)
if err := db.Exec(createTableSQL).Error; err != nil {
db.Rollback()
t.Fatal(err)
}
//插入数据
t1 := &Test1{Name: "test_name", CreatedAt: time.Now()}
if err := db.Save(t1).Error; err != nil {
db.Rollback()
t.Fatal(err)
}
//查询数据
list := []Test1{}
if err := db.Where("name=?", "test_name").Find(&list).Error; err != nil {
db.Rollback()
t.Fatal(err)
}
fmt.Println(list)
//删除表数据
if err := db.Exec(dropTableSQL).Error; err != nil {
db.Rollback()
t.Fatal(err)
}
db.Commit()
TearDown()
}
| ool(t *test |
root.go | // Copyright 2018 The CUE 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 cmd
import (
"context"
"io"
"os"
"strings"
"github.com/spf13/cobra"
"cuelang.org/go/cue/errors"
"cuelang.org/go/cue/token"
)
// TODO: commands
// fix: rewrite/refactor configuration files
// -i interactive: open diff and ask to update
// serve: like cmd, but for servers
// get: convert cue from other languages, like proto and go.
// gen: generate files for other languages
// generate like go generate (also convert cue to go doc)
// test load and fully evaluate test files.
//
// TODO: documentation of concepts
// tasks the key element for cmd, serve, and fix
type runFunction func(cmd *Command, args []string) error
func mkRunE(c *Command, f runFunction) func(*cobra.Command, []string) error {
return func(cmd *cobra.Command, args []string) error {
c.Command = cmd
err := f(c, args)
if err != nil {
exitOnErr(c, err, true)
}
return err
}
}
// newRootCmd creates the base command when called without any subcommands
func newRootCmd() *Command {
cmd := &cobra.Command{
Use: "cue",
Short: "cue emits configuration files to user-defined commands.",
Long: `cue evaluates CUE files, an extension of JSON, and sends them
to user-defined commands for processing.
Commands are defined in CUE as follows:
import "tool/exec"
command: deploy: {
exec.Run
cmd: "kubectl"
args: [ "-f", "deploy" ]
in: json.Encode(userValue) // encode the emitted configuration.
}
cue can also combine the results of http or grpc request with the input
configuration for further processing. For more information on defining commands
run 'cue help cmd' or go to cuelang.org/pkg/cmd.
For more information on writing CUE configuration files see cuelang.org.`,
// Uncomment the following line if your bare application
// has an action associated with it:
// Run: func(cmd *cobra.Command, args []string) { },
SilenceUsage: true,
}
c := &Command{Command: cmd, root: cmd}
cmdCmd := newCmdCmd(c)
c.cmd = cmdCmd
subCommands := []*cobra.Command{
cmdCmd,
newEvalCmd(c),
newDefCmd(c),
newExportCmd(c),
newFixCmd(c),
newFmtCmd(c),
newGetCmd(c),
newImportCmd(c),
newModCmd(c),
newTrimCmd(c),
newVersionCmd(c),
newVetCmd(c),
// Hidden
newAddCmd(c),
}
subCommands = append(subCommands, newHelpTopics(c)...)
addGlobalFlags(cmd.PersistentFlags())
for _, sub := range subCommands {
cmd.AddCommand(sub)
}
return c
}
// MainTest is like Main, runs the cue tool and returns the code for passing to os.Exit.
func MainTest() int {
inTest = true
return Main()
}
// Main runs the cue tool and returns the code for passing to os.Exit.
func Main() int {
cwd, _ := os.Getwd()
err := mainErr(context.Background(), os.Args[1:])
if err != nil {
if err != ErrPrintedError {
errors.Print(os.Stderr, err, &errors.Config{
Cwd: cwd,
ToSlash: inTest,
})
}
return 1
}
return 0
}
func mainErr(ctx context.Context, args []string) error {
cmd, err := New(args)
if err != nil {
return err
}
return cmd.Run(ctx)
}
type Command struct {
// The currently active command.
*cobra.Command
root *cobra.Command
// Subcommands
cmd *cobra.Command
hasErr bool
}
type errWriter Command
func (w *errWriter) Write(b []byte) (int, error) {
c := (*Command)(w)
c.hasErr = true
return c.Command.OutOrStderr().Write(b)
}
// Hint: search for uses of OutOrStderr other than the one here to see
// which output does not trigger a non-zero exit code. os.Stderr may never
// be used directly.
// Stderr returns a writer that should be used for error messages.
func (c *Command) Stderr() io.Writer {
return (*errWriter)(c)
}
// TODO: add something similar for Stdout. The output model of Cobra isn't
// entirely clear, and such a change seems non-trivial.
// Consider overriding these methods from Cobra using OutOrStdErr.
// We don't use them currently, but may be safer to block. Having them
// will encourage their usage, and the naming is inconsistent with other CUE APIs.
// PrintErrf(format string, args ...interface{})
// PrintErrln(args ...interface{})
// PrintErr(args ...interface{})
func (c *Command) SetOutput(w io.Writer) {
c.root.SetOut(w)
}
func (c *Command) SetInput(r io.Reader) {
c.root.SetIn(r)
}
// ErrPrintedError indicates error messages have been printed to stderr.
var ErrPrintedError = errors.New("terminating because of errors")
func (c *Command) Run(ctx context.Context) (err error) {
// Three categories of commands:
// - normal
// - user defined
// - help
// For the latter two, we need to use the default loading.
defer recoverError(&err)
if err := c.root.Execute(); err != nil {
return err
}
if c.hasErr {
return ErrPrintedError
}
return nil
}
func recoverError(err *error) {
switch e := recover().(type) {
case nil:
case panicError:
*err = e.Err
default:
panic(e)
}
// We use panic to escape, instead of os.Exit
}
func New(args []string) (cmd *Command, err error) {
defer recoverError(&err)
cmd = newRootCmd()
rootCmd := cmd.root
if len(args) == 0 {
return cmd, nil
}
rootCmd.SetArgs(args)
var sub = map[string]*subSpec{
"cmd": {commandSection, cmd.cmd},
// "serve": {"server", nil},
// "fix": {"fix", nil},
}
// handle help and --help on root 'cue' command
if args[0] == "help" || args[0] == "--help" {
// Allow errors.
_ = addSubcommands(cmd, sub, args[1:], true)
return cmd, nil
}
if _, ok := sub[args[0]]; ok {
return cmd, addSubcommands(cmd, sub, args, false)
}
// TODO: clean this up once we either use Cobra properly or when we remove
// it.
err = cmd.cmd.ParseFlags(args)
if err != nil {
return nil, err
}
tags, err := cmd.cmd.Flags().GetStringArray(string(flagInject))
if err != nil {
return nil, err
}
args = cmd.cmd.Flags().Args()
rootCmd.SetArgs(args)
if c, _, err := rootCmd.Find(args); err == nil && c != nil {
return cmd, nil
}
if !isCommandName(args[0]) {
return cmd, nil // Forces unknown command message from Cobra.
}
tools, err := buildTools(cmd, tags, args[1:])
if err != nil {
return cmd, err
}
_, err = addCustom(cmd, rootCmd, commandSection, args[0], tools)
if err != nil {
err = errors.Newf(token.NoPos,
`%s %q is not defined
Ensure commands are defined in a "_tool.cue" file.
Run 'cue help' to show available commands.`,
commandSection, args[0],
)
return cmd, err
}
return cmd, nil
}
type subSpec struct {
name string
cmd *cobra.Command
}
func addSubcommands(cmd *Command, sub map[string]*subSpec, args []string, isHelp bool) error {
var tags []string
if len(args) > 0 {
if _, ok := sub[args[0]]; ok {
oldargs := []string{args[0]}
args = args[1:]
// Check for 'cue cmd --help'
// it is behaving differently for this one command, cobra does not seem to pick it up
// See issue #340
if len(args) == 1 && args[0] == "--help" {
return cmd.Usage()
}
if !isHelp {
err := cmd.cmd.ParseFlags(args)
if err != nil {
return err
}
tags, err = cmd.cmd.Flags().GetStringArray(string(flagInject))
if err != nil {
return err
}
args = cmd.cmd.Flags().Args()
cmd.root.SetArgs(append(oldargs, args...))
}
}
}
if len(args) > 0 {
if !isCommandName(args[0]) {
return nil // Forces unknown command message from Cobra.
}
args = args[1:]
}
tools, err := buildTools(cmd, tags, args)
if err != nil {
return err
}
// TODO: for now we only allow one instance. Eventually, we can allow
// more if they all belong to the same package and we merge them
// before computing commands.
for _, spec := range sub {
commands := tools.Lookup(spec.name)
if !commands.Exists() {
return nil
}
i, err := commands.Fields()
if err != nil {
return errors.Newf(token.NoPos, "could not create command definitions: %v", err)
}
for i.Next() {
_, _ = addCustom(cmd, spec.cmd, spec.name, i.Label(), tools)
}
}
return nil
}
func isCommandName(s string) bool {
return !strings.Contains(s, `/\`) &&
!strings.HasPrefix(s, ".") &&
!strings.HasSuffix(s, ".cue")
}
type panicError struct {
Err error
}
func exit() {
panic(panicError{ErrPrintedError})
} | |
counter.py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8:
# Author: Binux<[email protected]>
# http://binux.me
# Created on 2012-11-14 17:09:50
from __future__ import unicode_literals, division, absolute_import
import time
import logging
from collections import deque
try:
from UserDict import DictMixin
except ImportError:
from collections import Mapping as DictMixin
import six
from six import iteritems
from six.moves import cPickle
class BaseCounter(object):
def __init__(self):
raise NotImplementedError
def event(self, value=1):
"""Fire a event."""
raise NotImplementedError
def value(self, value):
"""Set counter value."""
raise NotImplementedError
@property
def avg(self):
"""Get average value"""
raise NotImplementedError
@property
def sum(self):
"""Get sum of counter"""
raise NotImplementedError
def empty(self):
"""Clear counter"""
raise NotImplementedError
class TotalCounter(BaseCounter):
"""Total counter"""
def __init__(self):
self.cnt = 0
def event(self, value=1):
self.cnt += value
def value(self, value):
self.cnt = value
@property
def avg(self):
return self.cnt
@property
def sum(self):
return self.cnt
def empty(self):
return self.cnt == 0
class AverageWindowCounter(BaseCounter):
"""
Record last N(window) value
"""
def __init__(self, window_size=300):
self.window_size = window_size
self.values = deque(maxlen=window_size)
def event(self, value=1):
self.values.append(value)
value = event
@property
def avg(self):
return self.sum / len(self.values)
@property
def sum(self):
return sum(self.values)
def empty(self):
if not self.values:
return True
class TimebaseAverageWindowCounter(BaseCounter):
"""
Record last window_size * window_interval seconds values.
records will trim evert window_interval seconds
"""
def __init__(self, window_size=30, window_interval=10):
self.max_window_size = window_size
self.window_size = 0
self.window_interval = window_interval
self.values = deque(maxlen=window_size)
self.times = deque(maxlen=window_size)
self.cache_value = 0
self.cache_start = None
self._first_data_time = None
def event(self, value=1):
|
def value(self, value):
self.cache_value = value
def _trim_window(self):
now = time.time()
if self.cache_start and now - self.cache_start > self.window_interval:
self.values.append(self.cache_value)
self.times.append(self.cache_start)
self.on_append(self.cache_value, self.cache_start)
self.cache_value = 0
self.cache_start = None
if self.window_size != self.max_window_size and self._first_data_time is not None:
time_passed = now - self._first_data_time
self.window_size = min(self.max_window_size, time_passed / self.window_interval)
window_limit = now - self.window_size * self.window_interval
while self.times and self.times[0] < window_limit:
self.times.popleft()
self.values.popleft()
@property
def avg(self):
sum = float(self.sum)
if not self.window_size:
return 0
return sum / self.window_size / self.window_interval
@property
def sum(self):
self._trim_window()
return sum(self.values) + self.cache_value
def empty(self):
self._trim_window()
if not self.values and not self.cache_start:
return True
def on_append(self, value, time):
pass
class CounterValue(DictMixin):
"""
A dict like value item for CounterManager.
"""
def __init__(self, manager, keys):
self.manager = manager
self._keys = keys
def __getitem__(self, key):
if key == '__value__':
key = self._keys
return self.manager.counters[key]
else:
key = self._keys + (key, )
available_keys = []
for _key in self.manager.counters:
if _key[:len(key)] == key:
available_keys.append(_key)
if len(available_keys) == 0:
raise KeyError
elif len(available_keys) == 1:
if available_keys[0] == key:
return self.manager.counters[key]
else:
return CounterValue(self.manager, key)
else:
return CounterValue(self.manager, key)
def __len__(self):
return len(self.keys())
def __iter__(self):
return iter(self.keys())
def __contains__(self, key):
return key in self.keys()
def keys(self):
result = set()
for key in self.manager.counters:
if key[:len(self._keys)] == self._keys:
key = key[len(self._keys):]
result.add(key[0] if key else '__value__')
return result
def to_dict(self, get_value=None):
"""Dump counters as a dict"""
result = {}
for key, value in iteritems(self):
if isinstance(value, BaseCounter):
if get_value is not None:
value = getattr(value, get_value)
result[key] = value
else:
result[key] = value.to_dict(get_value)
return result
class CounterManager(DictMixin):
"""
A dict like counter manager.
When using a tuple as event key, say: ('foo', 'bar'), You can visite counter
with manager['foo']['bar']. Or get all counters which first element is 'foo'
by manager['foo'].
It's useful for a group of counters.
"""
def __init__(self, cls=TimebaseAverageWindowCounter):
"""init manager with Counter cls"""
self.cls = cls
self.counters = {}
def event(self, key, value=1):
"""Fire a event of a counter by counter key"""
if isinstance(key, six.string_types):
key = (key, )
assert isinstance(key, tuple), "event key type error"
if key not in self.counters:
self.counters[key] = self.cls()
self.counters[key].event(value)
return self
def value(self, key, value=1):
"""Set value of a counter by counter key"""
if isinstance(key, six.string_types):
key = (key, )
assert isinstance(key, tuple), "event key type error"
if key not in self.counters:
self.counters[key] = self.cls()
self.counters[key].value(value)
return self
def trim(self):
"""Clear not used counters"""
for key, value in list(iteritems(self.counters)):
if value.empty():
del self.counters[key]
def __getitem__(self, key):
key = (key, )
available_keys = []
for _key in self.counters:
if _key[:len(key)] == key:
available_keys.append(_key)
if len(available_keys) == 0:
raise KeyError
elif len(available_keys) == 1:
if available_keys[0] == key:
return self.counters[key]
else:
return CounterValue(self, key)
else:
return CounterValue(self, key)
def __iter__(self):
return iter(self.keys())
def __len__(self):
return len(self.keys())
def keys(self):
result = set()
for key in self.counters:
result.add(key[0] if key else ())
return result
def to_dict(self, get_value=None):
"""Dump counters as a dict"""
self.trim()
result = {}
for key, value in iteritems(self):
if isinstance(value, BaseCounter):
if get_value is not None:
value = getattr(value, get_value)
result[key] = value
else:
result[key] = value.to_dict(get_value)
return result
def dump(self, filename):
"""Dump counters to file"""
try:
with open(filename, 'wb') as fp:
cPickle.dump(self.counters, fp)
except:
logging.error("can't dump counter to file: %s" % filename)
return False
return True
def load(self, filename):
"""Load counters to file"""
try:
with open(filename) as fp:
self.counters = cPickle.load(fp)
except:
logging.debug("can't load counter from file: %s" % filename)
return False
return True
| now = time.time()
if self._first_data_time is None:
self._first_data_time = now
if self.cache_start is None:
self.cache_value = value
self.cache_start = now
elif now - self.cache_start > self.window_interval:
self.values.append(self.cache_value)
self.times.append(self.cache_start)
self.on_append(self.cache_value, self.cache_start)
self.cache_value = value
self.cache_start = now
else:
self.cache_value += value
return self |
cmd_db_nuke.go | // Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.
package client
import (
"github.com/keybase/cli"
"github.com/keybase/client/go/libcmdline"
"github.com/keybase/client/go/libkb"
"golang.org/x/net/context"
)
type CmdDbNuke struct {
libkb.Contextified
force bool
}
func (c *CmdDbNuke) ParseArgv(ctx *cli.Context) error {
c.force = ctx.Bool("force")
return nil
}
func (c *CmdDbNuke) Run() error {
var err error
if !c.force {
err = GlobUI.PromptForConfirmation("Really blast away your local database?")
}
if err == nil {
cli, err := GetCtlClient(c.G())
if err != nil {
return err
}
if err = RegisterProtocols(nil); err != nil {
return err
}
return cli.DbNuke(context.TODO(), 0)
}
return err
}
func NewCmdDbNuke(cl *libcmdline.CommandLine, g *libkb.GlobalContext) cli.Command {
return cli.Command{
Name: "nuke",
Usage: "Delete the local database",
Action: func(c *cli.Context) {
cl.ChooseCommand(NewCmdDbNukeRunner(g), "nuke", c)
},
Flags: []cli.Flag{ | Name: "force, f",
Usage: "Don't prompt.",
},
},
}
}
func NewCmdDbNukeRunner(g *libkb.GlobalContext) *CmdDbNuke {
return &CmdDbNuke{
Contextified: libkb.NewContextified(g),
force: false,
}
}
func NewCmdDb(cl *libcmdline.CommandLine, g *libkb.GlobalContext) cli.Command {
return cli.Command{
Name: "db",
Subcommands: []cli.Command{
NewCmdDbNuke(cl, g),
},
}
}
func (c *CmdDbNuke) GetUsage() libkb.Usage {
return libkb.Usage{
Config: true,
API: true,
}
} | cli.BoolFlag{ |
dump.go | // Copyright 2016 CodisLabs. All Rights Reserved.
// Licensed under the MIT (MIT-LICENSE.txt) license.
package run
import (
"bufio"
"io"
"net"
"os"
"time"
"pkg/libs/atomic2"
"pkg/libs/log"
"redis-shake/configure"
"redis-shake/common"
)
type CmdDump struct {
}
func (cmd *CmdDump) GetDetailedInfo() []interface{} {
return nil
}
func (cmd *CmdDump) Main() {
from, output := conf.Options.SourceAddress, conf.Options.OutputRdb
if len(from) == 0 {
log.Panic("invalid argument: from")
}
if len(output) == 0 {
output = "/dev/stdout"
}
log.Infof("dump from '%s' to '%s'\n", from, output)
var dumpto io.WriteCloser
if output != "/dev/stdout" {
dumpto = utils.OpenWriteFile(output)
defer dumpto.Close()
} else {
dumpto = os.Stdout
}
master, nsize := cmd.SendCmd(from, conf.Options.SourceAuthType, conf.Options.SourcePasswordRaw)
defer master.Close()
log.Infof("rdb file = %d\n", nsize)
reader := bufio.NewReaderSize(master, utils.ReaderBufferSize)
writer := bufio.NewWriterSize(dumpto, utils.WriterBufferSize)
cmd.DumpRDBFile(reader, writer, nsize)
if !conf.Options.ExtraInfo {
return
}
cmd.DumpCommand(reader, writer, nsize)
}
func (cmd *CmdDump) SendCmd(master, auth_type, passwd string) (net.Conn, int64) {
c, wait := utils.OpenSyncConn(master, auth_type, passwd)
var nsize int64
for nsize == 0 {
select {
case nsize = <-wait:
if nsize == 0 {
log.Info("+")
}
case <-time.After(time.Second):
log.Info("-")
}
}
return c, nsize
}
func (cmd *CmdDump) DumpRDBFile(reader *bufio.Reader, writer *bufio.Writer, nsize int64) {
var nread atomic2.Int64
wait := make(chan struct{})
go func() {
defer close(wait)
p := make([]byte, utils.WriterBufferSize)
for nsize != nread.Get() {
nstep := int(nsize - nread.Get())
ncopy := int64(utils.Iocopy(reader, writer, p, nstep))
nread.Add(ncopy)
utils.FlushWriter(writer)
}
}()
for done := false; !done; {
select {
case <-wait:
done = true
case <-time.After(time.Second):
}
n := nread.Get() | log.Infof("total = %d - %12d [%3d%%]\n", nsize, n, p)
}
log.Info("dump: rdb done")
}
func (cmd *CmdDump) DumpCommand(reader *bufio.Reader, writer *bufio.Writer, nsize int64) {
var nread atomic2.Int64
go func() {
p := make([]byte, utils.ReaderBufferSize)
for {
ncopy := int64(utils.Iocopy(reader, writer, p, len(p)))
nread.Add(ncopy)
utils.FlushWriter(writer)
}
}()
for {
time.Sleep(time.Second)
log.Infof("dump: total = %d\n", nsize+nread.Get())
}
} | p := 100 * n / nsize |
config.py | import frappe
from frappe import _
from chat.utils import validate_token, get_admin_name, get_chat_settings, get_user_settings
import json
@frappe.whitelist(allow_guest=True)
def settings(token):
|
@frappe.whitelist()
def user_settings(settings):
settings = json.loads(settings)
if not frappe.db.exists('Chat User Settings', frappe.session.user):
settings_doc = frappe.get_doc({
'doctype': 'Chat User Settings',
'user': frappe.session.user,
'enable_notifications': settings['enable_notifications'],
'enable_message_tone': settings['enable_message_tone'],
}).insert()
else:
settings_doc = frappe.get_doc(
'Chat User Settings', frappe.session.user)
settings_doc.enable_notifications = settings['enable_notifications']
settings_doc.enable_message_tone = settings['enable_message_tone']
settings_doc.save()
| """Fetch and return the settings for a chat session
Args:
token (str): Guest token.
"""
config = {
'socketio_port': frappe.conf.socketio_port,
'user_email': frappe.session.user,
'is_admin': True if 'user_type' in frappe.session.data else False,
'guest_title': ''.join(frappe.get_hooks('guest_title')),
}
config = {**config, **get_chat_settings()}
if config['is_admin']:
config['user'] = get_admin_name(config['user_email'])
config['user_settings'] = get_user_settings()
else:
config['user'] = 'Guest'
token_verify = validate_token(token)
if token_verify[0] is True:
config['room'] = token_verify[1]['room']
config['user_email'] = token_verify[1]['email']
config['is_verified'] = True
else:
config['is_verified'] = False
return config |
Message.js | (function() {
function Message($firebaseArray, Room) {
var Message = {};
var ref = firebase.database().ref().child("messages");
var messages = $firebaseArray(ref);
// newmessage = messages;
Message.current = messages;
Message.current = null;
// assigns the $firebaseArray to the Message object
// (the UID of the Room.activeroom) = activeroomId;
// Room.activeroom.Id = roomId;
// Room.activeroom.UID = activeroomId;
// Room.activeroom = activeroomId;
console.log("roomId!!!");
// Room.activeroom.$Id = activeroomId;
Message.getByRoomId = function(room) {
// Filter the messages by their room ID.
// ref.orderByChild(Message.roomId).equalTo()...
var newref = ref.orderByChild("roomId").equalTo(room.$id);
// the next line converts the filtered data
// to a useable array
Message.current = $firebaseArray(newref);
// Message = Message.current;
console.log('room.$id', room.$id);
console.log('Message.current', Message.current);
messages.$add(Message.current);
// Message = Message.current;
// return Message;
return Message.current;
// return Message.current.orderByChild("content");
// return Message.current.Child("content");
};
Message.send = function(newMessage){
// make a reference to the database
// var messref = firebase.database().ref().child("messages");
// newMessage = $firebaseArray(messref);
// messref.$set({
// newMessage
// });
console.log("newMessage!!!!!!", newMessage);
// var messref = ref.child("messages");
// var newMessref.push();
// newMessref.set({
// content: "newMessage";
// });
// messages.$add(newMessage);
messages.$add({content: newMessage, roomId: "-Ku-4b4frLOVOe7NGzfJ", sentAt:"whateverTime", username: "Tim"});
messages = Message.current;
// return messages; |
};
// this is a query that finds all messages that have
// a roomId (of the activeroom) that is equal to
// (the roomId of activeroom(in home.html?))
// Message.addMessage = function(newmessage,room) {
//
// var newref = ref.orderByChild("roomId").equalTo(room.$id);
// newmessage = $firebaseArray(newref);
// messages.$add(newmessage);
// // Room.add(roomName);
// }
// .child() method can either query an existing set of
// data or reference one you intend to populate with
// data in the future. The $firebaseArray service
// is used to ensure the data is returned as an array
return Message;
};
angular
.module('blocChat')
.factory('Message', ['$firebaseArray', 'Room', Message]);
})();
// https://blocchat-4058a.firebaseio.com/ | return Message.current;
// console.log(Message.current.room.$id;) |
sync_state.go | package virtualbox
import (
"github.com/Sirupsen/logrus"
"github.com/emc-advanced-dev/pkg/errors"
"github.com/emc-advanced-dev/unik/pkg/providers/common"
"github.com/emc-advanced-dev/unik/pkg/providers/virtualbox/virtualboxclient"
"github.com/emc-advanced-dev/unik/pkg/types"
unikutil "github.com/emc-advanced-dev/unik/pkg/util"
"os"
"strings"
"time"
)
func (p *VirtualboxProvider) syncState() error {
if len(p.state.GetInstances()) < 1 {
return nil
}
for _, instance := range p.state.GetInstances() {
vm, err := virtualboxclient.GetVm(instance.Name)
if err != nil |
macAddr := vm.MACAddr
if vm.Running {
instance.State = types.InstanceState_Running
} else {
instance.State = types.InstanceState_Stopped
}
var ipAddress string
unikutil.Retry(3, time.Duration(500*time.Millisecond), func() error {
if instance.Name == VboxUnikInstanceListener {
ipAddress = p.instanceListenerIp
} else {
var err error
ipAddress, err = common.GetInstanceIp(p.instanceListenerIp, 3000, macAddr)
if err != nil {
return err
}
}
return nil
})
if err := p.state.ModifyInstances(func(instances map[string]*types.Instance) error {
if _, ok := instances[instance.Id]; ok {
instances[instance.Id].IpAddress = ipAddress
instances[instance.Id].State = instance.State
}
return nil
}); err != nil {
return err
}
}
return nil
}
| {
if strings.Contains(err.Error(), "Could not find a registered machine") {
logrus.Warnf("instance found in state that is no longer registered to Virtualbox")
os.RemoveAll(getInstanceDir(instance.Name))
p.state.RemoveInstance(instance)
continue
}
return errors.New("retrieving vm for instance id "+instance.Name, err)
} |
minmax_filter.py | from __future__ import print_function, unicode_literals, absolute_import, division
import logging
logger = logging.getLogger(__name__)
import os
import numpy as np
from gputools import OCLArray, OCLProgram, get_device
from gputools.core.ocltypes import assert_bufs_type
from gputools.utils.tile_iterator import tile_iterator
from ._abspath import abspath
def _filter_max_2_gpu(data_g, size=10, res_g=None):
assert_bufs_type(np.float32, data_g)
prog = OCLProgram(abspath("kernels/minmax_filter.cl"))
tmp_g = OCLArray.empty_like(data_g)
if res_g is None:
res_g = OCLArray.empty_like(data_g)
prog.run_kernel("max_2_x", data_g.shape[::-1], None, data_g.data, tmp_g.data, np.int32(size[-1]))
prog.run_kernel("max_2_y", data_g.shape[::-1], None, tmp_g.data, res_g.data, np.int32(size[-2]))
return res_g
def _filter_max_3_gpu(data_g, size=10, res_g=None):
assert_bufs_type(np.float32, data_g)
prog = OCLProgram(abspath("kernels/minmax_filter.cl"))
tmp_g = OCLArray.empty_like(data_g)
if res_g is None:
res_g = OCLArray.empty_like(data_g)
prog.run_kernel("max_3_x", data_g.shape[::-1], None, data_g.data, res_g.data, np.int32(size[-1]))
prog.run_kernel("max_3_y", data_g.shape[::-1], None, res_g.data, tmp_g.data, np.int32(size[-2]))
prog.run_kernel("max_3_z", data_g.shape[::-1], None, tmp_g.data, res_g.data, np.int32(size[-3]))
return res_g
def _max_filter_gpu(data_g, size=5, res_g=None):
assert_bufs_type(np.float32, data_g)
assert (len(data_g.shape) == len(size))
if len(data_g.shape) == 2:
return _filter_max_2_gpu(data_g, size=size, res_g=res_g)
elif len(data_g.shape) == 3:
return _filter_max_3_gpu(data_g, size=size, res_g=res_g)
else:
raise NotImplementedError("only 2 or 3d arrays are supported for now")
def _max_filter_numpy(data, size=5):
data_g = OCLArray.from_array(data.astype(np.float32))
return _max_filter_gpu(data_g, size=size).get()
def max_filter(data, size=10, res_g=None, sub_blocks=(1, 1, 1)):
"""
maximum filter of given size
Parameters
----------
data: 2 or 3 dimensional ndarray or OCLArray of type float32
input data
size: scalar, tuple
the size of the patch to consider
res_g: OCLArray
store result in buffer if given
sub_blocks:
perform over subblock tiling (only if data is ndarray)
Returns
-------
filtered image or None (if OCLArray)
"""
if np.isscalar(size):
size = (size,)*len(data.shape)
if isinstance(data, np.ndarray):
data = np.ascontiguousarray(data)
if set(sub_blocks) == {1} or sub_blocks is None:
return _max_filter_numpy(data, size)
else:
# cut the image into tile and operate on every of them
N_sub = [int(np.ceil(1. * n / s)) for n, s in zip(data.shape, sub_blocks)]
Npads = tuple(map(lambda x: x//2, size))
res = np.empty(data.shape, np.float32) | for i, (data_tile, data_s_src, data_s_dest) \
in enumerate(tile_iterator(data, blocksize=N_sub,
padsize=Npads,
mode="constant")):
res_tile = _max_filter_numpy(data_tile.copy(),
size)
res[data_s_src] = res_tile[data_s_dest]
return res
elif isinstance(data, OCLArray):
return _max_filter_gpu(data, size=size, res_g=res_g)
else:
raise TypeError("array argument (1) has bad type: %s" % type(data))
def _filter_min_2_gpu(data_g, size=(10,10), res_g=None):
assert_bufs_type(np.float32, data_g)
prog = OCLProgram(abspath("kernels/minmax_filter.cl"))
tmp_g = OCLArray.empty_like(data_g)
if res_g is None:
res_g = OCLArray.empty_like(data_g)
prog.run_kernel("min_2_x", data_g.shape[::-1], None, data_g.data, tmp_g.data, np.int32(size[-1]))
prog.run_kernel("min_2_y", data_g.shape[::-1], None, tmp_g.data, res_g.data, np.int32(size[-2]))
return res_g
def _filter_min_3_gpu(data_g, size=(10,10,10), res_g=None):
assert_bufs_type(np.float32, data_g)
prog = OCLProgram(abspath("kernels/minmax_filter.cl"))
tmp_g = OCLArray.empty_like(data_g)
if res_g is None:
res_g = OCLArray.empty_like(data_g)
prog.run_kernel("min_3_x", data_g.shape[::-1], None, data_g.data, res_g.data, np.int32(size[-1]))
prog.run_kernel("min_3_y", data_g.shape[::-1], None, res_g.data, tmp_g.data, np.int32(size[-2]))
prog.run_kernel("min_3_z", data_g.shape[::-1], None, tmp_g.data, res_g.data, np.int32(size[-3]))
return res_g
def _min_filter_gpu(data_g, size=(10,10), res_g=None):
assert_bufs_type(np.float32, data_g)
assert (len(data_g.shape)==len(size))
if len(data_g.shape) == 2:
return _filter_min_2_gpu(data_g, size=size, res_g=res_g)
elif len(data_g.shape) == 3:
return _filter_min_3_gpu(data_g, size=size, res_g=res_g)
else:
raise NotImplementedError("only 2 or 3d arrays are supported for now")
def _min_filter_numpy(data, size=(10,10)):
data_g = OCLArray.from_array(data.astype(np.float32))
return _min_filter_gpu(data_g, size=size).get()
def min_filter(data, size=10, res_g=None, sub_blocks=(1, 1, 1)):
"""
minimum filter of given size
Parameters
----------
data: 2 or 3 dimensional ndarray or OCLArray of type float32
input data
size: scalar, tuple
the size of the patch to consider
res_g: OCLArray
store result in buffer if given
sub_blocks:
perform over subblock tiling (only if data is ndarray)
Returns
-------
filtered image or None (if OCLArray)
"""
if np.isscalar(size):
size = (size,)*len(data.shape)
if isinstance(data, np.ndarray):
if set(sub_blocks) == {1} or sub_blocks is None:
return _min_filter_numpy(data, size)
else:
# cut the image into tile and operate on every of them
N_sub = [int(np.ceil(1. * n / s)) for n, s in zip(data.shape, sub_blocks)]
Npads = tuple(map(lambda x: x//2, size))
res = np.empty(data.shape, np.float32)
for i, (data_tile, data_s_src, data_s_dest) \
in enumerate(tile_iterator(data, blocksize=N_sub,
padsize=Npads,
mode="constant")):
res_tile = _min_filter_numpy(data_tile.copy(),
size)
res[data_s_src] = res_tile[data_s_dest]
return res
elif isinstance(data, OCLArray):
return _min_filter_gpu(data, size=size, res_g=res_g)
else:
raise TypeError("array argument (1) has bad type: %s" % type(data)) | |
models.rs | /*
* Copyright 2018-2021 Cargill Incorporated
*
* 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.
* -----------------------------------------------------------------------------
*/
use std::time::SystemTime;
use super::schema::{notification_properties, notifications, user_notifications};
#[derive(Insertable, Queryable)] | #[table_name = "notifications"]
pub struct Notification {
pub id: String,
pub payload_title: String,
pub payload_body: String,
pub created: SystemTime,
pub recipients: Vec<String>,
}
#[derive(Insertable, Queryable)]
#[table_name = "user_notifications"]
pub struct UserNotification {
pub notification_id: String,
pub user_id: String,
pub unread: bool,
}
#[derive(Insertable, Queryable)]
#[table_name = "notification_properties"]
pub struct NotificationProperty {
pub id: i64,
pub notification_id: String,
pub property: String,
pub property_value: String,
} | |
load_dataset.py | from sklearn.model_selection import GroupKFold
import pandas as pd
import cv2
import os
import numpy as np
import ast
import torch
import albumentations
from config import CFG
from torch.utils.data import DataLoader
class RanzcrDataset(object):
def __init__(self, root, df, mode='test', transforms=None, train_anno=None):
self.root = root
self.transforms = transforms
self.filenames = (df['StudyInstanceUID']).values
self.mode = mode
self.train_anno = train_anno
def __len__(self):
return len(self.filenames)
def __getitem__(self, idx):
img_path = os.path.join(self.root, self.filenames[idx] + '.jpg')
img = cv2.imread(img_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
if self.mode == 'test':
img = self.transforms(image=img)['image']
img = img.astype('float32').transpose(2, 0, 1) / 255.
return img
else:
mask = np.zeros((img.shape[0], img.shape[1], 2)).astype('float32')
mask0 = mask[:, :, 0].copy()
mask1 = mask[:, :, 1].copy()
this_anno = self.train_anno.query(f'StudyInstanceUID == "{self.filenames[idx]}"')
for _, anno in this_anno.iterrows():
data = np.array(ast.literal_eval(anno["data"]))
mask0 = cv2.polylines(mask0, np.int32([data]), isClosed=False, color=1, thickness=15, lineType=16) # 管道位置画线
mask1 = cv2.circle(mask1, (data[0][0], data[0][1]), radius=15, color=1, thickness=25) # 管道开始位置画圈
mask1 = cv2.circle(mask1, (data[-1][0], data[-1][1]), radius=15, color=1, thickness=25) # 管道结束位置画圈
mask[:, :, 0] = mask0
mask[:, :, 1] = mask1
res = self.transforms(image=img, mask=mask)
img = res['image']
mask = res['mask']
img = img.astype('float32').transpose(2, 0, 1) / 255.
mask = mask.astype('float32').transpose(2, 0, 1)
return torch.tensor(img), torch.tensor(mask)
transforms_train = albumentations.Compose([
albumentations.Resize(CFG.image_size, CFG.image_size),
albumentations.HorizontalFlip(p=0.5),
albumentations.RandomBrightness(limit=0.1, p=0.75),
# albumentations.OneOf([
# albumentations.GaussNoise(var_limit=[10, 50]),
# albumentations.MotionBlur(),
# albumentations.MedianBlur(), | albumentations.ShiftScaleRotate(shift_limit=0.2, scale_limit=0.2, rotate_limit=30, border_mode=0, p=0.75),
albumentations.Cutout(max_h_size=int(CFG.image_size * 0.3), max_w_size=int(CFG.image_size * 0.3), num_holes=1, p=0.75),
# albumentations.Normalize(),
])
transforms_valid = albumentations.Compose([
albumentations.Resize(CFG.image_size, CFG.image_size),
# albumentations.Normalize(),
])
'''
K-fold划分数据集
'''
def get_folds(nfolds=5):
traindf = pd.read_csv(CFG.train_df_path)
folds = traindf.copy()
Fold = GroupKFold(n_splits=nfolds)
groups = folds['PatientID'].values
for n, (train_index, val_index) in enumerate(Fold.split(folds, folds[CFG.target_cols], groups)):
folds.loc[val_index, 'fold'] = int(n) # 添加一个fold列,将val_index对应的行设置为n
folds['fold'] = folds['fold'].astype(int)
return folds
'''
得到有标注信息的样本表格
'''
def get_df_with_anno():
folds = get_folds(5) # k折
train_anno = pd.read_csv(CFG.train_anno_path)
unique_anno = train_anno.drop_duplicates(['StudyInstanceUID']).copy() # 去掉重复的样本名
unique_anno['with_anno'] = True
# 连接两个表
train_v2 = pd.merge(folds, unique_anno[['StudyInstanceUID', 'with_anno']], left_on='StudyInstanceUID', right_on='StudyInstanceUID', how='left')
# 将没有annotation的样本设置为False
train_v2['with_anno'] = train_v2['with_anno'].fillna(value=False)
sample_with_anno_df = train_v2[train_v2['with_anno'] == True].copy()
return sample_with_anno_df
def get_seg_loader(fold_id, debug=False):
sample_with_anno_df = get_df_with_anno()
train_df = sample_with_anno_df[sample_with_anno_df.fold != fold_id]
valid_df = sample_with_anno_df[sample_with_anno_df.fold == fold_id]
# 小样本用作测试
if debug:
train_df = train_df.iloc[:16]
valid_df = train_df.iloc[:16]
train_anno = pd.read_csv(CFG.train_anno_path)
train_data = RanzcrDataset(CFG.train_img_path, train_df, mode='train', transforms=transforms_train, train_anno=train_anno)
valid_data = RanzcrDataset(CFG.train_img_path, valid_df, mode='valid', transforms=transforms_valid, train_anno=train_anno)
train_loader = DataLoader(train_data, batch_size=CFG.seg_batch_size, shuffle=True, num_workers=CFG.num_workers)
valid_loader = DataLoader(valid_data, batch_size=CFG.seg_batch_size, shuffle=False, num_workers=CFG.num_workers)
return train_loader, valid_loader | # ], p=0.2), |
views.py | # This file is part of Indico.
# Copyright (C) 2002 - 2019 CERN | # Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
from indico.modules.admin.views import WPAdmin
from indico.util.i18n import _
from indico.web.views import WPDecorated, WPJinjaMixin
class WPNews(WPJinjaMixin, WPDecorated):
template_prefix = 'news/'
title = _('News')
def _get_body(self, params):
return self._get_page_content(params)
class WPManageNews(WPAdmin):
template_prefix = 'news/' | # |
index.d.ts | // Type definitions for eslint 7.28
// Project: https://eslint.org
// Definitions by: Pierre-Marie Dartus <https://github.com/pmdartus>
// Jed Fox <https://github.com/j-f1>
// Saad Quadri <https://github.com/saadq>
// Jason Kwok <https://github.com/JasonHK>
// Brad Zacher <https://github.com/bradzacher>
// JounQin <https://github.com/JounQin>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="helpers.d.ts" />
/// <reference path="lib/rules/index.d.ts" />
import { JSONSchema4 } from "json-schema";
import * as ESTree from "estree";
export namespace AST {
type TokenType =
| "Boolean"
| "Null"
| "Identifier"
| "Keyword"
| "Punctuator"
| "JSXIdentifier"
| "JSXText"
| "Numeric"
| "String"
| "RegularExpression";
interface Token {
type: TokenType;
value: string;
range: Range;
loc: SourceLocation;
}
interface SourceLocation {
start: ESTree.Position;
end: ESTree.Position;
}
type Range = [number, number];
interface Program extends ESTree.Program {
comments: ESTree.Comment[];
tokens: Token[];
loc: SourceLocation;
range: Range;
}
}
export namespace Scope {
interface ScopeManager {
scopes: Scope[];
globalScope: Scope | null;
acquire(node: ESTree.Node, inner?: boolean): Scope | null;
getDeclaredVariables(node: ESTree.Node): Variable[];
}
interface Scope {
type:
| "block"
| "catch"
| "class"
| "for"
| "function"
| "function-expression-name"
| "global"
| "module"
| "switch"
| "with"
| "TDZ";
isStrict: boolean;
upper: Scope | null;
childScopes: Scope[];
variableScope: Scope;
block: ESTree.Node;
variables: Variable[];
set: Map<string, Variable>;
references: Reference[];
through: Reference[];
functionExpressionScope: boolean;
}
interface Variable {
name: string;
identifiers: ESTree.Identifier[];
references: Reference[];
defs: Definition[];
}
interface Reference {
identifier: ESTree.Identifier;
from: Scope;
resolved: Variable | null;
writeExpr: ESTree.Node | null;
init: boolean;
isWrite(): boolean;
isRead(): boolean;
isWriteOnly(): boolean;
isReadOnly(): boolean;
isReadWrite(): boolean;
}
type DefinitionType =
| { type: "CatchClause"; node: ESTree.CatchClause; parent: null }
| { type: "ClassName"; node: ESTree.ClassDeclaration | ESTree.ClassExpression; parent: null }
| { type: "FunctionName"; node: ESTree.FunctionDeclaration | ESTree.FunctionExpression; parent: null }
| { type: "ImplicitGlobalVariable"; node: ESTree.Program; parent: null }
| {
type: "ImportBinding";
node: ESTree.ImportSpecifier | ESTree.ImportDefaultSpecifier | ESTree.ImportNamespaceSpecifier;
parent: ESTree.ImportDeclaration;
}
| {
type: "Parameter";
node: ESTree.FunctionDeclaration | ESTree.FunctionExpression | ESTree.ArrowFunctionExpression;
parent: null;
}
| { type: "TDZ"; node: any; parent: null }
| { type: "Variable"; node: ESTree.VariableDeclarator; parent: ESTree.VariableDeclaration };
type Definition = DefinitionType & { name: ESTree.Identifier };
}
//#region SourceCode
export class SourceCode {
text: string;
ast: AST.Program;
lines: string[];
hasBOM: boolean;
parserServices: SourceCode.ParserServices;
scopeManager: Scope.ScopeManager;
visitorKeys: SourceCode.VisitorKeys;
constructor(text: string, ast: AST.Program);
constructor(config: SourceCode.Config);
static splitLines(text: string): string[];
getText(node?: ESTree.Node, beforeCount?: number, afterCount?: number): string;
getLines(): string[];
getAllComments(): ESTree.Comment[];
getComments(node: ESTree.Node): { leading: ESTree.Comment[]; trailing: ESTree.Comment[] };
getJSDocComment(node: ESTree.Node): ESTree.Comment | null;
getNodeByRangeIndex(index: number): ESTree.Node | null;
isSpaceBetweenTokens(first: AST.Token, second: AST.Token): boolean;
getLocFromIndex(index: number): ESTree.Position;
getIndexFromLoc(location: ESTree.Position): number;
// Inherited methods from TokenStore
// ---------------------------------
getTokenByRangeStart(offset: number, options?: { includeComments: false }): AST.Token | null;
getTokenByRangeStart(offset: number, options: { includeComments: boolean }): AST.Token | ESTree.Comment | null;
getFirstToken: SourceCode.UnaryNodeCursorWithSkipOptions;
getFirstTokens: SourceCode.UnaryNodeCursorWithCountOptions;
getLastToken: SourceCode.UnaryNodeCursorWithSkipOptions;
getLastTokens: SourceCode.UnaryNodeCursorWithCountOptions;
getTokenBefore: SourceCode.UnaryCursorWithSkipOptions;
getTokensBefore: SourceCode.UnaryCursorWithCountOptions;
getTokenAfter: SourceCode.UnaryCursorWithSkipOptions;
getTokensAfter: SourceCode.UnaryCursorWithCountOptions;
getFirstTokenBetween: SourceCode.BinaryCursorWithSkipOptions;
getFirstTokensBetween: SourceCode.BinaryCursorWithCountOptions;
getLastTokenBetween: SourceCode.BinaryCursorWithSkipOptions;
getLastTokensBetween: SourceCode.BinaryCursorWithCountOptions;
getTokensBetween: SourceCode.BinaryCursorWithCountOptions;
getTokens: ((node: ESTree.Node, beforeCount?: number, afterCount?: number) => AST.Token[]) &
SourceCode.UnaryNodeCursorWithCountOptions;
commentsExistBetween(
left: ESTree.Node | AST.Token | ESTree.Comment,
right: ESTree.Node | AST.Token | ESTree.Comment,
): boolean;
getCommentsBefore(nodeOrToken: ESTree.Node | AST.Token): ESTree.Comment[];
getCommentsAfter(nodeOrToken: ESTree.Node | AST.Token): ESTree.Comment[];
getCommentsInside(node: ESTree.Node): ESTree.Comment[];
}
export namespace SourceCode {
interface Config {
text: string;
ast: AST.Program;
parserServices?: ParserServices | undefined;
scopeManager?: Scope.ScopeManager | undefined;
visitorKeys?: VisitorKeys | undefined;
}
type ParserServices = any;
interface VisitorKeys {
[nodeType: string]: string[];
}
interface UnaryNodeCursorWithSkipOptions {
<T extends AST.Token>(
node: ESTree.Node,
options:
| ((token: AST.Token) => token is T)
| { filter: (token: AST.Token) => token is T; includeComments?: false | undefined; skip?: number | undefined },
): T | null;
<T extends AST.Token | ESTree.Comment>(
node: ESTree.Node,
options: {
filter: (tokenOrComment: AST.Token | ESTree.Comment) => tokenOrComment is T;
includeComments: boolean;
skip?: number | undefined;
},
): T | null;
(
node: ESTree.Node,
options?:
| { filter?: ((token: AST.Token) => boolean) | undefined; includeComments?: false | undefined; skip?: number | undefined }
| ((token: AST.Token) => boolean)
| number,
): AST.Token | null;
(
node: ESTree.Node,
options: {
filter?: ((token: AST.Token | ESTree.Comment) => boolean) | undefined;
includeComments: boolean;
skip?: number | undefined;
},
): AST.Token | ESTree.Comment | null;
}
interface UnaryNodeCursorWithCountOptions {
<T extends AST.Token>(
node: ESTree.Node,
options:
| ((token: AST.Token) => token is T)
| { filter: (token: AST.Token) => token is T; includeComments?: false | undefined; count?: number | undefined },
): T[];
<T extends AST.Token | ESTree.Comment>(
node: ESTree.Node,
options: {
filter: (tokenOrComment: AST.Token | ESTree.Comment) => tokenOrComment is T;
includeComments: boolean;
count?: number | undefined;
},
): T[];
(
node: ESTree.Node,
options?:
| { filter?: ((token: AST.Token) => boolean) | undefined; includeComments?: false | undefined; count?: number | undefined }
| ((token: AST.Token) => boolean)
| number,
): AST.Token[];
(
node: ESTree.Node,
options: {
filter?: ((token: AST.Token | ESTree.Comment) => boolean) | undefined;
includeComments: boolean;
count?: number | undefined;
},
): Array<AST.Token | ESTree.Comment>;
}
interface UnaryCursorWithSkipOptions {
<T extends AST.Token>(
node: ESTree.Node | AST.Token | ESTree.Comment,
options:
| ((token: AST.Token) => token is T)
| { filter: (token: AST.Token) => token is T; includeComments?: false | undefined; skip?: number | undefined },
): T | null;
<T extends AST.Token | ESTree.Comment>(
node: ESTree.Node | AST.Token | ESTree.Comment,
options: {
filter: (tokenOrComment: AST.Token | ESTree.Comment) => tokenOrComment is T;
includeComments: boolean;
skip?: number | undefined;
},
): T | null;
(
node: ESTree.Node | AST.Token | ESTree.Comment,
options?:
| { filter?: ((token: AST.Token) => boolean) | undefined; includeComments?: false | undefined; skip?: number | undefined }
| ((token: AST.Token) => boolean)
| number,
): AST.Token | null;
(
node: ESTree.Node | AST.Token | ESTree.Comment,
options: {
filter?: ((token: AST.Token | ESTree.Comment) => boolean) | undefined;
includeComments: boolean;
skip?: number | undefined;
},
): AST.Token | ESTree.Comment | null;
}
interface UnaryCursorWithCountOptions {
<T extends AST.Token>(
node: ESTree.Node | AST.Token | ESTree.Comment,
options:
| ((token: AST.Token) => token is T)
| { filter: (token: AST.Token) => token is T; includeComments?: false | undefined; count?: number | undefined },
): T[];
<T extends AST.Token | ESTree.Comment>(
node: ESTree.Node | AST.Token | ESTree.Comment,
options: {
filter: (tokenOrComment: AST.Token | ESTree.Comment) => tokenOrComment is T;
includeComments: boolean;
count?: number | undefined;
},
): T[];
(
node: ESTree.Node | AST.Token | ESTree.Comment,
options?:
| { filter?: ((token: AST.Token) => boolean) | undefined; includeComments?: false | undefined; count?: number | undefined }
| ((token: AST.Token) => boolean)
| number,
): AST.Token[];
(
node: ESTree.Node | AST.Token | ESTree.Comment,
options: {
filter?: ((token: AST.Token | ESTree.Comment) => boolean) | undefined;
includeComments: boolean;
count?: number | undefined;
},
): Array<AST.Token | ESTree.Comment>;
}
interface BinaryCursorWithSkipOptions {
<T extends AST.Token>(
left: ESTree.Node | AST.Token | ESTree.Comment,
right: ESTree.Node | AST.Token | ESTree.Comment,
options:
| ((token: AST.Token) => token is T)
| { filter: (token: AST.Token) => token is T; includeComments?: false | undefined; skip?: number | undefined },
): T | null;
<T extends AST.Token | ESTree.Comment>(
left: ESTree.Node | AST.Token | ESTree.Comment,
right: ESTree.Node | AST.Token | ESTree.Comment,
options: {
filter: (tokenOrComment: AST.Token | ESTree.Comment) => tokenOrComment is T;
includeComments: boolean;
skip?: number | undefined;
},
): T | null;
(
left: ESTree.Node | AST.Token | ESTree.Comment,
right: ESTree.Node | AST.Token | ESTree.Comment,
options?:
| { filter?: ((token: AST.Token) => boolean) | undefined; includeComments?: false | undefined; skip?: number | undefined }
| ((token: AST.Token) => boolean)
| number,
): AST.Token | null;
(
left: ESTree.Node | AST.Token | ESTree.Comment,
right: ESTree.Node | AST.Token | ESTree.Comment,
options: {
filter?: ((token: AST.Token | ESTree.Comment) => boolean) | undefined;
includeComments: boolean;
skip?: number | undefined;
},
): AST.Token | ESTree.Comment | null;
}
interface BinaryCursorWithCountOptions {
<T extends AST.Token>(
left: ESTree.Node | AST.Token | ESTree.Comment,
right: ESTree.Node | AST.Token | ESTree.Comment,
options:
| ((token: AST.Token) => token is T)
| { filter: (token: AST.Token) => token is T; includeComments?: false | undefined; count?: number | undefined },
): T[];
<T extends AST.Token | ESTree.Comment>(
left: ESTree.Node | AST.Token | ESTree.Comment,
right: ESTree.Node | AST.Token | ESTree.Comment,
options: {
filter: (tokenOrComment: AST.Token | ESTree.Comment) => tokenOrComment is T;
includeComments: boolean;
count?: number | undefined;
},
): T[];
(
left: ESTree.Node | AST.Token | ESTree.Comment,
right: ESTree.Node | AST.Token | ESTree.Comment,
options?:
| { filter?: ((token: AST.Token) => boolean) | undefined; includeComments?: false | undefined; count?: number | undefined }
| ((token: AST.Token) => boolean)
| number,
): AST.Token[];
(
left: ESTree.Node | AST.Token | ESTree.Comment,
right: ESTree.Node | AST.Token | ESTree.Comment,
options: {
filter?: ((token: AST.Token | ESTree.Comment) => boolean) | undefined;
includeComments: boolean;
count?: number | undefined;
},
): Array<AST.Token | ESTree.Comment>;
}
}
//#endregion
export namespace Rule {
interface RuleModule {
create(context: RuleContext): RuleListener;
meta?: RuleMetaData | undefined;
}
type NodeTypes = ESTree.Node["type"];
interface NodeListener {
ArrayExpression?: ((node: ESTree.ArrayExpression & NodeParentExtension) => void) | undefined;
ArrayPattern?: ((node: ESTree.ArrayPattern & NodeParentExtension) => void) | undefined;
ArrowFunctionExpression?: ((node: ESTree.ArrowFunctionExpression & NodeParentExtension) => void) | undefined;
AssignmentExpression?: ((node: ESTree.AssignmentExpression & NodeParentExtension) => void) | undefined;
AssignmentPattern?: ((node: ESTree.AssignmentPattern & NodeParentExtension) => void) | undefined;
AwaitExpression?: ((node: ESTree.AwaitExpression & NodeParentExtension) => void) | undefined;
BinaryExpression?: ((node: ESTree.BinaryExpression & NodeParentExtension) => void) | undefined;
BlockStatement?: ((node: ESTree.BlockStatement & NodeParentExtension) => void) | undefined;
BreakStatement?: ((node: ESTree.BreakStatement & NodeParentExtension) => void) | undefined;
CallExpression?: ((node: ESTree.CallExpression & NodeParentExtension) => void) | undefined;
CatchClause?: ((node: ESTree.CatchClause & NodeParentExtension) => void) | undefined;
ChainExpression?: ((node: ESTree.ChainExpression & NodeParentExtension) => void) | undefined;
ClassBody?: ((node: ESTree.ClassBody & NodeParentExtension) => void) | undefined;
ClassDeclaration?: ((node: ESTree.ClassDeclaration & NodeParentExtension) => void) | undefined;
ClassExpression?: ((node: ESTree.ClassExpression & NodeParentExtension) => void) | undefined;
ConditionalExpression?: ((node: ESTree.ConditionalExpression & NodeParentExtension) => void) | undefined;
ContinueStatement?: ((node: ESTree.ContinueStatement & NodeParentExtension) => void) | undefined;
DebuggerStatement?: ((node: ESTree.DebuggerStatement & NodeParentExtension) => void) | undefined;
DoWhileStatement?: ((node: ESTree.DoWhileStatement & NodeParentExtension) => void) | undefined;
EmptyStatement?: ((node: ESTree.EmptyStatement & NodeParentExtension) => void) | undefined;
ExportAllDeclaration?: ((node: ESTree.ExportAllDeclaration & NodeParentExtension) => void) | undefined;
ExportDefaultDeclaration?: ((node: ESTree.ExportDefaultDeclaration & NodeParentExtension) => void) | undefined;
ExportNamedDeclaration?: ((node: ESTree.ExportNamedDeclaration & NodeParentExtension) => void) | undefined;
ExportSpecifier?: ((node: ESTree.ExportSpecifier & NodeParentExtension) => void) | undefined;
ExpressionStatement?: ((node: ESTree.ExpressionStatement & NodeParentExtension) => void) | undefined;
ForInStatement?: ((node: ESTree.ForInStatement & NodeParentExtension) => void) | undefined;
ForOfStatement?: ((node: ESTree.ForOfStatement & NodeParentExtension) => void) | undefined;
ForStatement?: ((node: ESTree.ForStatement & NodeParentExtension) => void) | undefined;
FunctionDeclaration?: ((node: ESTree.FunctionDeclaration & NodeParentExtension) => void) | undefined;
FunctionExpression?: ((node: ESTree.FunctionExpression & NodeParentExtension) => void) | undefined;
Identifier?: ((node: ESTree.Identifier & NodeParentExtension) => void) | undefined;
IfStatement?: ((node: ESTree.IfStatement & NodeParentExtension) => void) | undefined; | ImportDeclaration?: ((node: ESTree.ImportDeclaration & NodeParentExtension) => void) | undefined;
ImportDefaultSpecifier?: ((node: ESTree.ImportDefaultSpecifier & NodeParentExtension) => void) | undefined;
ImportExpression?: ((node: ESTree.ImportExpression & NodeParentExtension) => void) | undefined;
ImportNamespaceSpecifier?: ((node: ESTree.ImportNamespaceSpecifier & NodeParentExtension) => void) | undefined;
ImportSpecifier?: ((node: ESTree.ImportSpecifier & NodeParentExtension) => void) | undefined;
LabeledStatement?: ((node: ESTree.LabeledStatement & NodeParentExtension) => void) | undefined;
Literal?: ((node: ESTree.Literal & NodeParentExtension) => void) | undefined;
LogicalExpression?: ((node: ESTree.LogicalExpression & NodeParentExtension) => void) | undefined;
MemberExpression?: ((node: ESTree.MemberExpression & NodeParentExtension) => void) | undefined;
MetaProperty?: ((node: ESTree.MetaProperty & NodeParentExtension) => void) | undefined;
MethodDefinition?: ((node: ESTree.MethodDefinition & NodeParentExtension) => void) | undefined;
NewExpression?: ((node: ESTree.NewExpression & NodeParentExtension) => void) | undefined;
ObjectExpression?: ((node: ESTree.ObjectExpression & NodeParentExtension) => void) | undefined;
ObjectPattern?: ((node: ESTree.ObjectPattern & NodeParentExtension) => void) | undefined;
Program?: ((node: ESTree.Program) => void) | undefined;
Property?: ((node: ESTree.Property & NodeParentExtension) => void) | undefined;
RestElement?: ((node: ESTree.RestElement & NodeParentExtension) => void) | undefined;
ReturnStatement?: ((node: ESTree.ReturnStatement & NodeParentExtension) => void) | undefined;
SequenceExpression?: ((node: ESTree.SequenceExpression & NodeParentExtension) => void) | undefined;
SpreadElement?: ((node: ESTree.SpreadElement & NodeParentExtension) => void) | undefined;
Super?: ((node: ESTree.Super & NodeParentExtension) => void) | undefined;
SwitchCase?: ((node: ESTree.SwitchCase & NodeParentExtension) => void) | undefined;
SwitchStatement?: ((node: ESTree.SwitchStatement & NodeParentExtension) => void) | undefined;
TaggedTemplateExpression?: ((node: ESTree.TaggedTemplateExpression & NodeParentExtension) => void) | undefined;
TemplateElement?: ((node: ESTree.TemplateElement & NodeParentExtension) => void) | undefined;
TemplateLiteral?: ((node: ESTree.TemplateLiteral & NodeParentExtension) => void) | undefined;
ThisExpression?: ((node: ESTree.ThisExpression & NodeParentExtension) => void) | undefined;
ThrowStatement?: ((node: ESTree.ThrowStatement & NodeParentExtension) => void) | undefined;
TryStatement?: ((node: ESTree.TryStatement & NodeParentExtension) => void) | undefined;
UnaryExpression?: ((node: ESTree.UnaryExpression & NodeParentExtension) => void) | undefined;
UpdateExpression?: ((node: ESTree.UpdateExpression & NodeParentExtension) => void) | undefined;
VariableDeclaration?: ((node: ESTree.VariableDeclaration & NodeParentExtension) => void) | undefined;
VariableDeclarator?: ((node: ESTree.VariableDeclarator & NodeParentExtension) => void) | undefined;
WhileStatement?: ((node: ESTree.WhileStatement & NodeParentExtension) => void) | undefined;
WithStatement?: ((node: ESTree.WithStatement & NodeParentExtension) => void) | undefined;
YieldExpression?: ((node: ESTree.YieldExpression & NodeParentExtension) => void) | undefined;
}
interface NodeParentExtension {
parent: Node;
}
type Node = ESTree.Node & NodeParentExtension;
interface RuleListener extends NodeListener {
onCodePathStart?(codePath: CodePath, node: Node): void;
onCodePathEnd?(codePath: CodePath, node: Node): void;
onCodePathSegmentStart?(segment: CodePathSegment, node: Node): void;
onCodePathSegmentEnd?(segment: CodePathSegment, node: Node): void;
onCodePathSegmentLoop?(fromSegment: CodePathSegment, toSegment: CodePathSegment, node: Node): void;
[key: string]:
| ((codePath: CodePath, node: Node) => void)
| ((segment: CodePathSegment, node: Node) => void)
| ((fromSegment: CodePathSegment, toSegment: CodePathSegment, node: Node) => void)
| ((node: Node) => void)
| NodeListener[keyof NodeListener]
| undefined;
}
interface CodePath {
id: string;
initialSegment: CodePathSegment;
finalSegments: CodePathSegment[];
returnedSegments: CodePathSegment[];
thrownSegments: CodePathSegment[];
currentSegments: CodePathSegment[];
upper: CodePath | null;
childCodePaths: CodePath[];
}
interface CodePathSegment {
id: string;
nextSegments: CodePathSegment[];
prevSegments: CodePathSegment[];
reachable: boolean;
}
interface RuleMetaData {
docs?: {
/** provides the short description of the rule in the [rules index](https://eslint.org/docs/rules/) */
description?: string | undefined;
/** specifies the heading under which the rule is listed in the [rules index](https://eslint.org/docs/rules/) */
category?: string | undefined;
/** is whether the `"extends": "eslint:recommended"` property in a [configuration file](https://eslint.org/docs/user-guide/configuring#extending-configuration-files) enables the rule */
recommended?: boolean | undefined;
/** specifies the URL at which the full documentation can be accessed */
url?: string | undefined;
/** specifies whether rules can return suggestions (defaults to false if omitted) */
suggestion?: boolean | undefined;
} | undefined;
messages?: { [messageId: string]: string } | undefined;
fixable?: "code" | "whitespace" | undefined;
schema?: JSONSchema4 | JSONSchema4[] | undefined;
deprecated?: boolean | undefined;
type?: "problem" | "suggestion" | "layout" | undefined;
}
interface RuleContext {
id: string;
options: any[];
settings: { [name: string]: any };
parserPath: string;
parserOptions: Linter.ParserOptions;
parserServices: SourceCode.ParserServices;
getAncestors(): ESTree.Node[];
getDeclaredVariables(node: ESTree.Node): Scope.Variable[];
getFilename(): string;
getPhysicalFilename(): string;
getCwd(): string;
getScope(): Scope.Scope;
getSourceCode(): SourceCode;
markVariableAsUsed(name: string): boolean;
report(descriptor: ReportDescriptor): void;
}
type ReportFixer = (fixer: RuleFixer) => null | Fix | IterableIterator<Fix> | Fix[];
interface ReportDescriptorOptionsBase {
data?: { [key: string]: string };
fix?: null | ReportFixer;
}
interface SuggestionReportOptions {
data?: { [key: string]: string };
fix: ReportFixer;
}
type SuggestionDescriptorMessage = { desc: string } | { messageId: string };
type SuggestionReportDescriptor = SuggestionDescriptorMessage & SuggestionReportOptions;
interface ReportDescriptorOptions extends ReportDescriptorOptionsBase {
suggest?: SuggestionReportDescriptor[] | null | undefined;
}
type ReportDescriptor = ReportDescriptorMessage & ReportDescriptorLocation & ReportDescriptorOptions;
type ReportDescriptorMessage = { message: string } | { messageId: string };
type ReportDescriptorLocation =
| { node: ESTree.Node }
| { loc: AST.SourceLocation | { line: number; column: number } };
interface RuleFixer {
insertTextAfter(nodeOrToken: ESTree.Node | AST.Token, text: string): Fix;
insertTextAfterRange(range: AST.Range, text: string): Fix;
insertTextBefore(nodeOrToken: ESTree.Node | AST.Token, text: string): Fix;
insertTextBeforeRange(range: AST.Range, text: string): Fix;
remove(nodeOrToken: ESTree.Node | AST.Token): Fix;
removeRange(range: AST.Range): Fix;
replaceText(nodeOrToken: ESTree.Node | AST.Token, text: string): Fix;
replaceTextRange(range: AST.Range, text: string): Fix;
}
interface Fix {
range: AST.Range;
text: string;
}
}
//#region Linter
export class Linter {
static version: string;
version: string;
constructor(options?: { cwd?: string | undefined });
verify(code: SourceCode | string, config: Linter.Config, filename?: string): Linter.LintMessage[];
verify(code: SourceCode | string, config: Linter.Config, options: Linter.LintOptions): Linter.LintMessage[];
verifyAndFix(code: string, config: Linter.Config, filename?: string): Linter.FixReport;
verifyAndFix(code: string, config: Linter.Config, options: Linter.FixOptions): Linter.FixReport;
getSourceCode(): SourceCode;
defineRule(name: string, rule: Rule.RuleModule): void;
defineRules(rules: { [name: string]: Rule.RuleModule }): void;
getRules(): Map<string, Rule.RuleModule>;
defineParser(name: string, parser: Linter.ParserModule): void;
}
export namespace Linter {
type Severity = 0 | 1 | 2;
type RuleLevel = Severity | "off" | "warn" | "error";
type RuleLevelAndOptions<Options extends any[] = any[]> = Prepend<Partial<Options>, RuleLevel>;
type RuleEntry<Options extends any[] = any[]> = RuleLevel | RuleLevelAndOptions<Options>;
interface RulesRecord {
[rule: string]: RuleEntry;
}
interface HasRules<Rules extends RulesRecord = RulesRecord> {
rules?: Partial<Rules> | undefined;
}
interface BaseConfig<Rules extends RulesRecord = RulesRecord> extends HasRules<Rules> {
$schema?: string | undefined;
env?: { [name: string]: boolean } | undefined;
extends?: string | string[] | undefined;
globals?: { [name: string]: boolean | "readonly" | "readable" | "writable" | "writeable" } | undefined;
noInlineConfig?: boolean | undefined;
overrides?: ConfigOverride[] | undefined;
parser?: string | undefined;
parserOptions?: ParserOptions | undefined;
plugins?: string[] | undefined;
processor?: string | undefined;
reportUnusedDisableDirectives?: boolean | undefined;
settings?: { [name: string]: any } | undefined;
}
interface ConfigOverride<Rules extends RulesRecord = RulesRecord> extends BaseConfig<Rules> {
excludedFiles?: string | string[] | undefined;
files: string | string[];
}
// https://github.com/eslint/eslint/blob/v6.8.0/conf/config-schema.js
interface Config<Rules extends RulesRecord = RulesRecord> extends BaseConfig<Rules> {
ignorePatterns?: string | string[] | undefined;
root?: boolean | undefined;
}
interface ParserOptions {
ecmaVersion?: 3 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 | 2021 | undefined;
sourceType?: "script" | "module" | undefined;
ecmaFeatures?: {
globalReturn?: boolean | undefined;
impliedStrict?: boolean | undefined;
jsx?: boolean | undefined;
experimentalObjectRestSpread?: boolean | undefined;
[key: string]: any;
} | undefined;
[key: string]: any;
}
interface LintOptions {
filename?: string | undefined;
preprocess?: ((code: string) => string[]) | undefined;
postprocess?: ((problemLists: LintMessage[][]) => LintMessage[]) | undefined;
filterCodeBlock?: boolean | undefined;
disableFixes?: boolean | undefined;
allowInlineConfig?: boolean | undefined;
reportUnusedDisableDirectives?: boolean | undefined;
}
interface LintSuggestion {
desc: string;
fix: Rule.Fix;
messageId?: string | undefined;
}
interface LintMessage {
column: number;
line: number;
endColumn?: number | undefined;
endLine?: number | undefined;
ruleId: string | null;
message: string;
messageId?: string | undefined;
nodeType?: string | undefined;
fatal?: true | undefined;
severity: Severity;
fix?: Rule.Fix | undefined;
/** @deprecated Use `linter.getSourceCode()` */
source?: string | null | undefined;
suggestions?: LintSuggestion[] | undefined;
}
interface FixOptions extends LintOptions {
fix?: boolean | undefined;
}
interface FixReport {
fixed: boolean;
output: string;
messages: LintMessage[];
}
type ParserModule =
| {
parse(text: string, options?: any): AST.Program;
}
| {
parseForESLint(text: string, options?: any): ESLintParseResult;
};
interface ESLintParseResult {
ast: AST.Program;
parserServices?: SourceCode.ParserServices | undefined;
scopeManager?: Scope.ScopeManager | undefined;
visitorKeys?: SourceCode.VisitorKeys | undefined;
}
interface ProcessorFile {
text: string;
filename: string;
}
// https://eslint.org/docs/developer-guide/working-with-plugins#processors-in-plugins
interface Processor<T extends string | ProcessorFile = string | ProcessorFile> {
supportsAutofix?: boolean | undefined;
preprocess?(text: string, filename: string): T[];
postprocess?(messages: LintMessage[][], filename: string): LintMessage[];
}
}
//#endregion
//#region ESLint
export class ESLint {
static version: string;
static outputFixes(results: ESLint.LintResult[]): Promise<void>;
static getErrorResults(results: ESLint.LintResult[]): ESLint.LintResult[];
constructor(options?: ESLint.Options);
lintFiles(patterns: string | string[]): Promise<ESLint.LintResult[]>;
lintText(code: string, options?: { filePath?: string | undefined; warnIgnored?: boolean | undefined }): Promise<ESLint.LintResult[]>;
calculateConfigForFile(filePath: string): Promise<any>;
isPathIgnored(filePath: string): Promise<boolean>;
loadFormatter(nameOrPath?: string): Promise<ESLint.Formatter>;
}
export namespace ESLint {
interface Options {
// File enumeration
cwd?: string | undefined;
errorOnUnmatchedPattern?: boolean | undefined;
extensions?: string[] | undefined;
globInputPaths?: boolean | undefined;
ignore?: boolean | undefined;
ignorePath?: string | undefined;
// Linting
allowInlineConfig?: boolean | undefined;
baseConfig?: Linter.Config | undefined;
overrideConfig?: Linter.Config | undefined;
overrideConfigFile?: string | undefined;
plugins?: Record<string, any> | undefined;
reportUnusedDisableDirectives?: Linter.RuleLevel | undefined;
resolvePluginsRelativeTo?: string | undefined;
rulePaths?: string[] | undefined;
useEslintrc?: boolean | undefined;
// Autofix
fix?: boolean | ((message: Linter.LintMessage) => boolean) | undefined;
fixTypes?: Array<Rule.RuleMetaData["type"]> | undefined;
// Cache-related
cache?: boolean | undefined;
cacheLocation?: string | undefined;
cacheStrategy?: "content" | "metadata" | undefined;
}
interface LintResult {
filePath: string;
messages: Linter.LintMessage[];
errorCount: number;
fatalErrorCount: number;
warningCount: number;
fixableErrorCount: number;
fixableWarningCount: number;
output?: string | undefined;
source?: string | undefined;
usedDeprecatedRules: DeprecatedRuleUse[];
}
interface LintResultData {
rulesMeta: {
[ruleId: string]: Rule.RuleMetaData;
};
}
interface DeprecatedRuleUse {
ruleId: string;
replacedBy: string[];
}
interface Formatter {
format(results: LintResult[], data?: LintResultData): string;
}
// Docs reference the type by this name
type EditInfo = Rule.Fix;
}
//#endregion
//#region CLIEngine
/** @deprecated Deprecated in favor of `ESLint` */
export class CLIEngine {
static version: string;
constructor(options: CLIEngine.Options);
executeOnFiles(patterns: string[]): CLIEngine.LintReport;
resolveFileGlobPatterns(patterns: string[]): string[];
getConfigForFile(filePath: string): Linter.Config;
executeOnText(text: string, filename?: string): CLIEngine.LintReport;
addPlugin(name: string, pluginObject: any): void;
isPathIgnored(filePath: string): boolean;
getFormatter(format?: string): CLIEngine.Formatter;
getRules(): Map<string, Rule.RuleModule>;
static getErrorResults(results: CLIEngine.LintResult[]): CLIEngine.LintResult[];
static getFormatter(format?: string): CLIEngine.Formatter;
static outputFixes(report: CLIEngine.LintReport): void;
}
/** @deprecated Deprecated in favor of `ESLint` */
export namespace CLIEngine {
class Options {
allowInlineConfig?: boolean | undefined;
baseConfig?: false | { [name: string]: any } | undefined;
cache?: boolean | undefined;
cacheFile?: string | undefined;
cacheLocation?: string | undefined;
cacheStrategy?: "content" | "metadata" | undefined;
configFile?: string | undefined;
cwd?: string | undefined;
envs?: string[] | undefined;
errorOnUnmatchedPattern?: boolean | undefined;
extensions?: string[] | undefined;
fix?: boolean | undefined;
globals?: string[] | undefined;
ignore?: boolean | undefined;
ignorePath?: string | undefined;
ignorePattern?: string | string[] | undefined;
useEslintrc?: boolean | undefined;
parser?: string | undefined;
parserOptions?: Linter.ParserOptions | undefined;
plugins?: string[] | undefined;
resolvePluginsRelativeTo?: string | undefined;
rules?: {
[name: string]: Linter.RuleLevel | Linter.RuleLevelAndOptions;
} | undefined;
rulePaths?: string[] | undefined;
reportUnusedDisableDirectives?: boolean | undefined;
}
type LintResult = ESLint.LintResult;
type LintResultData = ESLint.LintResultData;
interface LintReport {
results: LintResult[];
errorCount: number;
warningCount: number;
fixableErrorCount: number;
fixableWarningCount: number;
usedDeprecatedRules: DeprecatedRuleUse[];
}
type DeprecatedRuleUse = ESLint.DeprecatedRuleUse;
type Formatter = (results: LintResult[], data?: LintResultData) => string;
}
//#endregion
//#region RuleTester
export class RuleTester {
constructor(config?: any);
run(
name: string,
rule: Rule.RuleModule,
tests: {
valid?: Array<string | RuleTester.ValidTestCase> | undefined;
invalid?: RuleTester.InvalidTestCase[] | undefined;
},
): void;
}
export namespace RuleTester {
interface ValidTestCase {
code: string;
options?: any;
filename?: string | undefined;
parserOptions?: Linter.ParserOptions | undefined;
settings?: { [name: string]: any } | undefined;
parser?: string | undefined;
globals?: { [name: string]: boolean } | undefined;
}
interface SuggestionOutput {
messageId?: string | undefined;
desc?: string | undefined;
data?: Record<string, unknown> | undefined;
output: string;
}
interface InvalidTestCase extends ValidTestCase {
errors: number | Array<TestCaseError | string>;
output?: string | null | undefined;
}
interface TestCaseError {
message?: string | RegExp | undefined;
messageId?: string | undefined;
type?: string | undefined;
data?: any;
line?: number | undefined;
column?: number | undefined;
endLine?: number | undefined;
endColumn?: number | undefined;
suggestions?: SuggestionOutput[] | undefined;
}
}
//#endregion | |
dbloader.go | package appregistry
import (
"context"
"database/sql"
"fmt"
"os"
"github.com/operator-framework/operator-registry/pkg/registry"
"github.com/operator-framework/operator-registry/pkg/sqlite"
"github.com/sirupsen/logrus"
)
func | (dbName string, logger *logrus.Entry) (*dbLoader, error) {
db, err := sql.Open("sqlite3", dbName)
if err != nil {
return nil, err
}
sqlLoader, err := sqlite.NewSQLLiteLoader(db)
if err != nil {
return nil, err
}
if err := sqlLoader.Migrate(context.TODO()); err != nil {
return nil, err
}
return &dbLoader{
loader: sqlLoader,
logger: logger,
db: db,
}, nil
}
type dbLoader struct {
db *sql.DB
loader registry.Load
logger *logrus.Entry
}
func (l *dbLoader) GetStore() registry.Query {
return sqlite.NewSQLLiteQuerierFromDb(l.db)
}
// LoadDataToSQLite uses configMaploader to load the downloaded operator
// manifest(s) into a sqllite database.
func (l *dbLoader) LoadFlattenedToSQLite(manifest *RawOperatorManifestData) error {
l.logger.Infof("using configmap loader to build sqlite database")
data := map[string]string{
"customResourceDefinitions": manifest.CustomResourceDefinitions,
"clusterServiceVersions": manifest.ClusterServiceVersions,
"packages": manifest.Packages,
}
configMapPopulator := sqlite.NewSQLLoaderForConfigMapData(l.logger, l.loader, data)
if err := configMapPopulator.Populate(); err != nil {
return err
}
s := sqlite.NewSQLLiteQuerierFromDb(l.db)
// sanity check that the db is available.
tables, err := s.ListTables(context.TODO())
if err != nil {
return fmt.Errorf("couldn't list tables in db, incorrect config: %v", err)
}
if len(tables) == 0 {
return fmt.Errorf("no tables found in db")
}
return nil
}
func (l *dbLoader) LoadBundleDirectoryToSQLite(directory string) error {
if _, err := os.Stat(directory); err != nil {
l.logger.Errorf("stat failed on target directory[%s] - %v", directory, err)
return err
}
loader := sqlite.NewSQLLoaderForDirectory(l.loader, directory)
if err := loader.Populate(); err != nil {
return err
}
return nil
}
func (l *dbLoader) Close() error {
if l.db != nil {
return l.db.Close()
}
return nil
}
| NewDbLoader |
tasks_hfclkstart.rs | #[doc = "Register `TASKS_HFCLKSTART` writer"]
pub struct W(crate::W<TASKS_HFCLKSTART_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<TASKS_HFCLKSTART_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<TASKS_HFCLKSTART_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<TASKS_HFCLKSTART_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Start HFCLK crystal oscillator\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TASKS_HFCLKSTART_AW {
#[doc = "1: Trigger task"]
TRIGGER = 1,
}
impl From<TASKS_HFCLKSTART_AW> for bool {
#[inline(always)]
fn from(variant: TASKS_HFCLKSTART_AW) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `TASKS_HFCLKSTART` writer - Start HFCLK crystal oscillator"]
pub struct TASKS_HFCLKSTART_W<'a> {
w: &'a mut W,
}
impl<'a> TASKS_HFCLKSTART_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TASKS_HFCLKSTART_AW) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Trigger task"]
#[inline(always)]
pub fn trigger(self) -> &'a mut W {
self.variant(TASKS_HFCLKSTART_AW::TRIGGER)
}
#[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) | (value as u32 & 0x01);
self.w
}
}
impl W { | }
#[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 = "Start HFCLK crystal oscillator\n\nThis register you can [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [tasks_hfclkstart](index.html) module"]
pub struct TASKS_HFCLKSTART_SPEC;
impl crate::RegisterSpec for TASKS_HFCLKSTART_SPEC {
type Ux = u32;
}
#[doc = "`write(|w| ..)` method takes [tasks_hfclkstart::W](W) writer structure"]
impl crate::Writable for TASKS_HFCLKSTART_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets TASKS_HFCLKSTART to value 0"]
impl crate::Resettable for TASKS_HFCLKSTART_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
} | #[doc = "Bit 0 - Start HFCLK crystal oscillator"]
#[inline(always)]
pub fn tasks_hfclkstart(&mut self) -> TASKS_HFCLKSTART_W {
TASKS_HFCLKSTART_W { w: self } |
packet.go | package quic
import (
"encoding/binary"
"log"
)
// Public Flags
const (
// QuicVersion - LSB 0x1 has value 1 iff the packet contains a Quic Version. This bit must be set by a client in all packets until confirmation from a server arrives agreeing to the proposed version is received by the client. A server indicates agreement on a version by sending packets without setting this bit.
QuicVersion = 0x1
// PublicReset - Bit at location, 0x2, is set to indicate that the packet is a Public Reset packet.
PublicReset = 0x2
// DataPacket is the bitmask for a data packet. If version and public reset aren't set.
DataPacket = 0x3
// ConnIDBitMask - Pair of bits, included in 0xC, together indicate the size of the connection ID that is present in the packet, but should be set to set to 0xC in all packets until agreeably negotiated to a different value, for a given direction (e.g., client may request fewer bytes of the connection id be presented). Within this 2 bit mask:
ConnIDBitMask = 0xC
ConnID8Bytes = 0xC
ConnID4Bytes = 0x8
ConnID1Byte = 0x4
ConnIDOmmited = 0x0
// SequenceNumberBitMask - Pair of bits included in 0x30 indicate the number of low-order-bytes of the packet sequence number that are present in each packet. Within this 2 bit mask:
SequenceNumberBitMask = 0x30
SequenceNumber6Bytes = 0x30
SequenceNumber4Bytes = 0x20
SequenceNumber2Bytes = 0x10
SequenceNumber1Byte = 0x00
)
// Private Flags
const (
// FlagEntropy - for data packets, signifies that this packet contains the 1 bit of entropy, for fec packets, contains the xor of the entropy of protected packets.
FlagEntropy = 0x01
// FlagFECGroup - indicates whether the fec byte is present.
FlagFECGroup = 0x02
// FlagFEC - signifies that this packet represents an FEC packet.
FlagFEC = 0x04
)
// Packet represents a packet
type Packet struct {
PublicFlags byte
ConnID, QuicVersion, SequenceNumber uint64
PrivateFlags byte
FECGroupNumber uint64
Type byte
Frames []Frame
}
// ParsePacket parses a byte array and returns the corresponding packet
func ParsePacket(buf []byte) (*Packet, error) | {
p := Packet{}
i := 0
p.PublicFlags = buf[i]
i++
// Connection ID
connIDLen := 0
switch p.PublicFlags & ConnIDBitMask {
case ConnID8Bytes:
connIDLen = 8
case ConnID4Bytes:
connIDLen = 4
case ConnID1Byte:
connIDLen = 1
}
n := 0
p.ConnID, n = binary.Uvarint(buf[i : i+connIDLen])
if n <= 0 {
log.Println("n", n)
}
i += connIDLen
// Quic Version
if p.PublicFlags&QuicVersion == QuicVersion {
p.QuicVersion, n = binary.Uvarint(buf[i : i+4])
if n <= 0 {
log.Println("n", n)
}
i += 4
}
p.Type = p.PublicFlags & DataPacket
// Sequence Number
sequenceNumberLen := 1
switch p.PublicFlags & ConnIDBitMask {
case SequenceNumber6Bytes:
sequenceNumberLen = 6
case SequenceNumber4Bytes:
sequenceNumberLen = 4
case SequenceNumber2Bytes:
sequenceNumberLen = 2
}
p.SequenceNumber, n = binary.Uvarint(buf[i : i+sequenceNumberLen])
if n <= 0 {
log.Println("n", n)
}
i += sequenceNumberLen
p.PrivateFlags = buf[i]
i++
if p.PrivateFlags&FlagFECGroup > 0 {
offset := uint64(buf[i])
p.FECGroupNumber = p.SequenceNumber - offset
i++
}
// DataPacket
if p.Type == 0x0 {
log.Println("DATA PACKET")
} else if p.PrivateFlags&FlagFEC > 0 {
log.Println("TODO: FEC PACKETS")
return &p, nil
} else {
//log.Println("unknown packet type", p.Type)
}
// Frames
for i < len(buf) {
typeField := buf[i]
i++
if typeField&StreamFrame > 0 {
log.Println("StreamFrame")
frame := FrameStream{}
// Stream ID
streamIDLen := int(typeField&StreamIDMask) + 1
frame.StreamID, n = binary.Uvarint(buf[i : i+streamIDLen])
i += streamIDLen
if n <= 0 {
log.Println("n", n)
}
// Offset
offsetLen := int(typeField & OffsetMask >> 2)
if offsetLen > 0 {
offsetLen++
frame.Offset, n = binary.Uvarint(buf[i : i+offsetLen])
i += offsetLen
if n <= 0 {
log.Println("n", n)
}
}
// DataLen
dataLenPresent := typeField&DataLenMask > 0
if dataLenPresent {
frame.DataLen, n = binary.Uvarint(buf[i : i+2])
i += 2
}
// Fin
frame.Fin = typeField&FinMask > 0
if dataLenPresent {
frame.Data = string(buf[i : i+int(frame.DataLen)])
i += int(frame.DataLen)
} else if !frame.Fin {
frame.Data = string(buf[i:])
i += len(buf[i:])
}
p.Frames = append(p.Frames, frame)
continue
} else if typeField&AckFrameMask == AckFrame {
log.Println("AckFrame")
frame := FrameAck{}
p.Frames = append(p.Frames, frame)
} else if typeField&CongestionFeedbackFrameMask == CongestionFeedbackFrame {
/*log.Println("CongestionFeedbackFrame")
frame := FrameCongestionFeedback{}
// Not currently used according to docs but sent anyways. :|
p.Frames = append(p.Frames, frame)*/
continue
} else {
switch typeField {
case PaddingFrame:
log.Println("PaddingFrame")
p.Frames = append(p.Frames, &FramePadding{})
// reset of packet is padding, nothing needs to happen
break
case ResetStreamFrame:
log.Println("ResetStreamFrame")
frame := FrameResetStream{}
frame.StreamID, n = binary.Uvarint(buf[i : i+4])
i += 4
if n <= 0 {
log.Println("n", n)
}
frame.ErrorCode, n = binary.Uvarint(buf[i : i+4])
i += 4
if n <= 0 {
log.Println("n", n)
}
p.Frames = append(p.Frames, frame)
continue
case ConnectionCloseFrame:
log.Println("ConnectionCloseFrame")
frame := FrameConnectionClose{}
frame.ErrorCode, n = binary.Uvarint(buf[i : i+4])
i += 4
if n <= 0 {
log.Println("n", n)
}
length, n2 := binary.Uvarint(buf[i : i+2])
i += 2
if n2 <= 0 {
log.Println("n", n)
}
frame.Reason = string(buf[i : i+int(length)])
i += int(length)
p.Frames = append(p.Frames, frame)
continue
case GoAwayFrame:
log.Println("GoAwayFrame")
frame := FrameGoAway{}
frame.ErrorCode, n = binary.Uvarint(buf[i : i+4])
i += 4
if n <= 0 {
log.Println("n", n)
}
frame.LastGoodStreamID, n = binary.Uvarint(buf[i : i+4])
i += 4
if n <= 0 {
log.Println("n", n)
}
length, n2 := binary.Uvarint(buf[i : i+2])
i += 2
if n2 <= 0 {
log.Println("n", n)
}
frame.Reason = string(buf[i : i+int(length)])
i += int(length)
p.Frames = append(p.Frames, frame)
continue
case WindowUpdateFrame:
log.Println("WindowUpdateFrame")
frame := FrameWindowUpdate{}
frame.StreamID, n = binary.Uvarint(buf[i : i+4])
i += 4
if n <= 0 {
log.Println("n", n)
}
frame.ByteOffset, n = binary.Uvarint(buf[i : i+8])
i += 8
if n <= 0 {
log.Println("n", n)
}
p.Frames = append(p.Frames, frame)
continue
case BlockedFrame:
log.Println("BlockedFrame")
frame := FrameBlocked{}
frame.StreamID, n = binary.Uvarint(buf[i : i+4])
i += 4
if n <= 0 {
log.Println("n", n)
}
p.Frames = append(p.Frames, frame)
continue
case StopWaitingFrame:
log.Println("StopWaitingFrame")
frame := FrameStopWaiting{}
frame.SentEntropy = buf[i]
i++
frame.LeastUnackedDelta, n = binary.Uvarint(buf[i : i+sequenceNumberLen])
i += sequenceNumberLen
if n <= 0 {
log.Println("n", n)
}
p.Frames = append(p.Frames, frame)
continue
case PingFrame:
log.Println("PingFrame")
p.Frames = append(p.Frames, &FramePing{})
continue
default:
log.Println("UnknownFrame", typeField)
}
}
log.Println("UNHANDLED FRAME BREAKING!", typeField)
break
}
//log.Println("Remainder", string(buf[i:]))
return &p, nil
} |
|
logger.ts | /* tslint:disable:no-console */
const logPrefix = "[WKVEC] ";
export class | {
private prefix: string;
private disableLogging: boolean;
constructor() {
this.prefix = logPrefix;
this.disableLogging = false; // Set to false for development
}
public debug(msg: string, ...args: any[]) {
if (this.disableLogging) {
return;
}
console.debug(this.prefix + msg, ...args);
}
public info(msg: string, ...args: any[]) {
if (this.disableLogging) {
return;
}
console.log(this.prefix + msg, ...args);
}
public warn(msg: string, ...args: any[]) {
if (this.disableLogging) {
return;
}
console.warn(this.prefix + msg, ...args);
}
public error(msg: string, ...args: any[]) {
if (this.disableLogging) {
return;
}
console.error(this.prefix + msg, ...args);
}
}
| Logger |
cmdline.go | package appkit
import (
"flag"
"fmt"
"io"
"os"
"regexp"
"strings"
"text/tabwriter"
)
var cmdParseRegex = regexp.MustCompile(`[A-Za-z0-9][-A-Za-z0-9]*`)
type Command struct {
Cmd []string
// Help that describes command
Help string
// The sub-command portion of the Usage line in the help
SubCommandHelp string
// The argument portion of the Usage line in the help
ArgumentHelp string
Flags *flag.FlagSet
subCommands []*Command
parent *Command
}
// HasFlags returns true if a flag.FlagSet has any flags.
func HasFlags(fs *flag.FlagSet) bool {
ret := false
fs.VisitAll(func(f *flag.Flag) {
ret = true
})
return ret
}
// SplitCommand splits a command string to a command and its synonyms. See
// NewCommand for more information.
func SplitCommand(cmdstr string) []string {
return strings.Fields(cmdstr)
}
// SplitArguments splits the arguments from the option "cmdline-args". See
// Parse for details.
func SplitArguments(argstr string) []string {
if argstr == "" {
return []string{}
}
return strings.Split(argstr[0:len(argstr)-1], "\000")
}
// JoinArguments is the counter operation for SplitArguments. See that for
// more details.
func JoinArguments(args []string) string {
if len(args) == 0 {
return ""
}
return strings.Join(args, "\000") + "\000"
}
// NewCommand creates a recursive command line argument with flags.
//
// Parent of the top-level command should be nil. The cmd string can contain
// multiple space-separated commands that are regarded as synonyms of the
// command. The help string is displayed if help option is given.
//
// If parent == nil, then the Usage function prints out all sub-commands with
// helps. This can be overridden by re-defining the Flags.Usage function.
//
// Example:
//
// opts := appkit.NewOptions()
// base := appkit.NewCommand(nil, "", "")
// optVersion := base.Flags.Bool("version", false, "Display version")
// add := appkit.NewCommand(base, "add a", "Adding stuff")
// _ = appkit.NewCommand(add, "package p", "Add package")
// _ = appkit.NewCommand(add, "dependency d", "Add dependency")
// del := appkit.NewCommand(base, "delete del d", "Deleting stuff")
// _ = appkit.NewCommand(del, "package p", "Delete package")
// _ = appkit.NewCommand(del, "dependency d", "Delete dependency")
// optRecurse := del.Flags.Bool("recurse", false, "Delete recursively")
//
// err = base.Parse(os.Args[1:], opts)
// if err == flag.ErrHelp {
// os.Exit(0)
// }
//
// if *optVersion {
// fmt.Println(appkit.VersionString(opts))
// os.Exit(0)
// }
// cmd := opts.Get("cmdline-command", "")
// switch cmd {
// case "add package":
// ...
// case "delete package":
// ...
// }
func | (parent *Command, cmd string, help string) *Command {
cmds := []string{""}
if len(cmd) > 0 {
cmds = SplitCommand(cmd)
for i := range cmds {
if !cmdParseRegex.MatchString(cmds[i]) {
s := fmt.Sprintf("Error: Could not parse command: %s", cmds[i])
panic(s)
}
}
}
flags := flag.NewFlagSet(cmds[0], flag.ContinueOnError)
ret := &Command{
Cmd: cmds,
Help: help,
SubCommandHelp: "",
// By default, the arguments for a command are accumulated
ArgumentHelp: "[ARG ...]",
Flags: flags,
parent: parent,
}
flags.Usage = func() {
out := flags.Output()
optstring := " [OPTIONS]"
if !HasFlags(flags) {
// The -h and -help come from the flag-package.
optstring = " [-h|-help]"
}
cmdstring := ret.SubCommandHelp
if ret.HasSubcommands() {
// Add sub-command help if it has NOT been overridden
if cmdstring == "" {
cmdstring = "[COMMAND]"
}
cmdstring = " " + cmdstring
}
if ret.IsTopLevel() {
fmt.Fprintf(out, "Usage: %s%s%s %s\n\n%s\n", os.Args[0],
optstring, cmdstring, ret.ArgumentHelp,
ret.Help)
if ret.HasSubcommands() {
fmt.Fprintf(out, "\nCommands:\n")
ret.CommandList(out)
}
} else {
fmt.Fprintf(out, "Usage: %s %s%s%s %s\n\n%s\n",
os.Args[0], ret.FullCommandName(),
optstring, cmdstring, ret.ArgumentHelp,
ret.Help)
if ret.HasSubcommands() {
fmt.Fprintf(out, "\nSub-commands:\n")
ret.CommandList(out)
}
}
if HasFlags(flags) {
fmt.Fprintf(out, "\nOptions:\n")
flags.PrintDefaults()
}
}
if !ret.IsTopLevel() {
parent.subCommands = append(parent.subCommands, ret)
}
return ret
}
// Parse the command line arguments according to the recursive command
// structure.
//
// The actual command will be set to the option "cmdline-command" inside the
// opts structure. Additional positional arguments after the command are in
// the "cmdline-args" option.
//
// Recursive commands in "cmdline-command" are space separated. If there are
// multiple synonyms defined for a command, the first one is listed.
//
// The positional arguments in "cmdline-args" are NUL separated inside the
// string. They can be split to an array using SplitArguments.
func (c *Command) Parse(args []string, opts Options) error {
var err error
if c.Flags != nil {
err = c.Flags.Parse(args)
if err != nil {
return err
}
}
args = c.Flags.Args()
cmd := ""
if c.Cmd[0] != "" {
cmd = opts.Get("cmdline-command", "") + " " + c.Cmd[0]
cmd = strings.TrimLeft(cmd, " ")
}
opts.Set("cmdline-command", cmd)
opts.Set("cmdline-args", JoinArguments(args))
if len(args) == 0 {
return nil
}
for _, sc := range c.subCommands {
for i := range sc.Cmd {
if sc.Cmd[i] == args[0] {
err = sc.Parse(args[1:], opts)
if err != nil {
return err
}
}
}
}
return nil
}
// CommandList prints out a recursive tree of sub-commands to the given
// io.Writer.
func (c *Command) CommandList(out io.Writer) {
wr := tabwriter.NewWriter(out, 0, 4, 2, ' ', 0)
var printall func(pfx string, c *Command)
printall = func(pfx string, c *Command) {
fmt.Fprintf(wr, "%s%s\t-\t%s\n", pfx, strings.Join(c.Cmd, ", "), c.Help)
for _, sc := range c.subCommands {
printall(pfx+" ", sc)
}
}
for _, sc := range c.subCommands {
printall(" ", sc)
}
wr.Flush()
}
// HasSubcommands returns true if a command has any sub-commands defined.
func (c *Command) HasSubcommands() bool {
return c.subCommands != nil && len(c.subCommands) > 0
}
// IsTopLevel returns true if the command has no parents
func (c *Command) IsTopLevel() bool {
return c.parent == nil
}
// FullCommandName returns the full (sub-)command as a string
func (c *Command) FullCommandName() string {
var buildCommandPath func(c *Command) string
buildCommandPath = func(c *Command) string {
if c == nil {
return ""
}
return buildCommandPath(c.parent) + " " + c.Cmd[0]
}
return strings.TrimLeft(buildCommandPath(c), " ")
}
| NewCommand |
lib.rs | //! A forest of B+-trees.
//!
//! This crate provides a data structures representing a set of small ordered sets or maps.
//! It is implemented as a forest of B+-trees all allocating nodes out of the same pool.
//!
//! **These are not general purpose data structures that are somehow magically faster that the
//! standard library's `BTreeSet` and `BTreeMap` types.**
//!
//! The tradeoffs are different:
//!
//! - Keys and values are expected to be small and copyable. We optimize for 32-bit types.
//! - A comparator object is used to compare keys, allowing smaller "context free" keys.
//! - Empty trees have a very small 32-bit footprint.
//! - All the trees in a forest can be cleared in constant time.
#![deny(missing_docs, trivial_numeric_casts, unused_extern_crates)]
#![warn(unused_import_braces)]
#![cfg_attr(feature = "std", warn(unstable_features))]
#![cfg_attr(
feature = "clippy",
plugin(clippy(conf_file = "../../clippy.toml"))
)]
#![cfg_attr(
feature = "cargo-clippy",
allow(new_without_default, new_without_default_derive)
)]
#![cfg_attr(
feature = "cargo-clippy",
warn(
float_arithmetic,
mut_mut,
nonminimal_bool,
option_map_unwrap_or,
option_map_unwrap_or_else,
print_stdout,
unicode_not_nfc,
use_self
)
)]
// Turns on no_std and alloc features if std is not available.
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(not(feature = "std"), feature(alloc))]
/// This replaces `std` in builds with `core`.
#[cfg(not(feature = "std"))]
mod std {
extern crate alloc;
pub use self::alloc::{boxed, string, vec};
pub use core::*;
}
#[macro_use]
extern crate cranelift_entity as entity;
use entity::packed_option;
use std::borrow::BorrowMut;
use std::cmp::Ordering;
mod map;
mod node;
mod path;
mod pool;
mod set;
pub use self::map::{Map, MapCursor, MapForest, MapIter};
pub use self::set::{Set, SetCursor, SetForest, SetIter};
use self::node::NodeData;
use self::path::Path;
use self::pool::NodePool;
/// The maximum branching factor of an inner node in a B+-tree.
/// The minimum number of outgoing edges is `INNER_SIZE/2`.
const INNER_SIZE: usize = 8;
/// Given the worst case branching factor of `INNER_SIZE/2` = 4, this is the
/// worst case path length from the root node to a leaf node in a tree with 2^32
/// entries. We would run out of node references before we hit `MAX_PATH`.
const MAX_PATH: usize = 16;
/// Key comparator.
///
/// Keys don't need to implement `Ord`. They are compared using a comparator object which
/// provides a context for comparison.
pub trait Comparator<K>
where
K: Copy,
{
/// Compare keys `a` and `b`.
///
/// This relation must provide a total ordering or the key space.
fn cmp(&self, a: K, b: K) -> Ordering;
/// Binary search for `k` in an ordered slice.
///
/// Assume that `s` is already sorted according to this ordering, search for the key `k`.
///
/// Returns `Ok(idx)` if `k` was found in the slice or `Err(idx)` with the position where it
/// should be inserted to preserve the ordering.
fn search(&self, k: K, s: &[K]) -> Result<usize, usize> {
s.binary_search_by(|x| self.cmp(*x, k))
}
}
/// Trivial comparator that doesn't actually provide any context.
impl<K> Comparator<K> for ()
where
K: Copy + Ord,
{
fn cmp(&self, a: K, b: K) -> Ordering {
a.cmp(&b)
}
}
/// Family of types shared by the map and set forest implementations.
trait Forest {
/// The key type is present for both sets and maps.
type Key: Copy;
/// The value type is `()` for sets.
type Value: Copy;
/// An array of keys for the leaf nodes.
type LeafKeys: Copy + BorrowMut<[Self::Key]>;
/// An array of values for the leaf nodes.
type LeafValues: Copy + BorrowMut<[Self::Value]>;
/// Splat a single key into a whole array.
fn splat_key(key: Self::Key) -> Self::LeafKeys;
/// Splat a single value inst a whole array
fn splat_value(value: Self::Value) -> Self::LeafValues;
}
/// A reference to a B+-tree node.
#[derive(Clone, Copy, PartialEq, Eq)]
struct Node(u32);
entity_impl!(Node, "node");
/// Empty type to be used as the "value" in B-trees representing sets.
#[derive(Clone, Copy)]
struct SetValue();
/// Insert `x` into `s` at position `i`, pushing out the last element.
fn slice_insert<T: Copy>(s: &mut [T], i: usize, x: T) {
for j in (i + 1..s.len()).rev() {
s[j] = s[j - 1];
}
s[i] = x;
}
/// Shift elements in `s` to the left by `n` positions.
fn slice_shift<T: Copy>(s: &mut [T], n: usize) {
for j in 0..s.len() - n {
s[j] = s[j + n];
}
}
#[cfg(test)]
mod test {
use super::*;
use entity::EntityRef;
/// An opaque reference to an extended basic block in a function.
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Ebb(u32);
entity_impl!(Ebb, "ebb");
#[test]
fn comparator() {
let ebb1 = Ebb::new(1);
let ebb2 = Ebb::new(2);
let ebb3 = Ebb::new(3);
let ebb4 = Ebb::new(4);
let vals = [ebb1, ebb2, ebb4];
let comp = ();
assert_eq!(comp.search(ebb1, &vals), Ok(0));
assert_eq!(comp.search(ebb3, &vals), Err(2));
assert_eq!(comp.search(ebb4, &vals), Ok(2));
}
#[test]
fn slice_insertion() |
#[test]
fn slice_shifting() {
let mut a = ['a', 'b', 'c', 'd'];
slice_shift(&mut a[0..1], 1);
assert_eq!(a, ['a', 'b', 'c', 'd']);
slice_shift(&mut a[1..], 1);
assert_eq!(a, ['a', 'c', 'd', 'd']);
slice_shift(&mut a, 2);
assert_eq!(a, ['d', 'd', 'd', 'd']);
}
}
| {
let mut a = ['a', 'b', 'c', 'd'];
slice_insert(&mut a[0..1], 0, 'e');
assert_eq!(a, ['e', 'b', 'c', 'd']);
slice_insert(&mut a, 0, 'a');
assert_eq!(a, ['a', 'e', 'b', 'c']);
slice_insert(&mut a, 3, 'g');
assert_eq!(a, ['a', 'e', 'b', 'g']);
slice_insert(&mut a, 1, 'h');
assert_eq!(a, ['a', 'h', 'e', 'b']);
} |
ProjectListCtrl.js | angular.module('KanboardCtrl')
.controller('ProjectListController', function($scope, navigation, dataFactory) {
$scope.$navigation = navigation;
var projectList = this; | for (var i = 0; i < $scope.endpoints.length; i++) {
$scope.endpoints[i].id = i;
var id = i + 1;
var result;
dataFactory.getProjects(id).then(
function(request) {
result = request.data.result;
$scope.endpoints[id-1].projects = result;
},
function(error) {
console.log(error);
});
}
}); |
$scope.endpoints = dataFactory.getEndpoints();
|
vgg16.py | """
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import argparse
import os
from datetime import datetime
import numpy
import oneflow as flow
import oneflow.core.operator.op_conf_pb2 as op_conf_util
_DATA_DIR = "/dataset/PNGS/PNG224/of_record_repeated"
_SINGLE_DATA_DIR = "/dataset/PNGS/PNG224/of_record"
_MODEL_LOAD_DIR = "/dataset/PNGS/cnns_model_for_test/vgg16/models/of_model"
_MODEL_SAVE_DIR = "./model_save-{}".format(
str(datetime.now().strftime("%Y-%m-%d-%H:%M:%S"))
)
NODE_LIST = "192.168.1.12,192.168.1.14"
class DLNetSpec(object):
def __init__(self, enable_auto_mixed_precision):
self.batch_size = 8
self.data_part_num = 32
self.eval_dir = _DATA_DIR
self.train_dir = _DATA_DIR
self.model_save_dir = _MODEL_SAVE_DIR
self.model_load_dir = _MODEL_LOAD_DIR
self.num_nodes = 1
self.gpu_num_per_node = 1
self.iter_num = 10
self.enable_auto_mixed_precision = enable_auto_mixed_precision
parser = argparse.ArgumentParser(description="flags for multi-node and resource")
parser.add_argument("-g", "--gpu_num_per_node", type=int, default=1, required=False)
parser.add_argument("-i", "--iter_num", type=int, default=10, required=False)
parser.add_argument(
"-m", "--multinode", default=False, action="store_true", required=False
)
parser.add_argument("-n", "--node_list", type=str, default=NODE_LIST, required=False)
parser.add_argument(
"-s", "--skip_scp_binary", default=False, action="store_true", required=False
)
parser.add_argument(
"-c",
"--scp_binary_without_uuid",
default=False,
action="store_true",
required=False,
)
parser.add_argument(
"-r", "--remote_by_hand", default=False, action="store_true", required=False
)
parser.add_argument("-e", "--eval_dir", type=str, default=_DATA_DIR, required=False)
parser.add_argument("-t", "--train_dir", type=str, default=_DATA_DIR, required=False)
parser.add_argument(
"-load", "--model_load_dir", type=str, default=_MODEL_LOAD_DIR, required=False
)
parser.add_argument(
"-save", "--model_save_dir", type=str, default=_MODEL_SAVE_DIR, required=False
)
parser.add_argument("-dn", "--data_part_num", type=int, default=32, required=False)
parser.add_argument("-b", "--batch_size", type=int, default=8, required=False)
def _conv2d_layer(
name,
input,
filters,
kernel_size=3,
strides=1,
padding="VALID",
data_format="NCHW",
dilation_rate=1,
activation=op_conf_util.kRelu,
use_bias=True,
weight_initializer=flow.random_uniform_initializer(),
bias_initializer=flow.constant_initializer(),
):
weight_shape = (filters, input.shape[1], kernel_size, kernel_size)
weight = flow.get_variable(
name + "-weight",
shape=weight_shape,
dtype=input.dtype,
initializer=weight_initializer,
)
output = flow.nn.conv2d(
input, weight, strides, padding, data_format, dilation_rate, name=name
)
if use_bias:
bias = flow.get_variable(
name + "-bias",
shape=(filters,),
dtype=input.dtype,
initializer=bias_initializer,
)
output = flow.nn.bias_add(output, bias, "NCHW")
if activation is not None:
if activation == op_conf_util.kRelu:
output = flow.math.relu(output)
else:
raise NotImplementedError
return output
def _data_load_layer(args, data_dir):
node_num = args.num_nodes
total_batch_size = args.batch_size * args.gpu_num_per_node * node_num
rgb_mean = [123.68, 116.78, 103.94]
ofrecord = flow.data.ofrecord_reader(
data_dir,
batch_size=total_batch_size,
data_part_num=args.data_part_num,
name="decode",
)
image = flow.data.ofrecord_image_decoder(ofrecord, "encoded", color_space="RGB")
label = flow.data.ofrecord_raw_decoder(
ofrecord, "class/label", shape=(), dtype=flow.int32
)
rsz = flow.image.resize(image, resize_x=224, resize_y=224, color_space="RGB")
normal = flow.image.crop_mirror_normalize(
rsz,
color_space="RGB",
output_layout="NCHW",
mean=rgb_mean,
output_dtype=flow.float,
)
return label, normal
def _conv_block(in_blob, index, filters, conv_times):
conv_block = []
conv_block.insert(0, in_blob)
for i in range(conv_times):
conv_i = _conv2d_layer(
name="conv{}".format(index),
input=conv_block[i],
filters=filters,
kernel_size=3,
strides=1,
)
conv_block.append(conv_i)
index += 1
return conv_block
def vgg(images, labels, trainable=True):
to_return = []
conv1 = _conv_block(images, 0, 64, 2)
pool1 = flow.nn.max_pool2d(conv1[-1], 2, 2, "VALID", "NCHW", name="pool1")
conv2 = _conv_block(pool1, 2, 128, 2)
pool2 = flow.nn.max_pool2d(conv2[-1], 2, 2, "VALID", "NCHW", name="pool2")
conv3 = _conv_block(pool2, 4, 256, 3)
pool3 = flow.nn.max_pool2d(conv3[-1], 2, 2, "VALID", "NCHW", name="pool3")
conv4 = _conv_block(pool3, 7, 512, 3)
pool4 = flow.nn.max_pool2d(conv4[-1], 2, 2, "VALID", "NCHW", name="pool4")
conv5 = _conv_block(pool4, 10, 512, 3)
pool5 = flow.nn.max_pool2d(conv5[-1], 2, 2, "VALID", "NCHW", name="pool5")
def _get_kernel_initializer():
kernel_initializer = op_conf_util.InitializerConf()
kernel_initializer.truncated_normal_conf.std = 0.816496580927726
return kernel_initializer
def _get_bias_initializer():
bias_initializer = op_conf_util.InitializerConf()
bias_initializer.constant_conf.value = 0.0
return bias_initializer
pool5 = flow.reshape(pool5, [-1, 512])
fc6 = flow.layers.dense(
inputs=pool5,
units=4096,
activation=flow.math.relu,
use_bias=True,
kernel_initializer=_get_kernel_initializer(),
bias_initializer=_get_bias_initializer(),
trainable=trainable,
name="fc1",
)
fc7 = flow.layers.dense(
inputs=fc6,
units=4096,
activation=flow.math.relu,
use_bias=True,
kernel_initializer=_get_kernel_initializer(),
bias_initializer=_get_bias_initializer(),
trainable=trainable,
name="fc2",
)
fc8 = flow.layers.dense(
inputs=fc7,
units=1001,
use_bias=True,
kernel_initializer=_get_kernel_initializer(),
bias_initializer=_get_bias_initializer(),
trainable=trainable,
name="fc_final",
)
loss = flow.nn.sparse_softmax_cross_entropy_with_logits(
labels, fc8, name="softmax_loss"
)
to_return.append(loss)
return tuple(to_return)
def main(args):
flow.config.machine_num(args.num_nodes)
flow.config.gpu_device_num(args.gpu_num_per_node)
train_config = flow.FunctionConfig()
train_config.default_distribute_strategy(flow.scope.consistent_view())
train_config.default_data_type(flow.float)
train_config.train.primary_lr(0.00001)
train_config.train.model_update_conf(dict(naive_conf={}))
train_config.enable_auto_mixed_precision(args.enable_auto_mixed_precision)
@flow.global_function(train_config)
def vgg_train_job():
(labels, images) = _data_load_layer(args, args.train_dir)
to_return = vgg(images, labels)
loss = to_return[-1]
flow.losses.add_loss(loss)
return loss
eval_config = flow.FunctionConfig()
eval_config.default_distribute_strategy(flow.scope.consistent_view())
eval_config.default_data_type(flow.float)
eval_config.enable_auto_mixed_precision(args.enable_auto_mixed_precision)
@flow.global_function(eval_config)
def vgg_eval_job():
(labels, images) = _data_load_layer(args, args.eval_dir) | check_point.init()
else:
check_point.load(args.model_load_dir)
num_nodes = args.num_nodes
print(
"Traning vgg16: num_gpu_per_node = {}, num_nodes = {}.".format(
args.gpu_num_per_node, num_nodes
)
)
print("{:>12} {:>12} {:>12}".format("iter", "loss type", "loss value"))
loss = []
for i in range(args.iter_num):
train_loss = vgg_train_job().get().mean()
loss.append(train_loss)
fmt_str = "{:>12} {:>12} {:>12.6f}"
print(fmt_str.format(i, "train loss:", train_loss))
# if (i + 1) % 10 == 0:
# eval_loss = alexnet_eval_job().get().mean()
# print(
# fmt_str.format(
# i, "eval loss:", eval_loss
# )
# )
if (i + 1) % 100 == 0:
check_point.save(_MODEL_SAVE_DIR + str(i))
# save loss to file
loss_file = "{}n{}c.npy".format(
str(num_nodes), str(args.gpu_num_per_node * num_nodes)
)
loss_path = "./of_loss/vgg16"
if not os.path.exists(loss_path):
os.makedirs(loss_path)
numpy.save(os.path.join(loss_path, loss_file), loss)
if __name__ == "__main__":
args = parser.parse_args()
flow.env.grpc_use_no_signal()
flow.env.log_dir("./log")
if args.multinode:
flow.env.ctrl_port(12138)
nodes = []
for n in args.node_list.strip().split(","):
addr_dict = {}
addr_dict["addr"] = n
nodes.append(addr_dict)
flow.env.machine(nodes)
if args.remote_by_hand is False:
if args.scp_binary_without_uuid:
flow.deprecated.init_worker(scp_binary=True, use_uuid=False)
elif args.skip_scp_binary:
flow.deprecated.init_worker(scp_binary=False, use_uuid=False)
else:
flow.deprecated.init_worker(scp_binary=True, use_uuid=True)
main(args)
if (
args.multinode
and args.skip_scp_binary is False
and args.scp_binary_without_uuid is False
):
flow.deprecated.delete_worker() | return vgg(images, labels, False)
check_point = flow.train.CheckPoint()
if not args.model_load_dir: |
25-1-object-create.js | /**
* Tạo một đối tượng student gồm các property name, sex, age
* Example:
name: "CodersX",
sex: "Male",
age: 1
* Viết hàm showInfo trả về object đó
*/
var student = {
name: 'Some One',
sex: 'male',
age: 18
}
function showInfo(obj) {
// | de ở đây
return obj;
} | viết co |
cieRgbConverter.js | /*
With these functions you can convert the CIE color space to the RGB color space and vice versa.
The developer documentation for Philips Hue provides the formulas used in the code below:
https://developers.meethue.com/documentation/color-conversions-rgb-xy
I've used the formulas and Objective-C example code and transfered it to JavaScript.
Examples:
var rgb = cie_to_rgb(0.6611, 0.2936)
var cie = rgb_to_cie(255, 39, 60)
------------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2017 www.usolved.net
Published under https://github.com/usolved/cie-rgb-converter
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.
*/
/**
* Converts CIE color space to RGB color space
* @param {Number} x
* @param {Number} y
* @param {Number} brightness - Ranges from 1 to 254
* @return {Array} Array that contains the color values for red, green and blue
*/
export function | (x, y, brightness)
{
//Set to maximum brightness if no custom value was given (Not the slick ECMAScript 6 way for compatibility reasons)
if (brightness === undefined) {
brightness = 254;
}
var z = 1.0 - x - y;
var Y = (brightness / 254).toFixed(2);
var X = (Y / y) * x;
var Z = (Y / y) * z;
//Convert to RGB using Wide RGB D65 conversion
var red = X * 1.656492 - Y * 0.354851 - Z * 0.255038;
var green = -X * 0.707196 + Y * 1.655397 + Z * 0.036152;
var blue = X * 0.051713 - Y * 0.121364 + Z * 1.011530;
//If red, green or blue is larger than 1.0 set it back to the maximum of 1.0
if (red > blue && red > green && red > 1.0) {
green = green / red;
blue = blue / red;
red = 1.0;
}
else if (green > blue && green > red && green > 1.0) {
red = red / green;
blue = blue / green;
green = 1.0;
}
else if (blue > red && blue > green && blue > 1.0) {
red = red / blue;
green = green / blue;
blue = 1.0;
}
//Reverse gamma correction
red = red <= 0.0031308 ? 12.92 * red : (1.0 + 0.055) * Math.pow(red, (1.0 / 2.4)) - 0.055;
green = green <= 0.0031308 ? 12.92 * green : (1.0 + 0.055) * Math.pow(green, (1.0 / 2.4)) - 0.055;
blue = blue <= 0.0031308 ? 12.92 * blue : (1.0 + 0.055) * Math.pow(blue, (1.0 / 2.4)) - 0.055;
//Convert normalized decimal to decimal
red = Math.round(red * 255);
green = Math.round(green * 255);
blue = Math.round(blue * 255);
if (isNaN(red))
red = 0;
if (isNaN(green))
green = 0;
if (isNaN(blue))
blue = 0;
return [red, green, blue];
}
/**
* Converts RGB color space to CIE color space
* @param {Number} red
* @param {Number} green
* @param {Number} blue
* @return {Array} Array that contains the CIE color values for x and y
*/
export function rgb_to_cie(red, green, blue)
{
//Apply a gamma correction to the RGB values, which makes the color more vivid and more the like the color displayed on the screen of your device
var red = (red > 0.04045) ? Math.pow((red + 0.055) / (1.0 + 0.055), 2.4) : (red / 12.92);
var green = (green > 0.04045) ? Math.pow((green + 0.055) / (1.0 + 0.055), 2.4) : (green / 12.92);
var blue = (blue > 0.04045) ? Math.pow((blue + 0.055) / (1.0 + 0.055), 2.4) : (blue / 12.92);
//RGB values to XYZ using the Wide RGB D65 conversion formula
var X = red * 0.664511 + green * 0.154324 + blue * 0.162028;
var Y = red * 0.283881 + green * 0.668433 + blue * 0.047685;
var Z = red * 0.000088 + green * 0.072310 + blue * 0.986039;
//Calculate the xy values from the XYZ values
var x = (X / (X + Y + Z)).toFixed(4);
var y = (Y / (X + Y + Z)).toFixed(4);
if (isNaN(x))
x = 0;
if (isNaN(y))
y = 0;
return [+x, +y];
}
| cie_to_rgb |
lib.rs | mod advanced;
mod concurrency;
mod oop;
mod patterns;
mod smart_pointers;
pub fn test_smart_pointers() {
println!("* test_smart_pointers");
smart_pointers::box_save_to_heap();
smart_pointers::implement_cons_list_use_box();
smart_pointers::implement_custom_smart_pointer();
println!("");
}
pub fn test_concurrency() {
println!("* test_concurrency");
concurrency::threads::value_move_into_closure();
concurrency::message_passing::send_single_message();
concurrency::message_passing::send_multiple_messages();
concurrency::message_passing::send_messages_from_multiple_producer();
concurrency::share::lock_use_mutex();
println!("");
}
pub fn test_oop() {
println!("* test_oop");
oop::implementing_the_trait();
oop::implementing_state_design_pattern_as_trait();
oop::implementing_state_design_pattern_as_type();
println!("");
}
pub fn test_patterns() {
println!("* test_patterns");
patterns::destructure_structs();
patterns::destructure_structs_in_match();
patterns::destructure_enums();
patterns::destructure_reference();
patterns::destructure_structs_and_tuples();
patterns::create_reference();
patterns::create_mutable_reference(); |
#[allow(unused_must_use)]
pub fn test_advanced() {
println!("* test_advanced");
advanced::unsafe_rust::create_raw_pointer();
advanced::unsafe_rust::dereference_raw_pointer();
advanced::unsafe_rust::call_the_dangerous_function();
advanced::unsafe_rust::create_safe_abstract_on_unsafe_code();
advanced::unsafe_rust::use_the_ffi();
advanced::unsafe_rust::access_to_static_mutable_variable();
advanced::lifetime::lifetime_subtyping();
advanced::lifetime::lifetime_bound();
advanced::lifetime::lifetime_of_trait_object();
advanced::traits::default_generic_type_parameter_and_operator_overloading();
advanced::traits::use_fully_qualified_syntax();
advanced::traits::use_super_trait();
advanced::traits::use_newtype_pattern();
advanced::types::use_type_alias();
advanced::types::allow_dynamically_sized_type_with_generic();
advanced::fn_closure::use_function_pointer();
advanced::fn_closure::returns_closure();
println!("");
} | patterns::match_guards();
patterns::at_operator_bindings();
println!("");
} |
sync_tamusers.py | from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.management.base import BaseCommand
from django.contrib.sites.models import Site
from allauth.socialaccount.models import SocialApp
from tamusers.providers.tampere.provider import TampereProvider
class Command(BaseCommand):
help = 'Create or update tamusers allauth SocialApp'
def handle(self, *args, **options):
changed = False
try:
app = SocialApp.objects.get(provider=TampereProvider.id)
except SocialApp.DoesNotExist:
app = SocialApp(provider=TampereProvider.id)
self.stdout.write(self.style.SUCCESS('Creating new SocialApp'))
if not app.name:
app.name = 'Tampereen kaupungin työntekijät'
changed = True
client_id = secret_key = None
jwt_settings = getattr(settings, 'JWT_AUTH')
if jwt_settings:
client_id = jwt_settings.get('JWT_AUDIENCE')
secret_key = jwt_settings.get('JWT_SECRET_KEY')
if not client_id:
ra | if not secret_key:
raise ImproperlyConfigured("You must set JWT_AUTH['JWT_SECRET_KEY'] to correspond to your secret key")
if app.client_id != client_id:
changed = True
app.client_id = client_id
if app.secret != secret_key:
changed = True
app.secret = secret_key
if changed:
app.save()
if not app.sites.exists():
app.sites.add(Site.objects.get(id=settings.SITE_ID))
changed = True
if changed:
self.stdout.write(self.style.SUCCESS('SocialApp successfully updated'))
else:
self.stdout.write(self.style.NOTICE('Already synced -- no changes needed'))
| ise ImproperlyConfigured("You must set JWT_AUTH['JWT_AUDIENCE'] to correspond to your client ID")
|
schema.rs | use std::env::current_dir;
use std::fs::create_dir_all;
use cosmwasm_schema::{export_schema, remove_schemas, schema_for};
use sg_std::{StargazeMsg, StargazeMsgWrapper}; | let mut out_dir = current_dir().unwrap();
out_dir.push("schema");
create_dir_all(&out_dir).unwrap();
remove_schemas(&out_dir).unwrap();
export_schema(&schema_for!(StargazeMsgWrapper), &out_dir);
export_schema(&schema_for!(StargazeMsg), &out_dir);
} | fn main() { |
cel-service_test.go | package protofiles
import (
"testing"
"github.com/stretchr/testify/assert"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/structpb"
)
func TestYamlProto(t *testing.T) {
ast := assert.New(t)
jsonContext := map[string]interface{}{
"data": map[string]interface{}{
"value": 1,
},
}
structValue, err := structpb.NewStruct(jsonContext)
ast.Nil(err)
celRequest := CelRequest{
Context: structValue,
Expression: "data.value == 1",
}
ast.NotNil(celRequest)
out, err := proto.Marshal(&celRequest)
ast.Nil(err)
ast.NotNil(out)
celReq2 := &CelRequest{}
err = proto.Unmarshal(out, celReq2)
ast.Nil(err)
ast.NotNil(celReq2)
ast.Equal(celRequest.Expression, celReq2.Expression)
| } |
|
index.ts | export * from './IApplication';
export * from './IConfig';
export * from './IDatabaseOption';
export * from './IDatabase'; | export * from './IRabbitMQ'; |
|
gb_yolact.py | import torch, torchvision
import torch.nn as nn
import torch.nn.functional as F
from torchvision.models.resnet import Bottleneck, conv1x1, conv3x3
import numpy as np
from functools import partial
from itertools import product, chain
from math import sqrt
from typing import List, Tuple
use_torch2trt = False
use_jit = False if use_torch2trt else torch.cuda.device_count() <= 1
NoneTensor = None if use_torch2trt else torch.Tensor()
ScriptModuleWrapper = torch.jit.ScriptModule if use_jit else nn.Module
script_method_wrapper = torch.jit.script_method if use_jit else lambda fn, _rcn=None: fn
class InterpolateModule(nn.Module):
"""
This is a module version of F.interpolate (rip nn.Upsampling).
Any arguments you give it just get passed along for the ride.
"""
def __init__(self, *args, **kwdargs):
super().__init__()
self.args = args
self.kwdargs = kwdargs
def forward(self, x):
return F.interpolate(x, *self.args, **self.kwdargs)
def make_net(in_channels, conf, include_last_relu=True):
"""
A helper function to take a config setting and turn it into a network.
Used by protonet and extrahead. Returns (network, out_channels)
"""
def make_layer(layer_cfg):
nonlocal in_channels
# Possible patterns:
# ( 256, 3, {}) -> conv
# ( 256,-2, {}) -> deconv
# (None,-2, {}) -> bilinear interpolate
# ('cat',[],{}) -> concat the subnetworks in the list
#
# You know it would have probably been simpler just to adopt a 'c' 'd' 'u' naming scheme.
# Whatever, it's too late now.
if isinstance(layer_cfg[0], str):
layer_name = layer_cfg[0]
if layer_name == 'cat':
nets = [make_net(in_channels, x) for x in layer_cfg[1]]
layer = Concat([net[0] for net in nets], layer_cfg[2])
num_channels = sum([net[1] for net in nets])
else:
num_channels = layer_cfg[0]
kernel_size = layer_cfg[1]
if kernel_size > 0:
layer = nn.Conv2d(in_channels, num_channels, kernel_size, **layer_cfg[2])
else:
if num_channels is None:
layer = InterpolateModule(scale_factor=-kernel_size, mode='bilinear', align_corners=False, **layer_cfg[2])
else:
layer = nn.ConvTranspose2d(in_channels, num_channels, -kernel_size, **layer_cfg[2])
in_channels = num_channels if num_channels is not None else in_channels
# Don't return a ReLU layer if we're doing an upsample. This probably doesn't affect anything
# output-wise, but there's no need to go through a ReLU here.
# Commented out for backwards compatibility with previous models
# if num_channels is None:
# return [layer]
# else:
return [layer, nn.ReLU(inplace=True)]
# Use sum to concat together all the component layer lists
net = sum([make_layer(x) for x in conf], [])
if not include_last_relu:
net = net[:-1]
return nn.Sequential(*(net)), in_channels
class Bottleneck(nn.Module):
""" Adapted from torchvision.models.resnet """
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, norm_layer=nn.BatchNorm2d, dilation=1):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False, dilation=dilation)
self.bn1 = norm_layer(planes)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
padding=dilation, bias=False, dilation=dilation)
self.bn2 = norm_layer(planes)
self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False, dilation=dilation)
self.bn3 = norm_layer(planes * 4)
self.relu = nn.ReLU(inplace=True)
if downsample is not None:
self.downsample = downsample
else:
self.downsample = nn.Sequential()
self.stride = stride
def forward(self, x):
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class ResNetBackbone(nn.Module):
""" Adapted from torchvision.models.resnet """
def __init__(self, layers, atrous_layers=[], block=Bottleneck, norm_layer=nn.BatchNorm2d):
super().__init__()
# These will be populated by _make_layer
self.num_base_layers = len(layers)
self.layers = nn.ModuleList()
self.channels = []
self.norm_layer = norm_layer
self.dilation = 1
self.atrous_layers = atrous_layers
# From torchvision.models.resnet.Resnet
self.inplanes = 64
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
self.bn1 = norm_layer(64)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self._make_layer(block, 64, layers[0])
self._make_layer(block, 128, layers[1], stride=2)
self._make_layer(block, 256, layers[2], stride=2)
self._make_layer(block, 512, layers[3], stride=2)
# This contains every module that should be initialized by loading in pretrained weights.
# Any extra layers added onto this that won't be initialized by init_backbone will not be
# in this list. That way, Yolact::init_weights knows which backbone weights to initialize
# with xavier, and which ones to leave alone.
self.backbone_modules = [m for m in self.modules() if isinstance(m, nn.Conv2d)]
def _make_layer(self, block, planes, blocks, stride=1):
""" Here one layer means a string of n Bottleneck blocks. """
downsample = None
# This is actually just to create the connection between layers, and not necessarily to
# downsample. Even if the second condition is met, it only downsamples when stride != 1
if stride != 1 or self.inplanes != planes * block.expansion:
if len(self.layers) in self.atrous_layers:
self.dilation += 1
stride = 1
downsample = nn.Sequential(
nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=1, stride=stride, bias=False,
dilation=self.dilation),
self.norm_layer(planes * block.expansion),
)
layers = []
layers.append(block(self.inplanes, planes, stride, downsample, self.norm_layer, self.dilation))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(block(self.inplanes, planes, norm_layer=self.norm_layer))
layer = nn.Sequential(*layers)
self.channels.append(planes * block.expansion)
self.layers.append(layer)
return layer
def forward(self, x, partial:bool=False):
""" Returns a list of convouts for each layer. """
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
outs = []
layer_idx = 0
for layer in self.layers:
layer_idx += 1
if not partial or layer_idx <= 2:
x = layer(x)
outs.append(x)
return outs
def init_backbone(self, path, map_location=None):
""" Initializes the backbone weights for training. """
state_dict = torch.load(path, map_location=map_location)
# Replace layer1 -> layers.0 etc.
keys = list(state_dict)
for key in keys:
if key.startswith('layer'):
idx = int(key[5])
new_key = 'layers.' + str(idx-1) + key[6:]
state_dict[new_key] = state_dict.pop(key)
# Note: Using strict=False is berry scary. Triple check this.
self.load_state_dict(state_dict, strict=False)
def add_layer(self, conv_channels=1024, downsample=2, depth=1, block=Bottleneck):
""" Add a downsample layer to the backbone as per what SSD does. """
self._make_layer(block, conv_channels // block.expansion, blocks=depth, stride=downsample)
class FPN_phase_1(ScriptModuleWrapper):
__constants__ = ['interpolation_mode', 'lat_layers']
def __init__(self, in_channels):
super().__init__()
self.src_channels = in_channels
self.lat_layers = nn.ModuleList([
nn.Conv2d(x, 256, kernel_size=1)
for x in reversed(in_channels)
])
self.interpolation_mode = 'bilinear'
@script_method_wrapper
def forward(self, x1=NoneTensor, x2=NoneTensor, x3=NoneTensor, x4=NoneTensor, x5=NoneTensor, x6=NoneTensor, x7=NoneTensor):
"""
Args:
- convouts (list): A list of convouts for the corresponding layers in in_channels.
Returns:
- A list of FPN convouts in the same order as x with extra downsample layers if requested.
"""
convouts_ = [x1, x2, x3, x4, x5, x6, x7]
convouts = []
j = 0
while j < len(convouts_):
if convouts_[j] is not None and convouts_[j].size(0):
convouts.append(convouts_[j])
j += 1
# convouts = [x for x in convouts if x is not None]
out = []
lat_layers = []
x = torch.zeros(1, device=convouts[0].device)
for i in range(len(convouts)):
out.append(x)
lat_layers.append(x)
# For backward compatability, the conv layers are stored in reverse but the input and output is
# given in the correct order. Thus, use j=-i-1 for the input and output and i for the conv layers.
j = len(convouts)
for lat_layer in self.lat_layers:
j -= 1
if j < len(convouts) - 1:
_, _, h, w = convouts[j].size()
x = F.interpolate(x, size=(h, w), mode=self.interpolation_mode, align_corners=False)
lat_j = lat_layer(convouts[j])
lat_layers[j] = lat_j
x = x + lat_j
out[j] = x
for i in range(len(convouts)):
out.append(lat_layers[i])
return out
class FPN_phase_2(ScriptModuleWrapper):
__constants__ = ['num_downsample', 'use_conv_downsample', 'pred_layers', 'downsample_layers']
def __init__(self, in_channels):
super().__init__()
self.src_channels = in_channels
# This is here for backwards compatability
padding = 1
self.pred_layers = nn.ModuleList([
nn.Conv2d(256, 256, kernel_size=3, padding=padding)
for _ in in_channels
])
self.downsample_layers = nn.ModuleList([
nn.Conv2d(256, 256, kernel_size=3, padding=1, stride=2)
for _ in range(2)
])
self.num_downsample = 2
self.use_conv_downsample = True
@script_method_wrapper
def forward(self, x1=NoneTensor, x2=NoneTensor, x3=NoneTensor, x4=NoneTensor, x5=NoneTensor, x6=NoneTensor, x7=NoneTensor):
"""
Args:
- convouts (list): A list of convouts for the corresponding layers in in_channels.
Returns:
- A list of FPN convouts in the same order as x with extra downsample layers if requested.
"""
# out = [x1, x2, x3, x4, x5, x6, x7]
# out = [x for x in out if x is not None]
out_ = [x1, x2, x3, x4, x5, x6, x7]
out = []
j = 0
while j < len(out_):
if out_[j] is not None and out_[j].size(0):
out.append(out_[j])
j += 1
len_convouts = len(out)
j = len_convouts
for pred_layer in self.pred_layers:
j -= 1
out[j] = F.relu(pred_layer(out[j]))
# In the original paper, this takes care of P6
if self.use_conv_downsample:
for downsample_layer in self.downsample_layers:
out.append(downsample_layer(out[-1]))
else:
for idx in range(self.num_downsample):
# Note: this is an untested alternative to out.append(out[-1][:, :, ::2, ::2]). Thanks TorchScript.
out.append(nn.functional.max_pool2d(out[-1], 1, stride=2))
return out
class FPN(ScriptModuleWrapper):
"""
Implements a general version of the FPN introduced in
https://arxiv.org/pdf/1612.03144.pdf
Parameters (in cfg.fpn):
- num_features (int): The number of output features in the fpn layers.
- interpolation_mode (str): The mode to pass to F.interpolate.
- num_downsample (int): The number of downsampled layers to add onto the selected layers.
These extra layers are downsampled from the last selected layer.
Args:
- in_channels (list): For each conv layer you supply in the forward pass,
how many features will it have?
"""
__constants__ = ['interpolation_mode', 'num_downsample', 'use_conv_downsample',
'lat_layers', 'pred_layers', 'downsample_layers']
def __init__(self, in_channels):
super().__init__()
self.lat_layers = nn.ModuleList([
nn.Conv2d(x, cfg.fpn.num_features, kernel_size=1)
for x in reversed(in_channels)
])
# This is here for backwards compatability
padding = 1 if cfg.fpn.pad else 0
self.pred_layers = nn.ModuleList([
nn.Conv2d(256, 256, kernel_size=3, padding=padding)
for _ in in_channels
])
if cfg.fpn.use_conv_downsample:
self.downsample_layers = nn.ModuleList([
nn.Conv2d(256, 256, kernel_size=3, padding=1, stride=2)
for _ in range(2)
])
self.interpolation_mode = 'bilinear'
self.num_downsample = 2
self.use_conv_downsample = True
@script_method_wrapper
def forward(self, convouts:List[torch.Tensor]):
"""
Args:
- convouts (list): A list of convouts for the corresponding layers in in_channels.
Returns:
- A list of FPN convouts in the same order as x with extra downsample layers if requested.
"""
out = []
x = torch.zeros(1, device=convouts[0].device)
for i in range(len(convouts)):
out.append(x)
# For backward compatability, the conv layers are stored in reverse but the input and output is
# given in the correct order. Thus, use j=-i-1 for the input and output and i for the conv layers.
j = len(convouts)
for lat_layer in self.lat_layers:
j -= 1
if j < len(convouts) - 1:
_, _, h, w = convouts[j].size()
x = F.interpolate(x, size=(h, w), mode=self.interpolation_mode, align_corners=False)
x = x + lat_layer(convouts[j])
out[j] = x
# This janky second loop is here because TorchScript.
j = len(convouts)
for pred_layer in self.pred_layers:
j -= 1
out[j] = F.relu(pred_layer(out[j]))
# In the original paper, this takes care of P6
if self.use_conv_downsample:
for downsample_layer in self.downsample_layers:
out.append(downsample_layer(out[-1]))
else:
for idx in range(self.num_downsample):
# Note: this is an untested alternative to out.append(out[-1][:, :, ::2, ::2]). Thanks TorchScript.
out.append(nn.functional.max_pool2d(out[-1], 1, stride=2))
return out
class PredictionModule(nn.Module):
"""
The (c) prediction module adapted from DSSD:
https://arxiv.org/pdf/1701.06659.pdf
Note that this is slightly different to the module in the paper
because the Bottleneck block actually has a 3x3 convolution in
the middle instead of a 1x1 convolution. Though, I really can't
be arsed to implement it myself, and, who knows, this might be
better.
Args:
- in_channels: The input feature size.
- out_channels: The output feature size (must be a multiple of 4).
- aspect_ratios: A list of lists of priorbox aspect ratios (one list per scale).
- scales: A list of priorbox scales relative to this layer's convsize.
For instance: If this layer has convouts of size 30x30 for
an image of size 600x600, the 'default' (scale
of 1) for this layer would produce bounding
boxes with an area of 20x20px. If the scale is
.5 on the other hand, this layer would consider
bounding boxes with area 10x10px, etc.
- parent: If parent is a PredictionModule, this module will use all the layers
from parent instead of from this module.
"""
def __init__(self, in_channels, out_channels=1024, aspect_ratios=[[1]], scales=[1], parent=None, index=0, mask_dim=None, num_classes=81):
super().__init__()
self.params = [in_channels, out_channels, aspect_ratios, scales, parent, index]
self.num_classes = num_classes
self.mask_dim = mask_dim
self.num_priors = sum(len(x) for x in aspect_ratios)
self.parent = [parent] # Don't include this in the state dict
self.index = index
self.extra_head_net = [(256, 3, {'padding': 1})]
self.head_layer_params = {'kernel_size': 3, 'padding': 1}
self.num_instance_coeffs = 64
if parent is None:
if self.extra_head_net is None:
out_channels = in_channels
else:
self.upfeature, out_channels = make_net(in_channels, self.extra_head_net)
self.bbox_layer = nn.Conv2d(out_channels, self.num_priors * 4, **(self.head_layer_params))
self.conf_layer = nn.Conv2d(out_channels, self.num_priors * self.num_classes, **(self.head_layer_params))
self.mask_layer = nn.Conv2d(out_channels, self.num_priors * self.mask_dim, **(self.head_layer_params))
# What is this ugly lambda doing in the middle of all this clean prediction module code?
def make_extra(num_layers):
if num_layers == 0:
return lambda x: x
else:
# Looks more complicated than it is. This just creates an array of num_layers alternating conv-relu
return nn.Sequential(*sum([[
nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1),
nn.ReLU(inplace=True)
] for _ in range(num_layers)], []))
extra_layers = (0, 0, 0)
self.bbox_extra, self.conf_extra, self.mask_extra = [make_extra(x) for x in extra_layers]
self.aspect_ratios = aspect_ratios
self.scales = scales
self.priors = None
self.last_conv_size = None
def forward(self, x):
"""
Args:
- x: The convOut from a layer in the backbone network
Size: [batch_size, in_channels, conv_h, conv_w])
Returns a tuple (bbox_coords, class_confs, mask_output, prior_boxes) with sizes
- bbox_coords: [batch_size, conv_h*conv_w*num_priors, 4]
- class_confs: [batch_size, conv_h*conv_w*num_priors, num_classes]
- mask_output: [batch_size, conv_h*conv_w*num_priors, mask_dim]
- prior_boxes: [conv_h*conv_w*num_priors, 4]
"""
# In case we want to use another module's layers
src = self if self.parent[0] is None else self.parent[0]
conv_h = x.size(2)
conv_w = x.size(3)
if self.extra_head_net is not None:
x = src.upfeature(x)
bbox_x = src.bbox_extra(x)
conf_x = src.conf_extra(x)
mask_x = src.mask_extra(x)
bbox = src.bbox_layer(bbox_x).permute(0, 2, 3, 1).contiguous().view(x.size(0), -1, 4)
conf = src.conf_layer(conf_x).permute(0, 2, 3, 1).contiguous().view(x.size(0), -1, self.num_classes)
mask = src.mask_layer(mask_x).permute(0, 2, 3, 1).contiguous().view(x.size(0), -1, self.mask_dim)
mask = torch.tanh(mask)
priors = self.make_priors(conv_h, conv_w)
preds = { 'loc': bbox, 'conf': conf, 'mask': mask, 'priors': priors }
return preds
class Detect(object):
"""At test time, Detect is the final layer of SSD. Decode location preds,
apply non-maximum suppression to location predictions based on conf
scores and threshold to a top_k number of output predictions for both
confidence score and locations, as the predicted masks.
"""
# TODO: Refactor this whole class away. It needs to go.
def __init__(self, num_classes, bkg_label, top_k, conf_thresh, nms_thresh):
self.num_classes = num_classes
self.background_label = bkg_label
self.top_k = top_k
# Parameters used in nms.
self.nms_thresh = nms_thresh
if nms_thresh <= 0:
raise ValueError('nms_threshold must be non negative.')
self.conf_thresh = conf_thresh
self.cross_class_nms = False
self.use_fast_nms = False
def __call__(self, predictions, extras=None):
"""
Args:
loc_data: (tensor) Loc preds from loc layers
Shape: [batch, num_priors, 4]
conf_data: (tensor) Shape: Conf preds from conf layers
Shape: [batch, num_priors, num_classes]
mask_data: (tensor) Mask preds from mask layers
Shape: [batch, num_priors, mask_dim]
prior_data: (tensor) Prior boxes and variances from priorbox layers
Shape: [num_priors, 4]
proto_data: (tensor) If using mask_type.lincomb, the prototype masks
Shape: [batch, mask_h, mask_w, mask_dim]
Returns:
output of shape (batch_size, top_k, 1 + 1 + 4 + mask_dim)
These outputs are in the order: class idx, confidence, bbox coords, and mask.
Note that the outputs are sorted only if cross_class_nms is False
"""
loc_data = predictions['loc']
conf_data = predictions['conf']
mask_data = predictions['mask']
prior_data = predictions['priors']
proto_data = predictions['proto'] if 'proto' in predictions else None
inst_data = predictions['inst'] if 'inst' in predictions else None
out = []
with timer.env('Detect'):
batch_size = loc_data.size(0)
num_priors = prior_data.size(0)
conf_preds = conf_data.view(batch_size, num_priors, self.num_classes).transpose(2, 1).contiguous()
for batch_idx in range(batch_size):
decoded_boxes = decode(loc_data[batch_idx], prior_data)
result = self.detect(batch_idx, conf_preds, decoded_boxes, mask_data, inst_data, extras)
if result is not None and proto_data is not None:
result['proto'] = proto_data[batch_idx]
out.append(result)
return out
def detect(self, batch_idx, conf_preds, decoded_boxes, mask_data, inst_data, extras=None):
""" Perform nms for only the max scoring class that isn't background (class 0) """
cur_scores = conf_preds[batch_idx, 1:, :]
conf_scores, _ = torch.max(cur_scores, dim=0)
keep = (conf_scores > self.conf_thresh)
scores = cur_scores[:, keep]
boxes = decoded_boxes[keep, :]
masks = mask_data[batch_idx, keep, :]
if inst_data is not None:
inst = inst_data[batch_idx, keep, :]
if scores.size(1) == 0:
return None
if self.use_fast_nms:
boxes, masks, classes, scores = self.fast_nms(boxes, masks, scores, self.nms_thresh, self.top_k)
else:
boxes, masks, classes, scores = self.traditional_nms(boxes, masks, scores, self.nms_thresh, self.conf_thresh)
return {'box': boxes, 'mask': masks, 'class': classes, 'score': scores}
def coefficient_nms(self, coeffs, scores, cos_threshold=0.9, top_k=400):
_, idx = scores.sort(0, descending=True)
idx = idx[:top_k]
coeffs_norm = F.normalize(coeffs[idx], dim=1)
# Compute the pairwise cosine similarity between the coefficients
cos_similarity = coeffs_norm @ coeffs_norm.t()
# Zero out the lower triangle of the cosine similarity matrix and diagonal
cos_similarity.triu_(diagonal=1)
# Now that everything in the diagonal and below is zeroed out, if we take the max
# of the cos similarity matrix along the columns, each column will represent the
# maximum cosine similarity between this element and every element with a higher
# score than this element.
cos_max, _ = torch.max(cos_similarity, dim=0)
# Now just filter out the ones higher than the threshold
idx_out = idx[cos_max <= cos_threshold]
# new_mask_norm = F.normalize(masks[idx_out], dim=1)
# print(new_mask_norm[:5] @ new_mask_norm[:5].t())
return idx_out, idx_out.size(0)
def fast_nms(self, boxes, masks, scores, iou_threshold:float=0.5, top_k:int=200, second_threshold:bool=False):
scores, idx = scores.sort(1, descending=True)
idx = idx[:, :top_k].contiguous()
scores = scores[:, :top_k]
num_classes, num_dets = idx.size()
boxes = boxes[idx.view(-1), :].view(num_classes, num_dets, 4)
masks = masks[idx.view(-1), :].view(num_classes, num_dets, -1)
iou = jaccard(boxes, boxes)
iou.triu_(diagonal=1)
iou_max, _ = iou.max(dim=1)
# Now just filter out the ones higher than the threshold
keep = (iou_max <= iou_threshold)
# We should also only keep detections over the confidence threshold, but at the cost of
# maxing out your detection count for every image, you can just not do that. Because we
# have such a minimal amount of computation per detection (matrix mulitplication only),
# this increase doesn't affect us much (+0.2 mAP for 34 -> 33 fps), so we leave it out.
# However, when you implement this in your method, you should do this second threshold.
if second_threshold:
keep *= (scores > self.conf_thresh)
# Assign each kept detection to its corresponding class
classes = torch.arange(num_classes, device=boxes.device)[:, None].expand_as(keep)
# This try-except block aims to fix the IndexError that we might encounter when we train on custom datasets and evaluate with TensorRT enabled. See https://github.com/haotian-liu/yolact_edge/issues/27.
try:
classes = classes[keep]
except IndexError:
import logging
logger = logging.getLogger("yolact.layers.detect")
logger.warning("Encountered IndexError as mentioned in https://github.com/haotian-liu/yolact_edge/issues/27. Flattening predictions to avoid error, please verify the outputs. If there are any problems you met related to this, please report an issue.")
classes = torch.flatten(classes, end_dim=1)
boxes = torch.flatten(boxes, end_dim=1)
masks = torch.flatten(masks, end_dim=1)
scores = torch.flatten(scores, end_dim=1)
keep = torch.flatten(keep, end_dim=1)
classes = classes[keep]
boxes = boxes[keep]
masks = masks[keep]
scores = scores[keep]
# Only keep the top cfg.max_num_detections highest scores across all classes
scores, idx = scores.sort(0, descending=True)
idx = idx[:cfg.max_num_detections]
scores = scores[:cfg.max_num_detections]
try:
classes = classes[idx]
boxes = boxes[idx]
masks = masks[idx]
except IndexError:
import logging
logger = logging.getLogger("yolact.layers.detect")
logger.warning("Encountered IndexError as mentioned in https://github.com/haotian-liu/yolact_edge/issues/27. Using `torch.index_select` to avoid error, please verify the outputs. If there are any problems you met related to this, please report an issue.")
classes = torch.index_select(classes, 0, idx)
boxes = torch.index_select(boxes, 0, idx)
masks = torch.index_select(masks, 0, idx)
return boxes, masks, classes, scores
def traditional_nms(self, boxes, masks, scores, iou_threshold=0.5, conf_thresh=0.05):
num_classes = scores.size(0)
idx_lst = []
cls_lst = []
scr_lst = []
# Multiplying by max_size is necessary because of how cnms computes its area and intersections
boxes = boxes * cfg.max_size
for _cls in range(num_classes):
cls_scores = scores[_cls, :]
conf_mask = cls_scores > conf_thresh
idx = torch.arange(cls_scores.size(0), device=boxes.device)
cls_scores = cls_scores[conf_mask]
idx = idx[conf_mask]
if cls_scores.size(0) == 0:
continue
preds = torch.cat([boxes[conf_mask], cls_scores[:, None]], dim=1).cpu().numpy()
keep = cnms(preds, iou_threshold)
keep = torch.Tensor(keep, device=boxes.device).long()
idx_lst.append(idx[keep])
cls_lst.append(keep * 0 + _cls)
scr_lst.append(cls_scores[keep])
idx = torch.cat(idx_lst, dim=0)
classes = torch.cat(cls_lst, dim=0)
scores = torch.cat(scr_lst, dim=0)
scores, idx2 = scores.sort(0, descending=True)
idx2 = idx2[:cfg.max_num_detections]
scores = scores[:cfg.max_num_detections]
idx = idx[idx2]
classes = classes[idx2]
# Undo the multiplication above
return boxes[idx] / cfg.max_size, masks[idx], classes, scores
class yolactedge(nn.Module):
def | (self, training=False):
super().__init__()
self.training = training
self.fpn_num_features = 256
self.backbone = ResNetBackbone([3, 4, 23, 3])
num_layers = max(list(range(1, 4))) + 1
while len(self.backbone.layers) < num_layers:
self.backbone.add_layer()
self.num_grids = 0
self.proto_src = 0
self.num_classes = 81
in_channels = self.fpn_num_features
in_channels += self.num_grids
# The include_last_relu=false here is because we might want to change it to another function
mask_proto_net = [(256, 3, {'padding': 1})] * 3 + [(None, -2, {}), (256, 3, {'padding': 1})] + [(32, 1, {})]
self.proto_net, self.mask_dim = make_net(in_channels, mask_proto_net, include_last_relu=False)
self.selected_layers = list(range(1, 4))
src_channels = self.backbone.channels
self.fpn_phase_1 = FPN_phase_1([src_channels[i] for i in self.selected_layers])
self.fpn_phase_2 = FPN_phase_2([src_channels[i] for i in self.selected_layers])
self.selected_layers = list(range(len(self.selected_layers) + 2))
src_channels = [self.fpn_num_features] * len(self.selected_layers)
self.prediction_layers = nn.ModuleList()
for idx, layer_idx in enumerate(self.selected_layers):
# If we're sharing prediction module weights, have every module's parent be the first one
parent = None
if idx > 0:
parent = self.prediction_layers[0]
pred_aspect_ratios = [ [[1, 1/2, 2]] ]*5
pred_scales = [[24], [48], [96], [192], [384]]
pred = PredictionModule(src_channels[layer_idx], src_channels[layer_idx],
aspect_ratios = pred_aspect_ratios[idx],
scales = pred_scales[idx],
parent = parent,
index = idx,
mask_dim = self.mask_dim,
num_classes = self.num_classes)
self.prediction_layers.append(pred)
self.semantic_seg_conv = nn.Conv2d(src_channels[0], self.num_classes-1, kernel_size=1)
# # For use in evaluation
# self.detect = Detect(self.num_classes, bkg_label=0, top_k=200, conf_thresh=0.05, nms_thresh=0.5)
def forward(self, inp):
return inp
if __name__ == '__main__':
print('hello world')
net = yolactedge().cuda()
dummy_input = torch.randn(10, 3, 550, 550, device='cuda')
torch.onnx.export(net, dummy_input, "test.onnx", verbose=True)
| __init__ |
pool.rs | //! A simple connection pool
#![deprecated="Use https://github.com/sfackler/r2d2-postgres instead"]
#![allow(deprecated)]
use std::sync::{Arc, Mutex};
use {PostgresConnectParams, IntoConnectParams, PostgresConnection, SslMode};
use error::PostgresConnectError;
struct InnerConnectionPool {
params: PostgresConnectParams,
ssl: SslMode,
pool: Vec<PostgresConnection>,
}
impl InnerConnectionPool {
fn add_connection(&mut self) -> Result<(), PostgresConnectError> {
PostgresConnection::connect(self.params.clone(), &self.ssl)
.map(|c| self.pool.push(c))
}
}
/// A simple fixed-size Postgres connection pool.
///
/// It can be shared across tasks.
///
/// ## Example
///
/// ```rust,no_run
/// # #![allow(deprecated)]
/// # use postgres::NoSsl;
/// # use postgres::pool::PostgresConnectionPool;
/// let pool = PostgresConnectionPool::new("postgres://postgres@localhost",
/// NoSsl, 5).unwrap();
/// for _ in range(0u, 10) {
/// let pool = pool.clone();
/// spawn(proc() {
/// let conn = pool.get_connection();
/// conn.execute("UPDATE foo SET bar = 1", []).unwrap();
/// });
/// }
/// ```
#[deriving(Clone)]
pub struct PostgresConnectionPool {
pool: Arc<Mutex<InnerConnectionPool>>
}
impl PostgresConnectionPool {
/// Creates a new pool with the specified number of connections.
///
/// Returns an error if the specified number of connections cannot be
/// created.
pub fn new<T: IntoConnectParams>(params: T, ssl: SslMode, pool_size: uint)
-> Result<PostgresConnectionPool, PostgresConnectError> {
let mut pool = InnerConnectionPool {
params: try!(params.into_connect_params()),
ssl: ssl,
pool: vec![],
};
for _ in range(0, pool_size) {
try!(pool.add_connection());
}
Ok(PostgresConnectionPool {
pool: Arc::new(Mutex::new(pool))
})
}
/// Retrieves a connection from the pool.
///
/// If all connections are in use, blocks until one becomes available.
pub fn get_connection(&self) -> PooledPostgresConnection {
let mut pool = self.pool.lock();
loop {
match pool.pool.pop() {
Some(conn) => {
return PooledPostgresConnection {
pool: self.clone(),
conn: Some(conn),
};
}
None => pool.cond.wait()
}
}
}
}
/// A Postgres connection pulled from a connection pool.
///
/// It will be returned to the pool when it falls out of scope, even due to
/// task failure.
pub struct PooledPostgresConnection {
pool: PostgresConnectionPool,
// TODO remove the Option wrapper when drop takes self by value
conn: Option<PostgresConnection>
}
impl Drop for PooledPostgresConnection {
fn drop(&mut self) |
}
impl Deref<PostgresConnection> for PooledPostgresConnection {
fn deref<'a>(&'a self) -> &'a PostgresConnection {
self.conn.as_ref().unwrap()
}
}
| {
let mut pool = self.pool.pool.lock();
pool.pool.push(self.conn.take().unwrap());
pool.cond.signal();
} |
numeric-constants.go | package main
import "fmt"
const (
// 将1左移100位来创建一个非常大的数字,2^100
// 即这个数的二进制是1后面跟着100个0
Big = 1 << 100
// 再往右移99位,即Small = 1 << 1, 或者说Small = 2 |
func needInt(x int) int {
return x*10 + 1
}
func needFloat(x float64) float64 {
return x*0.1
}
func main() {
fmt.Println(needInt(Small))
fmt.Println(needFloat(Small))
// fmt.Println("Big = %e", Big)
fmt.Println(needFloat(Big))
// fmt.Println(needInt(Big)) // overflows int
} | Small = Big >> 99
) |
vision-gen.go | // Copyright 2021 Google LLC.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Code generated file. DO NOT EDIT.
// Package vision provides access to the Cloud Vision API.
//
// This package is DEPRECATED. Use package cloud.google.com/go/vision/apiv1 instead.
//
// For product documentation, see: https://cloud.google.com/vision/
//
// Creating a client
//
// Usage example:
//
// import "google.golang.org/api/vision/v1"
// ...
// ctx := context.Background()
// visionService, err := vision.NewService(ctx)
//
// In this example, Google Application Default Credentials are used for authentication.
//
// For information on how to create and obtain Application Default Credentials, see https://developers.google.com/identity/protocols/application-default-credentials.
//
// Other authentication options
//
// By default, all available scopes (see "Constants") are used to authenticate. To restrict scopes, use option.WithScopes:
//
// visionService, err := vision.NewService(ctx, option.WithScopes(vision.CloudVisionScope))
//
// To use an API key for authentication (note: some APIs do not support API keys), use option.WithAPIKey:
//
// visionService, err := vision.NewService(ctx, option.WithAPIKey("AIza..."))
//
// To use an OAuth token (e.g., a user token obtained via a three-legged OAuth flow), use option.WithTokenSource:
//
// config := &oauth2.Config{...}
// // ...
// token, err := config.Exchange(ctx, ...)
// visionService, err := vision.NewService(ctx, option.WithTokenSource(config.TokenSource(ctx, token)))
//
// See https://godoc.org/google.golang.org/api/option/ for details on options.
package vision // import "google.golang.org/api/vision/v1"
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
googleapi "google.golang.org/api/googleapi"
gensupport "google.golang.org/api/internal/gensupport"
option "google.golang.org/api/option"
internaloption "google.golang.org/api/option/internaloption"
htransport "google.golang.org/api/transport/http"
)
// Always reference these packages, just in case the auto-generated code
// below doesn't.
var _ = bytes.NewBuffer
var _ = strconv.Itoa
var _ = fmt.Sprintf
var _ = json.NewDecoder
var _ = io.Copy
var _ = url.Parse
var _ = gensupport.MarshalJSON
var _ = googleapi.Version
var _ = errors.New
var _ = strings.Replace
var _ = context.Canceled
var _ = internaloption.WithDefaultEndpoint
const apiId = "vision:v1"
const apiName = "vision"
const apiVersion = "v1"
const basePath = "https://vision.googleapis.com/"
const mtlsBasePath = "https://vision.mtls.googleapis.com/"
// OAuth2 scopes used by this API.
const (
// See, edit, configure, and delete your Google Cloud data and see the
// email address for your Google Account.
CloudPlatformScope = "https://www.googleapis.com/auth/cloud-platform"
// Apply machine learning models to understand and label images
CloudVisionScope = "https://www.googleapis.com/auth/cloud-vision"
)
// NewService creates a new Service.
func NewService(ctx context.Context, opts ...option.ClientOption) (*Service, error) {
scopesOption := option.WithScopes(
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-vision",
)
// NOTE: prepend, so we don't override user-specified scopes.
opts = append([]option.ClientOption{scopesOption}, opts...)
opts = append(opts, internaloption.WithDefaultEndpoint(basePath))
opts = append(opts, internaloption.WithDefaultMTLSEndpoint(mtlsBasePath))
client, endpoint, err := htransport.NewClient(ctx, opts...)
if err != nil {
return nil, err
}
s, err := New(client)
if err != nil {
return nil, err
}
if endpoint != "" {
s.BasePath = endpoint
}
return s, nil
}
// New creates a new Service. It uses the provided http.Client for requests.
//
// Deprecated: please use NewService instead.
// To provide a custom HTTP client, use option.WithHTTPClient.
// If you are using google.golang.org/api/googleapis/transport.APIKey, use option.WithAPIKey with NewService instead.
func New(client *http.Client) (*Service, error) {
if client == nil {
return nil, errors.New("client is nil")
}
s := &Service{client: client, BasePath: basePath}
s.Files = NewFilesService(s)
s.Images = NewImagesService(s)
s.Locations = NewLocationsService(s)
s.Operations = NewOperationsService(s)
s.Projects = NewProjectsService(s)
return s, nil
}
type Service struct {
client *http.Client
BasePath string // API endpoint base URL
UserAgent string // optional additional User-Agent fragment
Files *FilesService
Images *ImagesService
Locations *LocationsService
Operations *OperationsService
Projects *ProjectsService
}
func (s *Service) userAgent() string {
if s.UserAgent == "" {
return googleapi.UserAgent
}
return googleapi.UserAgent + " " + s.UserAgent
}
func NewFilesService(s *Service) *FilesService {
rs := &FilesService{s: s}
return rs
}
type FilesService struct {
s *Service
}
func NewImagesService(s *Service) *ImagesService {
rs := &ImagesService{s: s}
return rs
}
type ImagesService struct {
s *Service
}
func NewLocationsService(s *Service) *LocationsService {
rs := &LocationsService{s: s}
rs.Operations = NewLocationsOperationsService(s)
return rs
}
type LocationsService struct {
s *Service
Operations *LocationsOperationsService
}
func NewLocationsOperationsService(s *Service) *LocationsOperationsService {
rs := &LocationsOperationsService{s: s}
return rs
}
type LocationsOperationsService struct {
s *Service
}
func NewOperationsService(s *Service) *OperationsService {
rs := &OperationsService{s: s}
return rs
}
type OperationsService struct {
s *Service
}
func NewProjectsService(s *Service) *ProjectsService {
rs := &ProjectsService{s: s}
rs.Files = NewProjectsFilesService(s)
rs.Images = NewProjectsImagesService(s)
rs.Locations = NewProjectsLocationsService(s)
rs.Operations = NewProjectsOperationsService(s)
return rs
}
type ProjectsService struct {
s *Service
Files *ProjectsFilesService
Images *ProjectsImagesService
Locations *ProjectsLocationsService
Operations *ProjectsOperationsService
}
func NewProjectsFilesService(s *Service) *ProjectsFilesService {
rs := &ProjectsFilesService{s: s}
return rs
}
type ProjectsFilesService struct {
s *Service
}
func NewProjectsImagesService(s *Service) *ProjectsImagesService {
rs := &ProjectsImagesService{s: s}
return rs
}
type ProjectsImagesService struct {
s *Service
}
func NewProjectsLocationsService(s *Service) *ProjectsLocationsService {
rs := &ProjectsLocationsService{s: s}
rs.Files = NewProjectsLocationsFilesService(s)
rs.Images = NewProjectsLocationsImagesService(s)
rs.Operations = NewProjectsLocationsOperationsService(s)
rs.ProductSets = NewProjectsLocationsProductSetsService(s)
rs.Products = NewProjectsLocationsProductsService(s)
return rs
}
type ProjectsLocationsService struct {
s *Service
Files *ProjectsLocationsFilesService
Images *ProjectsLocationsImagesService
Operations *ProjectsLocationsOperationsService
ProductSets *ProjectsLocationsProductSetsService
Products *ProjectsLocationsProductsService
}
func NewProjectsLocationsFilesService(s *Service) *ProjectsLocationsFilesService {
rs := &ProjectsLocationsFilesService{s: s}
return rs
}
type ProjectsLocationsFilesService struct {
s *Service
}
func NewProjectsLocationsImagesService(s *Service) *ProjectsLocationsImagesService {
rs := &ProjectsLocationsImagesService{s: s}
return rs
}
type ProjectsLocationsImagesService struct {
s *Service
}
func NewProjectsLocationsOperationsService(s *Service) *ProjectsLocationsOperationsService {
rs := &ProjectsLocationsOperationsService{s: s}
return rs
}
type ProjectsLocationsOperationsService struct {
s *Service
}
func NewProjectsLocationsProductSetsService(s *Service) *ProjectsLocationsProductSetsService |
type ProjectsLocationsProductSetsService struct {
s *Service
Products *ProjectsLocationsProductSetsProductsService
}
func NewProjectsLocationsProductSetsProductsService(s *Service) *ProjectsLocationsProductSetsProductsService {
rs := &ProjectsLocationsProductSetsProductsService{s: s}
return rs
}
type ProjectsLocationsProductSetsProductsService struct {
s *Service
}
func NewProjectsLocationsProductsService(s *Service) *ProjectsLocationsProductsService {
rs := &ProjectsLocationsProductsService{s: s}
rs.ReferenceImages = NewProjectsLocationsProductsReferenceImagesService(s)
return rs
}
type ProjectsLocationsProductsService struct {
s *Service
ReferenceImages *ProjectsLocationsProductsReferenceImagesService
}
func NewProjectsLocationsProductsReferenceImagesService(s *Service) *ProjectsLocationsProductsReferenceImagesService {
rs := &ProjectsLocationsProductsReferenceImagesService{s: s}
return rs
}
type ProjectsLocationsProductsReferenceImagesService struct {
s *Service
}
func NewProjectsOperationsService(s *Service) *ProjectsOperationsService {
rs := &ProjectsOperationsService{s: s}
return rs
}
type ProjectsOperationsService struct {
s *Service
}
// AddProductToProductSetRequest: Request message for the
// `AddProductToProductSet` method.
type AddProductToProductSetRequest struct {
// Product: Required. The resource name for the Product to be added to
// this ProductSet. Format is:
// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`
Product string `json:"product,omitempty"`
// ForceSendFields is a list of field names (e.g. "Product") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Product") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *AddProductToProductSetRequest) MarshalJSON() ([]byte, error) {
type NoMethod AddProductToProductSetRequest
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// AnnotateFileRequest: A request to annotate one single file, e.g. a
// PDF, TIFF or GIF file.
type AnnotateFileRequest struct {
// Features: Required. Requested features.
Features []*Feature `json:"features,omitempty"`
// ImageContext: Additional context that may accompany the image(s) in
// the file.
ImageContext *ImageContext `json:"imageContext,omitempty"`
// InputConfig: Required. Information about the input file.
InputConfig *InputConfig `json:"inputConfig,omitempty"`
// Pages: Pages of the file to perform image annotation. Pages starts
// from 1, we assume the first page of the file is page 1. At most 5
// pages are supported per request. Pages can be negative. Page 1 means
// the first page. Page 2 means the second page. Page -1 means the last
// page. Page -2 means the second to the last page. If the file is GIF
// instead of PDF or TIFF, page refers to GIF frames. If this field is
// empty, by default the service performs image annotation for the first
// 5 pages of the file.
Pages []int64 `json:"pages,omitempty"`
// ForceSendFields is a list of field names (e.g. "Features") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Features") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *AnnotateFileRequest) MarshalJSON() ([]byte, error) {
type NoMethod AnnotateFileRequest
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// AnnotateFileResponse: Response to a single file annotation request. A
// file may contain one or more images, which individually have their
// own responses.
type AnnotateFileResponse struct {
// Error: If set, represents the error message for the failed request.
// The `responses` field will not be set in this case.
Error *Status `json:"error,omitempty"`
// InputConfig: Information about the file for which this response is
// generated.
InputConfig *InputConfig `json:"inputConfig,omitempty"`
// Responses: Individual responses to images found within the file. This
// field will be empty if the `error` field is set.
Responses []*AnnotateImageResponse `json:"responses,omitempty"`
// TotalPages: This field gives the total number of pages in the file.
TotalPages int64 `json:"totalPages,omitempty"`
// ForceSendFields is a list of field names (e.g. "Error") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Error") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *AnnotateFileResponse) MarshalJSON() ([]byte, error) {
type NoMethod AnnotateFileResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// AnnotateImageRequest: Request for performing Google Cloud Vision API
// tasks over a user-provided image, with user-requested features, and
// with context information.
type AnnotateImageRequest struct {
// Features: Requested features.
Features []*Feature `json:"features,omitempty"`
// Image: The image to be processed.
Image *Image `json:"image,omitempty"`
// ImageContext: Additional context that may accompany the image.
ImageContext *ImageContext `json:"imageContext,omitempty"`
// ForceSendFields is a list of field names (e.g. "Features") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Features") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *AnnotateImageRequest) MarshalJSON() ([]byte, error) {
type NoMethod AnnotateImageRequest
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// AnnotateImageResponse: Response to an image annotation request.
type AnnotateImageResponse struct {
// Context: If present, contextual information is needed to understand
// where this image comes from.
Context *ImageAnnotationContext `json:"context,omitempty"`
// CropHintsAnnotation: If present, crop hints have completed
// successfully.
CropHintsAnnotation *CropHintsAnnotation `json:"cropHintsAnnotation,omitempty"`
// Error: If set, represents the error message for the operation. Note
// that filled-in image annotations are guaranteed to be correct, even
// when `error` is set.
Error *Status `json:"error,omitempty"`
// FaceAnnotations: If present, face detection has completed
// successfully.
FaceAnnotations []*FaceAnnotation `json:"faceAnnotations,omitempty"`
// FullTextAnnotation: If present, text (OCR) detection or document
// (OCR) text detection has completed successfully. This annotation
// provides the structural hierarchy for the OCR detected text.
FullTextAnnotation *TextAnnotation `json:"fullTextAnnotation,omitempty"`
// ImagePropertiesAnnotation: If present, image properties were
// extracted successfully.
ImagePropertiesAnnotation *ImageProperties `json:"imagePropertiesAnnotation,omitempty"`
// LabelAnnotations: If present, label detection has completed
// successfully.
LabelAnnotations []*EntityAnnotation `json:"labelAnnotations,omitempty"`
// LandmarkAnnotations: If present, landmark detection has completed
// successfully.
LandmarkAnnotations []*EntityAnnotation `json:"landmarkAnnotations,omitempty"`
// LocalizedObjectAnnotations: If present, localized object detection
// has completed successfully. This will be sorted descending by
// confidence score.
LocalizedObjectAnnotations []*LocalizedObjectAnnotation `json:"localizedObjectAnnotations,omitempty"`
// LogoAnnotations: If present, logo detection has completed
// successfully.
LogoAnnotations []*EntityAnnotation `json:"logoAnnotations,omitempty"`
// ProductSearchResults: If present, product search has completed
// successfully.
ProductSearchResults *ProductSearchResults `json:"productSearchResults,omitempty"`
// SafeSearchAnnotation: If present, safe-search annotation has
// completed successfully.
SafeSearchAnnotation *SafeSearchAnnotation `json:"safeSearchAnnotation,omitempty"`
// TextAnnotations: If present, text (OCR) detection has completed
// successfully.
TextAnnotations []*EntityAnnotation `json:"textAnnotations,omitempty"`
// WebDetection: If present, web detection has completed successfully.
WebDetection *WebDetection `json:"webDetection,omitempty"`
// ForceSendFields is a list of field names (e.g. "Context") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Context") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *AnnotateImageResponse) MarshalJSON() ([]byte, error) {
type NoMethod AnnotateImageResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// AsyncAnnotateFileRequest: An offline file annotation request.
type AsyncAnnotateFileRequest struct {
// Features: Required. Requested features.
Features []*Feature `json:"features,omitempty"`
// ImageContext: Additional context that may accompany the image(s) in
// the file.
ImageContext *ImageContext `json:"imageContext,omitempty"`
// InputConfig: Required. Information about the input file.
InputConfig *InputConfig `json:"inputConfig,omitempty"`
// OutputConfig: Required. The desired output location and metadata
// (e.g. format).
OutputConfig *OutputConfig `json:"outputConfig,omitempty"`
// ForceSendFields is a list of field names (e.g. "Features") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Features") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *AsyncAnnotateFileRequest) MarshalJSON() ([]byte, error) {
type NoMethod AsyncAnnotateFileRequest
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// AsyncAnnotateFileResponse: The response for a single offline file
// annotation request.
type AsyncAnnotateFileResponse struct {
// OutputConfig: The output location and metadata from
// AsyncAnnotateFileRequest.
OutputConfig *OutputConfig `json:"outputConfig,omitempty"`
// ForceSendFields is a list of field names (e.g. "OutputConfig") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "OutputConfig") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *AsyncAnnotateFileResponse) MarshalJSON() ([]byte, error) {
type NoMethod AsyncAnnotateFileResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// AsyncBatchAnnotateFilesRequest: Multiple async file annotation
// requests are batched into a single service call.
type AsyncBatchAnnotateFilesRequest struct {
// Parent: Optional. Target project and location to make a call. Format:
// `projects/{project-id}/locations/{location-id}`. If no parent is
// specified, a region will be chosen automatically. Supported
// location-ids: `us`: USA country only, `asia`: East asia areas, like
// Japan, Taiwan, `eu`: The European Union. Example:
// `projects/project-A/locations/eu`.
Parent string `json:"parent,omitempty"`
// Requests: Required. Individual async file annotation requests for
// this batch.
Requests []*AsyncAnnotateFileRequest `json:"requests,omitempty"`
// ForceSendFields is a list of field names (e.g. "Parent") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Parent") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *AsyncBatchAnnotateFilesRequest) MarshalJSON() ([]byte, error) {
type NoMethod AsyncBatchAnnotateFilesRequest
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// AsyncBatchAnnotateFilesResponse: Response to an async batch file
// annotation request.
type AsyncBatchAnnotateFilesResponse struct {
// Responses: The list of file annotation responses, one for each
// request in AsyncBatchAnnotateFilesRequest.
Responses []*AsyncAnnotateFileResponse `json:"responses,omitempty"`
// ForceSendFields is a list of field names (e.g. "Responses") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Responses") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *AsyncBatchAnnotateFilesResponse) MarshalJSON() ([]byte, error) {
type NoMethod AsyncBatchAnnotateFilesResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// AsyncBatchAnnotateImagesRequest: Request for async image annotation
// for a list of images.
type AsyncBatchAnnotateImagesRequest struct {
// OutputConfig: Required. The desired output location and metadata
// (e.g. format).
OutputConfig *OutputConfig `json:"outputConfig,omitempty"`
// Parent: Optional. Target project and location to make a call. Format:
// `projects/{project-id}/locations/{location-id}`. If no parent is
// specified, a region will be chosen automatically. Supported
// location-ids: `us`: USA country only, `asia`: East asia areas, like
// Japan, Taiwan, `eu`: The European Union. Example:
// `projects/project-A/locations/eu`.
Parent string `json:"parent,omitempty"`
// Requests: Required. Individual image annotation requests for this
// batch.
Requests []*AnnotateImageRequest `json:"requests,omitempty"`
// ForceSendFields is a list of field names (e.g. "OutputConfig") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "OutputConfig") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *AsyncBatchAnnotateImagesRequest) MarshalJSON() ([]byte, error) {
type NoMethod AsyncBatchAnnotateImagesRequest
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// AsyncBatchAnnotateImagesResponse: Response to an async batch image
// annotation request.
type AsyncBatchAnnotateImagesResponse struct {
// OutputConfig: The output location and metadata from
// AsyncBatchAnnotateImagesRequest.
OutputConfig *OutputConfig `json:"outputConfig,omitempty"`
// ForceSendFields is a list of field names (e.g. "OutputConfig") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "OutputConfig") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *AsyncBatchAnnotateImagesResponse) MarshalJSON() ([]byte, error) {
type NoMethod AsyncBatchAnnotateImagesResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// BatchAnnotateFilesRequest: A list of requests to annotate files using
// the BatchAnnotateFiles API.
type BatchAnnotateFilesRequest struct {
// Parent: Optional. Target project and location to make a call. Format:
// `projects/{project-id}/locations/{location-id}`. If no parent is
// specified, a region will be chosen automatically. Supported
// location-ids: `us`: USA country only, `asia`: East asia areas, like
// Japan, Taiwan, `eu`: The European Union. Example:
// `projects/project-A/locations/eu`.
Parent string `json:"parent,omitempty"`
// Requests: Required. The list of file annotation requests. Right now
// we support only one AnnotateFileRequest in BatchAnnotateFilesRequest.
Requests []*AnnotateFileRequest `json:"requests,omitempty"`
// ForceSendFields is a list of field names (e.g. "Parent") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Parent") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *BatchAnnotateFilesRequest) MarshalJSON() ([]byte, error) {
type NoMethod BatchAnnotateFilesRequest
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// BatchAnnotateFilesResponse: A list of file annotation responses.
type BatchAnnotateFilesResponse struct {
// Responses: The list of file annotation responses, each response
// corresponding to each AnnotateFileRequest in
// BatchAnnotateFilesRequest.
Responses []*AnnotateFileResponse `json:"responses,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Responses") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Responses") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *BatchAnnotateFilesResponse) MarshalJSON() ([]byte, error) {
type NoMethod BatchAnnotateFilesResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// BatchAnnotateImagesRequest: Multiple image annotation requests are
// batched into a single service call.
type BatchAnnotateImagesRequest struct {
// Parent: Optional. Target project and location to make a call. Format:
// `projects/{project-id}/locations/{location-id}`. If no parent is
// specified, a region will be chosen automatically. Supported
// location-ids: `us`: USA country only, `asia`: East asia areas, like
// Japan, Taiwan, `eu`: The European Union. Example:
// `projects/project-A/locations/eu`.
Parent string `json:"parent,omitempty"`
// Requests: Required. Individual image annotation requests for this
// batch.
Requests []*AnnotateImageRequest `json:"requests,omitempty"`
// ForceSendFields is a list of field names (e.g. "Parent") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Parent") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *BatchAnnotateImagesRequest) MarshalJSON() ([]byte, error) {
type NoMethod BatchAnnotateImagesRequest
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// BatchAnnotateImagesResponse: Response to a batch image annotation
// request.
type BatchAnnotateImagesResponse struct {
// Responses: Individual responses to image annotation requests within
// the batch.
Responses []*AnnotateImageResponse `json:"responses,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Responses") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Responses") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *BatchAnnotateImagesResponse) MarshalJSON() ([]byte, error) {
type NoMethod BatchAnnotateImagesResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// BatchOperationMetadata: Metadata for the batch operations such as the
// current state. This is included in the `metadata` field of the
// `Operation` returned by the `GetOperation` call of the
// `google::longrunning::Operations` service.
type BatchOperationMetadata struct {
// EndTime: The time when the batch request is finished and
// google.longrunning.Operation.done is set to true.
EndTime string `json:"endTime,omitempty"`
// State: The current state of the batch operation.
//
// Possible values:
// "STATE_UNSPECIFIED" - Invalid.
// "PROCESSING" - Request is actively being processed.
// "SUCCESSFUL" - The request is done and at least one item has been
// successfully processed.
// "FAILED" - The request is done and no item has been successfully
// processed.
// "CANCELLED" - The request is done after the
// longrunning.Operations.CancelOperation has been called by the user.
// Any records that were processed before the cancel command are output
// as specified in the request.
State string `json:"state,omitempty"`
// SubmitTime: The time when the batch request was submitted to the
// server.
SubmitTime string `json:"submitTime,omitempty"`
// ForceSendFields is a list of field names (e.g. "EndTime") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "EndTime") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *BatchOperationMetadata) MarshalJSON() ([]byte, error) {
type NoMethod BatchOperationMetadata
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Block: Logical element on the page.
type Block struct {
// BlockType: Detected block type (text, image etc) for this block.
//
// Possible values:
// "UNKNOWN" - Unknown block type.
// "TEXT" - Regular text block.
// "TABLE" - Table block.
// "PICTURE" - Image block.
// "RULER" - Horizontal/vertical line box.
// "BARCODE" - Barcode block.
BlockType string `json:"blockType,omitempty"`
// BoundingBox: The bounding box for the block. The vertices are in the
// order of top-left, top-right, bottom-right, bottom-left. When a
// rotation of the bounding box is detected the rotation is represented
// as around the top-left corner as defined when the text is read in the
// 'natural' orientation. For example: * when the text is horizontal it
// might look like: 0----1 | | 3----2 * when it's rotated 180 degrees
// around the top-left corner it becomes: 2----3 | | 1----0 and the
// vertex order will still be (0, 1, 2, 3).
BoundingBox *BoundingPoly `json:"boundingBox,omitempty"`
// Confidence: Confidence of the OCR results on the block. Range [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// Paragraphs: List of paragraphs in this block (if this blocks is of
// type text).
Paragraphs []*Paragraph `json:"paragraphs,omitempty"`
// Property: Additional information detected for the block.
Property *TextProperty `json:"property,omitempty"`
// ForceSendFields is a list of field names (e.g. "BlockType") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BlockType") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Block) MarshalJSON() ([]byte, error) {
type NoMethod Block
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *Block) UnmarshalJSON(data []byte) error {
type NoMethod Block
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
return nil
}
// BoundingPoly: A bounding polygon for the detected image annotation.
type BoundingPoly struct {
// NormalizedVertices: The bounding polygon normalized vertices.
NormalizedVertices []*NormalizedVertex `json:"normalizedVertices,omitempty"`
// Vertices: The bounding polygon vertices.
Vertices []*Vertex `json:"vertices,omitempty"`
// ForceSendFields is a list of field names (e.g. "NormalizedVertices")
// to unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "NormalizedVertices") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *BoundingPoly) MarshalJSON() ([]byte, error) {
type NoMethod BoundingPoly
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// CancelOperationRequest: The request message for
// Operations.CancelOperation.
type CancelOperationRequest struct {
}
// Color: Represents a color in the RGBA color space. This
// representation is designed for simplicity of conversion to/from color
// representations in various languages over compactness. For example,
// the fields of this representation can be trivially provided to the
// constructor of `java.awt.Color` in Java; it can also be trivially
// provided to UIColor's `+colorWithRed:green:blue:alpha` method in iOS;
// and, with just a little work, it can be easily formatted into a CSS
// `rgba()` string in JavaScript. This reference page doesn't carry
// information about the absolute color space that should be used to
// interpret the RGB value (e.g. sRGB, Adobe RGB, DCI-P3, BT.2020,
// etc.). By default, applications should assume the sRGB color space.
// When color equality needs to be decided, implementations, unless
// documented otherwise, treat two colors as equal if all their red,
// green, blue, and alpha values each differ by at most 1e-5. Example
// (Java): import com.google.type.Color; // ... public static
// java.awt.Color fromProto(Color protocolor) { float alpha =
// protocolor.hasAlpha() ? protocolor.getAlpha().getValue() : 1.0;
// return new java.awt.Color( protocolor.getRed(),
// protocolor.getGreen(), protocolor.getBlue(), alpha); } public static
// Color toProto(java.awt.Color color) { float red = (float)
// color.getRed(); float green = (float) color.getGreen(); float blue =
// (float) color.getBlue(); float denominator = 255.0; Color.Builder
// resultBuilder = Color .newBuilder() .setRed(red / denominator)
// .setGreen(green / denominator) .setBlue(blue / denominator); int
// alpha = color.getAlpha(); if (alpha != 255) { result.setAlpha(
// FloatValue .newBuilder() .setValue(((float) alpha) / denominator)
// .build()); } return resultBuilder.build(); } // ... Example (iOS /
// Obj-C): // ... static UIColor* fromProto(Color* protocolor) { float
// red = [protocolor red]; float green = [protocolor green]; float blue
// = [protocolor blue]; FloatValue* alpha_wrapper = [protocolor alpha];
// float alpha = 1.0; if (alpha_wrapper != nil) { alpha = [alpha_wrapper
// value]; } return [UIColor colorWithRed:red green:green blue:blue
// alpha:alpha]; } static Color* toProto(UIColor* color) { CGFloat red,
// green, blue, alpha; if (![color getRed:&red green:&green blue:&blue
// alpha:&alpha]) { return nil; } Color* result = [[Color alloc] init];
// [result setRed:red]; [result setGreen:green]; [result setBlue:blue];
// if (alpha <= 0.9999) { [result
// setAlpha:floatWrapperWithValue(alpha)]; } [result autorelease];
// return result; } // ... Example (JavaScript): // ... var
// protoToCssColor = function(rgb_color) { var redFrac = rgb_color.red
// || 0.0; var greenFrac = rgb_color.green || 0.0; var blueFrac =
// rgb_color.blue || 0.0; var red = Math.floor(redFrac * 255); var green
// = Math.floor(greenFrac * 255); var blue = Math.floor(blueFrac * 255);
// if (!('alpha' in rgb_color)) { return rgbToCssColor(red, green,
// blue); } var alphaFrac = rgb_color.alpha.value || 0.0; var rgbParams
// = [red, green, blue].join(','); return ['rgba(', rgbParams, ',',
// alphaFrac, ')'].join(''); }; var rgbToCssColor = function(red, green,
// blue) { var rgbNumber = new Number((red << 16) | (green << 8) |
// blue); var hexString = rgbNumber.toString(16); var missingZeros = 6 -
// hexString.length; var resultBuilder = ['#']; for (var i = 0; i <
// missingZeros; i++) { resultBuilder.push('0'); }
// resultBuilder.push(hexString); return resultBuilder.join(''); }; //
// ...
type Color struct {
// Alpha: The fraction of this color that should be applied to the
// pixel. That is, the final pixel color is defined by the equation:
// `pixel color = alpha * (this color) + (1.0 - alpha) * (background
// color)` This means that a value of 1.0 corresponds to a solid color,
// whereas a value of 0.0 corresponds to a completely transparent color.
// This uses a wrapper message rather than a simple float scalar so that
// it is possible to distinguish between a default value and the value
// being unset. If omitted, this color object is rendered as a solid
// color (as if the alpha value had been explicitly given a value of
// 1.0).
Alpha float64 `json:"alpha,omitempty"`
// Blue: The amount of blue in the color as a value in the interval [0,
// 1].
Blue float64 `json:"blue,omitempty"`
// Green: The amount of green in the color as a value in the interval
// [0, 1].
Green float64 `json:"green,omitempty"`
// Red: The amount of red in the color as a value in the interval [0,
// 1].
Red float64 `json:"red,omitempty"`
// ForceSendFields is a list of field names (e.g. "Alpha") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Alpha") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Color) MarshalJSON() ([]byte, error) {
type NoMethod Color
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *Color) UnmarshalJSON(data []byte) error {
type NoMethod Color
var s1 struct {
Alpha gensupport.JSONFloat64 `json:"alpha"`
Blue gensupport.JSONFloat64 `json:"blue"`
Green gensupport.JSONFloat64 `json:"green"`
Red gensupport.JSONFloat64 `json:"red"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Alpha = float64(s1.Alpha)
s.Blue = float64(s1.Blue)
s.Green = float64(s1.Green)
s.Red = float64(s1.Red)
return nil
}
// ColorInfo: Color information consists of RGB channels, score, and the
// fraction of the image that the color occupies in the image.
type ColorInfo struct {
// Color: RGB components of the color.
Color *Color `json:"color,omitempty"`
// PixelFraction: The fraction of pixels the color occupies in the
// image. Value in range [0, 1].
PixelFraction float64 `json:"pixelFraction,omitempty"`
// Score: Image-specific score for this color. Value in range [0, 1].
Score float64 `json:"score,omitempty"`
// ForceSendFields is a list of field names (e.g. "Color") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Color") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ColorInfo) MarshalJSON() ([]byte, error) {
type NoMethod ColorInfo
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *ColorInfo) UnmarshalJSON(data []byte) error {
type NoMethod ColorInfo
var s1 struct {
PixelFraction gensupport.JSONFloat64 `json:"pixelFraction"`
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.PixelFraction = float64(s1.PixelFraction)
s.Score = float64(s1.Score)
return nil
}
// CropHint: Single crop hint that is used to generate a new crop when
// serving an image.
type CropHint struct {
// BoundingPoly: The bounding polygon for the crop region. The
// coordinates of the bounding box are in the original image's scale.
BoundingPoly *BoundingPoly `json:"boundingPoly,omitempty"`
// Confidence: Confidence of this being a salient region. Range [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// ImportanceFraction: Fraction of importance of this salient region
// with respect to the original image.
ImportanceFraction float64 `json:"importanceFraction,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingPoly") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingPoly") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *CropHint) MarshalJSON() ([]byte, error) {
type NoMethod CropHint
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *CropHint) UnmarshalJSON(data []byte) error {
type NoMethod CropHint
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
ImportanceFraction gensupport.JSONFloat64 `json:"importanceFraction"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
s.ImportanceFraction = float64(s1.ImportanceFraction)
return nil
}
// CropHintsAnnotation: Set of crop hints that are used to generate new
// crops when serving images.
type CropHintsAnnotation struct {
// CropHints: Crop hint results.
CropHints []*CropHint `json:"cropHints,omitempty"`
// ForceSendFields is a list of field names (e.g. "CropHints") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CropHints") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *CropHintsAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod CropHintsAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// CropHintsParams: Parameters for crop hints annotation request.
type CropHintsParams struct {
// AspectRatios: Aspect ratios in floats, representing the ratio of the
// width to the height of the image. For example, if the desired aspect
// ratio is 4/3, the corresponding float value should be 1.33333. If not
// specified, the best possible crop is returned. The number of provided
// aspect ratios is limited to a maximum of 16; any aspect ratios
// provided after the 16th are ignored.
AspectRatios []float64 `json:"aspectRatios,omitempty"`
// ForceSendFields is a list of field names (e.g. "AspectRatios") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "AspectRatios") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *CropHintsParams) MarshalJSON() ([]byte, error) {
type NoMethod CropHintsParams
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// DetectedBreak: Detected start or end of a structural component.
type DetectedBreak struct {
// IsPrefix: True if break prepends the element.
IsPrefix bool `json:"isPrefix,omitempty"`
// Type: Detected break type.
//
// Possible values:
// "UNKNOWN" - Unknown break label type.
// "SPACE" - Regular space.
// "SURE_SPACE" - Sure space (very wide).
// "EOL_SURE_SPACE" - Line-wrapping break.
// "HYPHEN" - End-line hyphen that is not present in text; does not
// co-occur with `SPACE`, `LEADER_SPACE`, or `LINE_BREAK`.
// "LINE_BREAK" - Line break that ends a paragraph.
Type string `json:"type,omitempty"`
// ForceSendFields is a list of field names (e.g. "IsPrefix") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "IsPrefix") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *DetectedBreak) MarshalJSON() ([]byte, error) {
type NoMethod DetectedBreak
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// DetectedLanguage: Detected language for a structural component.
type DetectedLanguage struct {
// Confidence: Confidence of detected language. Range [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// LanguageCode: The BCP-47 language code, such as "en-US" or "sr-Latn".
// For more information, see
// http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
LanguageCode string `json:"languageCode,omitempty"`
// ForceSendFields is a list of field names (e.g. "Confidence") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Confidence") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *DetectedLanguage) MarshalJSON() ([]byte, error) {
type NoMethod DetectedLanguage
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *DetectedLanguage) UnmarshalJSON(data []byte) error {
type NoMethod DetectedLanguage
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
return nil
}
// DominantColorsAnnotation: Set of dominant colors and their
// corresponding scores.
type DominantColorsAnnotation struct {
// Colors: RGB color values with their score and pixel fraction.
Colors []*ColorInfo `json:"colors,omitempty"`
// ForceSendFields is a list of field names (e.g. "Colors") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Colors") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *DominantColorsAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod DominantColorsAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Empty: A generic empty message that you can re-use to avoid defining
// duplicated empty messages in your APIs. A typical example is to use
// it as the request or the response type of an API method. For
// instance: service Foo { rpc Bar(google.protobuf.Empty) returns
// (google.protobuf.Empty); } The JSON representation for `Empty` is
// empty JSON object `{}`.
type Empty struct {
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
}
// EntityAnnotation: Set of detected entity features.
type EntityAnnotation struct {
// BoundingPoly: Image region to which this entity belongs. Not produced
// for `LABEL_DETECTION` features.
BoundingPoly *BoundingPoly `json:"boundingPoly,omitempty"`
// Confidence: **Deprecated. Use `score` instead.** The accuracy of the
// entity detection in an image. For example, for an image in which the
// "Eiffel Tower" entity is detected, this field represents the
// confidence that there is a tower in the query image. Range [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// Description: Entity textual description, expressed in its `locale`
// language.
Description string `json:"description,omitempty"`
// Locale: The language code for the locale in which the entity textual
// `description` is expressed.
Locale string `json:"locale,omitempty"`
// Locations: The location information for the detected entity. Multiple
// `LocationInfo` elements can be present because one location may
// indicate the location of the scene in the image, and another location
// may indicate the location of the place where the image was taken.
// Location information is usually present for landmarks.
Locations []*LocationInfo `json:"locations,omitempty"`
// Mid: Opaque entity ID. Some IDs may be available in Google Knowledge
// Graph Search API (https://developers.google.com/knowledge-graph/).
Mid string `json:"mid,omitempty"`
// Properties: Some entities may have optional user-supplied `Property`
// (name/value) fields, such a score or string that qualifies the
// entity.
Properties []*Property `json:"properties,omitempty"`
// Score: Overall score of the result. Range [0, 1].
Score float64 `json:"score,omitempty"`
// Topicality: The relevancy of the ICA (Image Content Annotation) label
// to the image. For example, the relevancy of "tower" is likely higher
// to an image containing the detected "Eiffel Tower" than to an image
// containing a detected distant towering building, even though the
// confidence that there is a tower in each image may be the same. Range
// [0, 1].
Topicality float64 `json:"topicality,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingPoly") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingPoly") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *EntityAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod EntityAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *EntityAnnotation) UnmarshalJSON(data []byte) error {
type NoMethod EntityAnnotation
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
Score gensupport.JSONFloat64 `json:"score"`
Topicality gensupport.JSONFloat64 `json:"topicality"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
s.Score = float64(s1.Score)
s.Topicality = float64(s1.Topicality)
return nil
}
// FaceAnnotation: A face annotation object contains the results of face
// detection.
type FaceAnnotation struct {
// AngerLikelihood: Anger likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
AngerLikelihood string `json:"angerLikelihood,omitempty"`
// BlurredLikelihood: Blurred likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
BlurredLikelihood string `json:"blurredLikelihood,omitempty"`
// BoundingPoly: The bounding polygon around the face. The coordinates
// of the bounding box are in the original image's scale. The bounding
// box is computed to "frame" the face in accordance with human
// expectations. It is based on the landmarker results. Note that one or
// more x and/or y coordinates may not be generated in the
// `BoundingPoly` (the polygon will be unbounded) if only a partial face
// appears in the image to be annotated.
BoundingPoly *BoundingPoly `json:"boundingPoly,omitempty"`
// DetectionConfidence: Detection confidence. Range [0, 1].
DetectionConfidence float64 `json:"detectionConfidence,omitempty"`
// FdBoundingPoly: The `fd_bounding_poly` bounding polygon is tighter
// than the `boundingPoly`, and encloses only the skin part of the face.
// Typically, it is used to eliminate the face from any image analysis
// that detects the "amount of skin" visible in an image. It is not
// based on the landmarker results, only on the initial face detection,
// hence the fd (face detection) prefix.
FdBoundingPoly *BoundingPoly `json:"fdBoundingPoly,omitempty"`
// HeadwearLikelihood: Headwear likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
HeadwearLikelihood string `json:"headwearLikelihood,omitempty"`
// JoyLikelihood: Joy likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
JoyLikelihood string `json:"joyLikelihood,omitempty"`
// LandmarkingConfidence: Face landmarking confidence. Range [0, 1].
LandmarkingConfidence float64 `json:"landmarkingConfidence,omitempty"`
// Landmarks: Detected face landmarks.
Landmarks []*Landmark `json:"landmarks,omitempty"`
// PanAngle: Yaw angle, which indicates the leftward/rightward angle
// that the face is pointing relative to the vertical plane
// perpendicular to the image. Range [-180,180].
PanAngle float64 `json:"panAngle,omitempty"`
// RollAngle: Roll angle, which indicates the amount of
// clockwise/anti-clockwise rotation of the face relative to the image
// vertical about the axis perpendicular to the face. Range [-180,180].
RollAngle float64 `json:"rollAngle,omitempty"`
// SorrowLikelihood: Sorrow likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
SorrowLikelihood string `json:"sorrowLikelihood,omitempty"`
// SurpriseLikelihood: Surprise likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
SurpriseLikelihood string `json:"surpriseLikelihood,omitempty"`
// TiltAngle: Pitch angle, which indicates the upwards/downwards angle
// that the face is pointing relative to the image's horizontal plane.
// Range [-180,180].
TiltAngle float64 `json:"tiltAngle,omitempty"`
// UnderExposedLikelihood: Under-exposed likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
UnderExposedLikelihood string `json:"underExposedLikelihood,omitempty"`
// ForceSendFields is a list of field names (e.g. "AngerLikelihood") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "AngerLikelihood") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *FaceAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod FaceAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *FaceAnnotation) UnmarshalJSON(data []byte) error {
type NoMethod FaceAnnotation
var s1 struct {
DetectionConfidence gensupport.JSONFloat64 `json:"detectionConfidence"`
LandmarkingConfidence gensupport.JSONFloat64 `json:"landmarkingConfidence"`
PanAngle gensupport.JSONFloat64 `json:"panAngle"`
RollAngle gensupport.JSONFloat64 `json:"rollAngle"`
TiltAngle gensupport.JSONFloat64 `json:"tiltAngle"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.DetectionConfidence = float64(s1.DetectionConfidence)
s.LandmarkingConfidence = float64(s1.LandmarkingConfidence)
s.PanAngle = float64(s1.PanAngle)
s.RollAngle = float64(s1.RollAngle)
s.TiltAngle = float64(s1.TiltAngle)
return nil
}
// Feature: The type of Google Cloud Vision API detection to perform,
// and the maximum number of results to return for that type. Multiple
// `Feature` objects can be specified in the `features` list.
type Feature struct {
// MaxResults: Maximum number of results of this type. Does not apply to
// `TEXT_DETECTION`, `DOCUMENT_TEXT_DETECTION`, or `CROP_HINTS`.
MaxResults int64 `json:"maxResults,omitempty"`
// Model: Model to use for the feature. Supported values:
// "builtin/stable" (the default if unset) and "builtin/latest".
Model string `json:"model,omitempty"`
// Type: The feature type.
//
// Possible values:
// "TYPE_UNSPECIFIED" - Unspecified feature type.
// "FACE_DETECTION" - Run face detection.
// "LANDMARK_DETECTION" - Run landmark detection.
// "LOGO_DETECTION" - Run logo detection.
// "LABEL_DETECTION" - Run label detection.
// "TEXT_DETECTION" - Run text detection / optical character
// recognition (OCR). Text detection is optimized for areas of text
// within a larger image; if the image is a document, use
// `DOCUMENT_TEXT_DETECTION` instead.
// "DOCUMENT_TEXT_DETECTION" - Run dense text document OCR. Takes
// precedence when both `DOCUMENT_TEXT_DETECTION` and `TEXT_DETECTION`
// are present.
// "SAFE_SEARCH_DETECTION" - Run Safe Search to detect potentially
// unsafe or undesirable content.
// "IMAGE_PROPERTIES" - Compute a set of image properties, such as the
// image's dominant colors.
// "CROP_HINTS" - Run crop hints.
// "WEB_DETECTION" - Run web detection.
// "PRODUCT_SEARCH" - Run Product Search.
// "OBJECT_LOCALIZATION" - Run localizer for object detection.
Type string `json:"type,omitempty"`
// ForceSendFields is a list of field names (e.g. "MaxResults") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "MaxResults") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Feature) MarshalJSON() ([]byte, error) {
type NoMethod Feature
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GcsDestination: The Google Cloud Storage location where the output
// will be written to.
type GcsDestination struct {
// Uri: Google Cloud Storage URI prefix where the results will be
// stored. Results will be in JSON format and preceded by its
// corresponding input URI prefix. This field can either represent a gcs
// file prefix or gcs directory. In either case, the uri should be
// unique because in order to get all of the output files, you will need
// to do a wildcard gcs search on the uri prefix you provide. Examples:
// * File Prefix: gs://bucket-name/here/filenameprefix The output files
// will be created in gs://bucket-name/here/ and the names of the output
// files will begin with "filenameprefix". * Directory Prefix:
// gs://bucket-name/some/location/ The output files will be created in
// gs://bucket-name/some/location/ and the names of the output files
// could be anything because there was no filename prefix specified. If
// multiple outputs, each response is still AnnotateFileResponse, each
// of which contains some subset of the full list of
// AnnotateImageResponse. Multiple outputs can happen if, for example,
// the output JSON is too large and overflows into multiple sharded
// files.
Uri string `json:"uri,omitempty"`
// ForceSendFields is a list of field names (e.g. "Uri") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Uri") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GcsDestination) MarshalJSON() ([]byte, error) {
type NoMethod GcsDestination
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GcsSource: The Google Cloud Storage location where the input will be
// read from.
type GcsSource struct {
// Uri: Google Cloud Storage URI for the input file. This must only be a
// Google Cloud Storage object. Wildcards are not currently supported.
Uri string `json:"uri,omitempty"`
// ForceSendFields is a list of field names (e.g. "Uri") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Uri") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GcsSource) MarshalJSON() ([]byte, error) {
type NoMethod GcsSource
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p1beta1AnnotateFileResponse: Response to a single
// file annotation request. A file may contain one or more images, which
// individually have their own responses.
type GoogleCloudVisionV1p1beta1AnnotateFileResponse struct {
// Error: If set, represents the error message for the failed request.
// The `responses` field will not be set in this case.
Error *Status `json:"error,omitempty"`
// InputConfig: Information about the file for which this response is
// generated.
InputConfig *GoogleCloudVisionV1p1beta1InputConfig `json:"inputConfig,omitempty"`
// Responses: Individual responses to images found within the file. This
// field will be empty if the `error` field is set.
Responses []*GoogleCloudVisionV1p1beta1AnnotateImageResponse `json:"responses,omitempty"`
// TotalPages: This field gives the total number of pages in the file.
TotalPages int64 `json:"totalPages,omitempty"`
// ForceSendFields is a list of field names (e.g. "Error") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Error") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1AnnotateFileResponse) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1AnnotateFileResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p1beta1AnnotateImageResponse: Response to an image
// annotation request.
type GoogleCloudVisionV1p1beta1AnnotateImageResponse struct {
// Context: If present, contextual information is needed to understand
// where this image comes from.
Context *GoogleCloudVisionV1p1beta1ImageAnnotationContext `json:"context,omitempty"`
// CropHintsAnnotation: If present, crop hints have completed
// successfully.
CropHintsAnnotation *GoogleCloudVisionV1p1beta1CropHintsAnnotation `json:"cropHintsAnnotation,omitempty"`
// Error: If set, represents the error message for the operation. Note
// that filled-in image annotations are guaranteed to be correct, even
// when `error` is set.
Error *Status `json:"error,omitempty"`
// FaceAnnotations: If present, face detection has completed
// successfully.
FaceAnnotations []*GoogleCloudVisionV1p1beta1FaceAnnotation `json:"faceAnnotations,omitempty"`
// FullTextAnnotation: If present, text (OCR) detection or document
// (OCR) text detection has completed successfully. This annotation
// provides the structural hierarchy for the OCR detected text.
FullTextAnnotation *GoogleCloudVisionV1p1beta1TextAnnotation `json:"fullTextAnnotation,omitempty"`
// ImagePropertiesAnnotation: If present, image properties were
// extracted successfully.
ImagePropertiesAnnotation *GoogleCloudVisionV1p1beta1ImageProperties `json:"imagePropertiesAnnotation,omitempty"`
// LabelAnnotations: If present, label detection has completed
// successfully.
LabelAnnotations []*GoogleCloudVisionV1p1beta1EntityAnnotation `json:"labelAnnotations,omitempty"`
// LandmarkAnnotations: If present, landmark detection has completed
// successfully.
LandmarkAnnotations []*GoogleCloudVisionV1p1beta1EntityAnnotation `json:"landmarkAnnotations,omitempty"`
// LocalizedObjectAnnotations: If present, localized object detection
// has completed successfully. This will be sorted descending by
// confidence score.
LocalizedObjectAnnotations []*GoogleCloudVisionV1p1beta1LocalizedObjectAnnotation `json:"localizedObjectAnnotations,omitempty"`
// LogoAnnotations: If present, logo detection has completed
// successfully.
LogoAnnotations []*GoogleCloudVisionV1p1beta1EntityAnnotation `json:"logoAnnotations,omitempty"`
// ProductSearchResults: If present, product search has completed
// successfully.
ProductSearchResults *GoogleCloudVisionV1p1beta1ProductSearchResults `json:"productSearchResults,omitempty"`
// SafeSearchAnnotation: If present, safe-search annotation has
// completed successfully.
SafeSearchAnnotation *GoogleCloudVisionV1p1beta1SafeSearchAnnotation `json:"safeSearchAnnotation,omitempty"`
// TextAnnotations: If present, text (OCR) detection has completed
// successfully.
TextAnnotations []*GoogleCloudVisionV1p1beta1EntityAnnotation `json:"textAnnotations,omitempty"`
// WebDetection: If present, web detection has completed successfully.
WebDetection *GoogleCloudVisionV1p1beta1WebDetection `json:"webDetection,omitempty"`
// ForceSendFields is a list of field names (e.g. "Context") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Context") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1AnnotateImageResponse) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1AnnotateImageResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p1beta1AsyncAnnotateFileResponse: The response for
// a single offline file annotation request.
type GoogleCloudVisionV1p1beta1AsyncAnnotateFileResponse struct {
// OutputConfig: The output location and metadata from
// AsyncAnnotateFileRequest.
OutputConfig *GoogleCloudVisionV1p1beta1OutputConfig `json:"outputConfig,omitempty"`
// ForceSendFields is a list of field names (e.g. "OutputConfig") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "OutputConfig") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1AsyncAnnotateFileResponse) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1AsyncAnnotateFileResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p1beta1AsyncBatchAnnotateFilesResponse: Response
// to an async batch file annotation request.
type GoogleCloudVisionV1p1beta1AsyncBatchAnnotateFilesResponse struct {
// Responses: The list of file annotation responses, one for each
// request in AsyncBatchAnnotateFilesRequest.
Responses []*GoogleCloudVisionV1p1beta1AsyncAnnotateFileResponse `json:"responses,omitempty"`
// ForceSendFields is a list of field names (e.g. "Responses") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Responses") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1AsyncBatchAnnotateFilesResponse) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1AsyncBatchAnnotateFilesResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p1beta1Block: Logical element on the page.
type GoogleCloudVisionV1p1beta1Block struct {
// BlockType: Detected block type (text, image etc) for this block.
//
// Possible values:
// "UNKNOWN" - Unknown block type.
// "TEXT" - Regular text block.
// "TABLE" - Table block.
// "PICTURE" - Image block.
// "RULER" - Horizontal/vertical line box.
// "BARCODE" - Barcode block.
BlockType string `json:"blockType,omitempty"`
// BoundingBox: The bounding box for the block. The vertices are in the
// order of top-left, top-right, bottom-right, bottom-left. When a
// rotation of the bounding box is detected the rotation is represented
// as around the top-left corner as defined when the text is read in the
// 'natural' orientation. For example: * when the text is horizontal it
// might look like: 0----1 | | 3----2 * when it's rotated 180 degrees
// around the top-left corner it becomes: 2----3 | | 1----0 and the
// vertex order will still be (0, 1, 2, 3).
BoundingBox *GoogleCloudVisionV1p1beta1BoundingPoly `json:"boundingBox,omitempty"`
// Confidence: Confidence of the OCR results on the block. Range [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// Paragraphs: List of paragraphs in this block (if this blocks is of
// type text).
Paragraphs []*GoogleCloudVisionV1p1beta1Paragraph `json:"paragraphs,omitempty"`
// Property: Additional information detected for the block.
Property *GoogleCloudVisionV1p1beta1TextAnnotationTextProperty `json:"property,omitempty"`
// ForceSendFields is a list of field names (e.g. "BlockType") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BlockType") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1Block) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1Block
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p1beta1Block) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p1beta1Block
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
return nil
}
// GoogleCloudVisionV1p1beta1BoundingPoly: A bounding polygon for the
// detected image annotation.
type GoogleCloudVisionV1p1beta1BoundingPoly struct {
// NormalizedVertices: The bounding polygon normalized vertices.
NormalizedVertices []*GoogleCloudVisionV1p1beta1NormalizedVertex `json:"normalizedVertices,omitempty"`
// Vertices: The bounding polygon vertices.
Vertices []*GoogleCloudVisionV1p1beta1Vertex `json:"vertices,omitempty"`
// ForceSendFields is a list of field names (e.g. "NormalizedVertices")
// to unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "NormalizedVertices") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1BoundingPoly) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1BoundingPoly
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p1beta1ColorInfo: Color information consists of
// RGB channels, score, and the fraction of the image that the color
// occupies in the image.
type GoogleCloudVisionV1p1beta1ColorInfo struct {
// Color: RGB components of the color.
Color *Color `json:"color,omitempty"`
// PixelFraction: The fraction of pixels the color occupies in the
// image. Value in range [0, 1].
PixelFraction float64 `json:"pixelFraction,omitempty"`
// Score: Image-specific score for this color. Value in range [0, 1].
Score float64 `json:"score,omitempty"`
// ForceSendFields is a list of field names (e.g. "Color") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Color") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1ColorInfo) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1ColorInfo
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p1beta1ColorInfo) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p1beta1ColorInfo
var s1 struct {
PixelFraction gensupport.JSONFloat64 `json:"pixelFraction"`
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.PixelFraction = float64(s1.PixelFraction)
s.Score = float64(s1.Score)
return nil
}
// GoogleCloudVisionV1p1beta1CropHint: Single crop hint that is used to
// generate a new crop when serving an image.
type GoogleCloudVisionV1p1beta1CropHint struct {
// BoundingPoly: The bounding polygon for the crop region. The
// coordinates of the bounding box are in the original image's scale.
BoundingPoly *GoogleCloudVisionV1p1beta1BoundingPoly `json:"boundingPoly,omitempty"`
// Confidence: Confidence of this being a salient region. Range [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// ImportanceFraction: Fraction of importance of this salient region
// with respect to the original image.
ImportanceFraction float64 `json:"importanceFraction,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingPoly") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingPoly") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1CropHint) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1CropHint
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p1beta1CropHint) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p1beta1CropHint
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
ImportanceFraction gensupport.JSONFloat64 `json:"importanceFraction"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
s.ImportanceFraction = float64(s1.ImportanceFraction)
return nil
}
// GoogleCloudVisionV1p1beta1CropHintsAnnotation: Set of crop hints that
// are used to generate new crops when serving images.
type GoogleCloudVisionV1p1beta1CropHintsAnnotation struct {
// CropHints: Crop hint results.
CropHints []*GoogleCloudVisionV1p1beta1CropHint `json:"cropHints,omitempty"`
// ForceSendFields is a list of field names (e.g. "CropHints") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CropHints") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1CropHintsAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1CropHintsAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p1beta1DominantColorsAnnotation: Set of dominant
// colors and their corresponding scores.
type GoogleCloudVisionV1p1beta1DominantColorsAnnotation struct {
// Colors: RGB color values with their score and pixel fraction.
Colors []*GoogleCloudVisionV1p1beta1ColorInfo `json:"colors,omitempty"`
// ForceSendFields is a list of field names (e.g. "Colors") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Colors") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1DominantColorsAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1DominantColorsAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p1beta1EntityAnnotation: Set of detected entity
// features.
type GoogleCloudVisionV1p1beta1EntityAnnotation struct {
// BoundingPoly: Image region to which this entity belongs. Not produced
// for `LABEL_DETECTION` features.
BoundingPoly *GoogleCloudVisionV1p1beta1BoundingPoly `json:"boundingPoly,omitempty"`
// Confidence: **Deprecated. Use `score` instead.** The accuracy of the
// entity detection in an image. For example, for an image in which the
// "Eiffel Tower" entity is detected, this field represents the
// confidence that there is a tower in the query image. Range [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// Description: Entity textual description, expressed in its `locale`
// language.
Description string `json:"description,omitempty"`
// Locale: The language code for the locale in which the entity textual
// `description` is expressed.
Locale string `json:"locale,omitempty"`
// Locations: The location information for the detected entity. Multiple
// `LocationInfo` elements can be present because one location may
// indicate the location of the scene in the image, and another location
// may indicate the location of the place where the image was taken.
// Location information is usually present for landmarks.
Locations []*GoogleCloudVisionV1p1beta1LocationInfo `json:"locations,omitempty"`
// Mid: Opaque entity ID. Some IDs may be available in Google Knowledge
// Graph Search API (https://developers.google.com/knowledge-graph/).
Mid string `json:"mid,omitempty"`
// Properties: Some entities may have optional user-supplied `Property`
// (name/value) fields, such a score or string that qualifies the
// entity.
Properties []*GoogleCloudVisionV1p1beta1Property `json:"properties,omitempty"`
// Score: Overall score of the result. Range [0, 1].
Score float64 `json:"score,omitempty"`
// Topicality: The relevancy of the ICA (Image Content Annotation) label
// to the image. For example, the relevancy of "tower" is likely higher
// to an image containing the detected "Eiffel Tower" than to an image
// containing a detected distant towering building, even though the
// confidence that there is a tower in each image may be the same. Range
// [0, 1].
Topicality float64 `json:"topicality,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingPoly") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingPoly") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1EntityAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1EntityAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p1beta1EntityAnnotation) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p1beta1EntityAnnotation
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
Score gensupport.JSONFloat64 `json:"score"`
Topicality gensupport.JSONFloat64 `json:"topicality"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
s.Score = float64(s1.Score)
s.Topicality = float64(s1.Topicality)
return nil
}
// GoogleCloudVisionV1p1beta1FaceAnnotation: A face annotation object
// contains the results of face detection.
type GoogleCloudVisionV1p1beta1FaceAnnotation struct {
// AngerLikelihood: Anger likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
AngerLikelihood string `json:"angerLikelihood,omitempty"`
// BlurredLikelihood: Blurred likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
BlurredLikelihood string `json:"blurredLikelihood,omitempty"`
// BoundingPoly: The bounding polygon around the face. The coordinates
// of the bounding box are in the original image's scale. The bounding
// box is computed to "frame" the face in accordance with human
// expectations. It is based on the landmarker results. Note that one or
// more x and/or y coordinates may not be generated in the
// `BoundingPoly` (the polygon will be unbounded) if only a partial face
// appears in the image to be annotated.
BoundingPoly *GoogleCloudVisionV1p1beta1BoundingPoly `json:"boundingPoly,omitempty"`
// DetectionConfidence: Detection confidence. Range [0, 1].
DetectionConfidence float64 `json:"detectionConfidence,omitempty"`
// FdBoundingPoly: The `fd_bounding_poly` bounding polygon is tighter
// than the `boundingPoly`, and encloses only the skin part of the face.
// Typically, it is used to eliminate the face from any image analysis
// that detects the "amount of skin" visible in an image. It is not
// based on the landmarker results, only on the initial face detection,
// hence the fd (face detection) prefix.
FdBoundingPoly *GoogleCloudVisionV1p1beta1BoundingPoly `json:"fdBoundingPoly,omitempty"`
// HeadwearLikelihood: Headwear likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
HeadwearLikelihood string `json:"headwearLikelihood,omitempty"`
// JoyLikelihood: Joy likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
JoyLikelihood string `json:"joyLikelihood,omitempty"`
// LandmarkingConfidence: Face landmarking confidence. Range [0, 1].
LandmarkingConfidence float64 `json:"landmarkingConfidence,omitempty"`
// Landmarks: Detected face landmarks.
Landmarks []*GoogleCloudVisionV1p1beta1FaceAnnotationLandmark `json:"landmarks,omitempty"`
// PanAngle: Yaw angle, which indicates the leftward/rightward angle
// that the face is pointing relative to the vertical plane
// perpendicular to the image. Range [-180,180].
PanAngle float64 `json:"panAngle,omitempty"`
// RollAngle: Roll angle, which indicates the amount of
// clockwise/anti-clockwise rotation of the face relative to the image
// vertical about the axis perpendicular to the face. Range [-180,180].
RollAngle float64 `json:"rollAngle,omitempty"`
// SorrowLikelihood: Sorrow likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
SorrowLikelihood string `json:"sorrowLikelihood,omitempty"`
// SurpriseLikelihood: Surprise likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
SurpriseLikelihood string `json:"surpriseLikelihood,omitempty"`
// TiltAngle: Pitch angle, which indicates the upwards/downwards angle
// that the face is pointing relative to the image's horizontal plane.
// Range [-180,180].
TiltAngle float64 `json:"tiltAngle,omitempty"`
// UnderExposedLikelihood: Under-exposed likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
UnderExposedLikelihood string `json:"underExposedLikelihood,omitempty"`
// ForceSendFields is a list of field names (e.g. "AngerLikelihood") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "AngerLikelihood") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1FaceAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1FaceAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p1beta1FaceAnnotation) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p1beta1FaceAnnotation
var s1 struct {
DetectionConfidence gensupport.JSONFloat64 `json:"detectionConfidence"`
LandmarkingConfidence gensupport.JSONFloat64 `json:"landmarkingConfidence"`
PanAngle gensupport.JSONFloat64 `json:"panAngle"`
RollAngle gensupport.JSONFloat64 `json:"rollAngle"`
TiltAngle gensupport.JSONFloat64 `json:"tiltAngle"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.DetectionConfidence = float64(s1.DetectionConfidence)
s.LandmarkingConfidence = float64(s1.LandmarkingConfidence)
s.PanAngle = float64(s1.PanAngle)
s.RollAngle = float64(s1.RollAngle)
s.TiltAngle = float64(s1.TiltAngle)
return nil
}
// GoogleCloudVisionV1p1beta1FaceAnnotationLandmark: A face-specific
// landmark (for example, a face feature).
type GoogleCloudVisionV1p1beta1FaceAnnotationLandmark struct {
// Position: Face landmark position.
Position *GoogleCloudVisionV1p1beta1Position `json:"position,omitempty"`
// Type: Face landmark type.
//
// Possible values:
// "UNKNOWN_LANDMARK" - Unknown face landmark detected. Should not be
// filled.
// "LEFT_EYE" - Left eye.
// "RIGHT_EYE" - Right eye.
// "LEFT_OF_LEFT_EYEBROW" - Left of left eyebrow.
// "RIGHT_OF_LEFT_EYEBROW" - Right of left eyebrow.
// "LEFT_OF_RIGHT_EYEBROW" - Left of right eyebrow.
// "RIGHT_OF_RIGHT_EYEBROW" - Right of right eyebrow.
// "MIDPOINT_BETWEEN_EYES" - Midpoint between eyes.
// "NOSE_TIP" - Nose tip.
// "UPPER_LIP" - Upper lip.
// "LOWER_LIP" - Lower lip.
// "MOUTH_LEFT" - Mouth left.
// "MOUTH_RIGHT" - Mouth right.
// "MOUTH_CENTER" - Mouth center.
// "NOSE_BOTTOM_RIGHT" - Nose, bottom right.
// "NOSE_BOTTOM_LEFT" - Nose, bottom left.
// "NOSE_BOTTOM_CENTER" - Nose, bottom center.
// "LEFT_EYE_TOP_BOUNDARY" - Left eye, top boundary.
// "LEFT_EYE_RIGHT_CORNER" - Left eye, right corner.
// "LEFT_EYE_BOTTOM_BOUNDARY" - Left eye, bottom boundary.
// "LEFT_EYE_LEFT_CORNER" - Left eye, left corner.
// "RIGHT_EYE_TOP_BOUNDARY" - Right eye, top boundary.
// "RIGHT_EYE_RIGHT_CORNER" - Right eye, right corner.
// "RIGHT_EYE_BOTTOM_BOUNDARY" - Right eye, bottom boundary.
// "RIGHT_EYE_LEFT_CORNER" - Right eye, left corner.
// "LEFT_EYEBROW_UPPER_MIDPOINT" - Left eyebrow, upper midpoint.
// "RIGHT_EYEBROW_UPPER_MIDPOINT" - Right eyebrow, upper midpoint.
// "LEFT_EAR_TRAGION" - Left ear tragion.
// "RIGHT_EAR_TRAGION" - Right ear tragion.
// "LEFT_EYE_PUPIL" - Left eye pupil.
// "RIGHT_EYE_PUPIL" - Right eye pupil.
// "FOREHEAD_GLABELLA" - Forehead glabella.
// "CHIN_GNATHION" - Chin gnathion.
// "CHIN_LEFT_GONION" - Chin left gonion.
// "CHIN_RIGHT_GONION" - Chin right gonion.
// "LEFT_CHEEK_CENTER" - Left cheek center.
// "RIGHT_CHEEK_CENTER" - Right cheek center.
Type string `json:"type,omitempty"`
// ForceSendFields is a list of field names (e.g. "Position") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Position") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1FaceAnnotationLandmark) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1FaceAnnotationLandmark
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p1beta1GcsDestination: The Google Cloud Storage
// location where the output will be written to.
type GoogleCloudVisionV1p1beta1GcsDestination struct {
// Uri: Google Cloud Storage URI prefix where the results will be
// stored. Results will be in JSON format and preceded by its
// corresponding input URI prefix. This field can either represent a gcs
// file prefix or gcs directory. In either case, the uri should be
// unique because in order to get all of the output files, you will need
// to do a wildcard gcs search on the uri prefix you provide. Examples:
// * File Prefix: gs://bucket-name/here/filenameprefix The output files
// will be created in gs://bucket-name/here/ and the names of the output
// files will begin with "filenameprefix". * Directory Prefix:
// gs://bucket-name/some/location/ The output files will be created in
// gs://bucket-name/some/location/ and the names of the output files
// could be anything because there was no filename prefix specified. If
// multiple outputs, each response is still AnnotateFileResponse, each
// of which contains some subset of the full list of
// AnnotateImageResponse. Multiple outputs can happen if, for example,
// the output JSON is too large and overflows into multiple sharded
// files.
Uri string `json:"uri,omitempty"`
// ForceSendFields is a list of field names (e.g. "Uri") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Uri") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1GcsDestination) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1GcsDestination
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p1beta1GcsSource: The Google Cloud Storage
// location where the input will be read from.
type GoogleCloudVisionV1p1beta1GcsSource struct {
// Uri: Google Cloud Storage URI for the input file. This must only be a
// Google Cloud Storage object. Wildcards are not currently supported.
Uri string `json:"uri,omitempty"`
// ForceSendFields is a list of field names (e.g. "Uri") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Uri") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1GcsSource) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1GcsSource
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p1beta1ImageAnnotationContext: If an image was
// produced from a file (e.g. a PDF), this message gives information
// about the source of that image.
type GoogleCloudVisionV1p1beta1ImageAnnotationContext struct {
// PageNumber: If the file was a PDF or TIFF, this field gives the page
// number within the file used to produce the image.
PageNumber int64 `json:"pageNumber,omitempty"`
// Uri: The URI of the file used to produce the image.
Uri string `json:"uri,omitempty"`
// ForceSendFields is a list of field names (e.g. "PageNumber") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "PageNumber") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1ImageAnnotationContext) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1ImageAnnotationContext
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p1beta1ImageProperties: Stores image properties,
// such as dominant colors.
type GoogleCloudVisionV1p1beta1ImageProperties struct {
// DominantColors: If present, dominant colors completed successfully.
DominantColors *GoogleCloudVisionV1p1beta1DominantColorsAnnotation `json:"dominantColors,omitempty"`
// ForceSendFields is a list of field names (e.g. "DominantColors") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "DominantColors") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1ImageProperties) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1ImageProperties
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p1beta1InputConfig: The desired input location and
// metadata.
type GoogleCloudVisionV1p1beta1InputConfig struct {
// Content: File content, represented as a stream of bytes. Note: As
// with all `bytes` fields, protobuffers use a pure binary
// representation, whereas JSON representations use base64. Currently,
// this field only works for BatchAnnotateFiles requests. It does not
// work for AsyncBatchAnnotateFiles requests.
Content string `json:"content,omitempty"`
// GcsSource: The Google Cloud Storage location to read the input from.
GcsSource *GoogleCloudVisionV1p1beta1GcsSource `json:"gcsSource,omitempty"`
// MimeType: The type of the file. Currently only "application/pdf",
// "image/tiff" and "image/gif" are supported. Wildcards are not
// supported.
MimeType string `json:"mimeType,omitempty"`
// ForceSendFields is a list of field names (e.g. "Content") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Content") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1InputConfig) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1InputConfig
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p1beta1LocalizedObjectAnnotation: Set of detected
// objects with bounding boxes.
type GoogleCloudVisionV1p1beta1LocalizedObjectAnnotation struct {
// BoundingPoly: Image region to which this object belongs. This must be
// populated.
BoundingPoly *GoogleCloudVisionV1p1beta1BoundingPoly `json:"boundingPoly,omitempty"`
// LanguageCode: The BCP-47 language code, such as "en-US" or "sr-Latn".
// For more information, see
// http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
LanguageCode string `json:"languageCode,omitempty"`
// Mid: Object ID that should align with EntityAnnotation mid.
Mid string `json:"mid,omitempty"`
// Name: Object name, expressed in its `language_code` language.
Name string `json:"name,omitempty"`
// Score: Score of the result. Range [0, 1].
Score float64 `json:"score,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingPoly") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingPoly") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1LocalizedObjectAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1LocalizedObjectAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p1beta1LocalizedObjectAnnotation) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p1beta1LocalizedObjectAnnotation
var s1 struct {
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Score = float64(s1.Score)
return nil
}
// GoogleCloudVisionV1p1beta1LocationInfo: Detected entity location
// information.
type GoogleCloudVisionV1p1beta1LocationInfo struct {
// LatLng: lat/long location coordinates.
LatLng *LatLng `json:"latLng,omitempty"`
// ForceSendFields is a list of field names (e.g. "LatLng") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "LatLng") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1LocationInfo) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1LocationInfo
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p1beta1NormalizedVertex: A vertex represents a 2D
// point in the image. NOTE: the normalized vertex coordinates are
// relative to the original image and range from 0 to 1.
type GoogleCloudVisionV1p1beta1NormalizedVertex struct {
// X: X coordinate.
X float64 `json:"x,omitempty"`
// Y: Y coordinate.
Y float64 `json:"y,omitempty"`
// ForceSendFields is a list of field names (e.g. "X") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "X") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1NormalizedVertex) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1NormalizedVertex
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p1beta1NormalizedVertex) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p1beta1NormalizedVertex
var s1 struct {
X gensupport.JSONFloat64 `json:"x"`
Y gensupport.JSONFloat64 `json:"y"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.X = float64(s1.X)
s.Y = float64(s1.Y)
return nil
}
// GoogleCloudVisionV1p1beta1OperationMetadata: Contains metadata for
// the BatchAnnotateImages operation.
type GoogleCloudVisionV1p1beta1OperationMetadata struct {
// CreateTime: The time when the batch request was received.
CreateTime string `json:"createTime,omitempty"`
// State: Current state of the batch operation.
//
// Possible values:
// "STATE_UNSPECIFIED" - Invalid.
// "CREATED" - Request is received.
// "RUNNING" - Request is actively being processed.
// "DONE" - The batch processing is done.
// "CANCELLED" - The batch processing was cancelled.
State string `json:"state,omitempty"`
// UpdateTime: The time when the operation result was last updated.
UpdateTime string `json:"updateTime,omitempty"`
// ForceSendFields is a list of field names (e.g. "CreateTime") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CreateTime") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1OperationMetadata) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1OperationMetadata
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p1beta1OutputConfig: The desired output location
// and metadata.
type GoogleCloudVisionV1p1beta1OutputConfig struct {
// BatchSize: The max number of response protos to put into each output
// JSON file on Google Cloud Storage. The valid range is [1, 100]. If
// not specified, the default value is 20. For example, for one pdf file
// with 100 pages, 100 response protos will be generated. If
// `batch_size` = 20, then 5 json files each containing 20 response
// protos will be written under the prefix `gcs_destination`.`uri`.
// Currently, batch_size only applies to GcsDestination, with potential
// future support for other output configurations.
BatchSize int64 `json:"batchSize,omitempty"`
// GcsDestination: The Google Cloud Storage location to write the
// output(s) to.
GcsDestination *GoogleCloudVisionV1p1beta1GcsDestination `json:"gcsDestination,omitempty"`
// ForceSendFields is a list of field names (e.g. "BatchSize") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BatchSize") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1OutputConfig) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1OutputConfig
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p1beta1Page: Detected page from OCR.
type GoogleCloudVisionV1p1beta1Page struct {
// Blocks: List of blocks of text, images etc on this page.
Blocks []*GoogleCloudVisionV1p1beta1Block `json:"blocks,omitempty"`
// Confidence: Confidence of the OCR results on the page. Range [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// Height: Page height. For PDFs the unit is points. For images
// (including TIFFs) the unit is pixels.
Height int64 `json:"height,omitempty"`
// Property: Additional information detected on the page.
Property *GoogleCloudVisionV1p1beta1TextAnnotationTextProperty `json:"property,omitempty"`
// Width: Page width. For PDFs the unit is points. For images (including
// TIFFs) the unit is pixels.
Width int64 `json:"width,omitempty"`
// ForceSendFields is a list of field names (e.g. "Blocks") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Blocks") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1Page) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1Page
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p1beta1Page) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p1beta1Page
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
return nil
}
// GoogleCloudVisionV1p1beta1Paragraph: Structural unit of text
// representing a number of words in certain order.
type GoogleCloudVisionV1p1beta1Paragraph struct {
// BoundingBox: The bounding box for the paragraph. The vertices are in
// the order of top-left, top-right, bottom-right, bottom-left. When a
// rotation of the bounding box is detected the rotation is represented
// as around the top-left corner as defined when the text is read in the
// 'natural' orientation. For example: * when the text is horizontal it
// might look like: 0----1 | | 3----2 * when it's rotated 180 degrees
// around the top-left corner it becomes: 2----3 | | 1----0 and the
// vertex order will still be (0, 1, 2, 3).
BoundingBox *GoogleCloudVisionV1p1beta1BoundingPoly `json:"boundingBox,omitempty"`
// Confidence: Confidence of the OCR results for the paragraph. Range
// [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// Property: Additional information detected for the paragraph.
Property *GoogleCloudVisionV1p1beta1TextAnnotationTextProperty `json:"property,omitempty"`
// Words: List of all words in this paragraph.
Words []*GoogleCloudVisionV1p1beta1Word `json:"words,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingBox") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingBox") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1Paragraph) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1Paragraph
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p1beta1Paragraph) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p1beta1Paragraph
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
return nil
}
// GoogleCloudVisionV1p1beta1Position: A 3D position in the image, used
// primarily for Face detection landmarks. A valid Position must have
// both x and y coordinates. The position coordinates are in the same
// scale as the original image.
type GoogleCloudVisionV1p1beta1Position struct {
// X: X coordinate.
X float64 `json:"x,omitempty"`
// Y: Y coordinate.
Y float64 `json:"y,omitempty"`
// Z: Z coordinate (or depth).
Z float64 `json:"z,omitempty"`
// ForceSendFields is a list of field names (e.g. "X") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "X") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1Position) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1Position
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p1beta1Position) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p1beta1Position
var s1 struct {
X gensupport.JSONFloat64 `json:"x"`
Y gensupport.JSONFloat64 `json:"y"`
Z gensupport.JSONFloat64 `json:"z"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.X = float64(s1.X)
s.Y = float64(s1.Y)
s.Z = float64(s1.Z)
return nil
}
// GoogleCloudVisionV1p1beta1Product: A Product contains
// ReferenceImages.
type GoogleCloudVisionV1p1beta1Product struct {
// Description: User-provided metadata to be stored with this product.
// Must be at most 4096 characters long.
Description string `json:"description,omitempty"`
// DisplayName: The user-provided name for this Product. Must not be
// empty. Must be at most 4096 characters long.
DisplayName string `json:"displayName,omitempty"`
// Name: The resource name of the product. Format is:
// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`. This
// field is ignored when creating a product.
Name string `json:"name,omitempty"`
// ProductCategory: Immutable. The category for the product identified
// by the reference image. This should be one of "homegoods-v2",
// "apparel-v2", "toys-v2", "packagedgoods-v1" or "general-v1". The
// legacy categories "homegoods", "apparel", and "toys" are still
// supported, but these should not be used for new products.
ProductCategory string `json:"productCategory,omitempty"`
// ProductLabels: Key-value pairs that can be attached to a product. At
// query time, constraints can be specified based on the product_labels.
// Note that integer values can be provided as strings, e.g. "1199".
// Only strings with integer values can match a range-based restriction
// which is to be supported soon. Multiple values can be assigned to the
// same key. One product may have up to 500 product_labels. Notice that
// the total number of distinct product_labels over all products in one
// ProductSet cannot exceed 1M, otherwise the product search pipeline
// will refuse to work for that ProductSet.
ProductLabels []*GoogleCloudVisionV1p1beta1ProductKeyValue `json:"productLabels,omitempty"`
// ForceSendFields is a list of field names (e.g. "Description") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Description") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1Product) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1Product
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p1beta1ProductKeyValue: A product label
// represented as a key-value pair.
type GoogleCloudVisionV1p1beta1ProductKeyValue struct {
// Key: The key of the label attached to the product. Cannot be empty
// and cannot exceed 128 bytes.
Key string `json:"key,omitempty"`
// Value: The value of the label attached to the product. Cannot be
// empty and cannot exceed 128 bytes.
Value string `json:"value,omitempty"`
// ForceSendFields is a list of field names (e.g. "Key") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Key") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1ProductKeyValue) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1ProductKeyValue
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p1beta1ProductSearchResults: Results for a product
// search request.
type GoogleCloudVisionV1p1beta1ProductSearchResults struct {
// IndexTime: Timestamp of the index which provided these results.
// Products added to the product set and products removed from the
// product set after this time are not reflected in the current results.
IndexTime string `json:"indexTime,omitempty"`
// ProductGroupedResults: List of results grouped by products detected
// in the query image. Each entry corresponds to one bounding polygon in
// the query image, and contains the matching products specific to that
// region. There may be duplicate product matches in the union of all
// the per-product results.
ProductGroupedResults []*GoogleCloudVisionV1p1beta1ProductSearchResultsGroupedResult `json:"productGroupedResults,omitempty"`
// Results: List of results, one for each product match.
Results []*GoogleCloudVisionV1p1beta1ProductSearchResultsResult `json:"results,omitempty"`
// ForceSendFields is a list of field names (e.g. "IndexTime") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "IndexTime") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1ProductSearchResults) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1ProductSearchResults
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p1beta1ProductSearchResultsGroupedResult:
// Information about the products similar to a single product in a query
// image.
type GoogleCloudVisionV1p1beta1ProductSearchResultsGroupedResult struct {
// BoundingPoly: The bounding polygon around the product detected in the
// query image.
BoundingPoly *GoogleCloudVisionV1p1beta1BoundingPoly `json:"boundingPoly,omitempty"`
// ObjectAnnotations: List of generic predictions for the object in the
// bounding box.
ObjectAnnotations []*GoogleCloudVisionV1p1beta1ProductSearchResultsObjectAnnotation `json:"objectAnnotations,omitempty"`
// Results: List of results, one for each product match.
Results []*GoogleCloudVisionV1p1beta1ProductSearchResultsResult `json:"results,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingPoly") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingPoly") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1ProductSearchResultsGroupedResult) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1ProductSearchResultsGroupedResult
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p1beta1ProductSearchResultsObjectAnnotation:
// Prediction for what the object in the bounding box is.
type GoogleCloudVisionV1p1beta1ProductSearchResultsObjectAnnotation struct {
// LanguageCode: The BCP-47 language code, such as "en-US" or "sr-Latn".
// For more information, see
// http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
LanguageCode string `json:"languageCode,omitempty"`
// Mid: Object ID that should align with EntityAnnotation mid.
Mid string `json:"mid,omitempty"`
// Name: Object name, expressed in its `language_code` language.
Name string `json:"name,omitempty"`
// Score: Score of the result. Range [0, 1].
Score float64 `json:"score,omitempty"`
// ForceSendFields is a list of field names (e.g. "LanguageCode") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "LanguageCode") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1ProductSearchResultsObjectAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1ProductSearchResultsObjectAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p1beta1ProductSearchResultsObjectAnnotation) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p1beta1ProductSearchResultsObjectAnnotation
var s1 struct {
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Score = float64(s1.Score)
return nil
}
// GoogleCloudVisionV1p1beta1ProductSearchResultsResult: Information
// about a product.
type GoogleCloudVisionV1p1beta1ProductSearchResultsResult struct {
// Image: The resource name of the image from the product that is the
// closest match to the query.
Image string `json:"image,omitempty"`
// Product: The Product.
Product *GoogleCloudVisionV1p1beta1Product `json:"product,omitempty"`
// Score: A confidence level on the match, ranging from 0 (no
// confidence) to 1 (full confidence).
Score float64 `json:"score,omitempty"`
// ForceSendFields is a list of field names (e.g. "Image") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Image") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1ProductSearchResultsResult) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1ProductSearchResultsResult
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p1beta1ProductSearchResultsResult) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p1beta1ProductSearchResultsResult
var s1 struct {
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Score = float64(s1.Score)
return nil
}
// GoogleCloudVisionV1p1beta1Property: A `Property` consists of a
// user-supplied name/value pair.
type GoogleCloudVisionV1p1beta1Property struct {
// Name: Name of the property.
Name string `json:"name,omitempty"`
// Uint64Value: Value of numeric properties.
Uint64Value uint64 `json:"uint64Value,omitempty,string"`
// Value: Value of the property.
Value string `json:"value,omitempty"`
// ForceSendFields is a list of field names (e.g. "Name") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Name") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1Property) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1Property
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p1beta1SafeSearchAnnotation: Set of features
// pertaining to the image, computed by computer vision methods over
// safe-search verticals (for example, adult, spoof, medical, violence).
type GoogleCloudVisionV1p1beta1SafeSearchAnnotation struct {
// Adult: Represents the adult content likelihood for the image. Adult
// content may contain elements such as nudity, pornographic images or
// cartoons, or sexual activities.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
Adult string `json:"adult,omitempty"`
// Medical: Likelihood that this is a medical image.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
Medical string `json:"medical,omitempty"`
// Racy: Likelihood that the request image contains racy content. Racy
// content may include (but is not limited to) skimpy or sheer clothing,
// strategically covered nudity, lewd or provocative poses, or close-ups
// of sensitive body areas.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
Racy string `json:"racy,omitempty"`
// Spoof: Spoof likelihood. The likelihood that an modification was made
// to the image's canonical version to make it appear funny or
// offensive.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
Spoof string `json:"spoof,omitempty"`
// Violence: Likelihood that this image contains violent content.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
Violence string `json:"violence,omitempty"`
// ForceSendFields is a list of field names (e.g. "Adult") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Adult") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1SafeSearchAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1SafeSearchAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p1beta1Symbol: A single symbol representation.
type GoogleCloudVisionV1p1beta1Symbol struct {
// BoundingBox: The bounding box for the symbol. The vertices are in the
// order of top-left, top-right, bottom-right, bottom-left. When a
// rotation of the bounding box is detected the rotation is represented
// as around the top-left corner as defined when the text is read in the
// 'natural' orientation. For example: * when the text is horizontal it
// might look like: 0----1 | | 3----2 * when it's rotated 180 degrees
// around the top-left corner it becomes: 2----3 | | 1----0 and the
// vertex order will still be (0, 1, 2, 3).
BoundingBox *GoogleCloudVisionV1p1beta1BoundingPoly `json:"boundingBox,omitempty"`
// Confidence: Confidence of the OCR results for the symbol. Range [0,
// 1].
Confidence float64 `json:"confidence,omitempty"`
// Property: Additional information detected for the symbol.
Property *GoogleCloudVisionV1p1beta1TextAnnotationTextProperty `json:"property,omitempty"`
// Text: The actual UTF-8 representation of the symbol.
Text string `json:"text,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingBox") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingBox") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1Symbol) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1Symbol
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p1beta1Symbol) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p1beta1Symbol
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
return nil
}
// GoogleCloudVisionV1p1beta1TextAnnotation: TextAnnotation contains a
// structured representation of OCR extracted text. The hierarchy of an
// OCR extracted text structure is like this: TextAnnotation -> Page ->
// Block -> Paragraph -> Word -> Symbol Each structural component,
// starting from Page, may further have their own properties. Properties
// describe detected languages, breaks etc.. Please refer to the
// TextAnnotation.TextProperty message definition below for more detail.
type GoogleCloudVisionV1p1beta1TextAnnotation struct {
// Pages: List of pages detected by OCR.
Pages []*GoogleCloudVisionV1p1beta1Page `json:"pages,omitempty"`
// Text: UTF-8 text detected on the pages.
Text string `json:"text,omitempty"`
// ForceSendFields is a list of field names (e.g. "Pages") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Pages") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1TextAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1TextAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p1beta1TextAnnotationDetectedBreak: Detected start
// or end of a structural component.
type GoogleCloudVisionV1p1beta1TextAnnotationDetectedBreak struct {
// IsPrefix: True if break prepends the element.
IsPrefix bool `json:"isPrefix,omitempty"`
// Type: Detected break type.
//
// Possible values:
// "UNKNOWN" - Unknown break label type.
// "SPACE" - Regular space.
// "SURE_SPACE" - Sure space (very wide).
// "EOL_SURE_SPACE" - Line-wrapping break.
// "HYPHEN" - End-line hyphen that is not present in text; does not
// co-occur with `SPACE`, `LEADER_SPACE`, or `LINE_BREAK`.
// "LINE_BREAK" - Line break that ends a paragraph.
Type string `json:"type,omitempty"`
// ForceSendFields is a list of field names (e.g. "IsPrefix") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "IsPrefix") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1TextAnnotationDetectedBreak) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1TextAnnotationDetectedBreak
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p1beta1TextAnnotationDetectedLanguage: Detected
// language for a structural component.
type GoogleCloudVisionV1p1beta1TextAnnotationDetectedLanguage struct {
// Confidence: Confidence of detected language. Range [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// LanguageCode: The BCP-47 language code, such as "en-US" or "sr-Latn".
// For more information, see
// http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
LanguageCode string `json:"languageCode,omitempty"`
// ForceSendFields is a list of field names (e.g. "Confidence") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Confidence") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1TextAnnotationDetectedLanguage) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1TextAnnotationDetectedLanguage
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p1beta1TextAnnotationDetectedLanguage) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p1beta1TextAnnotationDetectedLanguage
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
return nil
}
// GoogleCloudVisionV1p1beta1TextAnnotationTextProperty: Additional
// information detected on the structural component.
type GoogleCloudVisionV1p1beta1TextAnnotationTextProperty struct {
// DetectedBreak: Detected start or end of a text segment.
DetectedBreak *GoogleCloudVisionV1p1beta1TextAnnotationDetectedBreak `json:"detectedBreak,omitempty"`
// DetectedLanguages: A list of detected languages together with
// confidence.
DetectedLanguages []*GoogleCloudVisionV1p1beta1TextAnnotationDetectedLanguage `json:"detectedLanguages,omitempty"`
// ForceSendFields is a list of field names (e.g. "DetectedBreak") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "DetectedBreak") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1TextAnnotationTextProperty) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1TextAnnotationTextProperty
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p1beta1Vertex: A vertex represents a 2D point in
// the image. NOTE: the vertex coordinates are in the same scale as the
// original image.
type GoogleCloudVisionV1p1beta1Vertex struct {
// X: X coordinate.
X int64 `json:"x,omitempty"`
// Y: Y coordinate.
Y int64 `json:"y,omitempty"`
// ForceSendFields is a list of field names (e.g. "X") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "X") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1Vertex) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1Vertex
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p1beta1WebDetection: Relevant information for the
// image from the Internet.
type GoogleCloudVisionV1p1beta1WebDetection struct {
// BestGuessLabels: The service's best guess as to the topic of the
// request image. Inferred from similar images on the open web.
BestGuessLabels []*GoogleCloudVisionV1p1beta1WebDetectionWebLabel `json:"bestGuessLabels,omitempty"`
// FullMatchingImages: Fully matching images from the Internet. Can
// include resized copies of the query image.
FullMatchingImages []*GoogleCloudVisionV1p1beta1WebDetectionWebImage `json:"fullMatchingImages,omitempty"`
// PagesWithMatchingImages: Web pages containing the matching images
// from the Internet.
PagesWithMatchingImages []*GoogleCloudVisionV1p1beta1WebDetectionWebPage `json:"pagesWithMatchingImages,omitempty"`
// PartialMatchingImages: Partial matching images from the Internet.
// Those images are similar enough to share some key-point features. For
// example an original image will likely have partial matching for its
// crops.
PartialMatchingImages []*GoogleCloudVisionV1p1beta1WebDetectionWebImage `json:"partialMatchingImages,omitempty"`
// VisuallySimilarImages: The visually similar image results.
VisuallySimilarImages []*GoogleCloudVisionV1p1beta1WebDetectionWebImage `json:"visuallySimilarImages,omitempty"`
// WebEntities: Deduced entities from similar images on the Internet.
WebEntities []*GoogleCloudVisionV1p1beta1WebDetectionWebEntity `json:"webEntities,omitempty"`
// ForceSendFields is a list of field names (e.g. "BestGuessLabels") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BestGuessLabels") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1WebDetection) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1WebDetection
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p1beta1WebDetectionWebEntity: Entity deduced from
// similar images on the Internet.
type GoogleCloudVisionV1p1beta1WebDetectionWebEntity struct {
// Description: Canonical description of the entity, in English.
Description string `json:"description,omitempty"`
// EntityId: Opaque entity ID.
EntityId string `json:"entityId,omitempty"`
// Score: Overall relevancy score for the entity. Not normalized and not
// comparable across different image queries.
Score float64 `json:"score,omitempty"`
// ForceSendFields is a list of field names (e.g. "Description") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Description") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1WebDetectionWebEntity) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1WebDetectionWebEntity
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p1beta1WebDetectionWebEntity) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p1beta1WebDetectionWebEntity
var s1 struct {
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Score = float64(s1.Score)
return nil
}
// GoogleCloudVisionV1p1beta1WebDetectionWebImage: Metadata for online
// images.
type GoogleCloudVisionV1p1beta1WebDetectionWebImage struct {
// Score: (Deprecated) Overall relevancy score for the image.
Score float64 `json:"score,omitempty"`
// Url: The result image URL.
Url string `json:"url,omitempty"`
// ForceSendFields is a list of field names (e.g. "Score") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Score") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1WebDetectionWebImage) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1WebDetectionWebImage
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p1beta1WebDetectionWebImage) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p1beta1WebDetectionWebImage
var s1 struct {
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Score = float64(s1.Score)
return nil
}
// GoogleCloudVisionV1p1beta1WebDetectionWebLabel: Label to provide
// extra metadata for the web detection.
type GoogleCloudVisionV1p1beta1WebDetectionWebLabel struct {
// Label: Label for extra metadata.
Label string `json:"label,omitempty"`
// LanguageCode: The BCP-47 language code for `label`, such as "en-US"
// or "sr-Latn". For more information, see
// http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
LanguageCode string `json:"languageCode,omitempty"`
// ForceSendFields is a list of field names (e.g. "Label") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Label") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1WebDetectionWebLabel) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1WebDetectionWebLabel
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p1beta1WebDetectionWebPage: Metadata for web
// pages.
type GoogleCloudVisionV1p1beta1WebDetectionWebPage struct {
// FullMatchingImages: Fully matching images on the page. Can include
// resized copies of the query image.
FullMatchingImages []*GoogleCloudVisionV1p1beta1WebDetectionWebImage `json:"fullMatchingImages,omitempty"`
// PageTitle: Title for the web page, may contain HTML markups.
PageTitle string `json:"pageTitle,omitempty"`
// PartialMatchingImages: Partial matching images on the page. Those
// images are similar enough to share some key-point features. For
// example an original image will likely have partial matching for its
// crops.
PartialMatchingImages []*GoogleCloudVisionV1p1beta1WebDetectionWebImage `json:"partialMatchingImages,omitempty"`
// Score: (Deprecated) Overall relevancy score for the web page.
Score float64 `json:"score,omitempty"`
// Url: The result web page URL.
Url string `json:"url,omitempty"`
// ForceSendFields is a list of field names (e.g. "FullMatchingImages")
// to unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "FullMatchingImages") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1WebDetectionWebPage) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1WebDetectionWebPage
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p1beta1WebDetectionWebPage) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p1beta1WebDetectionWebPage
var s1 struct {
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Score = float64(s1.Score)
return nil
}
// GoogleCloudVisionV1p1beta1Word: A word representation.
type GoogleCloudVisionV1p1beta1Word struct {
// BoundingBox: The bounding box for the word. The vertices are in the
// order of top-left, top-right, bottom-right, bottom-left. When a
// rotation of the bounding box is detected the rotation is represented
// as around the top-left corner as defined when the text is read in the
// 'natural' orientation. For example: * when the text is horizontal it
// might look like: 0----1 | | 3----2 * when it's rotated 180 degrees
// around the top-left corner it becomes: 2----3 | | 1----0 and the
// vertex order will still be (0, 1, 2, 3).
BoundingBox *GoogleCloudVisionV1p1beta1BoundingPoly `json:"boundingBox,omitempty"`
// Confidence: Confidence of the OCR results for the word. Range [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// Property: Additional information detected for the word.
Property *GoogleCloudVisionV1p1beta1TextAnnotationTextProperty `json:"property,omitempty"`
// Symbols: List of symbols in the word. The order of the symbols
// follows the natural reading order.
Symbols []*GoogleCloudVisionV1p1beta1Symbol `json:"symbols,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingBox") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingBox") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p1beta1Word) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p1beta1Word
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p1beta1Word) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p1beta1Word
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
return nil
}
// GoogleCloudVisionV1p2beta1AnnotateFileResponse: Response to a single
// file annotation request. A file may contain one or more images, which
// individually have their own responses.
type GoogleCloudVisionV1p2beta1AnnotateFileResponse struct {
// Error: If set, represents the error message for the failed request.
// The `responses` field will not be set in this case.
Error *Status `json:"error,omitempty"`
// InputConfig: Information about the file for which this response is
// generated.
InputConfig *GoogleCloudVisionV1p2beta1InputConfig `json:"inputConfig,omitempty"`
// Responses: Individual responses to images found within the file. This
// field will be empty if the `error` field is set.
Responses []*GoogleCloudVisionV1p2beta1AnnotateImageResponse `json:"responses,omitempty"`
// TotalPages: This field gives the total number of pages in the file.
TotalPages int64 `json:"totalPages,omitempty"`
// ForceSendFields is a list of field names (e.g. "Error") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Error") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1AnnotateFileResponse) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1AnnotateFileResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p2beta1AnnotateImageResponse: Response to an image
// annotation request.
type GoogleCloudVisionV1p2beta1AnnotateImageResponse struct {
// Context: If present, contextual information is needed to understand
// where this image comes from.
Context *GoogleCloudVisionV1p2beta1ImageAnnotationContext `json:"context,omitempty"`
// CropHintsAnnotation: If present, crop hints have completed
// successfully.
CropHintsAnnotation *GoogleCloudVisionV1p2beta1CropHintsAnnotation `json:"cropHintsAnnotation,omitempty"`
// Error: If set, represents the error message for the operation. Note
// that filled-in image annotations are guaranteed to be correct, even
// when `error` is set.
Error *Status `json:"error,omitempty"`
// FaceAnnotations: If present, face detection has completed
// successfully.
FaceAnnotations []*GoogleCloudVisionV1p2beta1FaceAnnotation `json:"faceAnnotations,omitempty"`
// FullTextAnnotation: If present, text (OCR) detection or document
// (OCR) text detection has completed successfully. This annotation
// provides the structural hierarchy for the OCR detected text.
FullTextAnnotation *GoogleCloudVisionV1p2beta1TextAnnotation `json:"fullTextAnnotation,omitempty"`
// ImagePropertiesAnnotation: If present, image properties were
// extracted successfully.
ImagePropertiesAnnotation *GoogleCloudVisionV1p2beta1ImageProperties `json:"imagePropertiesAnnotation,omitempty"`
// LabelAnnotations: If present, label detection has completed
// successfully.
LabelAnnotations []*GoogleCloudVisionV1p2beta1EntityAnnotation `json:"labelAnnotations,omitempty"`
// LandmarkAnnotations: If present, landmark detection has completed
// successfully.
LandmarkAnnotations []*GoogleCloudVisionV1p2beta1EntityAnnotation `json:"landmarkAnnotations,omitempty"`
// LocalizedObjectAnnotations: If present, localized object detection
// has completed successfully. This will be sorted descending by
// confidence score.
LocalizedObjectAnnotations []*GoogleCloudVisionV1p2beta1LocalizedObjectAnnotation `json:"localizedObjectAnnotations,omitempty"`
// LogoAnnotations: If present, logo detection has completed
// successfully.
LogoAnnotations []*GoogleCloudVisionV1p2beta1EntityAnnotation `json:"logoAnnotations,omitempty"`
// ProductSearchResults: If present, product search has completed
// successfully.
ProductSearchResults *GoogleCloudVisionV1p2beta1ProductSearchResults `json:"productSearchResults,omitempty"`
// SafeSearchAnnotation: If present, safe-search annotation has
// completed successfully.
SafeSearchAnnotation *GoogleCloudVisionV1p2beta1SafeSearchAnnotation `json:"safeSearchAnnotation,omitempty"`
// TextAnnotations: If present, text (OCR) detection has completed
// successfully.
TextAnnotations []*GoogleCloudVisionV1p2beta1EntityAnnotation `json:"textAnnotations,omitempty"`
// WebDetection: If present, web detection has completed successfully.
WebDetection *GoogleCloudVisionV1p2beta1WebDetection `json:"webDetection,omitempty"`
// ForceSendFields is a list of field names (e.g. "Context") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Context") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1AnnotateImageResponse) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1AnnotateImageResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p2beta1AsyncAnnotateFileResponse: The response for
// a single offline file annotation request.
type GoogleCloudVisionV1p2beta1AsyncAnnotateFileResponse struct {
// OutputConfig: The output location and metadata from
// AsyncAnnotateFileRequest.
OutputConfig *GoogleCloudVisionV1p2beta1OutputConfig `json:"outputConfig,omitempty"`
// ForceSendFields is a list of field names (e.g. "OutputConfig") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "OutputConfig") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1AsyncAnnotateFileResponse) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1AsyncAnnotateFileResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p2beta1AsyncBatchAnnotateFilesResponse: Response
// to an async batch file annotation request.
type GoogleCloudVisionV1p2beta1AsyncBatchAnnotateFilesResponse struct {
// Responses: The list of file annotation responses, one for each
// request in AsyncBatchAnnotateFilesRequest.
Responses []*GoogleCloudVisionV1p2beta1AsyncAnnotateFileResponse `json:"responses,omitempty"`
// ForceSendFields is a list of field names (e.g. "Responses") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Responses") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1AsyncBatchAnnotateFilesResponse) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1AsyncBatchAnnotateFilesResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p2beta1Block: Logical element on the page.
type GoogleCloudVisionV1p2beta1Block struct {
// BlockType: Detected block type (text, image etc) for this block.
//
// Possible values:
// "UNKNOWN" - Unknown block type.
// "TEXT" - Regular text block.
// "TABLE" - Table block.
// "PICTURE" - Image block.
// "RULER" - Horizontal/vertical line box.
// "BARCODE" - Barcode block.
BlockType string `json:"blockType,omitempty"`
// BoundingBox: The bounding box for the block. The vertices are in the
// order of top-left, top-right, bottom-right, bottom-left. When a
// rotation of the bounding box is detected the rotation is represented
// as around the top-left corner as defined when the text is read in the
// 'natural' orientation. For example: * when the text is horizontal it
// might look like: 0----1 | | 3----2 * when it's rotated 180 degrees
// around the top-left corner it becomes: 2----3 | | 1----0 and the
// vertex order will still be (0, 1, 2, 3).
BoundingBox *GoogleCloudVisionV1p2beta1BoundingPoly `json:"boundingBox,omitempty"`
// Confidence: Confidence of the OCR results on the block. Range [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// Paragraphs: List of paragraphs in this block (if this blocks is of
// type text).
Paragraphs []*GoogleCloudVisionV1p2beta1Paragraph `json:"paragraphs,omitempty"`
// Property: Additional information detected for the block.
Property *GoogleCloudVisionV1p2beta1TextAnnotationTextProperty `json:"property,omitempty"`
// ForceSendFields is a list of field names (e.g. "BlockType") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BlockType") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1Block) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1Block
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p2beta1Block) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p2beta1Block
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
return nil
}
// GoogleCloudVisionV1p2beta1BoundingPoly: A bounding polygon for the
// detected image annotation.
type GoogleCloudVisionV1p2beta1BoundingPoly struct {
// NormalizedVertices: The bounding polygon normalized vertices.
NormalizedVertices []*GoogleCloudVisionV1p2beta1NormalizedVertex `json:"normalizedVertices,omitempty"`
// Vertices: The bounding polygon vertices.
Vertices []*GoogleCloudVisionV1p2beta1Vertex `json:"vertices,omitempty"`
// ForceSendFields is a list of field names (e.g. "NormalizedVertices")
// to unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "NormalizedVertices") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1BoundingPoly) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1BoundingPoly
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p2beta1ColorInfo: Color information consists of
// RGB channels, score, and the fraction of the image that the color
// occupies in the image.
type GoogleCloudVisionV1p2beta1ColorInfo struct {
// Color: RGB components of the color.
Color *Color `json:"color,omitempty"`
// PixelFraction: The fraction of pixels the color occupies in the
// image. Value in range [0, 1].
PixelFraction float64 `json:"pixelFraction,omitempty"`
// Score: Image-specific score for this color. Value in range [0, 1].
Score float64 `json:"score,omitempty"`
// ForceSendFields is a list of field names (e.g. "Color") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Color") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1ColorInfo) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1ColorInfo
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p2beta1ColorInfo) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p2beta1ColorInfo
var s1 struct {
PixelFraction gensupport.JSONFloat64 `json:"pixelFraction"`
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.PixelFraction = float64(s1.PixelFraction)
s.Score = float64(s1.Score)
return nil
}
// GoogleCloudVisionV1p2beta1CropHint: Single crop hint that is used to
// generate a new crop when serving an image.
type GoogleCloudVisionV1p2beta1CropHint struct {
// BoundingPoly: The bounding polygon for the crop region. The
// coordinates of the bounding box are in the original image's scale.
BoundingPoly *GoogleCloudVisionV1p2beta1BoundingPoly `json:"boundingPoly,omitempty"`
// Confidence: Confidence of this being a salient region. Range [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// ImportanceFraction: Fraction of importance of this salient region
// with respect to the original image.
ImportanceFraction float64 `json:"importanceFraction,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingPoly") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingPoly") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1CropHint) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1CropHint
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p2beta1CropHint) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p2beta1CropHint
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
ImportanceFraction gensupport.JSONFloat64 `json:"importanceFraction"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
s.ImportanceFraction = float64(s1.ImportanceFraction)
return nil
}
// GoogleCloudVisionV1p2beta1CropHintsAnnotation: Set of crop hints that
// are used to generate new crops when serving images.
type GoogleCloudVisionV1p2beta1CropHintsAnnotation struct {
// CropHints: Crop hint results.
CropHints []*GoogleCloudVisionV1p2beta1CropHint `json:"cropHints,omitempty"`
// ForceSendFields is a list of field names (e.g. "CropHints") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CropHints") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1CropHintsAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1CropHintsAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p2beta1DominantColorsAnnotation: Set of dominant
// colors and their corresponding scores.
type GoogleCloudVisionV1p2beta1DominantColorsAnnotation struct {
// Colors: RGB color values with their score and pixel fraction.
Colors []*GoogleCloudVisionV1p2beta1ColorInfo `json:"colors,omitempty"`
// ForceSendFields is a list of field names (e.g. "Colors") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Colors") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1DominantColorsAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1DominantColorsAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p2beta1EntityAnnotation: Set of detected entity
// features.
type GoogleCloudVisionV1p2beta1EntityAnnotation struct {
// BoundingPoly: Image region to which this entity belongs. Not produced
// for `LABEL_DETECTION` features.
BoundingPoly *GoogleCloudVisionV1p2beta1BoundingPoly `json:"boundingPoly,omitempty"`
// Confidence: **Deprecated. Use `score` instead.** The accuracy of the
// entity detection in an image. For example, for an image in which the
// "Eiffel Tower" entity is detected, this field represents the
// confidence that there is a tower in the query image. Range [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// Description: Entity textual description, expressed in its `locale`
// language.
Description string `json:"description,omitempty"`
// Locale: The language code for the locale in which the entity textual
// `description` is expressed.
Locale string `json:"locale,omitempty"`
// Locations: The location information for the detected entity. Multiple
// `LocationInfo` elements can be present because one location may
// indicate the location of the scene in the image, and another location
// may indicate the location of the place where the image was taken.
// Location information is usually present for landmarks.
Locations []*GoogleCloudVisionV1p2beta1LocationInfo `json:"locations,omitempty"`
// Mid: Opaque entity ID. Some IDs may be available in Google Knowledge
// Graph Search API (https://developers.google.com/knowledge-graph/).
Mid string `json:"mid,omitempty"`
// Properties: Some entities may have optional user-supplied `Property`
// (name/value) fields, such a score or string that qualifies the
// entity.
Properties []*GoogleCloudVisionV1p2beta1Property `json:"properties,omitempty"`
// Score: Overall score of the result. Range [0, 1].
Score float64 `json:"score,omitempty"`
// Topicality: The relevancy of the ICA (Image Content Annotation) label
// to the image. For example, the relevancy of "tower" is likely higher
// to an image containing the detected "Eiffel Tower" than to an image
// containing a detected distant towering building, even though the
// confidence that there is a tower in each image may be the same. Range
// [0, 1].
Topicality float64 `json:"topicality,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingPoly") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingPoly") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1EntityAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1EntityAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p2beta1EntityAnnotation) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p2beta1EntityAnnotation
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
Score gensupport.JSONFloat64 `json:"score"`
Topicality gensupport.JSONFloat64 `json:"topicality"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
s.Score = float64(s1.Score)
s.Topicality = float64(s1.Topicality)
return nil
}
// GoogleCloudVisionV1p2beta1FaceAnnotation: A face annotation object
// contains the results of face detection.
type GoogleCloudVisionV1p2beta1FaceAnnotation struct {
// AngerLikelihood: Anger likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
AngerLikelihood string `json:"angerLikelihood,omitempty"`
// BlurredLikelihood: Blurred likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
BlurredLikelihood string `json:"blurredLikelihood,omitempty"`
// BoundingPoly: The bounding polygon around the face. The coordinates
// of the bounding box are in the original image's scale. The bounding
// box is computed to "frame" the face in accordance with human
// expectations. It is based on the landmarker results. Note that one or
// more x and/or y coordinates may not be generated in the
// `BoundingPoly` (the polygon will be unbounded) if only a partial face
// appears in the image to be annotated.
BoundingPoly *GoogleCloudVisionV1p2beta1BoundingPoly `json:"boundingPoly,omitempty"`
// DetectionConfidence: Detection confidence. Range [0, 1].
DetectionConfidence float64 `json:"detectionConfidence,omitempty"`
// FdBoundingPoly: The `fd_bounding_poly` bounding polygon is tighter
// than the `boundingPoly`, and encloses only the skin part of the face.
// Typically, it is used to eliminate the face from any image analysis
// that detects the "amount of skin" visible in an image. It is not
// based on the landmarker results, only on the initial face detection,
// hence the fd (face detection) prefix.
FdBoundingPoly *GoogleCloudVisionV1p2beta1BoundingPoly `json:"fdBoundingPoly,omitempty"`
// HeadwearLikelihood: Headwear likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
HeadwearLikelihood string `json:"headwearLikelihood,omitempty"`
// JoyLikelihood: Joy likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
JoyLikelihood string `json:"joyLikelihood,omitempty"`
// LandmarkingConfidence: Face landmarking confidence. Range [0, 1].
LandmarkingConfidence float64 `json:"landmarkingConfidence,omitempty"`
// Landmarks: Detected face landmarks.
Landmarks []*GoogleCloudVisionV1p2beta1FaceAnnotationLandmark `json:"landmarks,omitempty"`
// PanAngle: Yaw angle, which indicates the leftward/rightward angle
// that the face is pointing relative to the vertical plane
// perpendicular to the image. Range [-180,180].
PanAngle float64 `json:"panAngle,omitempty"`
// RollAngle: Roll angle, which indicates the amount of
// clockwise/anti-clockwise rotation of the face relative to the image
// vertical about the axis perpendicular to the face. Range [-180,180].
RollAngle float64 `json:"rollAngle,omitempty"`
// SorrowLikelihood: Sorrow likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
SorrowLikelihood string `json:"sorrowLikelihood,omitempty"`
// SurpriseLikelihood: Surprise likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
SurpriseLikelihood string `json:"surpriseLikelihood,omitempty"`
// TiltAngle: Pitch angle, which indicates the upwards/downwards angle
// that the face is pointing relative to the image's horizontal plane.
// Range [-180,180].
TiltAngle float64 `json:"tiltAngle,omitempty"`
// UnderExposedLikelihood: Under-exposed likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
UnderExposedLikelihood string `json:"underExposedLikelihood,omitempty"`
// ForceSendFields is a list of field names (e.g. "AngerLikelihood") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "AngerLikelihood") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1FaceAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1FaceAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p2beta1FaceAnnotation) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p2beta1FaceAnnotation
var s1 struct {
DetectionConfidence gensupport.JSONFloat64 `json:"detectionConfidence"`
LandmarkingConfidence gensupport.JSONFloat64 `json:"landmarkingConfidence"`
PanAngle gensupport.JSONFloat64 `json:"panAngle"`
RollAngle gensupport.JSONFloat64 `json:"rollAngle"`
TiltAngle gensupport.JSONFloat64 `json:"tiltAngle"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.DetectionConfidence = float64(s1.DetectionConfidence)
s.LandmarkingConfidence = float64(s1.LandmarkingConfidence)
s.PanAngle = float64(s1.PanAngle)
s.RollAngle = float64(s1.RollAngle)
s.TiltAngle = float64(s1.TiltAngle)
return nil
}
// GoogleCloudVisionV1p2beta1FaceAnnotationLandmark: A face-specific
// landmark (for example, a face feature).
type GoogleCloudVisionV1p2beta1FaceAnnotationLandmark struct {
// Position: Face landmark position.
Position *GoogleCloudVisionV1p2beta1Position `json:"position,omitempty"`
// Type: Face landmark type.
//
// Possible values:
// "UNKNOWN_LANDMARK" - Unknown face landmark detected. Should not be
// filled.
// "LEFT_EYE" - Left eye.
// "RIGHT_EYE" - Right eye.
// "LEFT_OF_LEFT_EYEBROW" - Left of left eyebrow.
// "RIGHT_OF_LEFT_EYEBROW" - Right of left eyebrow.
// "LEFT_OF_RIGHT_EYEBROW" - Left of right eyebrow.
// "RIGHT_OF_RIGHT_EYEBROW" - Right of right eyebrow.
// "MIDPOINT_BETWEEN_EYES" - Midpoint between eyes.
// "NOSE_TIP" - Nose tip.
// "UPPER_LIP" - Upper lip.
// "LOWER_LIP" - Lower lip.
// "MOUTH_LEFT" - Mouth left.
// "MOUTH_RIGHT" - Mouth right.
// "MOUTH_CENTER" - Mouth center.
// "NOSE_BOTTOM_RIGHT" - Nose, bottom right.
// "NOSE_BOTTOM_LEFT" - Nose, bottom left.
// "NOSE_BOTTOM_CENTER" - Nose, bottom center.
// "LEFT_EYE_TOP_BOUNDARY" - Left eye, top boundary.
// "LEFT_EYE_RIGHT_CORNER" - Left eye, right corner.
// "LEFT_EYE_BOTTOM_BOUNDARY" - Left eye, bottom boundary.
// "LEFT_EYE_LEFT_CORNER" - Left eye, left corner.
// "RIGHT_EYE_TOP_BOUNDARY" - Right eye, top boundary.
// "RIGHT_EYE_RIGHT_CORNER" - Right eye, right corner.
// "RIGHT_EYE_BOTTOM_BOUNDARY" - Right eye, bottom boundary.
// "RIGHT_EYE_LEFT_CORNER" - Right eye, left corner.
// "LEFT_EYEBROW_UPPER_MIDPOINT" - Left eyebrow, upper midpoint.
// "RIGHT_EYEBROW_UPPER_MIDPOINT" - Right eyebrow, upper midpoint.
// "LEFT_EAR_TRAGION" - Left ear tragion.
// "RIGHT_EAR_TRAGION" - Right ear tragion.
// "LEFT_EYE_PUPIL" - Left eye pupil.
// "RIGHT_EYE_PUPIL" - Right eye pupil.
// "FOREHEAD_GLABELLA" - Forehead glabella.
// "CHIN_GNATHION" - Chin gnathion.
// "CHIN_LEFT_GONION" - Chin left gonion.
// "CHIN_RIGHT_GONION" - Chin right gonion.
// "LEFT_CHEEK_CENTER" - Left cheek center.
// "RIGHT_CHEEK_CENTER" - Right cheek center.
Type string `json:"type,omitempty"`
// ForceSendFields is a list of field names (e.g. "Position") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Position") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1FaceAnnotationLandmark) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1FaceAnnotationLandmark
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p2beta1GcsDestination: The Google Cloud Storage
// location where the output will be written to.
type GoogleCloudVisionV1p2beta1GcsDestination struct {
// Uri: Google Cloud Storage URI prefix where the results will be
// stored. Results will be in JSON format and preceded by its
// corresponding input URI prefix. This field can either represent a gcs
// file prefix or gcs directory. In either case, the uri should be
// unique because in order to get all of the output files, you will need
// to do a wildcard gcs search on the uri prefix you provide. Examples:
// * File Prefix: gs://bucket-name/here/filenameprefix The output files
// will be created in gs://bucket-name/here/ and the names of the output
// files will begin with "filenameprefix". * Directory Prefix:
// gs://bucket-name/some/location/ The output files will be created in
// gs://bucket-name/some/location/ and the names of the output files
// could be anything because there was no filename prefix specified. If
// multiple outputs, each response is still AnnotateFileResponse, each
// of which contains some subset of the full list of
// AnnotateImageResponse. Multiple outputs can happen if, for example,
// the output JSON is too large and overflows into multiple sharded
// files.
Uri string `json:"uri,omitempty"`
// ForceSendFields is a list of field names (e.g. "Uri") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Uri") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1GcsDestination) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1GcsDestination
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p2beta1GcsSource: The Google Cloud Storage
// location where the input will be read from.
type GoogleCloudVisionV1p2beta1GcsSource struct {
// Uri: Google Cloud Storage URI for the input file. This must only be a
// Google Cloud Storage object. Wildcards are not currently supported.
Uri string `json:"uri,omitempty"`
// ForceSendFields is a list of field names (e.g. "Uri") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Uri") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1GcsSource) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1GcsSource
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p2beta1ImageAnnotationContext: If an image was
// produced from a file (e.g. a PDF), this message gives information
// about the source of that image.
type GoogleCloudVisionV1p2beta1ImageAnnotationContext struct {
// PageNumber: If the file was a PDF or TIFF, this field gives the page
// number within the file used to produce the image.
PageNumber int64 `json:"pageNumber,omitempty"`
// Uri: The URI of the file used to produce the image.
Uri string `json:"uri,omitempty"`
// ForceSendFields is a list of field names (e.g. "PageNumber") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "PageNumber") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1ImageAnnotationContext) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1ImageAnnotationContext
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p2beta1ImageProperties: Stores image properties,
// such as dominant colors.
type GoogleCloudVisionV1p2beta1ImageProperties struct {
// DominantColors: If present, dominant colors completed successfully.
DominantColors *GoogleCloudVisionV1p2beta1DominantColorsAnnotation `json:"dominantColors,omitempty"`
// ForceSendFields is a list of field names (e.g. "DominantColors") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "DominantColors") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1ImageProperties) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1ImageProperties
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p2beta1InputConfig: The desired input location and
// metadata.
type GoogleCloudVisionV1p2beta1InputConfig struct {
// Content: File content, represented as a stream of bytes. Note: As
// with all `bytes` fields, protobuffers use a pure binary
// representation, whereas JSON representations use base64. Currently,
// this field only works for BatchAnnotateFiles requests. It does not
// work for AsyncBatchAnnotateFiles requests.
Content string `json:"content,omitempty"`
// GcsSource: The Google Cloud Storage location to read the input from.
GcsSource *GoogleCloudVisionV1p2beta1GcsSource `json:"gcsSource,omitempty"`
// MimeType: The type of the file. Currently only "application/pdf",
// "image/tiff" and "image/gif" are supported. Wildcards are not
// supported.
MimeType string `json:"mimeType,omitempty"`
// ForceSendFields is a list of field names (e.g. "Content") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Content") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1InputConfig) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1InputConfig
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p2beta1LocalizedObjectAnnotation: Set of detected
// objects with bounding boxes.
type GoogleCloudVisionV1p2beta1LocalizedObjectAnnotation struct {
// BoundingPoly: Image region to which this object belongs. This must be
// populated.
BoundingPoly *GoogleCloudVisionV1p2beta1BoundingPoly `json:"boundingPoly,omitempty"`
// LanguageCode: The BCP-47 language code, such as "en-US" or "sr-Latn".
// For more information, see
// http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
LanguageCode string `json:"languageCode,omitempty"`
// Mid: Object ID that should align with EntityAnnotation mid.
Mid string `json:"mid,omitempty"`
// Name: Object name, expressed in its `language_code` language.
Name string `json:"name,omitempty"`
// Score: Score of the result. Range [0, 1].
Score float64 `json:"score,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingPoly") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingPoly") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1LocalizedObjectAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1LocalizedObjectAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p2beta1LocalizedObjectAnnotation) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p2beta1LocalizedObjectAnnotation
var s1 struct {
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Score = float64(s1.Score)
return nil
}
// GoogleCloudVisionV1p2beta1LocationInfo: Detected entity location
// information.
type GoogleCloudVisionV1p2beta1LocationInfo struct {
// LatLng: lat/long location coordinates.
LatLng *LatLng `json:"latLng,omitempty"`
// ForceSendFields is a list of field names (e.g. "LatLng") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "LatLng") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1LocationInfo) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1LocationInfo
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p2beta1NormalizedVertex: A vertex represents a 2D
// point in the image. NOTE: the normalized vertex coordinates are
// relative to the original image and range from 0 to 1.
type GoogleCloudVisionV1p2beta1NormalizedVertex struct {
// X: X coordinate.
X float64 `json:"x,omitempty"`
// Y: Y coordinate.
Y float64 `json:"y,omitempty"`
// ForceSendFields is a list of field names (e.g. "X") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "X") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1NormalizedVertex) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1NormalizedVertex
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p2beta1NormalizedVertex) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p2beta1NormalizedVertex
var s1 struct {
X gensupport.JSONFloat64 `json:"x"`
Y gensupport.JSONFloat64 `json:"y"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.X = float64(s1.X)
s.Y = float64(s1.Y)
return nil
}
// GoogleCloudVisionV1p2beta1OperationMetadata: Contains metadata for
// the BatchAnnotateImages operation.
type GoogleCloudVisionV1p2beta1OperationMetadata struct {
// CreateTime: The time when the batch request was received.
CreateTime string `json:"createTime,omitempty"`
// State: Current state of the batch operation.
//
// Possible values:
// "STATE_UNSPECIFIED" - Invalid.
// "CREATED" - Request is received.
// "RUNNING" - Request is actively being processed.
// "DONE" - The batch processing is done.
// "CANCELLED" - The batch processing was cancelled.
State string `json:"state,omitempty"`
// UpdateTime: The time when the operation result was last updated.
UpdateTime string `json:"updateTime,omitempty"`
// ForceSendFields is a list of field names (e.g. "CreateTime") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CreateTime") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1OperationMetadata) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1OperationMetadata
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p2beta1OutputConfig: The desired output location
// and metadata.
type GoogleCloudVisionV1p2beta1OutputConfig struct {
// BatchSize: The max number of response protos to put into each output
// JSON file on Google Cloud Storage. The valid range is [1, 100]. If
// not specified, the default value is 20. For example, for one pdf file
// with 100 pages, 100 response protos will be generated. If
// `batch_size` = 20, then 5 json files each containing 20 response
// protos will be written under the prefix `gcs_destination`.`uri`.
// Currently, batch_size only applies to GcsDestination, with potential
// future support for other output configurations.
BatchSize int64 `json:"batchSize,omitempty"`
// GcsDestination: The Google Cloud Storage location to write the
// output(s) to.
GcsDestination *GoogleCloudVisionV1p2beta1GcsDestination `json:"gcsDestination,omitempty"`
// ForceSendFields is a list of field names (e.g. "BatchSize") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BatchSize") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1OutputConfig) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1OutputConfig
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p2beta1Page: Detected page from OCR.
type GoogleCloudVisionV1p2beta1Page struct {
// Blocks: List of blocks of text, images etc on this page.
Blocks []*GoogleCloudVisionV1p2beta1Block `json:"blocks,omitempty"`
// Confidence: Confidence of the OCR results on the page. Range [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// Height: Page height. For PDFs the unit is points. For images
// (including TIFFs) the unit is pixels.
Height int64 `json:"height,omitempty"`
// Property: Additional information detected on the page.
Property *GoogleCloudVisionV1p2beta1TextAnnotationTextProperty `json:"property,omitempty"`
// Width: Page width. For PDFs the unit is points. For images (including
// TIFFs) the unit is pixels.
Width int64 `json:"width,omitempty"`
// ForceSendFields is a list of field names (e.g. "Blocks") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Blocks") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1Page) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1Page
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p2beta1Page) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p2beta1Page
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
return nil
}
// GoogleCloudVisionV1p2beta1Paragraph: Structural unit of text
// representing a number of words in certain order.
type GoogleCloudVisionV1p2beta1Paragraph struct {
// BoundingBox: The bounding box for the paragraph. The vertices are in
// the order of top-left, top-right, bottom-right, bottom-left. When a
// rotation of the bounding box is detected the rotation is represented
// as around the top-left corner as defined when the text is read in the
// 'natural' orientation. For example: * when the text is horizontal it
// might look like: 0----1 | | 3----2 * when it's rotated 180 degrees
// around the top-left corner it becomes: 2----3 | | 1----0 and the
// vertex order will still be (0, 1, 2, 3).
BoundingBox *GoogleCloudVisionV1p2beta1BoundingPoly `json:"boundingBox,omitempty"`
// Confidence: Confidence of the OCR results for the paragraph. Range
// [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// Property: Additional information detected for the paragraph.
Property *GoogleCloudVisionV1p2beta1TextAnnotationTextProperty `json:"property,omitempty"`
// Words: List of all words in this paragraph.
Words []*GoogleCloudVisionV1p2beta1Word `json:"words,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingBox") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingBox") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1Paragraph) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1Paragraph
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p2beta1Paragraph) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p2beta1Paragraph
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
return nil
}
// GoogleCloudVisionV1p2beta1Position: A 3D position in the image, used
// primarily for Face detection landmarks. A valid Position must have
// both x and y coordinates. The position coordinates are in the same
// scale as the original image.
type GoogleCloudVisionV1p2beta1Position struct {
// X: X coordinate.
X float64 `json:"x,omitempty"`
// Y: Y coordinate.
Y float64 `json:"y,omitempty"`
// Z: Z coordinate (or depth).
Z float64 `json:"z,omitempty"`
// ForceSendFields is a list of field names (e.g. "X") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "X") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1Position) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1Position
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p2beta1Position) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p2beta1Position
var s1 struct {
X gensupport.JSONFloat64 `json:"x"`
Y gensupport.JSONFloat64 `json:"y"`
Z gensupport.JSONFloat64 `json:"z"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.X = float64(s1.X)
s.Y = float64(s1.Y)
s.Z = float64(s1.Z)
return nil
}
// GoogleCloudVisionV1p2beta1Product: A Product contains
// ReferenceImages.
type GoogleCloudVisionV1p2beta1Product struct {
// Description: User-provided metadata to be stored with this product.
// Must be at most 4096 characters long.
Description string `json:"description,omitempty"`
// DisplayName: The user-provided name for this Product. Must not be
// empty. Must be at most 4096 characters long.
DisplayName string `json:"displayName,omitempty"`
// Name: The resource name of the product. Format is:
// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`. This
// field is ignored when creating a product.
Name string `json:"name,omitempty"`
// ProductCategory: Immutable. The category for the product identified
// by the reference image. This should be one of "homegoods-v2",
// "apparel-v2", "toys-v2", "packagedgoods-v1" or "general-v1". The
// legacy categories "homegoods", "apparel", and "toys" are still
// supported, but these should not be used for new products.
ProductCategory string `json:"productCategory,omitempty"`
// ProductLabels: Key-value pairs that can be attached to a product. At
// query time, constraints can be specified based on the product_labels.
// Note that integer values can be provided as strings, e.g. "1199".
// Only strings with integer values can match a range-based restriction
// which is to be supported soon. Multiple values can be assigned to the
// same key. One product may have up to 500 product_labels. Notice that
// the total number of distinct product_labels over all products in one
// ProductSet cannot exceed 1M, otherwise the product search pipeline
// will refuse to work for that ProductSet.
ProductLabels []*GoogleCloudVisionV1p2beta1ProductKeyValue `json:"productLabels,omitempty"`
// ForceSendFields is a list of field names (e.g. "Description") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Description") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1Product) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1Product
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p2beta1ProductKeyValue: A product label
// represented as a key-value pair.
type GoogleCloudVisionV1p2beta1ProductKeyValue struct {
// Key: The key of the label attached to the product. Cannot be empty
// and cannot exceed 128 bytes.
Key string `json:"key,omitempty"`
// Value: The value of the label attached to the product. Cannot be
// empty and cannot exceed 128 bytes.
Value string `json:"value,omitempty"`
// ForceSendFields is a list of field names (e.g. "Key") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Key") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1ProductKeyValue) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1ProductKeyValue
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p2beta1ProductSearchResults: Results for a product
// search request.
type GoogleCloudVisionV1p2beta1ProductSearchResults struct {
// IndexTime: Timestamp of the index which provided these results.
// Products added to the product set and products removed from the
// product set after this time are not reflected in the current results.
IndexTime string `json:"indexTime,omitempty"`
// ProductGroupedResults: List of results grouped by products detected
// in the query image. Each entry corresponds to one bounding polygon in
// the query image, and contains the matching products specific to that
// region. There may be duplicate product matches in the union of all
// the per-product results.
ProductGroupedResults []*GoogleCloudVisionV1p2beta1ProductSearchResultsGroupedResult `json:"productGroupedResults,omitempty"`
// Results: List of results, one for each product match.
Results []*GoogleCloudVisionV1p2beta1ProductSearchResultsResult `json:"results,omitempty"`
// ForceSendFields is a list of field names (e.g. "IndexTime") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "IndexTime") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1ProductSearchResults) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1ProductSearchResults
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p2beta1ProductSearchResultsGroupedResult:
// Information about the products similar to a single product in a query
// image.
type GoogleCloudVisionV1p2beta1ProductSearchResultsGroupedResult struct {
// BoundingPoly: The bounding polygon around the product detected in the
// query image.
BoundingPoly *GoogleCloudVisionV1p2beta1BoundingPoly `json:"boundingPoly,omitempty"`
// ObjectAnnotations: List of generic predictions for the object in the
// bounding box.
ObjectAnnotations []*GoogleCloudVisionV1p2beta1ProductSearchResultsObjectAnnotation `json:"objectAnnotations,omitempty"`
// Results: List of results, one for each product match.
Results []*GoogleCloudVisionV1p2beta1ProductSearchResultsResult `json:"results,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingPoly") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingPoly") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1ProductSearchResultsGroupedResult) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1ProductSearchResultsGroupedResult
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p2beta1ProductSearchResultsObjectAnnotation:
// Prediction for what the object in the bounding box is.
type GoogleCloudVisionV1p2beta1ProductSearchResultsObjectAnnotation struct {
// LanguageCode: The BCP-47 language code, such as "en-US" or "sr-Latn".
// For more information, see
// http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
LanguageCode string `json:"languageCode,omitempty"`
// Mid: Object ID that should align with EntityAnnotation mid.
Mid string `json:"mid,omitempty"`
// Name: Object name, expressed in its `language_code` language.
Name string `json:"name,omitempty"`
// Score: Score of the result. Range [0, 1].
Score float64 `json:"score,omitempty"`
// ForceSendFields is a list of field names (e.g. "LanguageCode") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "LanguageCode") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1ProductSearchResultsObjectAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1ProductSearchResultsObjectAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p2beta1ProductSearchResultsObjectAnnotation) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p2beta1ProductSearchResultsObjectAnnotation
var s1 struct {
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Score = float64(s1.Score)
return nil
}
// GoogleCloudVisionV1p2beta1ProductSearchResultsResult: Information
// about a product.
type GoogleCloudVisionV1p2beta1ProductSearchResultsResult struct {
// Image: The resource name of the image from the product that is the
// closest match to the query.
Image string `json:"image,omitempty"`
// Product: The Product.
Product *GoogleCloudVisionV1p2beta1Product `json:"product,omitempty"`
// Score: A confidence level on the match, ranging from 0 (no
// confidence) to 1 (full confidence).
Score float64 `json:"score,omitempty"`
// ForceSendFields is a list of field names (e.g. "Image") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Image") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1ProductSearchResultsResult) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1ProductSearchResultsResult
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p2beta1ProductSearchResultsResult) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p2beta1ProductSearchResultsResult
var s1 struct {
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Score = float64(s1.Score)
return nil
}
// GoogleCloudVisionV1p2beta1Property: A `Property` consists of a
// user-supplied name/value pair.
type GoogleCloudVisionV1p2beta1Property struct {
// Name: Name of the property.
Name string `json:"name,omitempty"`
// Uint64Value: Value of numeric properties.
Uint64Value uint64 `json:"uint64Value,omitempty,string"`
// Value: Value of the property.
Value string `json:"value,omitempty"`
// ForceSendFields is a list of field names (e.g. "Name") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Name") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1Property) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1Property
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p2beta1SafeSearchAnnotation: Set of features
// pertaining to the image, computed by computer vision methods over
// safe-search verticals (for example, adult, spoof, medical, violence).
type GoogleCloudVisionV1p2beta1SafeSearchAnnotation struct {
// Adult: Represents the adult content likelihood for the image. Adult
// content may contain elements such as nudity, pornographic images or
// cartoons, or sexual activities.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
Adult string `json:"adult,omitempty"`
// Medical: Likelihood that this is a medical image.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
Medical string `json:"medical,omitempty"`
// Racy: Likelihood that the request image contains racy content. Racy
// content may include (but is not limited to) skimpy or sheer clothing,
// strategically covered nudity, lewd or provocative poses, or close-ups
// of sensitive body areas.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
Racy string `json:"racy,omitempty"`
// Spoof: Spoof likelihood. The likelihood that an modification was made
// to the image's canonical version to make it appear funny or
// offensive.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
Spoof string `json:"spoof,omitempty"`
// Violence: Likelihood that this image contains violent content.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
Violence string `json:"violence,omitempty"`
// ForceSendFields is a list of field names (e.g. "Adult") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Adult") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1SafeSearchAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1SafeSearchAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p2beta1Symbol: A single symbol representation.
type GoogleCloudVisionV1p2beta1Symbol struct {
// BoundingBox: The bounding box for the symbol. The vertices are in the
// order of top-left, top-right, bottom-right, bottom-left. When a
// rotation of the bounding box is detected the rotation is represented
// as around the top-left corner as defined when the text is read in the
// 'natural' orientation. For example: * when the text is horizontal it
// might look like: 0----1 | | 3----2 * when it's rotated 180 degrees
// around the top-left corner it becomes: 2----3 | | 1----0 and the
// vertex order will still be (0, 1, 2, 3).
BoundingBox *GoogleCloudVisionV1p2beta1BoundingPoly `json:"boundingBox,omitempty"`
// Confidence: Confidence of the OCR results for the symbol. Range [0,
// 1].
Confidence float64 `json:"confidence,omitempty"`
// Property: Additional information detected for the symbol.
Property *GoogleCloudVisionV1p2beta1TextAnnotationTextProperty `json:"property,omitempty"`
// Text: The actual UTF-8 representation of the symbol.
Text string `json:"text,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingBox") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingBox") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1Symbol) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1Symbol
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p2beta1Symbol) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p2beta1Symbol
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
return nil
}
// GoogleCloudVisionV1p2beta1TextAnnotation: TextAnnotation contains a
// structured representation of OCR extracted text. The hierarchy of an
// OCR extracted text structure is like this: TextAnnotation -> Page ->
// Block -> Paragraph -> Word -> Symbol Each structural component,
// starting from Page, may further have their own properties. Properties
// describe detected languages, breaks etc.. Please refer to the
// TextAnnotation.TextProperty message definition below for more detail.
type GoogleCloudVisionV1p2beta1TextAnnotation struct {
// Pages: List of pages detected by OCR.
Pages []*GoogleCloudVisionV1p2beta1Page `json:"pages,omitempty"`
// Text: UTF-8 text detected on the pages.
Text string `json:"text,omitempty"`
// ForceSendFields is a list of field names (e.g. "Pages") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Pages") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1TextAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1TextAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p2beta1TextAnnotationDetectedBreak: Detected start
// or end of a structural component.
type GoogleCloudVisionV1p2beta1TextAnnotationDetectedBreak struct {
// IsPrefix: True if break prepends the element.
IsPrefix bool `json:"isPrefix,omitempty"`
// Type: Detected break type.
//
// Possible values:
// "UNKNOWN" - Unknown break label type.
// "SPACE" - Regular space.
// "SURE_SPACE" - Sure space (very wide).
// "EOL_SURE_SPACE" - Line-wrapping break.
// "HYPHEN" - End-line hyphen that is not present in text; does not
// co-occur with `SPACE`, `LEADER_SPACE`, or `LINE_BREAK`.
// "LINE_BREAK" - Line break that ends a paragraph.
Type string `json:"type,omitempty"`
// ForceSendFields is a list of field names (e.g. "IsPrefix") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "IsPrefix") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1TextAnnotationDetectedBreak) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1TextAnnotationDetectedBreak
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p2beta1TextAnnotationDetectedLanguage: Detected
// language for a structural component.
type GoogleCloudVisionV1p2beta1TextAnnotationDetectedLanguage struct {
// Confidence: Confidence of detected language. Range [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// LanguageCode: The BCP-47 language code, such as "en-US" or "sr-Latn".
// For more information, see
// http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
LanguageCode string `json:"languageCode,omitempty"`
// ForceSendFields is a list of field names (e.g. "Confidence") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Confidence") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1TextAnnotationDetectedLanguage) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1TextAnnotationDetectedLanguage
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p2beta1TextAnnotationDetectedLanguage) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p2beta1TextAnnotationDetectedLanguage
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
return nil
}
// GoogleCloudVisionV1p2beta1TextAnnotationTextProperty: Additional
// information detected on the structural component.
type GoogleCloudVisionV1p2beta1TextAnnotationTextProperty struct {
// DetectedBreak: Detected start or end of a text segment.
DetectedBreak *GoogleCloudVisionV1p2beta1TextAnnotationDetectedBreak `json:"detectedBreak,omitempty"`
// DetectedLanguages: A list of detected languages together with
// confidence.
DetectedLanguages []*GoogleCloudVisionV1p2beta1TextAnnotationDetectedLanguage `json:"detectedLanguages,omitempty"`
// ForceSendFields is a list of field names (e.g. "DetectedBreak") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "DetectedBreak") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1TextAnnotationTextProperty) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1TextAnnotationTextProperty
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p2beta1Vertex: A vertex represents a 2D point in
// the image. NOTE: the vertex coordinates are in the same scale as the
// original image.
type GoogleCloudVisionV1p2beta1Vertex struct {
// X: X coordinate.
X int64 `json:"x,omitempty"`
// Y: Y coordinate.
Y int64 `json:"y,omitempty"`
// ForceSendFields is a list of field names (e.g. "X") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "X") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1Vertex) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1Vertex
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p2beta1WebDetection: Relevant information for the
// image from the Internet.
type GoogleCloudVisionV1p2beta1WebDetection struct {
// BestGuessLabels: The service's best guess as to the topic of the
// request image. Inferred from similar images on the open web.
BestGuessLabels []*GoogleCloudVisionV1p2beta1WebDetectionWebLabel `json:"bestGuessLabels,omitempty"`
// FullMatchingImages: Fully matching images from the Internet. Can
// include resized copies of the query image.
FullMatchingImages []*GoogleCloudVisionV1p2beta1WebDetectionWebImage `json:"fullMatchingImages,omitempty"`
// PagesWithMatchingImages: Web pages containing the matching images
// from the Internet.
PagesWithMatchingImages []*GoogleCloudVisionV1p2beta1WebDetectionWebPage `json:"pagesWithMatchingImages,omitempty"`
// PartialMatchingImages: Partial matching images from the Internet.
// Those images are similar enough to share some key-point features. For
// example an original image will likely have partial matching for its
// crops.
PartialMatchingImages []*GoogleCloudVisionV1p2beta1WebDetectionWebImage `json:"partialMatchingImages,omitempty"`
// VisuallySimilarImages: The visually similar image results.
VisuallySimilarImages []*GoogleCloudVisionV1p2beta1WebDetectionWebImage `json:"visuallySimilarImages,omitempty"`
// WebEntities: Deduced entities from similar images on the Internet.
WebEntities []*GoogleCloudVisionV1p2beta1WebDetectionWebEntity `json:"webEntities,omitempty"`
// ForceSendFields is a list of field names (e.g. "BestGuessLabels") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BestGuessLabels") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1WebDetection) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1WebDetection
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p2beta1WebDetectionWebEntity: Entity deduced from
// similar images on the Internet.
type GoogleCloudVisionV1p2beta1WebDetectionWebEntity struct {
// Description: Canonical description of the entity, in English.
Description string `json:"description,omitempty"`
// EntityId: Opaque entity ID.
EntityId string `json:"entityId,omitempty"`
// Score: Overall relevancy score for the entity. Not normalized and not
// comparable across different image queries.
Score float64 `json:"score,omitempty"`
// ForceSendFields is a list of field names (e.g. "Description") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Description") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1WebDetectionWebEntity) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1WebDetectionWebEntity
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p2beta1WebDetectionWebEntity) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p2beta1WebDetectionWebEntity
var s1 struct {
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Score = float64(s1.Score)
return nil
}
// GoogleCloudVisionV1p2beta1WebDetectionWebImage: Metadata for online
// images.
type GoogleCloudVisionV1p2beta1WebDetectionWebImage struct {
// Score: (Deprecated) Overall relevancy score for the image.
Score float64 `json:"score,omitempty"`
// Url: The result image URL.
Url string `json:"url,omitempty"`
// ForceSendFields is a list of field names (e.g. "Score") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Score") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1WebDetectionWebImage) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1WebDetectionWebImage
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p2beta1WebDetectionWebImage) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p2beta1WebDetectionWebImage
var s1 struct {
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Score = float64(s1.Score)
return nil
}
// GoogleCloudVisionV1p2beta1WebDetectionWebLabel: Label to provide
// extra metadata for the web detection.
type GoogleCloudVisionV1p2beta1WebDetectionWebLabel struct {
// Label: Label for extra metadata.
Label string `json:"label,omitempty"`
// LanguageCode: The BCP-47 language code for `label`, such as "en-US"
// or "sr-Latn". For more information, see
// http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
LanguageCode string `json:"languageCode,omitempty"`
// ForceSendFields is a list of field names (e.g. "Label") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Label") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1WebDetectionWebLabel) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1WebDetectionWebLabel
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p2beta1WebDetectionWebPage: Metadata for web
// pages.
type GoogleCloudVisionV1p2beta1WebDetectionWebPage struct {
// FullMatchingImages: Fully matching images on the page. Can include
// resized copies of the query image.
FullMatchingImages []*GoogleCloudVisionV1p2beta1WebDetectionWebImage `json:"fullMatchingImages,omitempty"`
// PageTitle: Title for the web page, may contain HTML markups.
PageTitle string `json:"pageTitle,omitempty"`
// PartialMatchingImages: Partial matching images on the page. Those
// images are similar enough to share some key-point features. For
// example an original image will likely have partial matching for its
// crops.
PartialMatchingImages []*GoogleCloudVisionV1p2beta1WebDetectionWebImage `json:"partialMatchingImages,omitempty"`
// Score: (Deprecated) Overall relevancy score for the web page.
Score float64 `json:"score,omitempty"`
// Url: The result web page URL.
Url string `json:"url,omitempty"`
// ForceSendFields is a list of field names (e.g. "FullMatchingImages")
// to unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "FullMatchingImages") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1WebDetectionWebPage) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1WebDetectionWebPage
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p2beta1WebDetectionWebPage) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p2beta1WebDetectionWebPage
var s1 struct {
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Score = float64(s1.Score)
return nil
}
// GoogleCloudVisionV1p2beta1Word: A word representation.
type GoogleCloudVisionV1p2beta1Word struct {
// BoundingBox: The bounding box for the word. The vertices are in the
// order of top-left, top-right, bottom-right, bottom-left. When a
// rotation of the bounding box is detected the rotation is represented
// as around the top-left corner as defined when the text is read in the
// 'natural' orientation. For example: * when the text is horizontal it
// might look like: 0----1 | | 3----2 * when it's rotated 180 degrees
// around the top-left corner it becomes: 2----3 | | 1----0 and the
// vertex order will still be (0, 1, 2, 3).
BoundingBox *GoogleCloudVisionV1p2beta1BoundingPoly `json:"boundingBox,omitempty"`
// Confidence: Confidence of the OCR results for the word. Range [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// Property: Additional information detected for the word.
Property *GoogleCloudVisionV1p2beta1TextAnnotationTextProperty `json:"property,omitempty"`
// Symbols: List of symbols in the word. The order of the symbols
// follows the natural reading order.
Symbols []*GoogleCloudVisionV1p2beta1Symbol `json:"symbols,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingBox") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingBox") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p2beta1Word) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p2beta1Word
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p2beta1Word) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p2beta1Word
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
return nil
}
// GoogleCloudVisionV1p3beta1AnnotateFileResponse: Response to a single
// file annotation request. A file may contain one or more images, which
// individually have their own responses.
type GoogleCloudVisionV1p3beta1AnnotateFileResponse struct {
// Error: If set, represents the error message for the failed request.
// The `responses` field will not be set in this case.
Error *Status `json:"error,omitempty"`
// InputConfig: Information about the file for which this response is
// generated.
InputConfig *GoogleCloudVisionV1p3beta1InputConfig `json:"inputConfig,omitempty"`
// Responses: Individual responses to images found within the file. This
// field will be empty if the `error` field is set.
Responses []*GoogleCloudVisionV1p3beta1AnnotateImageResponse `json:"responses,omitempty"`
// TotalPages: This field gives the total number of pages in the file.
TotalPages int64 `json:"totalPages,omitempty"`
// ForceSendFields is a list of field names (e.g. "Error") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Error") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1AnnotateFileResponse) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1AnnotateFileResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p3beta1AnnotateImageResponse: Response to an image
// annotation request.
type GoogleCloudVisionV1p3beta1AnnotateImageResponse struct {
// Context: If present, contextual information is needed to understand
// where this image comes from.
Context *GoogleCloudVisionV1p3beta1ImageAnnotationContext `json:"context,omitempty"`
// CropHintsAnnotation: If present, crop hints have completed
// successfully.
CropHintsAnnotation *GoogleCloudVisionV1p3beta1CropHintsAnnotation `json:"cropHintsAnnotation,omitempty"`
// Error: If set, represents the error message for the operation. Note
// that filled-in image annotations are guaranteed to be correct, even
// when `error` is set.
Error *Status `json:"error,omitempty"`
// FaceAnnotations: If present, face detection has completed
// successfully.
FaceAnnotations []*GoogleCloudVisionV1p3beta1FaceAnnotation `json:"faceAnnotations,omitempty"`
// FullTextAnnotation: If present, text (OCR) detection or document
// (OCR) text detection has completed successfully. This annotation
// provides the structural hierarchy for the OCR detected text.
FullTextAnnotation *GoogleCloudVisionV1p3beta1TextAnnotation `json:"fullTextAnnotation,omitempty"`
// ImagePropertiesAnnotation: If present, image properties were
// extracted successfully.
ImagePropertiesAnnotation *GoogleCloudVisionV1p3beta1ImageProperties `json:"imagePropertiesAnnotation,omitempty"`
// LabelAnnotations: If present, label detection has completed
// successfully.
LabelAnnotations []*GoogleCloudVisionV1p3beta1EntityAnnotation `json:"labelAnnotations,omitempty"`
// LandmarkAnnotations: If present, landmark detection has completed
// successfully.
LandmarkAnnotations []*GoogleCloudVisionV1p3beta1EntityAnnotation `json:"landmarkAnnotations,omitempty"`
// LocalizedObjectAnnotations: If present, localized object detection
// has completed successfully. This will be sorted descending by
// confidence score.
LocalizedObjectAnnotations []*GoogleCloudVisionV1p3beta1LocalizedObjectAnnotation `json:"localizedObjectAnnotations,omitempty"`
// LogoAnnotations: If present, logo detection has completed
// successfully.
LogoAnnotations []*GoogleCloudVisionV1p3beta1EntityAnnotation `json:"logoAnnotations,omitempty"`
// ProductSearchResults: If present, product search has completed
// successfully.
ProductSearchResults *GoogleCloudVisionV1p3beta1ProductSearchResults `json:"productSearchResults,omitempty"`
// SafeSearchAnnotation: If present, safe-search annotation has
// completed successfully.
SafeSearchAnnotation *GoogleCloudVisionV1p3beta1SafeSearchAnnotation `json:"safeSearchAnnotation,omitempty"`
// TextAnnotations: If present, text (OCR) detection has completed
// successfully.
TextAnnotations []*GoogleCloudVisionV1p3beta1EntityAnnotation `json:"textAnnotations,omitempty"`
// WebDetection: If present, web detection has completed successfully.
WebDetection *GoogleCloudVisionV1p3beta1WebDetection `json:"webDetection,omitempty"`
// ForceSendFields is a list of field names (e.g. "Context") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Context") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1AnnotateImageResponse) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1AnnotateImageResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p3beta1AsyncAnnotateFileResponse: The response for
// a single offline file annotation request.
type GoogleCloudVisionV1p3beta1AsyncAnnotateFileResponse struct {
// OutputConfig: The output location and metadata from
// AsyncAnnotateFileRequest.
OutputConfig *GoogleCloudVisionV1p3beta1OutputConfig `json:"outputConfig,omitempty"`
// ForceSendFields is a list of field names (e.g. "OutputConfig") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "OutputConfig") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1AsyncAnnotateFileResponse) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1AsyncAnnotateFileResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p3beta1AsyncBatchAnnotateFilesResponse: Response
// to an async batch file annotation request.
type GoogleCloudVisionV1p3beta1AsyncBatchAnnotateFilesResponse struct {
// Responses: The list of file annotation responses, one for each
// request in AsyncBatchAnnotateFilesRequest.
Responses []*GoogleCloudVisionV1p3beta1AsyncAnnotateFileResponse `json:"responses,omitempty"`
// ForceSendFields is a list of field names (e.g. "Responses") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Responses") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1AsyncBatchAnnotateFilesResponse) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1AsyncBatchAnnotateFilesResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p3beta1BatchOperationMetadata: Metadata for the
// batch operations such as the current state. This is included in the
// `metadata` field of the `Operation` returned by the `GetOperation`
// call of the `google::longrunning::Operations` service.
type GoogleCloudVisionV1p3beta1BatchOperationMetadata struct {
// EndTime: The time when the batch request is finished and
// google.longrunning.Operation.done is set to true.
EndTime string `json:"endTime,omitempty"`
// State: The current state of the batch operation.
//
// Possible values:
// "STATE_UNSPECIFIED" - Invalid.
// "PROCESSING" - Request is actively being processed.
// "SUCCESSFUL" - The request is done and at least one item has been
// successfully processed.
// "FAILED" - The request is done and no item has been successfully
// processed.
// "CANCELLED" - The request is done after the
// longrunning.Operations.CancelOperation has been called by the user.
// Any records that were processed before the cancel command are output
// as specified in the request.
State string `json:"state,omitempty"`
// SubmitTime: The time when the batch request was submitted to the
// server.
SubmitTime string `json:"submitTime,omitempty"`
// ForceSendFields is a list of field names (e.g. "EndTime") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "EndTime") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1BatchOperationMetadata) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1BatchOperationMetadata
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p3beta1Block: Logical element on the page.
type GoogleCloudVisionV1p3beta1Block struct {
// BlockType: Detected block type (text, image etc) for this block.
//
// Possible values:
// "UNKNOWN" - Unknown block type.
// "TEXT" - Regular text block.
// "TABLE" - Table block.
// "PICTURE" - Image block.
// "RULER" - Horizontal/vertical line box.
// "BARCODE" - Barcode block.
BlockType string `json:"blockType,omitempty"`
// BoundingBox: The bounding box for the block. The vertices are in the
// order of top-left, top-right, bottom-right, bottom-left. When a
// rotation of the bounding box is detected the rotation is represented
// as around the top-left corner as defined when the text is read in the
// 'natural' orientation. For example: * when the text is horizontal it
// might look like: 0----1 | | 3----2 * when it's rotated 180 degrees
// around the top-left corner it becomes: 2----3 | | 1----0 and the
// vertex order will still be (0, 1, 2, 3).
BoundingBox *GoogleCloudVisionV1p3beta1BoundingPoly `json:"boundingBox,omitempty"`
// Confidence: Confidence of the OCR results on the block. Range [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// Paragraphs: List of paragraphs in this block (if this blocks is of
// type text).
Paragraphs []*GoogleCloudVisionV1p3beta1Paragraph `json:"paragraphs,omitempty"`
// Property: Additional information detected for the block.
Property *GoogleCloudVisionV1p3beta1TextAnnotationTextProperty `json:"property,omitempty"`
// ForceSendFields is a list of field names (e.g. "BlockType") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BlockType") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1Block) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1Block
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p3beta1Block) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p3beta1Block
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
return nil
}
// GoogleCloudVisionV1p3beta1BoundingPoly: A bounding polygon for the
// detected image annotation.
type GoogleCloudVisionV1p3beta1BoundingPoly struct {
// NormalizedVertices: The bounding polygon normalized vertices.
NormalizedVertices []*GoogleCloudVisionV1p3beta1NormalizedVertex `json:"normalizedVertices,omitempty"`
// Vertices: The bounding polygon vertices.
Vertices []*GoogleCloudVisionV1p3beta1Vertex `json:"vertices,omitempty"`
// ForceSendFields is a list of field names (e.g. "NormalizedVertices")
// to unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "NormalizedVertices") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1BoundingPoly) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1BoundingPoly
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p3beta1ColorInfo: Color information consists of
// RGB channels, score, and the fraction of the image that the color
// occupies in the image.
type GoogleCloudVisionV1p3beta1ColorInfo struct {
// Color: RGB components of the color.
Color *Color `json:"color,omitempty"`
// PixelFraction: The fraction of pixels the color occupies in the
// image. Value in range [0, 1].
PixelFraction float64 `json:"pixelFraction,omitempty"`
// Score: Image-specific score for this color. Value in range [0, 1].
Score float64 `json:"score,omitempty"`
// ForceSendFields is a list of field names (e.g. "Color") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Color") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1ColorInfo) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1ColorInfo
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p3beta1ColorInfo) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p3beta1ColorInfo
var s1 struct {
PixelFraction gensupport.JSONFloat64 `json:"pixelFraction"`
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.PixelFraction = float64(s1.PixelFraction)
s.Score = float64(s1.Score)
return nil
}
// GoogleCloudVisionV1p3beta1CropHint: Single crop hint that is used to
// generate a new crop when serving an image.
type GoogleCloudVisionV1p3beta1CropHint struct {
// BoundingPoly: The bounding polygon for the crop region. The
// coordinates of the bounding box are in the original image's scale.
BoundingPoly *GoogleCloudVisionV1p3beta1BoundingPoly `json:"boundingPoly,omitempty"`
// Confidence: Confidence of this being a salient region. Range [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// ImportanceFraction: Fraction of importance of this salient region
// with respect to the original image.
ImportanceFraction float64 `json:"importanceFraction,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingPoly") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingPoly") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1CropHint) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1CropHint
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p3beta1CropHint) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p3beta1CropHint
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
ImportanceFraction gensupport.JSONFloat64 `json:"importanceFraction"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
s.ImportanceFraction = float64(s1.ImportanceFraction)
return nil
}
// GoogleCloudVisionV1p3beta1CropHintsAnnotation: Set of crop hints that
// are used to generate new crops when serving images.
type GoogleCloudVisionV1p3beta1CropHintsAnnotation struct {
// CropHints: Crop hint results.
CropHints []*GoogleCloudVisionV1p3beta1CropHint `json:"cropHints,omitempty"`
// ForceSendFields is a list of field names (e.g. "CropHints") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CropHints") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1CropHintsAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1CropHintsAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p3beta1DominantColorsAnnotation: Set of dominant
// colors and their corresponding scores.
type GoogleCloudVisionV1p3beta1DominantColorsAnnotation struct {
// Colors: RGB color values with their score and pixel fraction.
Colors []*GoogleCloudVisionV1p3beta1ColorInfo `json:"colors,omitempty"`
// ForceSendFields is a list of field names (e.g. "Colors") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Colors") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1DominantColorsAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1DominantColorsAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p3beta1EntityAnnotation: Set of detected entity
// features.
type GoogleCloudVisionV1p3beta1EntityAnnotation struct {
// BoundingPoly: Image region to which this entity belongs. Not produced
// for `LABEL_DETECTION` features.
BoundingPoly *GoogleCloudVisionV1p3beta1BoundingPoly `json:"boundingPoly,omitempty"`
// Confidence: **Deprecated. Use `score` instead.** The accuracy of the
// entity detection in an image. For example, for an image in which the
// "Eiffel Tower" entity is detected, this field represents the
// confidence that there is a tower in the query image. Range [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// Description: Entity textual description, expressed in its `locale`
// language.
Description string `json:"description,omitempty"`
// Locale: The language code for the locale in which the entity textual
// `description` is expressed.
Locale string `json:"locale,omitempty"`
// Locations: The location information for the detected entity. Multiple
// `LocationInfo` elements can be present because one location may
// indicate the location of the scene in the image, and another location
// may indicate the location of the place where the image was taken.
// Location information is usually present for landmarks.
Locations []*GoogleCloudVisionV1p3beta1LocationInfo `json:"locations,omitempty"`
// Mid: Opaque entity ID. Some IDs may be available in Google Knowledge
// Graph Search API (https://developers.google.com/knowledge-graph/).
Mid string `json:"mid,omitempty"`
// Properties: Some entities may have optional user-supplied `Property`
// (name/value) fields, such a score or string that qualifies the
// entity.
Properties []*GoogleCloudVisionV1p3beta1Property `json:"properties,omitempty"`
// Score: Overall score of the result. Range [0, 1].
Score float64 `json:"score,omitempty"`
// Topicality: The relevancy of the ICA (Image Content Annotation) label
// to the image. For example, the relevancy of "tower" is likely higher
// to an image containing the detected "Eiffel Tower" than to an image
// containing a detected distant towering building, even though the
// confidence that there is a tower in each image may be the same. Range
// [0, 1].
Topicality float64 `json:"topicality,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingPoly") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingPoly") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1EntityAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1EntityAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p3beta1EntityAnnotation) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p3beta1EntityAnnotation
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
Score gensupport.JSONFloat64 `json:"score"`
Topicality gensupport.JSONFloat64 `json:"topicality"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
s.Score = float64(s1.Score)
s.Topicality = float64(s1.Topicality)
return nil
}
// GoogleCloudVisionV1p3beta1FaceAnnotation: A face annotation object
// contains the results of face detection.
type GoogleCloudVisionV1p3beta1FaceAnnotation struct {
// AngerLikelihood: Anger likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
AngerLikelihood string `json:"angerLikelihood,omitempty"`
// BlurredLikelihood: Blurred likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
BlurredLikelihood string `json:"blurredLikelihood,omitempty"`
// BoundingPoly: The bounding polygon around the face. The coordinates
// of the bounding box are in the original image's scale. The bounding
// box is computed to "frame" the face in accordance with human
// expectations. It is based on the landmarker results. Note that one or
// more x and/or y coordinates may not be generated in the
// `BoundingPoly` (the polygon will be unbounded) if only a partial face
// appears in the image to be annotated.
BoundingPoly *GoogleCloudVisionV1p3beta1BoundingPoly `json:"boundingPoly,omitempty"`
// DetectionConfidence: Detection confidence. Range [0, 1].
DetectionConfidence float64 `json:"detectionConfidence,omitempty"`
// FdBoundingPoly: The `fd_bounding_poly` bounding polygon is tighter
// than the `boundingPoly`, and encloses only the skin part of the face.
// Typically, it is used to eliminate the face from any image analysis
// that detects the "amount of skin" visible in an image. It is not
// based on the landmarker results, only on the initial face detection,
// hence the fd (face detection) prefix.
FdBoundingPoly *GoogleCloudVisionV1p3beta1BoundingPoly `json:"fdBoundingPoly,omitempty"`
// HeadwearLikelihood: Headwear likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
HeadwearLikelihood string `json:"headwearLikelihood,omitempty"`
// JoyLikelihood: Joy likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
JoyLikelihood string `json:"joyLikelihood,omitempty"`
// LandmarkingConfidence: Face landmarking confidence. Range [0, 1].
LandmarkingConfidence float64 `json:"landmarkingConfidence,omitempty"`
// Landmarks: Detected face landmarks.
Landmarks []*GoogleCloudVisionV1p3beta1FaceAnnotationLandmark `json:"landmarks,omitempty"`
// PanAngle: Yaw angle, which indicates the leftward/rightward angle
// that the face is pointing relative to the vertical plane
// perpendicular to the image. Range [-180,180].
PanAngle float64 `json:"panAngle,omitempty"`
// RollAngle: Roll angle, which indicates the amount of
// clockwise/anti-clockwise rotation of the face relative to the image
// vertical about the axis perpendicular to the face. Range [-180,180].
RollAngle float64 `json:"rollAngle,omitempty"`
// SorrowLikelihood: Sorrow likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
SorrowLikelihood string `json:"sorrowLikelihood,omitempty"`
// SurpriseLikelihood: Surprise likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
SurpriseLikelihood string `json:"surpriseLikelihood,omitempty"`
// TiltAngle: Pitch angle, which indicates the upwards/downwards angle
// that the face is pointing relative to the image's horizontal plane.
// Range [-180,180].
TiltAngle float64 `json:"tiltAngle,omitempty"`
// UnderExposedLikelihood: Under-exposed likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
UnderExposedLikelihood string `json:"underExposedLikelihood,omitempty"`
// ForceSendFields is a list of field names (e.g. "AngerLikelihood") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "AngerLikelihood") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1FaceAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1FaceAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p3beta1FaceAnnotation) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p3beta1FaceAnnotation
var s1 struct {
DetectionConfidence gensupport.JSONFloat64 `json:"detectionConfidence"`
LandmarkingConfidence gensupport.JSONFloat64 `json:"landmarkingConfidence"`
PanAngle gensupport.JSONFloat64 `json:"panAngle"`
RollAngle gensupport.JSONFloat64 `json:"rollAngle"`
TiltAngle gensupport.JSONFloat64 `json:"tiltAngle"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.DetectionConfidence = float64(s1.DetectionConfidence)
s.LandmarkingConfidence = float64(s1.LandmarkingConfidence)
s.PanAngle = float64(s1.PanAngle)
s.RollAngle = float64(s1.RollAngle)
s.TiltAngle = float64(s1.TiltAngle)
return nil
}
// GoogleCloudVisionV1p3beta1FaceAnnotationLandmark: A face-specific
// landmark (for example, a face feature).
type GoogleCloudVisionV1p3beta1FaceAnnotationLandmark struct {
// Position: Face landmark position.
Position *GoogleCloudVisionV1p3beta1Position `json:"position,omitempty"`
// Type: Face landmark type.
//
// Possible values:
// "UNKNOWN_LANDMARK" - Unknown face landmark detected. Should not be
// filled.
// "LEFT_EYE" - Left eye.
// "RIGHT_EYE" - Right eye.
// "LEFT_OF_LEFT_EYEBROW" - Left of left eyebrow.
// "RIGHT_OF_LEFT_EYEBROW" - Right of left eyebrow.
// "LEFT_OF_RIGHT_EYEBROW" - Left of right eyebrow.
// "RIGHT_OF_RIGHT_EYEBROW" - Right of right eyebrow.
// "MIDPOINT_BETWEEN_EYES" - Midpoint between eyes.
// "NOSE_TIP" - Nose tip.
// "UPPER_LIP" - Upper lip.
// "LOWER_LIP" - Lower lip.
// "MOUTH_LEFT" - Mouth left.
// "MOUTH_RIGHT" - Mouth right.
// "MOUTH_CENTER" - Mouth center.
// "NOSE_BOTTOM_RIGHT" - Nose, bottom right.
// "NOSE_BOTTOM_LEFT" - Nose, bottom left.
// "NOSE_BOTTOM_CENTER" - Nose, bottom center.
// "LEFT_EYE_TOP_BOUNDARY" - Left eye, top boundary.
// "LEFT_EYE_RIGHT_CORNER" - Left eye, right corner.
// "LEFT_EYE_BOTTOM_BOUNDARY" - Left eye, bottom boundary.
// "LEFT_EYE_LEFT_CORNER" - Left eye, left corner.
// "RIGHT_EYE_TOP_BOUNDARY" - Right eye, top boundary.
// "RIGHT_EYE_RIGHT_CORNER" - Right eye, right corner.
// "RIGHT_EYE_BOTTOM_BOUNDARY" - Right eye, bottom boundary.
// "RIGHT_EYE_LEFT_CORNER" - Right eye, left corner.
// "LEFT_EYEBROW_UPPER_MIDPOINT" - Left eyebrow, upper midpoint.
// "RIGHT_EYEBROW_UPPER_MIDPOINT" - Right eyebrow, upper midpoint.
// "LEFT_EAR_TRAGION" - Left ear tragion.
// "RIGHT_EAR_TRAGION" - Right ear tragion.
// "LEFT_EYE_PUPIL" - Left eye pupil.
// "RIGHT_EYE_PUPIL" - Right eye pupil.
// "FOREHEAD_GLABELLA" - Forehead glabella.
// "CHIN_GNATHION" - Chin gnathion.
// "CHIN_LEFT_GONION" - Chin left gonion.
// "CHIN_RIGHT_GONION" - Chin right gonion.
// "LEFT_CHEEK_CENTER" - Left cheek center.
// "RIGHT_CHEEK_CENTER" - Right cheek center.
Type string `json:"type,omitempty"`
// ForceSendFields is a list of field names (e.g. "Position") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Position") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1FaceAnnotationLandmark) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1FaceAnnotationLandmark
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p3beta1GcsDestination: The Google Cloud Storage
// location where the output will be written to.
type GoogleCloudVisionV1p3beta1GcsDestination struct {
// Uri: Google Cloud Storage URI prefix where the results will be
// stored. Results will be in JSON format and preceded by its
// corresponding input URI prefix. This field can either represent a gcs
// file prefix or gcs directory. In either case, the uri should be
// unique because in order to get all of the output files, you will need
// to do a wildcard gcs search on the uri prefix you provide. Examples:
// * File Prefix: gs://bucket-name/here/filenameprefix The output files
// will be created in gs://bucket-name/here/ and the names of the output
// files will begin with "filenameprefix". * Directory Prefix:
// gs://bucket-name/some/location/ The output files will be created in
// gs://bucket-name/some/location/ and the names of the output files
// could be anything because there was no filename prefix specified. If
// multiple outputs, each response is still AnnotateFileResponse, each
// of which contains some subset of the full list of
// AnnotateImageResponse. Multiple outputs can happen if, for example,
// the output JSON is too large and overflows into multiple sharded
// files.
Uri string `json:"uri,omitempty"`
// ForceSendFields is a list of field names (e.g. "Uri") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Uri") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1GcsDestination) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1GcsDestination
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p3beta1GcsSource: The Google Cloud Storage
// location where the input will be read from.
type GoogleCloudVisionV1p3beta1GcsSource struct {
// Uri: Google Cloud Storage URI for the input file. This must only be a
// Google Cloud Storage object. Wildcards are not currently supported.
Uri string `json:"uri,omitempty"`
// ForceSendFields is a list of field names (e.g. "Uri") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Uri") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1GcsSource) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1GcsSource
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p3beta1ImageAnnotationContext: If an image was
// produced from a file (e.g. a PDF), this message gives information
// about the source of that image.
type GoogleCloudVisionV1p3beta1ImageAnnotationContext struct {
// PageNumber: If the file was a PDF or TIFF, this field gives the page
// number within the file used to produce the image.
PageNumber int64 `json:"pageNumber,omitempty"`
// Uri: The URI of the file used to produce the image.
Uri string `json:"uri,omitempty"`
// ForceSendFields is a list of field names (e.g. "PageNumber") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "PageNumber") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1ImageAnnotationContext) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1ImageAnnotationContext
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p3beta1ImageProperties: Stores image properties,
// such as dominant colors.
type GoogleCloudVisionV1p3beta1ImageProperties struct {
// DominantColors: If present, dominant colors completed successfully.
DominantColors *GoogleCloudVisionV1p3beta1DominantColorsAnnotation `json:"dominantColors,omitempty"`
// ForceSendFields is a list of field names (e.g. "DominantColors") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "DominantColors") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1ImageProperties) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1ImageProperties
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p3beta1ImportProductSetsResponse: Response message
// for the `ImportProductSets` method. This message is returned by the
// google.longrunning.Operations.GetOperation method in the returned
// google.longrunning.Operation.response field.
type GoogleCloudVisionV1p3beta1ImportProductSetsResponse struct {
// ReferenceImages: The list of reference_images that are imported
// successfully.
ReferenceImages []*GoogleCloudVisionV1p3beta1ReferenceImage `json:"referenceImages,omitempty"`
// Statuses: The rpc status for each ImportProductSet request, including
// both successes and errors. The number of statuses here matches the
// number of lines in the csv file, and statuses[i] stores the success
// or failure status of processing the i-th line of the csv, starting
// from line 0.
Statuses []*Status `json:"statuses,omitempty"`
// ForceSendFields is a list of field names (e.g. "ReferenceImages") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ReferenceImages") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1ImportProductSetsResponse) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1ImportProductSetsResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p3beta1InputConfig: The desired input location and
// metadata.
type GoogleCloudVisionV1p3beta1InputConfig struct {
// Content: File content, represented as a stream of bytes. Note: As
// with all `bytes` fields, protobuffers use a pure binary
// representation, whereas JSON representations use base64. Currently,
// this field only works for BatchAnnotateFiles requests. It does not
// work for AsyncBatchAnnotateFiles requests.
Content string `json:"content,omitempty"`
// GcsSource: The Google Cloud Storage location to read the input from.
GcsSource *GoogleCloudVisionV1p3beta1GcsSource `json:"gcsSource,omitempty"`
// MimeType: The type of the file. Currently only "application/pdf",
// "image/tiff" and "image/gif" are supported. Wildcards are not
// supported.
MimeType string `json:"mimeType,omitempty"`
// ForceSendFields is a list of field names (e.g. "Content") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Content") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1InputConfig) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1InputConfig
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p3beta1LocalizedObjectAnnotation: Set of detected
// objects with bounding boxes.
type GoogleCloudVisionV1p3beta1LocalizedObjectAnnotation struct {
// BoundingPoly: Image region to which this object belongs. This must be
// populated.
BoundingPoly *GoogleCloudVisionV1p3beta1BoundingPoly `json:"boundingPoly,omitempty"`
// LanguageCode: The BCP-47 language code, such as "en-US" or "sr-Latn".
// For more information, see
// http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
LanguageCode string `json:"languageCode,omitempty"`
// Mid: Object ID that should align with EntityAnnotation mid.
Mid string `json:"mid,omitempty"`
// Name: Object name, expressed in its `language_code` language.
Name string `json:"name,omitempty"`
// Score: Score of the result. Range [0, 1].
Score float64 `json:"score,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingPoly") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingPoly") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1LocalizedObjectAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1LocalizedObjectAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p3beta1LocalizedObjectAnnotation) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p3beta1LocalizedObjectAnnotation
var s1 struct {
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Score = float64(s1.Score)
return nil
}
// GoogleCloudVisionV1p3beta1LocationInfo: Detected entity location
// information.
type GoogleCloudVisionV1p3beta1LocationInfo struct {
// LatLng: lat/long location coordinates.
LatLng *LatLng `json:"latLng,omitempty"`
// ForceSendFields is a list of field names (e.g. "LatLng") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "LatLng") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1LocationInfo) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1LocationInfo
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p3beta1NormalizedVertex: A vertex represents a 2D
// point in the image. NOTE: the normalized vertex coordinates are
// relative to the original image and range from 0 to 1.
type GoogleCloudVisionV1p3beta1NormalizedVertex struct {
// X: X coordinate.
X float64 `json:"x,omitempty"`
// Y: Y coordinate.
Y float64 `json:"y,omitempty"`
// ForceSendFields is a list of field names (e.g. "X") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "X") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1NormalizedVertex) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1NormalizedVertex
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p3beta1NormalizedVertex) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p3beta1NormalizedVertex
var s1 struct {
X gensupport.JSONFloat64 `json:"x"`
Y gensupport.JSONFloat64 `json:"y"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.X = float64(s1.X)
s.Y = float64(s1.Y)
return nil
}
// GoogleCloudVisionV1p3beta1OperationMetadata: Contains metadata for
// the BatchAnnotateImages operation.
type GoogleCloudVisionV1p3beta1OperationMetadata struct {
// CreateTime: The time when the batch request was received.
CreateTime string `json:"createTime,omitempty"`
// State: Current state of the batch operation.
//
// Possible values:
// "STATE_UNSPECIFIED" - Invalid.
// "CREATED" - Request is received.
// "RUNNING" - Request is actively being processed.
// "DONE" - The batch processing is done.
// "CANCELLED" - The batch processing was cancelled.
State string `json:"state,omitempty"`
// UpdateTime: The time when the operation result was last updated.
UpdateTime string `json:"updateTime,omitempty"`
// ForceSendFields is a list of field names (e.g. "CreateTime") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CreateTime") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1OperationMetadata) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1OperationMetadata
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p3beta1OutputConfig: The desired output location
// and metadata.
type GoogleCloudVisionV1p3beta1OutputConfig struct {
// BatchSize: The max number of response protos to put into each output
// JSON file on Google Cloud Storage. The valid range is [1, 100]. If
// not specified, the default value is 20. For example, for one pdf file
// with 100 pages, 100 response protos will be generated. If
// `batch_size` = 20, then 5 json files each containing 20 response
// protos will be written under the prefix `gcs_destination`.`uri`.
// Currently, batch_size only applies to GcsDestination, with potential
// future support for other output configurations.
BatchSize int64 `json:"batchSize,omitempty"`
// GcsDestination: The Google Cloud Storage location to write the
// output(s) to.
GcsDestination *GoogleCloudVisionV1p3beta1GcsDestination `json:"gcsDestination,omitempty"`
// ForceSendFields is a list of field names (e.g. "BatchSize") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BatchSize") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1OutputConfig) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1OutputConfig
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p3beta1Page: Detected page from OCR.
type GoogleCloudVisionV1p3beta1Page struct {
// Blocks: List of blocks of text, images etc on this page.
Blocks []*GoogleCloudVisionV1p3beta1Block `json:"blocks,omitempty"`
// Confidence: Confidence of the OCR results on the page. Range [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// Height: Page height. For PDFs the unit is points. For images
// (including TIFFs) the unit is pixels.
Height int64 `json:"height,omitempty"`
// Property: Additional information detected on the page.
Property *GoogleCloudVisionV1p3beta1TextAnnotationTextProperty `json:"property,omitempty"`
// Width: Page width. For PDFs the unit is points. For images (including
// TIFFs) the unit is pixels.
Width int64 `json:"width,omitempty"`
// ForceSendFields is a list of field names (e.g. "Blocks") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Blocks") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1Page) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1Page
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p3beta1Page) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p3beta1Page
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
return nil
}
// GoogleCloudVisionV1p3beta1Paragraph: Structural unit of text
// representing a number of words in certain order.
type GoogleCloudVisionV1p3beta1Paragraph struct {
// BoundingBox: The bounding box for the paragraph. The vertices are in
// the order of top-left, top-right, bottom-right, bottom-left. When a
// rotation of the bounding box is detected the rotation is represented
// as around the top-left corner as defined when the text is read in the
// 'natural' orientation. For example: * when the text is horizontal it
// might look like: 0----1 | | 3----2 * when it's rotated 180 degrees
// around the top-left corner it becomes: 2----3 | | 1----0 and the
// vertex order will still be (0, 1, 2, 3).
BoundingBox *GoogleCloudVisionV1p3beta1BoundingPoly `json:"boundingBox,omitempty"`
// Confidence: Confidence of the OCR results for the paragraph. Range
// [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// Property: Additional information detected for the paragraph.
Property *GoogleCloudVisionV1p3beta1TextAnnotationTextProperty `json:"property,omitempty"`
// Words: List of all words in this paragraph.
Words []*GoogleCloudVisionV1p3beta1Word `json:"words,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingBox") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingBox") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1Paragraph) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1Paragraph
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p3beta1Paragraph) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p3beta1Paragraph
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
return nil
}
// GoogleCloudVisionV1p3beta1Position: A 3D position in the image, used
// primarily for Face detection landmarks. A valid Position must have
// both x and y coordinates. The position coordinates are in the same
// scale as the original image.
type GoogleCloudVisionV1p3beta1Position struct {
// X: X coordinate.
X float64 `json:"x,omitempty"`
// Y: Y coordinate.
Y float64 `json:"y,omitempty"`
// Z: Z coordinate (or depth).
Z float64 `json:"z,omitempty"`
// ForceSendFields is a list of field names (e.g. "X") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "X") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1Position) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1Position
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p3beta1Position) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p3beta1Position
var s1 struct {
X gensupport.JSONFloat64 `json:"x"`
Y gensupport.JSONFloat64 `json:"y"`
Z gensupport.JSONFloat64 `json:"z"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.X = float64(s1.X)
s.Y = float64(s1.Y)
s.Z = float64(s1.Z)
return nil
}
// GoogleCloudVisionV1p3beta1Product: A Product contains
// ReferenceImages.
type GoogleCloudVisionV1p3beta1Product struct {
// Description: User-provided metadata to be stored with this product.
// Must be at most 4096 characters long.
Description string `json:"description,omitempty"`
// DisplayName: The user-provided name for this Product. Must not be
// empty. Must be at most 4096 characters long.
DisplayName string `json:"displayName,omitempty"`
// Name: The resource name of the product. Format is:
// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`. This
// field is ignored when creating a product.
Name string `json:"name,omitempty"`
// ProductCategory: Immutable. The category for the product identified
// by the reference image. This should be one of "homegoods-v2",
// "apparel-v2", "toys-v2", "packagedgoods-v1" or "general-v1". The
// legacy categories "homegoods", "apparel", and "toys" are still
// supported, but these should not be used for new products.
ProductCategory string `json:"productCategory,omitempty"`
// ProductLabels: Key-value pairs that can be attached to a product. At
// query time, constraints can be specified based on the product_labels.
// Note that integer values can be provided as strings, e.g. "1199".
// Only strings with integer values can match a range-based restriction
// which is to be supported soon. Multiple values can be assigned to the
// same key. One product may have up to 500 product_labels. Notice that
// the total number of distinct product_labels over all products in one
// ProductSet cannot exceed 1M, otherwise the product search pipeline
// will refuse to work for that ProductSet.
ProductLabels []*GoogleCloudVisionV1p3beta1ProductKeyValue `json:"productLabels,omitempty"`
// ForceSendFields is a list of field names (e.g. "Description") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Description") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1Product) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1Product
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p3beta1ProductKeyValue: A product label
// represented as a key-value pair.
type GoogleCloudVisionV1p3beta1ProductKeyValue struct {
// Key: The key of the label attached to the product. Cannot be empty
// and cannot exceed 128 bytes.
Key string `json:"key,omitempty"`
// Value: The value of the label attached to the product. Cannot be
// empty and cannot exceed 128 bytes.
Value string `json:"value,omitempty"`
// ForceSendFields is a list of field names (e.g. "Key") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Key") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1ProductKeyValue) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1ProductKeyValue
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p3beta1ProductSearchResults: Results for a product
// search request.
type GoogleCloudVisionV1p3beta1ProductSearchResults struct {
// IndexTime: Timestamp of the index which provided these results.
// Products added to the product set and products removed from the
// product set after this time are not reflected in the current results.
IndexTime string `json:"indexTime,omitempty"`
// ProductGroupedResults: List of results grouped by products detected
// in the query image. Each entry corresponds to one bounding polygon in
// the query image, and contains the matching products specific to that
// region. There may be duplicate product matches in the union of all
// the per-product results.
ProductGroupedResults []*GoogleCloudVisionV1p3beta1ProductSearchResultsGroupedResult `json:"productGroupedResults,omitempty"`
// Results: List of results, one for each product match.
Results []*GoogleCloudVisionV1p3beta1ProductSearchResultsResult `json:"results,omitempty"`
// ForceSendFields is a list of field names (e.g. "IndexTime") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "IndexTime") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1ProductSearchResults) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1ProductSearchResults
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p3beta1ProductSearchResultsGroupedResult:
// Information about the products similar to a single product in a query
// image.
type GoogleCloudVisionV1p3beta1ProductSearchResultsGroupedResult struct {
// BoundingPoly: The bounding polygon around the product detected in the
// query image.
BoundingPoly *GoogleCloudVisionV1p3beta1BoundingPoly `json:"boundingPoly,omitempty"`
// ObjectAnnotations: List of generic predictions for the object in the
// bounding box.
ObjectAnnotations []*GoogleCloudVisionV1p3beta1ProductSearchResultsObjectAnnotation `json:"objectAnnotations,omitempty"`
// Results: List of results, one for each product match.
Results []*GoogleCloudVisionV1p3beta1ProductSearchResultsResult `json:"results,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingPoly") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingPoly") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1ProductSearchResultsGroupedResult) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1ProductSearchResultsGroupedResult
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p3beta1ProductSearchResultsObjectAnnotation:
// Prediction for what the object in the bounding box is.
type GoogleCloudVisionV1p3beta1ProductSearchResultsObjectAnnotation struct {
// LanguageCode: The BCP-47 language code, such as "en-US" or "sr-Latn".
// For more information, see
// http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
LanguageCode string `json:"languageCode,omitempty"`
// Mid: Object ID that should align with EntityAnnotation mid.
Mid string `json:"mid,omitempty"`
// Name: Object name, expressed in its `language_code` language.
Name string `json:"name,omitempty"`
// Score: Score of the result. Range [0, 1].
Score float64 `json:"score,omitempty"`
// ForceSendFields is a list of field names (e.g. "LanguageCode") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "LanguageCode") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1ProductSearchResultsObjectAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1ProductSearchResultsObjectAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p3beta1ProductSearchResultsObjectAnnotation) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p3beta1ProductSearchResultsObjectAnnotation
var s1 struct {
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Score = float64(s1.Score)
return nil
}
// GoogleCloudVisionV1p3beta1ProductSearchResultsResult: Information
// about a product.
type GoogleCloudVisionV1p3beta1ProductSearchResultsResult struct {
// Image: The resource name of the image from the product that is the
// closest match to the query.
Image string `json:"image,omitempty"`
// Product: The Product.
Product *GoogleCloudVisionV1p3beta1Product `json:"product,omitempty"`
// Score: A confidence level on the match, ranging from 0 (no
// confidence) to 1 (full confidence).
Score float64 `json:"score,omitempty"`
// ForceSendFields is a list of field names (e.g. "Image") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Image") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1ProductSearchResultsResult) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1ProductSearchResultsResult
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p3beta1ProductSearchResultsResult) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p3beta1ProductSearchResultsResult
var s1 struct {
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Score = float64(s1.Score)
return nil
}
// GoogleCloudVisionV1p3beta1Property: A `Property` consists of a
// user-supplied name/value pair.
type GoogleCloudVisionV1p3beta1Property struct {
// Name: Name of the property.
Name string `json:"name,omitempty"`
// Uint64Value: Value of numeric properties.
Uint64Value uint64 `json:"uint64Value,omitempty,string"`
// Value: Value of the property.
Value string `json:"value,omitempty"`
// ForceSendFields is a list of field names (e.g. "Name") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Name") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1Property) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1Property
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p3beta1ReferenceImage: A `ReferenceImage`
// represents a product image and its associated metadata, such as
// bounding boxes.
type GoogleCloudVisionV1p3beta1ReferenceImage struct {
// BoundingPolys: Optional. Bounding polygons around the areas of
// interest in the reference image. If this field is empty, the system
// will try to detect regions of interest. At most 10 bounding polygons
// will be used. The provided shape is converted into a non-rotated
// rectangle. Once converted, the small edge of the rectangle must be
// greater than or equal to 300 pixels. The aspect ratio must be 1:4 or
// less (i.e. 1:3 is ok; 1:5 is not).
BoundingPolys []*GoogleCloudVisionV1p3beta1BoundingPoly `json:"boundingPolys,omitempty"`
// Name: The resource name of the reference image. Format is:
// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceIma
// ges/IMAGE_ID`. This field is ignored when creating a reference image.
Name string `json:"name,omitempty"`
// Uri: Required. The Google Cloud Storage URI of the reference image.
// The URI must start with `gs://`.
Uri string `json:"uri,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingPolys") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingPolys") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1ReferenceImage) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1ReferenceImage
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p3beta1SafeSearchAnnotation: Set of features
// pertaining to the image, computed by computer vision methods over
// safe-search verticals (for example, adult, spoof, medical, violence).
type GoogleCloudVisionV1p3beta1SafeSearchAnnotation struct {
// Adult: Represents the adult content likelihood for the image. Adult
// content may contain elements such as nudity, pornographic images or
// cartoons, or sexual activities.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
Adult string `json:"adult,omitempty"`
// Medical: Likelihood that this is a medical image.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
Medical string `json:"medical,omitempty"`
// Racy: Likelihood that the request image contains racy content. Racy
// content may include (but is not limited to) skimpy or sheer clothing,
// strategically covered nudity, lewd or provocative poses, or close-ups
// of sensitive body areas.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
Racy string `json:"racy,omitempty"`
// Spoof: Spoof likelihood. The likelihood that an modification was made
// to the image's canonical version to make it appear funny or
// offensive.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
Spoof string `json:"spoof,omitempty"`
// Violence: Likelihood that this image contains violent content.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
Violence string `json:"violence,omitempty"`
// ForceSendFields is a list of field names (e.g. "Adult") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Adult") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1SafeSearchAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1SafeSearchAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p3beta1Symbol: A single symbol representation.
type GoogleCloudVisionV1p3beta1Symbol struct {
// BoundingBox: The bounding box for the symbol. The vertices are in the
// order of top-left, top-right, bottom-right, bottom-left. When a
// rotation of the bounding box is detected the rotation is represented
// as around the top-left corner as defined when the text is read in the
// 'natural' orientation. For example: * when the text is horizontal it
// might look like: 0----1 | | 3----2 * when it's rotated 180 degrees
// around the top-left corner it becomes: 2----3 | | 1----0 and the
// vertex order will still be (0, 1, 2, 3).
BoundingBox *GoogleCloudVisionV1p3beta1BoundingPoly `json:"boundingBox,omitempty"`
// Confidence: Confidence of the OCR results for the symbol. Range [0,
// 1].
Confidence float64 `json:"confidence,omitempty"`
// Property: Additional information detected for the symbol.
Property *GoogleCloudVisionV1p3beta1TextAnnotationTextProperty `json:"property,omitempty"`
// Text: The actual UTF-8 representation of the symbol.
Text string `json:"text,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingBox") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingBox") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1Symbol) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1Symbol
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p3beta1Symbol) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p3beta1Symbol
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
return nil
}
// GoogleCloudVisionV1p3beta1TextAnnotation: TextAnnotation contains a
// structured representation of OCR extracted text. The hierarchy of an
// OCR extracted text structure is like this: TextAnnotation -> Page ->
// Block -> Paragraph -> Word -> Symbol Each structural component,
// starting from Page, may further have their own properties. Properties
// describe detected languages, breaks etc.. Please refer to the
// TextAnnotation.TextProperty message definition below for more detail.
type GoogleCloudVisionV1p3beta1TextAnnotation struct {
// Pages: List of pages detected by OCR.
Pages []*GoogleCloudVisionV1p3beta1Page `json:"pages,omitempty"`
// Text: UTF-8 text detected on the pages.
Text string `json:"text,omitempty"`
// ForceSendFields is a list of field names (e.g. "Pages") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Pages") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1TextAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1TextAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p3beta1TextAnnotationDetectedBreak: Detected start
// or end of a structural component.
type GoogleCloudVisionV1p3beta1TextAnnotationDetectedBreak struct {
// IsPrefix: True if break prepends the element.
IsPrefix bool `json:"isPrefix,omitempty"`
// Type: Detected break type.
//
// Possible values:
// "UNKNOWN" - Unknown break label type.
// "SPACE" - Regular space.
// "SURE_SPACE" - Sure space (very wide).
// "EOL_SURE_SPACE" - Line-wrapping break.
// "HYPHEN" - End-line hyphen that is not present in text; does not
// co-occur with `SPACE`, `LEADER_SPACE`, or `LINE_BREAK`.
// "LINE_BREAK" - Line break that ends a paragraph.
Type string `json:"type,omitempty"`
// ForceSendFields is a list of field names (e.g. "IsPrefix") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "IsPrefix") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1TextAnnotationDetectedBreak) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1TextAnnotationDetectedBreak
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p3beta1TextAnnotationDetectedLanguage: Detected
// language for a structural component.
type GoogleCloudVisionV1p3beta1TextAnnotationDetectedLanguage struct {
// Confidence: Confidence of detected language. Range [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// LanguageCode: The BCP-47 language code, such as "en-US" or "sr-Latn".
// For more information, see
// http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
LanguageCode string `json:"languageCode,omitempty"`
// ForceSendFields is a list of field names (e.g. "Confidence") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Confidence") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1TextAnnotationDetectedLanguage) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1TextAnnotationDetectedLanguage
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p3beta1TextAnnotationDetectedLanguage) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p3beta1TextAnnotationDetectedLanguage
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
return nil
}
// GoogleCloudVisionV1p3beta1TextAnnotationTextProperty: Additional
// information detected on the structural component.
type GoogleCloudVisionV1p3beta1TextAnnotationTextProperty struct {
// DetectedBreak: Detected start or end of a text segment.
DetectedBreak *GoogleCloudVisionV1p3beta1TextAnnotationDetectedBreak `json:"detectedBreak,omitempty"`
// DetectedLanguages: A list of detected languages together with
// confidence.
DetectedLanguages []*GoogleCloudVisionV1p3beta1TextAnnotationDetectedLanguage `json:"detectedLanguages,omitempty"`
// ForceSendFields is a list of field names (e.g. "DetectedBreak") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "DetectedBreak") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1TextAnnotationTextProperty) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1TextAnnotationTextProperty
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p3beta1Vertex: A vertex represents a 2D point in
// the image. NOTE: the vertex coordinates are in the same scale as the
// original image.
type GoogleCloudVisionV1p3beta1Vertex struct {
// X: X coordinate.
X int64 `json:"x,omitempty"`
// Y: Y coordinate.
Y int64 `json:"y,omitempty"`
// ForceSendFields is a list of field names (e.g. "X") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "X") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1Vertex) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1Vertex
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p3beta1WebDetection: Relevant information for the
// image from the Internet.
type GoogleCloudVisionV1p3beta1WebDetection struct {
// BestGuessLabels: The service's best guess as to the topic of the
// request image. Inferred from similar images on the open web.
BestGuessLabels []*GoogleCloudVisionV1p3beta1WebDetectionWebLabel `json:"bestGuessLabels,omitempty"`
// FullMatchingImages: Fully matching images from the Internet. Can
// include resized copies of the query image.
FullMatchingImages []*GoogleCloudVisionV1p3beta1WebDetectionWebImage `json:"fullMatchingImages,omitempty"`
// PagesWithMatchingImages: Web pages containing the matching images
// from the Internet.
PagesWithMatchingImages []*GoogleCloudVisionV1p3beta1WebDetectionWebPage `json:"pagesWithMatchingImages,omitempty"`
// PartialMatchingImages: Partial matching images from the Internet.
// Those images are similar enough to share some key-point features. For
// example an original image will likely have partial matching for its
// crops.
PartialMatchingImages []*GoogleCloudVisionV1p3beta1WebDetectionWebImage `json:"partialMatchingImages,omitempty"`
// VisuallySimilarImages: The visually similar image results.
VisuallySimilarImages []*GoogleCloudVisionV1p3beta1WebDetectionWebImage `json:"visuallySimilarImages,omitempty"`
// WebEntities: Deduced entities from similar images on the Internet.
WebEntities []*GoogleCloudVisionV1p3beta1WebDetectionWebEntity `json:"webEntities,omitempty"`
// ForceSendFields is a list of field names (e.g. "BestGuessLabels") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BestGuessLabels") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1WebDetection) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1WebDetection
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p3beta1WebDetectionWebEntity: Entity deduced from
// similar images on the Internet.
type GoogleCloudVisionV1p3beta1WebDetectionWebEntity struct {
// Description: Canonical description of the entity, in English.
Description string `json:"description,omitempty"`
// EntityId: Opaque entity ID.
EntityId string `json:"entityId,omitempty"`
// Score: Overall relevancy score for the entity. Not normalized and not
// comparable across different image queries.
Score float64 `json:"score,omitempty"`
// ForceSendFields is a list of field names (e.g. "Description") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Description") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1WebDetectionWebEntity) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1WebDetectionWebEntity
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p3beta1WebDetectionWebEntity) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p3beta1WebDetectionWebEntity
var s1 struct {
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Score = float64(s1.Score)
return nil
}
// GoogleCloudVisionV1p3beta1WebDetectionWebImage: Metadata for online
// images.
type GoogleCloudVisionV1p3beta1WebDetectionWebImage struct {
// Score: (Deprecated) Overall relevancy score for the image.
Score float64 `json:"score,omitempty"`
// Url: The result image URL.
Url string `json:"url,omitempty"`
// ForceSendFields is a list of field names (e.g. "Score") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Score") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1WebDetectionWebImage) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1WebDetectionWebImage
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p3beta1WebDetectionWebImage) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p3beta1WebDetectionWebImage
var s1 struct {
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Score = float64(s1.Score)
return nil
}
// GoogleCloudVisionV1p3beta1WebDetectionWebLabel: Label to provide
// extra metadata for the web detection.
type GoogleCloudVisionV1p3beta1WebDetectionWebLabel struct {
// Label: Label for extra metadata.
Label string `json:"label,omitempty"`
// LanguageCode: The BCP-47 language code for `label`, such as "en-US"
// or "sr-Latn". For more information, see
// http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
LanguageCode string `json:"languageCode,omitempty"`
// ForceSendFields is a list of field names (e.g. "Label") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Label") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1WebDetectionWebLabel) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1WebDetectionWebLabel
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p3beta1WebDetectionWebPage: Metadata for web
// pages.
type GoogleCloudVisionV1p3beta1WebDetectionWebPage struct {
// FullMatchingImages: Fully matching images on the page. Can include
// resized copies of the query image.
FullMatchingImages []*GoogleCloudVisionV1p3beta1WebDetectionWebImage `json:"fullMatchingImages,omitempty"`
// PageTitle: Title for the web page, may contain HTML markups.
PageTitle string `json:"pageTitle,omitempty"`
// PartialMatchingImages: Partial matching images on the page. Those
// images are similar enough to share some key-point features. For
// example an original image will likely have partial matching for its
// crops.
PartialMatchingImages []*GoogleCloudVisionV1p3beta1WebDetectionWebImage `json:"partialMatchingImages,omitempty"`
// Score: (Deprecated) Overall relevancy score for the web page.
Score float64 `json:"score,omitempty"`
// Url: The result web page URL.
Url string `json:"url,omitempty"`
// ForceSendFields is a list of field names (e.g. "FullMatchingImages")
// to unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "FullMatchingImages") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1WebDetectionWebPage) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1WebDetectionWebPage
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p3beta1WebDetectionWebPage) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p3beta1WebDetectionWebPage
var s1 struct {
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Score = float64(s1.Score)
return nil
}
// GoogleCloudVisionV1p3beta1Word: A word representation.
type GoogleCloudVisionV1p3beta1Word struct {
// BoundingBox: The bounding box for the word. The vertices are in the
// order of top-left, top-right, bottom-right, bottom-left. When a
// rotation of the bounding box is detected the rotation is represented
// as around the top-left corner as defined when the text is read in the
// 'natural' orientation. For example: * when the text is horizontal it
// might look like: 0----1 | | 3----2 * when it's rotated 180 degrees
// around the top-left corner it becomes: 2----3 | | 1----0 and the
// vertex order will still be (0, 1, 2, 3).
BoundingBox *GoogleCloudVisionV1p3beta1BoundingPoly `json:"boundingBox,omitempty"`
// Confidence: Confidence of the OCR results for the word. Range [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// Property: Additional information detected for the word.
Property *GoogleCloudVisionV1p3beta1TextAnnotationTextProperty `json:"property,omitempty"`
// Symbols: List of symbols in the word. The order of the symbols
// follows the natural reading order.
Symbols []*GoogleCloudVisionV1p3beta1Symbol `json:"symbols,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingBox") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingBox") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p3beta1Word) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p3beta1Word
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p3beta1Word) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p3beta1Word
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
return nil
}
// GoogleCloudVisionV1p4beta1AnnotateFileResponse: Response to a single
// file annotation request. A file may contain one or more images, which
// individually have their own responses.
type GoogleCloudVisionV1p4beta1AnnotateFileResponse struct {
// Error: If set, represents the error message for the failed request.
// The `responses` field will not be set in this case.
Error *Status `json:"error,omitempty"`
// InputConfig: Information about the file for which this response is
// generated.
InputConfig *GoogleCloudVisionV1p4beta1InputConfig `json:"inputConfig,omitempty"`
// Responses: Individual responses to images found within the file. This
// field will be empty if the `error` field is set.
Responses []*GoogleCloudVisionV1p4beta1AnnotateImageResponse `json:"responses,omitempty"`
// TotalPages: This field gives the total number of pages in the file.
TotalPages int64 `json:"totalPages,omitempty"`
// ForceSendFields is a list of field names (e.g. "Error") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Error") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1AnnotateFileResponse) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1AnnotateFileResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p4beta1AnnotateImageResponse: Response to an image
// annotation request.
type GoogleCloudVisionV1p4beta1AnnotateImageResponse struct {
// Context: If present, contextual information is needed to understand
// where this image comes from.
Context *GoogleCloudVisionV1p4beta1ImageAnnotationContext `json:"context,omitempty"`
// CropHintsAnnotation: If present, crop hints have completed
// successfully.
CropHintsAnnotation *GoogleCloudVisionV1p4beta1CropHintsAnnotation `json:"cropHintsAnnotation,omitempty"`
// Error: If set, represents the error message for the operation. Note
// that filled-in image annotations are guaranteed to be correct, even
// when `error` is set.
Error *Status `json:"error,omitempty"`
// FaceAnnotations: If present, face detection has completed
// successfully.
FaceAnnotations []*GoogleCloudVisionV1p4beta1FaceAnnotation `json:"faceAnnotations,omitempty"`
// FullTextAnnotation: If present, text (OCR) detection or document
// (OCR) text detection has completed successfully. This annotation
// provides the structural hierarchy for the OCR detected text.
FullTextAnnotation *GoogleCloudVisionV1p4beta1TextAnnotation `json:"fullTextAnnotation,omitempty"`
// ImagePropertiesAnnotation: If present, image properties were
// extracted successfully.
ImagePropertiesAnnotation *GoogleCloudVisionV1p4beta1ImageProperties `json:"imagePropertiesAnnotation,omitempty"`
// LabelAnnotations: If present, label detection has completed
// successfully.
LabelAnnotations []*GoogleCloudVisionV1p4beta1EntityAnnotation `json:"labelAnnotations,omitempty"`
// LandmarkAnnotations: If present, landmark detection has completed
// successfully.
LandmarkAnnotations []*GoogleCloudVisionV1p4beta1EntityAnnotation `json:"landmarkAnnotations,omitempty"`
// LocalizedObjectAnnotations: If present, localized object detection
// has completed successfully. This will be sorted descending by
// confidence score.
LocalizedObjectAnnotations []*GoogleCloudVisionV1p4beta1LocalizedObjectAnnotation `json:"localizedObjectAnnotations,omitempty"`
// LogoAnnotations: If present, logo detection has completed
// successfully.
LogoAnnotations []*GoogleCloudVisionV1p4beta1EntityAnnotation `json:"logoAnnotations,omitempty"`
// ProductSearchResults: If present, product search has completed
// successfully.
ProductSearchResults *GoogleCloudVisionV1p4beta1ProductSearchResults `json:"productSearchResults,omitempty"`
// SafeSearchAnnotation: If present, safe-search annotation has
// completed successfully.
SafeSearchAnnotation *GoogleCloudVisionV1p4beta1SafeSearchAnnotation `json:"safeSearchAnnotation,omitempty"`
// TextAnnotations: If present, text (OCR) detection has completed
// successfully.
TextAnnotations []*GoogleCloudVisionV1p4beta1EntityAnnotation `json:"textAnnotations,omitempty"`
// WebDetection: If present, web detection has completed successfully.
WebDetection *GoogleCloudVisionV1p4beta1WebDetection `json:"webDetection,omitempty"`
// ForceSendFields is a list of field names (e.g. "Context") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Context") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1AnnotateImageResponse) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1AnnotateImageResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p4beta1AsyncAnnotateFileResponse: The response for
// a single offline file annotation request.
type GoogleCloudVisionV1p4beta1AsyncAnnotateFileResponse struct {
// OutputConfig: The output location and metadata from
// AsyncAnnotateFileRequest.
OutputConfig *GoogleCloudVisionV1p4beta1OutputConfig `json:"outputConfig,omitempty"`
// ForceSendFields is a list of field names (e.g. "OutputConfig") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "OutputConfig") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1AsyncAnnotateFileResponse) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1AsyncAnnotateFileResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p4beta1AsyncBatchAnnotateFilesResponse: Response
// to an async batch file annotation request.
type GoogleCloudVisionV1p4beta1AsyncBatchAnnotateFilesResponse struct {
// Responses: The list of file annotation responses, one for each
// request in AsyncBatchAnnotateFilesRequest.
Responses []*GoogleCloudVisionV1p4beta1AsyncAnnotateFileResponse `json:"responses,omitempty"`
// ForceSendFields is a list of field names (e.g. "Responses") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Responses") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1AsyncBatchAnnotateFilesResponse) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1AsyncBatchAnnotateFilesResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p4beta1AsyncBatchAnnotateImagesResponse: Response
// to an async batch image annotation request.
type GoogleCloudVisionV1p4beta1AsyncBatchAnnotateImagesResponse struct {
// OutputConfig: The output location and metadata from
// AsyncBatchAnnotateImagesRequest.
OutputConfig *GoogleCloudVisionV1p4beta1OutputConfig `json:"outputConfig,omitempty"`
// ForceSendFields is a list of field names (e.g. "OutputConfig") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "OutputConfig") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1AsyncBatchAnnotateImagesResponse) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1AsyncBatchAnnotateImagesResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p4beta1BatchAnnotateFilesResponse: A list of file
// annotation responses.
type GoogleCloudVisionV1p4beta1BatchAnnotateFilesResponse struct {
// Responses: The list of file annotation responses, each response
// corresponding to each AnnotateFileRequest in
// BatchAnnotateFilesRequest.
Responses []*GoogleCloudVisionV1p4beta1AnnotateFileResponse `json:"responses,omitempty"`
// ForceSendFields is a list of field names (e.g. "Responses") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Responses") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1BatchAnnotateFilesResponse) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1BatchAnnotateFilesResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p4beta1BatchOperationMetadata: Metadata for the
// batch operations such as the current state. This is included in the
// `metadata` field of the `Operation` returned by the `GetOperation`
// call of the `google::longrunning::Operations` service.
type GoogleCloudVisionV1p4beta1BatchOperationMetadata struct {
// EndTime: The time when the batch request is finished and
// google.longrunning.Operation.done is set to true.
EndTime string `json:"endTime,omitempty"`
// State: The current state of the batch operation.
//
// Possible values:
// "STATE_UNSPECIFIED" - Invalid.
// "PROCESSING" - Request is actively being processed.
// "SUCCESSFUL" - The request is done and at least one item has been
// successfully processed.
// "FAILED" - The request is done and no item has been successfully
// processed.
// "CANCELLED" - The request is done after the
// longrunning.Operations.CancelOperation has been called by the user.
// Any records that were processed before the cancel command are output
// as specified in the request.
State string `json:"state,omitempty"`
// SubmitTime: The time when the batch request was submitted to the
// server.
SubmitTime string `json:"submitTime,omitempty"`
// ForceSendFields is a list of field names (e.g. "EndTime") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "EndTime") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1BatchOperationMetadata) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1BatchOperationMetadata
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p4beta1Block: Logical element on the page.
type GoogleCloudVisionV1p4beta1Block struct {
// BlockType: Detected block type (text, image etc) for this block.
//
// Possible values:
// "UNKNOWN" - Unknown block type.
// "TEXT" - Regular text block.
// "TABLE" - Table block.
// "PICTURE" - Image block.
// "RULER" - Horizontal/vertical line box.
// "BARCODE" - Barcode block.
BlockType string `json:"blockType,omitempty"`
// BoundingBox: The bounding box for the block. The vertices are in the
// order of top-left, top-right, bottom-right, bottom-left. When a
// rotation of the bounding box is detected the rotation is represented
// as around the top-left corner as defined when the text is read in the
// 'natural' orientation. For example: * when the text is horizontal it
// might look like: 0----1 | | 3----2 * when it's rotated 180 degrees
// around the top-left corner it becomes: 2----3 | | 1----0 and the
// vertex order will still be (0, 1, 2, 3).
BoundingBox *GoogleCloudVisionV1p4beta1BoundingPoly `json:"boundingBox,omitempty"`
// Confidence: Confidence of the OCR results on the block. Range [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// Paragraphs: List of paragraphs in this block (if this blocks is of
// type text).
Paragraphs []*GoogleCloudVisionV1p4beta1Paragraph `json:"paragraphs,omitempty"`
// Property: Additional information detected for the block.
Property *GoogleCloudVisionV1p4beta1TextAnnotationTextProperty `json:"property,omitempty"`
// ForceSendFields is a list of field names (e.g. "BlockType") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BlockType") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1Block) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1Block
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p4beta1Block) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p4beta1Block
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
return nil
}
// GoogleCloudVisionV1p4beta1BoundingPoly: A bounding polygon for the
// detected image annotation.
type GoogleCloudVisionV1p4beta1BoundingPoly struct {
// NormalizedVertices: The bounding polygon normalized vertices.
NormalizedVertices []*GoogleCloudVisionV1p4beta1NormalizedVertex `json:"normalizedVertices,omitempty"`
// Vertices: The bounding polygon vertices.
Vertices []*GoogleCloudVisionV1p4beta1Vertex `json:"vertices,omitempty"`
// ForceSendFields is a list of field names (e.g. "NormalizedVertices")
// to unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "NormalizedVertices") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1BoundingPoly) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1BoundingPoly
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p4beta1Celebrity: A Celebrity is a group of Faces
// with an identity.
type GoogleCloudVisionV1p4beta1Celebrity struct {
// Description: The Celebrity's description.
Description string `json:"description,omitempty"`
// DisplayName: The Celebrity's display name.
DisplayName string `json:"displayName,omitempty"`
// Name: The resource name of the preloaded Celebrity. Has the format
// `builtin/{mid}`.
Name string `json:"name,omitempty"`
// ForceSendFields is a list of field names (e.g. "Description") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Description") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1Celebrity) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1Celebrity
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p4beta1ColorInfo: Color information consists of
// RGB channels, score, and the fraction of the image that the color
// occupies in the image.
type GoogleCloudVisionV1p4beta1ColorInfo struct {
// Color: RGB components of the color.
Color *Color `json:"color,omitempty"`
// PixelFraction: The fraction of pixels the color occupies in the
// image. Value in range [0, 1].
PixelFraction float64 `json:"pixelFraction,omitempty"`
// Score: Image-specific score for this color. Value in range [0, 1].
Score float64 `json:"score,omitempty"`
// ForceSendFields is a list of field names (e.g. "Color") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Color") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1ColorInfo) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1ColorInfo
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p4beta1ColorInfo) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p4beta1ColorInfo
var s1 struct {
PixelFraction gensupport.JSONFloat64 `json:"pixelFraction"`
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.PixelFraction = float64(s1.PixelFraction)
s.Score = float64(s1.Score)
return nil
}
// GoogleCloudVisionV1p4beta1CropHint: Single crop hint that is used to
// generate a new crop when serving an image.
type GoogleCloudVisionV1p4beta1CropHint struct {
// BoundingPoly: The bounding polygon for the crop region. The
// coordinates of the bounding box are in the original image's scale.
BoundingPoly *GoogleCloudVisionV1p4beta1BoundingPoly `json:"boundingPoly,omitempty"`
// Confidence: Confidence of this being a salient region. Range [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// ImportanceFraction: Fraction of importance of this salient region
// with respect to the original image.
ImportanceFraction float64 `json:"importanceFraction,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingPoly") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingPoly") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1CropHint) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1CropHint
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p4beta1CropHint) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p4beta1CropHint
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
ImportanceFraction gensupport.JSONFloat64 `json:"importanceFraction"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
s.ImportanceFraction = float64(s1.ImportanceFraction)
return nil
}
// GoogleCloudVisionV1p4beta1CropHintsAnnotation: Set of crop hints that
// are used to generate new crops when serving images.
type GoogleCloudVisionV1p4beta1CropHintsAnnotation struct {
// CropHints: Crop hint results.
CropHints []*GoogleCloudVisionV1p4beta1CropHint `json:"cropHints,omitempty"`
// ForceSendFields is a list of field names (e.g. "CropHints") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CropHints") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1CropHintsAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1CropHintsAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p4beta1DominantColorsAnnotation: Set of dominant
// colors and their corresponding scores.
type GoogleCloudVisionV1p4beta1DominantColorsAnnotation struct {
// Colors: RGB color values with their score and pixel fraction.
Colors []*GoogleCloudVisionV1p4beta1ColorInfo `json:"colors,omitempty"`
// ForceSendFields is a list of field names (e.g. "Colors") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Colors") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1DominantColorsAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1DominantColorsAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p4beta1EntityAnnotation: Set of detected entity
// features.
type GoogleCloudVisionV1p4beta1EntityAnnotation struct {
// BoundingPoly: Image region to which this entity belongs. Not produced
// for `LABEL_DETECTION` features.
BoundingPoly *GoogleCloudVisionV1p4beta1BoundingPoly `json:"boundingPoly,omitempty"`
// Confidence: **Deprecated. Use `score` instead.** The accuracy of the
// entity detection in an image. For example, for an image in which the
// "Eiffel Tower" entity is detected, this field represents the
// confidence that there is a tower in the query image. Range [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// Description: Entity textual description, expressed in its `locale`
// language.
Description string `json:"description,omitempty"`
// Locale: The language code for the locale in which the entity textual
// `description` is expressed.
Locale string `json:"locale,omitempty"`
// Locations: The location information for the detected entity. Multiple
// `LocationInfo` elements can be present because one location may
// indicate the location of the scene in the image, and another location
// may indicate the location of the place where the image was taken.
// Location information is usually present for landmarks.
Locations []*GoogleCloudVisionV1p4beta1LocationInfo `json:"locations,omitempty"`
// Mid: Opaque entity ID. Some IDs may be available in Google Knowledge
// Graph Search API (https://developers.google.com/knowledge-graph/).
Mid string `json:"mid,omitempty"`
// Properties: Some entities may have optional user-supplied `Property`
// (name/value) fields, such a score or string that qualifies the
// entity.
Properties []*GoogleCloudVisionV1p4beta1Property `json:"properties,omitempty"`
// Score: Overall score of the result. Range [0, 1].
Score float64 `json:"score,omitempty"`
// Topicality: The relevancy of the ICA (Image Content Annotation) label
// to the image. For example, the relevancy of "tower" is likely higher
// to an image containing the detected "Eiffel Tower" than to an image
// containing a detected distant towering building, even though the
// confidence that there is a tower in each image may be the same. Range
// [0, 1].
Topicality float64 `json:"topicality,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingPoly") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingPoly") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1EntityAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1EntityAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p4beta1EntityAnnotation) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p4beta1EntityAnnotation
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
Score gensupport.JSONFloat64 `json:"score"`
Topicality gensupport.JSONFloat64 `json:"topicality"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
s.Score = float64(s1.Score)
s.Topicality = float64(s1.Topicality)
return nil
}
// GoogleCloudVisionV1p4beta1FaceAnnotation: A face annotation object
// contains the results of face detection.
type GoogleCloudVisionV1p4beta1FaceAnnotation struct {
// AngerLikelihood: Anger likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
AngerLikelihood string `json:"angerLikelihood,omitempty"`
// BlurredLikelihood: Blurred likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
BlurredLikelihood string `json:"blurredLikelihood,omitempty"`
// BoundingPoly: The bounding polygon around the face. The coordinates
// of the bounding box are in the original image's scale. The bounding
// box is computed to "frame" the face in accordance with human
// expectations. It is based on the landmarker results. Note that one or
// more x and/or y coordinates may not be generated in the
// `BoundingPoly` (the polygon will be unbounded) if only a partial face
// appears in the image to be annotated.
BoundingPoly *GoogleCloudVisionV1p4beta1BoundingPoly `json:"boundingPoly,omitempty"`
// DetectionConfidence: Detection confidence. Range [0, 1].
DetectionConfidence float64 `json:"detectionConfidence,omitempty"`
// FdBoundingPoly: The `fd_bounding_poly` bounding polygon is tighter
// than the `boundingPoly`, and encloses only the skin part of the face.
// Typically, it is used to eliminate the face from any image analysis
// that detects the "amount of skin" visible in an image. It is not
// based on the landmarker results, only on the initial face detection,
// hence the fd (face detection) prefix.
FdBoundingPoly *GoogleCloudVisionV1p4beta1BoundingPoly `json:"fdBoundingPoly,omitempty"`
// HeadwearLikelihood: Headwear likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
HeadwearLikelihood string `json:"headwearLikelihood,omitempty"`
// JoyLikelihood: Joy likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
JoyLikelihood string `json:"joyLikelihood,omitempty"`
// LandmarkingConfidence: Face landmarking confidence. Range [0, 1].
LandmarkingConfidence float64 `json:"landmarkingConfidence,omitempty"`
// Landmarks: Detected face landmarks.
Landmarks []*GoogleCloudVisionV1p4beta1FaceAnnotationLandmark `json:"landmarks,omitempty"`
// PanAngle: Yaw angle, which indicates the leftward/rightward angle
// that the face is pointing relative to the vertical plane
// perpendicular to the image. Range [-180,180].
PanAngle float64 `json:"panAngle,omitempty"`
// RecognitionResult: Additional recognition information. Only computed
// if image_context.face_recognition_params is provided, **and** a match
// is found to a Celebrity in the input CelebritySet. This field is
// sorted in order of decreasing confidence values.
RecognitionResult []*GoogleCloudVisionV1p4beta1FaceRecognitionResult `json:"recognitionResult,omitempty"`
// RollAngle: Roll angle, which indicates the amount of
// clockwise/anti-clockwise rotation of the face relative to the image
// vertical about the axis perpendicular to the face. Range [-180,180].
RollAngle float64 `json:"rollAngle,omitempty"`
// SorrowLikelihood: Sorrow likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
SorrowLikelihood string `json:"sorrowLikelihood,omitempty"`
// SurpriseLikelihood: Surprise likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
SurpriseLikelihood string `json:"surpriseLikelihood,omitempty"`
// TiltAngle: Pitch angle, which indicates the upwards/downwards angle
// that the face is pointing relative to the image's horizontal plane.
// Range [-180,180].
TiltAngle float64 `json:"tiltAngle,omitempty"`
// UnderExposedLikelihood: Under-exposed likelihood.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
UnderExposedLikelihood string `json:"underExposedLikelihood,omitempty"`
// ForceSendFields is a list of field names (e.g. "AngerLikelihood") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "AngerLikelihood") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1FaceAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1FaceAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p4beta1FaceAnnotation) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p4beta1FaceAnnotation
var s1 struct {
DetectionConfidence gensupport.JSONFloat64 `json:"detectionConfidence"`
LandmarkingConfidence gensupport.JSONFloat64 `json:"landmarkingConfidence"`
PanAngle gensupport.JSONFloat64 `json:"panAngle"`
RollAngle gensupport.JSONFloat64 `json:"rollAngle"`
TiltAngle gensupport.JSONFloat64 `json:"tiltAngle"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.DetectionConfidence = float64(s1.DetectionConfidence)
s.LandmarkingConfidence = float64(s1.LandmarkingConfidence)
s.PanAngle = float64(s1.PanAngle)
s.RollAngle = float64(s1.RollAngle)
s.TiltAngle = float64(s1.TiltAngle)
return nil
}
// GoogleCloudVisionV1p4beta1FaceAnnotationLandmark: A face-specific
// landmark (for example, a face feature).
type GoogleCloudVisionV1p4beta1FaceAnnotationLandmark struct {
// Position: Face landmark position.
Position *GoogleCloudVisionV1p4beta1Position `json:"position,omitempty"`
// Type: Face landmark type.
//
// Possible values:
// "UNKNOWN_LANDMARK" - Unknown face landmark detected. Should not be
// filled.
// "LEFT_EYE" - Left eye.
// "RIGHT_EYE" - Right eye.
// "LEFT_OF_LEFT_EYEBROW" - Left of left eyebrow.
// "RIGHT_OF_LEFT_EYEBROW" - Right of left eyebrow.
// "LEFT_OF_RIGHT_EYEBROW" - Left of right eyebrow.
// "RIGHT_OF_RIGHT_EYEBROW" - Right of right eyebrow.
// "MIDPOINT_BETWEEN_EYES" - Midpoint between eyes.
// "NOSE_TIP" - Nose tip.
// "UPPER_LIP" - Upper lip.
// "LOWER_LIP" - Lower lip.
// "MOUTH_LEFT" - Mouth left.
// "MOUTH_RIGHT" - Mouth right.
// "MOUTH_CENTER" - Mouth center.
// "NOSE_BOTTOM_RIGHT" - Nose, bottom right.
// "NOSE_BOTTOM_LEFT" - Nose, bottom left.
// "NOSE_BOTTOM_CENTER" - Nose, bottom center.
// "LEFT_EYE_TOP_BOUNDARY" - Left eye, top boundary.
// "LEFT_EYE_RIGHT_CORNER" - Left eye, right corner.
// "LEFT_EYE_BOTTOM_BOUNDARY" - Left eye, bottom boundary.
// "LEFT_EYE_LEFT_CORNER" - Left eye, left corner.
// "RIGHT_EYE_TOP_BOUNDARY" - Right eye, top boundary.
// "RIGHT_EYE_RIGHT_CORNER" - Right eye, right corner.
// "RIGHT_EYE_BOTTOM_BOUNDARY" - Right eye, bottom boundary.
// "RIGHT_EYE_LEFT_CORNER" - Right eye, left corner.
// "LEFT_EYEBROW_UPPER_MIDPOINT" - Left eyebrow, upper midpoint.
// "RIGHT_EYEBROW_UPPER_MIDPOINT" - Right eyebrow, upper midpoint.
// "LEFT_EAR_TRAGION" - Left ear tragion.
// "RIGHT_EAR_TRAGION" - Right ear tragion.
// "LEFT_EYE_PUPIL" - Left eye pupil.
// "RIGHT_EYE_PUPIL" - Right eye pupil.
// "FOREHEAD_GLABELLA" - Forehead glabella.
// "CHIN_GNATHION" - Chin gnathion.
// "CHIN_LEFT_GONION" - Chin left gonion.
// "CHIN_RIGHT_GONION" - Chin right gonion.
// "LEFT_CHEEK_CENTER" - Left cheek center.
// "RIGHT_CHEEK_CENTER" - Right cheek center.
Type string `json:"type,omitempty"`
// ForceSendFields is a list of field names (e.g. "Position") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Position") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1FaceAnnotationLandmark) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1FaceAnnotationLandmark
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p4beta1FaceRecognitionResult: Information about a
// face's identity.
type GoogleCloudVisionV1p4beta1FaceRecognitionResult struct {
// Celebrity: The Celebrity that this face was matched to.
Celebrity *GoogleCloudVisionV1p4beta1Celebrity `json:"celebrity,omitempty"`
// Confidence: Recognition confidence. Range [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// ForceSendFields is a list of field names (e.g. "Celebrity") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Celebrity") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1FaceRecognitionResult) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1FaceRecognitionResult
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p4beta1FaceRecognitionResult) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p4beta1FaceRecognitionResult
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
return nil
}
// GoogleCloudVisionV1p4beta1GcsDestination: The Google Cloud Storage
// location where the output will be written to.
type GoogleCloudVisionV1p4beta1GcsDestination struct {
// Uri: Google Cloud Storage URI prefix where the results will be
// stored. Results will be in JSON format and preceded by its
// corresponding input URI prefix. This field can either represent a gcs
// file prefix or gcs directory. In either case, the uri should be
// unique because in order to get all of the output files, you will need
// to do a wildcard gcs search on the uri prefix you provide. Examples:
// * File Prefix: gs://bucket-name/here/filenameprefix The output files
// will be created in gs://bucket-name/here/ and the names of the output
// files will begin with "filenameprefix". * Directory Prefix:
// gs://bucket-name/some/location/ The output files will be created in
// gs://bucket-name/some/location/ and the names of the output files
// could be anything because there was no filename prefix specified. If
// multiple outputs, each response is still AnnotateFileResponse, each
// of which contains some subset of the full list of
// AnnotateImageResponse. Multiple outputs can happen if, for example,
// the output JSON is too large and overflows into multiple sharded
// files.
Uri string `json:"uri,omitempty"`
// ForceSendFields is a list of field names (e.g. "Uri") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Uri") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1GcsDestination) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1GcsDestination
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p4beta1GcsSource: The Google Cloud Storage
// location where the input will be read from.
type GoogleCloudVisionV1p4beta1GcsSource struct {
// Uri: Google Cloud Storage URI for the input file. This must only be a
// Google Cloud Storage object. Wildcards are not currently supported.
Uri string `json:"uri,omitempty"`
// ForceSendFields is a list of field names (e.g. "Uri") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Uri") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1GcsSource) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1GcsSource
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p4beta1ImageAnnotationContext: If an image was
// produced from a file (e.g. a PDF), this message gives information
// about the source of that image.
type GoogleCloudVisionV1p4beta1ImageAnnotationContext struct {
// PageNumber: If the file was a PDF or TIFF, this field gives the page
// number within the file used to produce the image.
PageNumber int64 `json:"pageNumber,omitempty"`
// Uri: The URI of the file used to produce the image.
Uri string `json:"uri,omitempty"`
// ForceSendFields is a list of field names (e.g. "PageNumber") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "PageNumber") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1ImageAnnotationContext) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1ImageAnnotationContext
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p4beta1ImageProperties: Stores image properties,
// such as dominant colors.
type GoogleCloudVisionV1p4beta1ImageProperties struct {
// DominantColors: If present, dominant colors completed successfully.
DominantColors *GoogleCloudVisionV1p4beta1DominantColorsAnnotation `json:"dominantColors,omitempty"`
// ForceSendFields is a list of field names (e.g. "DominantColors") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "DominantColors") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1ImageProperties) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1ImageProperties
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p4beta1ImportProductSetsResponse: Response message
// for the `ImportProductSets` method. This message is returned by the
// google.longrunning.Operations.GetOperation method in the returned
// google.longrunning.Operation.response field.
type GoogleCloudVisionV1p4beta1ImportProductSetsResponse struct {
// ReferenceImages: The list of reference_images that are imported
// successfully.
ReferenceImages []*GoogleCloudVisionV1p4beta1ReferenceImage `json:"referenceImages,omitempty"`
// Statuses: The rpc status for each ImportProductSet request, including
// both successes and errors. The number of statuses here matches the
// number of lines in the csv file, and statuses[i] stores the success
// or failure status of processing the i-th line of the csv, starting
// from line 0.
Statuses []*Status `json:"statuses,omitempty"`
// ForceSendFields is a list of field names (e.g. "ReferenceImages") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ReferenceImages") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1ImportProductSetsResponse) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1ImportProductSetsResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p4beta1InputConfig: The desired input location and
// metadata.
type GoogleCloudVisionV1p4beta1InputConfig struct {
// Content: File content, represented as a stream of bytes. Note: As
// with all `bytes` fields, protobuffers use a pure binary
// representation, whereas JSON representations use base64. Currently,
// this field only works for BatchAnnotateFiles requests. It does not
// work for AsyncBatchAnnotateFiles requests.
Content string `json:"content,omitempty"`
// GcsSource: The Google Cloud Storage location to read the input from.
GcsSource *GoogleCloudVisionV1p4beta1GcsSource `json:"gcsSource,omitempty"`
// MimeType: The type of the file. Currently only "application/pdf",
// "image/tiff" and "image/gif" are supported. Wildcards are not
// supported.
MimeType string `json:"mimeType,omitempty"`
// ForceSendFields is a list of field names (e.g. "Content") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Content") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1InputConfig) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1InputConfig
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p4beta1LocalizedObjectAnnotation: Set of detected
// objects with bounding boxes.
type GoogleCloudVisionV1p4beta1LocalizedObjectAnnotation struct {
// BoundingPoly: Image region to which this object belongs. This must be
// populated.
BoundingPoly *GoogleCloudVisionV1p4beta1BoundingPoly `json:"boundingPoly,omitempty"`
// LanguageCode: The BCP-47 language code, such as "en-US" or "sr-Latn".
// For more information, see
// http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
LanguageCode string `json:"languageCode,omitempty"`
// Mid: Object ID that should align with EntityAnnotation mid.
Mid string `json:"mid,omitempty"`
// Name: Object name, expressed in its `language_code` language.
Name string `json:"name,omitempty"`
// Score: Score of the result. Range [0, 1].
Score float64 `json:"score,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingPoly") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingPoly") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1LocalizedObjectAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1LocalizedObjectAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p4beta1LocalizedObjectAnnotation) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p4beta1LocalizedObjectAnnotation
var s1 struct {
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Score = float64(s1.Score)
return nil
}
// GoogleCloudVisionV1p4beta1LocationInfo: Detected entity location
// information.
type GoogleCloudVisionV1p4beta1LocationInfo struct {
// LatLng: lat/long location coordinates.
LatLng *LatLng `json:"latLng,omitempty"`
// ForceSendFields is a list of field names (e.g. "LatLng") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "LatLng") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1LocationInfo) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1LocationInfo
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p4beta1NormalizedVertex: A vertex represents a 2D
// point in the image. NOTE: the normalized vertex coordinates are
// relative to the original image and range from 0 to 1.
type GoogleCloudVisionV1p4beta1NormalizedVertex struct {
// X: X coordinate.
X float64 `json:"x,omitempty"`
// Y: Y coordinate.
Y float64 `json:"y,omitempty"`
// ForceSendFields is a list of field names (e.g. "X") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "X") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1NormalizedVertex) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1NormalizedVertex
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p4beta1NormalizedVertex) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p4beta1NormalizedVertex
var s1 struct {
X gensupport.JSONFloat64 `json:"x"`
Y gensupport.JSONFloat64 `json:"y"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.X = float64(s1.X)
s.Y = float64(s1.Y)
return nil
}
// GoogleCloudVisionV1p4beta1OperationMetadata: Contains metadata for
// the BatchAnnotateImages operation.
type GoogleCloudVisionV1p4beta1OperationMetadata struct {
// CreateTime: The time when the batch request was received.
CreateTime string `json:"createTime,omitempty"`
// State: Current state of the batch operation.
//
// Possible values:
// "STATE_UNSPECIFIED" - Invalid.
// "CREATED" - Request is received.
// "RUNNING" - Request is actively being processed.
// "DONE" - The batch processing is done.
// "CANCELLED" - The batch processing was cancelled.
State string `json:"state,omitempty"`
// UpdateTime: The time when the operation result was last updated.
UpdateTime string `json:"updateTime,omitempty"`
// ForceSendFields is a list of field names (e.g. "CreateTime") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CreateTime") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1OperationMetadata) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1OperationMetadata
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p4beta1OutputConfig: The desired output location
// and metadata.
type GoogleCloudVisionV1p4beta1OutputConfig struct {
// BatchSize: The max number of response protos to put into each output
// JSON file on Google Cloud Storage. The valid range is [1, 100]. If
// not specified, the default value is 20. For example, for one pdf file
// with 100 pages, 100 response protos will be generated. If
// `batch_size` = 20, then 5 json files each containing 20 response
// protos will be written under the prefix `gcs_destination`.`uri`.
// Currently, batch_size only applies to GcsDestination, with potential
// future support for other output configurations.
BatchSize int64 `json:"batchSize,omitempty"`
// GcsDestination: The Google Cloud Storage location to write the
// output(s) to.
GcsDestination *GoogleCloudVisionV1p4beta1GcsDestination `json:"gcsDestination,omitempty"`
// ForceSendFields is a list of field names (e.g. "BatchSize") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BatchSize") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1OutputConfig) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1OutputConfig
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p4beta1Page: Detected page from OCR.
type GoogleCloudVisionV1p4beta1Page struct {
// Blocks: List of blocks of text, images etc on this page.
Blocks []*GoogleCloudVisionV1p4beta1Block `json:"blocks,omitempty"`
// Confidence: Confidence of the OCR results on the page. Range [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// Height: Page height. For PDFs the unit is points. For images
// (including TIFFs) the unit is pixels.
Height int64 `json:"height,omitempty"`
// Property: Additional information detected on the page.
Property *GoogleCloudVisionV1p4beta1TextAnnotationTextProperty `json:"property,omitempty"`
// Width: Page width. For PDFs the unit is points. For images (including
// TIFFs) the unit is pixels.
Width int64 `json:"width,omitempty"`
// ForceSendFields is a list of field names (e.g. "Blocks") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Blocks") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1Page) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1Page
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p4beta1Page) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p4beta1Page
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
return nil
}
// GoogleCloudVisionV1p4beta1Paragraph: Structural unit of text
// representing a number of words in certain order.
type GoogleCloudVisionV1p4beta1Paragraph struct {
// BoundingBox: The bounding box for the paragraph. The vertices are in
// the order of top-left, top-right, bottom-right, bottom-left. When a
// rotation of the bounding box is detected the rotation is represented
// as around the top-left corner as defined when the text is read in the
// 'natural' orientation. For example: * when the text is horizontal it
// might look like: 0----1 | | 3----2 * when it's rotated 180 degrees
// around the top-left corner it becomes: 2----3 | | 1----0 and the
// vertex order will still be (0, 1, 2, 3).
BoundingBox *GoogleCloudVisionV1p4beta1BoundingPoly `json:"boundingBox,omitempty"`
// Confidence: Confidence of the OCR results for the paragraph. Range
// [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// Property: Additional information detected for the paragraph.
Property *GoogleCloudVisionV1p4beta1TextAnnotationTextProperty `json:"property,omitempty"`
// Words: List of all words in this paragraph.
Words []*GoogleCloudVisionV1p4beta1Word `json:"words,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingBox") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingBox") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1Paragraph) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1Paragraph
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p4beta1Paragraph) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p4beta1Paragraph
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
return nil
}
// GoogleCloudVisionV1p4beta1Position: A 3D position in the image, used
// primarily for Face detection landmarks. A valid Position must have
// both x and y coordinates. The position coordinates are in the same
// scale as the original image.
type GoogleCloudVisionV1p4beta1Position struct {
// X: X coordinate.
X float64 `json:"x,omitempty"`
// Y: Y coordinate.
Y float64 `json:"y,omitempty"`
// Z: Z coordinate (or depth).
Z float64 `json:"z,omitempty"`
// ForceSendFields is a list of field names (e.g. "X") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "X") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1Position) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1Position
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p4beta1Position) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p4beta1Position
var s1 struct {
X gensupport.JSONFloat64 `json:"x"`
Y gensupport.JSONFloat64 `json:"y"`
Z gensupport.JSONFloat64 `json:"z"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.X = float64(s1.X)
s.Y = float64(s1.Y)
s.Z = float64(s1.Z)
return nil
}
// GoogleCloudVisionV1p4beta1Product: A Product contains
// ReferenceImages.
type GoogleCloudVisionV1p4beta1Product struct {
// Description: User-provided metadata to be stored with this product.
// Must be at most 4096 characters long.
Description string `json:"description,omitempty"`
// DisplayName: The user-provided name for this Product. Must not be
// empty. Must be at most 4096 characters long.
DisplayName string `json:"displayName,omitempty"`
// Name: The resource name of the product. Format is:
// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`. This
// field is ignored when creating a product.
Name string `json:"name,omitempty"`
// ProductCategory: Immutable. The category for the product identified
// by the reference image. This should be one of "homegoods-v2",
// "apparel-v2", "toys-v2", "packagedgoods-v1" or "general-v1". The
// legacy categories "homegoods", "apparel", and "toys" are still
// supported, but these should not be used for new products.
ProductCategory string `json:"productCategory,omitempty"`
// ProductLabels: Key-value pairs that can be attached to a product. At
// query time, constraints can be specified based on the product_labels.
// Note that integer values can be provided as strings, e.g. "1199".
// Only strings with integer values can match a range-based restriction
// which is to be supported soon. Multiple values can be assigned to the
// same key. One product may have up to 500 product_labels. Notice that
// the total number of distinct product_labels over all products in one
// ProductSet cannot exceed 1M, otherwise the product search pipeline
// will refuse to work for that ProductSet.
ProductLabels []*GoogleCloudVisionV1p4beta1ProductKeyValue `json:"productLabels,omitempty"`
// ForceSendFields is a list of field names (e.g. "Description") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Description") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1Product) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1Product
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p4beta1ProductKeyValue: A product label
// represented as a key-value pair.
type GoogleCloudVisionV1p4beta1ProductKeyValue struct {
// Key: The key of the label attached to the product. Cannot be empty
// and cannot exceed 128 bytes.
Key string `json:"key,omitempty"`
// Value: The value of the label attached to the product. Cannot be
// empty and cannot exceed 128 bytes.
Value string `json:"value,omitempty"`
// ForceSendFields is a list of field names (e.g. "Key") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Key") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1ProductKeyValue) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1ProductKeyValue
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p4beta1ProductSearchResults: Results for a product
// search request.
type GoogleCloudVisionV1p4beta1ProductSearchResults struct {
// IndexTime: Timestamp of the index which provided these results.
// Products added to the product set and products removed from the
// product set after this time are not reflected in the current results.
IndexTime string `json:"indexTime,omitempty"`
// ProductGroupedResults: List of results grouped by products detected
// in the query image. Each entry corresponds to one bounding polygon in
// the query image, and contains the matching products specific to that
// region. There may be duplicate product matches in the union of all
// the per-product results.
ProductGroupedResults []*GoogleCloudVisionV1p4beta1ProductSearchResultsGroupedResult `json:"productGroupedResults,omitempty"`
// Results: List of results, one for each product match.
Results []*GoogleCloudVisionV1p4beta1ProductSearchResultsResult `json:"results,omitempty"`
// ForceSendFields is a list of field names (e.g. "IndexTime") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "IndexTime") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1ProductSearchResults) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1ProductSearchResults
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p4beta1ProductSearchResultsGroupedResult:
// Information about the products similar to a single product in a query
// image.
type GoogleCloudVisionV1p4beta1ProductSearchResultsGroupedResult struct {
// BoundingPoly: The bounding polygon around the product detected in the
// query image.
BoundingPoly *GoogleCloudVisionV1p4beta1BoundingPoly `json:"boundingPoly,omitempty"`
// ObjectAnnotations: List of generic predictions for the object in the
// bounding box.
ObjectAnnotations []*GoogleCloudVisionV1p4beta1ProductSearchResultsObjectAnnotation `json:"objectAnnotations,omitempty"`
// Results: List of results, one for each product match.
Results []*GoogleCloudVisionV1p4beta1ProductSearchResultsResult `json:"results,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingPoly") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingPoly") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1ProductSearchResultsGroupedResult) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1ProductSearchResultsGroupedResult
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p4beta1ProductSearchResultsObjectAnnotation:
// Prediction for what the object in the bounding box is.
type GoogleCloudVisionV1p4beta1ProductSearchResultsObjectAnnotation struct {
// LanguageCode: The BCP-47 language code, such as "en-US" or "sr-Latn".
// For more information, see
// http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
LanguageCode string `json:"languageCode,omitempty"`
// Mid: Object ID that should align with EntityAnnotation mid.
Mid string `json:"mid,omitempty"`
// Name: Object name, expressed in its `language_code` language.
Name string `json:"name,omitempty"`
// Score: Score of the result. Range [0, 1].
Score float64 `json:"score,omitempty"`
// ForceSendFields is a list of field names (e.g. "LanguageCode") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "LanguageCode") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1ProductSearchResultsObjectAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1ProductSearchResultsObjectAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p4beta1ProductSearchResultsObjectAnnotation) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p4beta1ProductSearchResultsObjectAnnotation
var s1 struct {
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Score = float64(s1.Score)
return nil
}
// GoogleCloudVisionV1p4beta1ProductSearchResultsResult: Information
// about a product.
type GoogleCloudVisionV1p4beta1ProductSearchResultsResult struct {
// Image: The resource name of the image from the product that is the
// closest match to the query.
Image string `json:"image,omitempty"`
// Product: The Product.
Product *GoogleCloudVisionV1p4beta1Product `json:"product,omitempty"`
// Score: A confidence level on the match, ranging from 0 (no
// confidence) to 1 (full confidence).
Score float64 `json:"score,omitempty"`
// ForceSendFields is a list of field names (e.g. "Image") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Image") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1ProductSearchResultsResult) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1ProductSearchResultsResult
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p4beta1ProductSearchResultsResult) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p4beta1ProductSearchResultsResult
var s1 struct {
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Score = float64(s1.Score)
return nil
}
// GoogleCloudVisionV1p4beta1Property: A `Property` consists of a
// user-supplied name/value pair.
type GoogleCloudVisionV1p4beta1Property struct {
// Name: Name of the property.
Name string `json:"name,omitempty"`
// Uint64Value: Value of numeric properties.
Uint64Value uint64 `json:"uint64Value,omitempty,string"`
// Value: Value of the property.
Value string `json:"value,omitempty"`
// ForceSendFields is a list of field names (e.g. "Name") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Name") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1Property) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1Property
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p4beta1ReferenceImage: A `ReferenceImage`
// represents a product image and its associated metadata, such as
// bounding boxes.
type GoogleCloudVisionV1p4beta1ReferenceImage struct {
// BoundingPolys: Optional. Bounding polygons around the areas of
// interest in the reference image. If this field is empty, the system
// will try to detect regions of interest. At most 10 bounding polygons
// will be used. The provided shape is converted into a non-rotated
// rectangle. Once converted, the small edge of the rectangle must be
// greater than or equal to 300 pixels. The aspect ratio must be 1:4 or
// less (i.e. 1:3 is ok; 1:5 is not).
BoundingPolys []*GoogleCloudVisionV1p4beta1BoundingPoly `json:"boundingPolys,omitempty"`
// Name: The resource name of the reference image. Format is:
// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceIma
// ges/IMAGE_ID`. This field is ignored when creating a reference image.
Name string `json:"name,omitempty"`
// Uri: Required. The Google Cloud Storage URI of the reference image.
// The URI must start with `gs://`.
Uri string `json:"uri,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingPolys") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingPolys") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1ReferenceImage) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1ReferenceImage
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p4beta1SafeSearchAnnotation: Set of features
// pertaining to the image, computed by computer vision methods over
// safe-search verticals (for example, adult, spoof, medical, violence).
type GoogleCloudVisionV1p4beta1SafeSearchAnnotation struct {
// Adult: Represents the adult content likelihood for the image. Adult
// content may contain elements such as nudity, pornographic images or
// cartoons, or sexual activities.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
Adult string `json:"adult,omitempty"`
// Medical: Likelihood that this is a medical image.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
Medical string `json:"medical,omitempty"`
// Racy: Likelihood that the request image contains racy content. Racy
// content may include (but is not limited to) skimpy or sheer clothing,
// strategically covered nudity, lewd or provocative poses, or close-ups
// of sensitive body areas.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
Racy string `json:"racy,omitempty"`
// Spoof: Spoof likelihood. The likelihood that an modification was made
// to the image's canonical version to make it appear funny or
// offensive.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
Spoof string `json:"spoof,omitempty"`
// Violence: Likelihood that this image contains violent content.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
Violence string `json:"violence,omitempty"`
// ForceSendFields is a list of field names (e.g. "Adult") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Adult") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1SafeSearchAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1SafeSearchAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p4beta1Symbol: A single symbol representation.
type GoogleCloudVisionV1p4beta1Symbol struct {
// BoundingBox: The bounding box for the symbol. The vertices are in the
// order of top-left, top-right, bottom-right, bottom-left. When a
// rotation of the bounding box is detected the rotation is represented
// as around the top-left corner as defined when the text is read in the
// 'natural' orientation. For example: * when the text is horizontal it
// might look like: 0----1 | | 3----2 * when it's rotated 180 degrees
// around the top-left corner it becomes: 2----3 | | 1----0 and the
// vertex order will still be (0, 1, 2, 3).
BoundingBox *GoogleCloudVisionV1p4beta1BoundingPoly `json:"boundingBox,omitempty"`
// Confidence: Confidence of the OCR results for the symbol. Range [0,
// 1].
Confidence float64 `json:"confidence,omitempty"`
// Property: Additional information detected for the symbol.
Property *GoogleCloudVisionV1p4beta1TextAnnotationTextProperty `json:"property,omitempty"`
// Text: The actual UTF-8 representation of the symbol.
Text string `json:"text,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingBox") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingBox") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1Symbol) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1Symbol
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p4beta1Symbol) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p4beta1Symbol
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
return nil
}
// GoogleCloudVisionV1p4beta1TextAnnotation: TextAnnotation contains a
// structured representation of OCR extracted text. The hierarchy of an
// OCR extracted text structure is like this: TextAnnotation -> Page ->
// Block -> Paragraph -> Word -> Symbol Each structural component,
// starting from Page, may further have their own properties. Properties
// describe detected languages, breaks etc.. Please refer to the
// TextAnnotation.TextProperty message definition below for more detail.
type GoogleCloudVisionV1p4beta1TextAnnotation struct {
// Pages: List of pages detected by OCR.
Pages []*GoogleCloudVisionV1p4beta1Page `json:"pages,omitempty"`
// Text: UTF-8 text detected on the pages.
Text string `json:"text,omitempty"`
// ForceSendFields is a list of field names (e.g. "Pages") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Pages") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1TextAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1TextAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p4beta1TextAnnotationDetectedBreak: Detected start
// or end of a structural component.
type GoogleCloudVisionV1p4beta1TextAnnotationDetectedBreak struct {
// IsPrefix: True if break prepends the element.
IsPrefix bool `json:"isPrefix,omitempty"`
// Type: Detected break type.
//
// Possible values:
// "UNKNOWN" - Unknown break label type.
// "SPACE" - Regular space.
// "SURE_SPACE" - Sure space (very wide).
// "EOL_SURE_SPACE" - Line-wrapping break.
// "HYPHEN" - End-line hyphen that is not present in text; does not
// co-occur with `SPACE`, `LEADER_SPACE`, or `LINE_BREAK`.
// "LINE_BREAK" - Line break that ends a paragraph.
Type string `json:"type,omitempty"`
// ForceSendFields is a list of field names (e.g. "IsPrefix") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "IsPrefix") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1TextAnnotationDetectedBreak) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1TextAnnotationDetectedBreak
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p4beta1TextAnnotationDetectedLanguage: Detected
// language for a structural component.
type GoogleCloudVisionV1p4beta1TextAnnotationDetectedLanguage struct {
// Confidence: Confidence of detected language. Range [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// LanguageCode: The BCP-47 language code, such as "en-US" or "sr-Latn".
// For more information, see
// http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
LanguageCode string `json:"languageCode,omitempty"`
// ForceSendFields is a list of field names (e.g. "Confidence") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Confidence") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1TextAnnotationDetectedLanguage) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1TextAnnotationDetectedLanguage
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p4beta1TextAnnotationDetectedLanguage) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p4beta1TextAnnotationDetectedLanguage
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
return nil
}
// GoogleCloudVisionV1p4beta1TextAnnotationTextProperty: Additional
// information detected on the structural component.
type GoogleCloudVisionV1p4beta1TextAnnotationTextProperty struct {
// DetectedBreak: Detected start or end of a text segment.
DetectedBreak *GoogleCloudVisionV1p4beta1TextAnnotationDetectedBreak `json:"detectedBreak,omitempty"`
// DetectedLanguages: A list of detected languages together with
// confidence.
DetectedLanguages []*GoogleCloudVisionV1p4beta1TextAnnotationDetectedLanguage `json:"detectedLanguages,omitempty"`
// ForceSendFields is a list of field names (e.g. "DetectedBreak") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "DetectedBreak") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1TextAnnotationTextProperty) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1TextAnnotationTextProperty
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p4beta1Vertex: A vertex represents a 2D point in
// the image. NOTE: the vertex coordinates are in the same scale as the
// original image.
type GoogleCloudVisionV1p4beta1Vertex struct {
// X: X coordinate.
X int64 `json:"x,omitempty"`
// Y: Y coordinate.
Y int64 `json:"y,omitempty"`
// ForceSendFields is a list of field names (e.g. "X") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "X") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1Vertex) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1Vertex
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p4beta1WebDetection: Relevant information for the
// image from the Internet.
type GoogleCloudVisionV1p4beta1WebDetection struct {
// BestGuessLabels: The service's best guess as to the topic of the
// request image. Inferred from similar images on the open web.
BestGuessLabels []*GoogleCloudVisionV1p4beta1WebDetectionWebLabel `json:"bestGuessLabels,omitempty"`
// FullMatchingImages: Fully matching images from the Internet. Can
// include resized copies of the query image.
FullMatchingImages []*GoogleCloudVisionV1p4beta1WebDetectionWebImage `json:"fullMatchingImages,omitempty"`
// PagesWithMatchingImages: Web pages containing the matching images
// from the Internet.
PagesWithMatchingImages []*GoogleCloudVisionV1p4beta1WebDetectionWebPage `json:"pagesWithMatchingImages,omitempty"`
// PartialMatchingImages: Partial matching images from the Internet.
// Those images are similar enough to share some key-point features. For
// example an original image will likely have partial matching for its
// crops.
PartialMatchingImages []*GoogleCloudVisionV1p4beta1WebDetectionWebImage `json:"partialMatchingImages,omitempty"`
// VisuallySimilarImages: The visually similar image results.
VisuallySimilarImages []*GoogleCloudVisionV1p4beta1WebDetectionWebImage `json:"visuallySimilarImages,omitempty"`
// WebEntities: Deduced entities from similar images on the Internet.
WebEntities []*GoogleCloudVisionV1p4beta1WebDetectionWebEntity `json:"webEntities,omitempty"`
// ForceSendFields is a list of field names (e.g. "BestGuessLabels") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BestGuessLabels") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1WebDetection) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1WebDetection
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p4beta1WebDetectionWebEntity: Entity deduced from
// similar images on the Internet.
type GoogleCloudVisionV1p4beta1WebDetectionWebEntity struct {
// Description: Canonical description of the entity, in English.
Description string `json:"description,omitempty"`
// EntityId: Opaque entity ID.
EntityId string `json:"entityId,omitempty"`
// Score: Overall relevancy score for the entity. Not normalized and not
// comparable across different image queries.
Score float64 `json:"score,omitempty"`
// ForceSendFields is a list of field names (e.g. "Description") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Description") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1WebDetectionWebEntity) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1WebDetectionWebEntity
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p4beta1WebDetectionWebEntity) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p4beta1WebDetectionWebEntity
var s1 struct {
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Score = float64(s1.Score)
return nil
}
// GoogleCloudVisionV1p4beta1WebDetectionWebImage: Metadata for online
// images.
type GoogleCloudVisionV1p4beta1WebDetectionWebImage struct {
// Score: (Deprecated) Overall relevancy score for the image.
Score float64 `json:"score,omitempty"`
// Url: The result image URL.
Url string `json:"url,omitempty"`
// ForceSendFields is a list of field names (e.g. "Score") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Score") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1WebDetectionWebImage) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1WebDetectionWebImage
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p4beta1WebDetectionWebImage) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p4beta1WebDetectionWebImage
var s1 struct {
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Score = float64(s1.Score)
return nil
}
// GoogleCloudVisionV1p4beta1WebDetectionWebLabel: Label to provide
// extra metadata for the web detection.
type GoogleCloudVisionV1p4beta1WebDetectionWebLabel struct {
// Label: Label for extra metadata.
Label string `json:"label,omitempty"`
// LanguageCode: The BCP-47 language code for `label`, such as "en-US"
// or "sr-Latn". For more information, see
// http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
LanguageCode string `json:"languageCode,omitempty"`
// ForceSendFields is a list of field names (e.g. "Label") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Label") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1WebDetectionWebLabel) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1WebDetectionWebLabel
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleCloudVisionV1p4beta1WebDetectionWebPage: Metadata for web
// pages.
type GoogleCloudVisionV1p4beta1WebDetectionWebPage struct {
// FullMatchingImages: Fully matching images on the page. Can include
// resized copies of the query image.
FullMatchingImages []*GoogleCloudVisionV1p4beta1WebDetectionWebImage `json:"fullMatchingImages,omitempty"`
// PageTitle: Title for the web page, may contain HTML markups.
PageTitle string `json:"pageTitle,omitempty"`
// PartialMatchingImages: Partial matching images on the page. Those
// images are similar enough to share some key-point features. For
// example an original image will likely have partial matching for its
// crops.
PartialMatchingImages []*GoogleCloudVisionV1p4beta1WebDetectionWebImage `json:"partialMatchingImages,omitempty"`
// Score: (Deprecated) Overall relevancy score for the web page.
Score float64 `json:"score,omitempty"`
// Url: The result web page URL.
Url string `json:"url,omitempty"`
// ForceSendFields is a list of field names (e.g. "FullMatchingImages")
// to unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "FullMatchingImages") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1WebDetectionWebPage) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1WebDetectionWebPage
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p4beta1WebDetectionWebPage) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p4beta1WebDetectionWebPage
var s1 struct {
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Score = float64(s1.Score)
return nil
}
// GoogleCloudVisionV1p4beta1Word: A word representation.
type GoogleCloudVisionV1p4beta1Word struct {
// BoundingBox: The bounding box for the word. The vertices are in the
// order of top-left, top-right, bottom-right, bottom-left. When a
// rotation of the bounding box is detected the rotation is represented
// as around the top-left corner as defined when the text is read in the
// 'natural' orientation. For example: * when the text is horizontal it
// might look like: 0----1 | | 3----2 * when it's rotated 180 degrees
// around the top-left corner it becomes: 2----3 | | 1----0 and the
// vertex order will still be (0, 1, 2, 3).
BoundingBox *GoogleCloudVisionV1p4beta1BoundingPoly `json:"boundingBox,omitempty"`
// Confidence: Confidence of the OCR results for the word. Range [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// Property: Additional information detected for the word.
Property *GoogleCloudVisionV1p4beta1TextAnnotationTextProperty `json:"property,omitempty"`
// Symbols: List of symbols in the word. The order of the symbols
// follows the natural reading order.
Symbols []*GoogleCloudVisionV1p4beta1Symbol `json:"symbols,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingBox") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingBox") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleCloudVisionV1p4beta1Word) MarshalJSON() ([]byte, error) {
type NoMethod GoogleCloudVisionV1p4beta1Word
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *GoogleCloudVisionV1p4beta1Word) UnmarshalJSON(data []byte) error {
type NoMethod GoogleCloudVisionV1p4beta1Word
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
return nil
}
// GroupedResult: Information about the products similar to a single
// product in a query image.
type GroupedResult struct {
// BoundingPoly: The bounding polygon around the product detected in the
// query image.
BoundingPoly *BoundingPoly `json:"boundingPoly,omitempty"`
// ObjectAnnotations: List of generic predictions for the object in the
// bounding box.
ObjectAnnotations []*ObjectAnnotation `json:"objectAnnotations,omitempty"`
// Results: List of results, one for each product match.
Results []*Result `json:"results,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingPoly") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingPoly") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GroupedResult) MarshalJSON() ([]byte, error) {
type NoMethod GroupedResult
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Image: Client image to perform Google Cloud Vision API tasks over.
type Image struct {
// Content: Image content, represented as a stream of bytes. Note: As
// with all `bytes` fields, protobuffers use a pure binary
// representation, whereas JSON representations use base64. Currently,
// this field only works for BatchAnnotateImages requests. It does not
// work for AsyncBatchAnnotateImages requests.
Content string `json:"content,omitempty"`
// Source: Google Cloud Storage image location, or publicly-accessible
// image URL. If both `content` and `source` are provided for an image,
// `content` takes precedence and is used to perform the image
// annotation request.
Source *ImageSource `json:"source,omitempty"`
// ForceSendFields is a list of field names (e.g. "Content") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Content") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Image) MarshalJSON() ([]byte, error) {
type NoMethod Image
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ImageAnnotationContext: If an image was produced from a file (e.g. a
// PDF), this message gives information about the source of that image.
type ImageAnnotationContext struct {
// PageNumber: If the file was a PDF or TIFF, this field gives the page
// number within the file used to produce the image.
PageNumber int64 `json:"pageNumber,omitempty"`
// Uri: The URI of the file used to produce the image.
Uri string `json:"uri,omitempty"`
// ForceSendFields is a list of field names (e.g. "PageNumber") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "PageNumber") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ImageAnnotationContext) MarshalJSON() ([]byte, error) {
type NoMethod ImageAnnotationContext
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ImageContext: Image context and/or feature-specific parameters.
type ImageContext struct {
// CropHintsParams: Parameters for crop hints annotation request.
CropHintsParams *CropHintsParams `json:"cropHintsParams,omitempty"`
// LanguageHints: List of languages to use for TEXT_DETECTION. In most
// cases, an empty value yields the best results since it enables
// automatic language detection. For languages based on the Latin
// alphabet, setting `language_hints` is not needed. In rare cases, when
// the language of the text in the image is known, setting a hint will
// help get better results (although it will be a significant hindrance
// if the hint is wrong). Text detection returns an error if one or more
// of the specified languages is not one of the supported languages
// (https://cloud.google.com/vision/docs/languages).
LanguageHints []string `json:"languageHints,omitempty"`
// LatLongRect: Not used.
LatLongRect *LatLongRect `json:"latLongRect,omitempty"`
// ProductSearchParams: Parameters for product search.
ProductSearchParams *ProductSearchParams `json:"productSearchParams,omitempty"`
// TextDetectionParams: Parameters for text detection and document text
// detection.
TextDetectionParams *TextDetectionParams `json:"textDetectionParams,omitempty"`
// WebDetectionParams: Parameters for web detection.
WebDetectionParams *WebDetectionParams `json:"webDetectionParams,omitempty"`
// ForceSendFields is a list of field names (e.g. "CropHintsParams") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CropHintsParams") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *ImageContext) MarshalJSON() ([]byte, error) {
type NoMethod ImageContext
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ImageProperties: Stores image properties, such as dominant colors.
type ImageProperties struct {
// DominantColors: If present, dominant colors completed successfully.
DominantColors *DominantColorsAnnotation `json:"dominantColors,omitempty"`
// ForceSendFields is a list of field names (e.g. "DominantColors") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "DominantColors") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *ImageProperties) MarshalJSON() ([]byte, error) {
type NoMethod ImageProperties
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ImageSource: External image source (Google Cloud Storage or web URL
// image location).
type ImageSource struct {
// GcsImageUri: **Use `image_uri` instead.** The Google Cloud Storage
// URI of the form `gs://bucket_name/object_name`. Object versioning is
// not supported. See Google Cloud Storage Request URIs
// (https://cloud.google.com/storage/docs/reference-uris) for more info.
GcsImageUri string `json:"gcsImageUri,omitempty"`
// ImageUri: The URI of the source image. Can be either: 1. A Google
// Cloud Storage URI of the form `gs://bucket_name/object_name`. Object
// versioning is not supported. See Google Cloud Storage Request URIs
// (https://cloud.google.com/storage/docs/reference-uris) for more info.
// 2. A publicly-accessible image HTTP/HTTPS URL. When fetching images
// from HTTP/HTTPS URLs, Google cannot guarantee that the request will
// be completed. Your request may fail if the specified host denies the
// request (e.g. due to request throttling or DOS prevention), or if
// Google throttles requests to the site for abuse prevention. You
// should not depend on externally-hosted images for production
// applications. When both `gcs_image_uri` and `image_uri` are
// specified, `image_uri` takes precedence.
ImageUri string `json:"imageUri,omitempty"`
// ForceSendFields is a list of field names (e.g. "GcsImageUri") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "GcsImageUri") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ImageSource) MarshalJSON() ([]byte, error) {
type NoMethod ImageSource
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ImportProductSetsGcsSource: The Google Cloud Storage location for a
// csv file which preserves a list of ImportProductSetRequests in each
// line.
type ImportProductSetsGcsSource struct {
// CsvFileUri: The Google Cloud Storage URI of the input csv file. The
// URI must start with `gs://`. The format of the input csv file should
// be one image per line. In each line, there are 8 columns. 1.
// image-uri 2. image-id 3. product-set-id 4. product-id 5.
// product-category 6. product-display-name 7. labels 8. bounding-poly
// The `image-uri`, `product-set-id`, `product-id`, and
// `product-category` columns are required. All other columns are
// optional. If the `ProductSet` or `Product` specified by the
// `product-set-id` and `product-id` values does not exist, then the
// system will create a new `ProductSet` or `Product` for the image. In
// this case, the `product-display-name` column refers to display_name,
// the `product-category` column refers to product_category, and the
// `labels` column refers to product_labels. The `image-id` column is
// optional but must be unique if provided. If it is empty, the system
// will automatically assign a unique id to the image. The
// `product-display-name` column is optional. If it is empty, the system
// sets the display_name field for the product to a space (" "). You can
// update the `display_name` later by using the API. If a `Product` with
// the specified `product-id` already exists, then the system ignores
// the `product-display-name`, `product-category`, and `labels` columns.
// The `labels` column (optional) is a line containing a list of
// comma-separated key-value pairs, in the following format:
// "key_1=value_1,key_2=value_2,...,key_n=value_n" The `bounding-poly`
// column (optional) identifies one region of interest from the image in
// the same manner as `CreateReferenceImage`. If you do not specify the
// `bounding-poly` column, then the system will try to detect regions of
// interest automatically. At most one `bounding-poly` column is allowed
// per line. If the image contains multiple regions of interest, add a
// line to the CSV file that includes the same product information, and
// the `bounding-poly` values for each region of interest. The
// `bounding-poly` column must contain an even number of comma-separated
// numbers, in the format "p1_x,p1_y,p2_x,p2_y,...,pn_x,pn_y". Use
// non-negative integers for absolute bounding polygons, and float
// values in [0, 1] for normalized bounding polygons. The system will
// resize the image if the image resolution is too large to process
// (larger than 20MP).
CsvFileUri string `json:"csvFileUri,omitempty"`
// ForceSendFields is a list of field names (e.g. "CsvFileUri") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CsvFileUri") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ImportProductSetsGcsSource) MarshalJSON() ([]byte, error) {
type NoMethod ImportProductSetsGcsSource
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ImportProductSetsInputConfig: The input content for the
// `ImportProductSets` method.
type ImportProductSetsInputConfig struct {
// GcsSource: The Google Cloud Storage location for a csv file which
// preserves a list of ImportProductSetRequests in each line.
GcsSource *ImportProductSetsGcsSource `json:"gcsSource,omitempty"`
// ForceSendFields is a list of field names (e.g. "GcsSource") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "GcsSource") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ImportProductSetsInputConfig) MarshalJSON() ([]byte, error) {
type NoMethod ImportProductSetsInputConfig
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ImportProductSetsRequest: Request message for the `ImportProductSets`
// method.
type ImportProductSetsRequest struct {
// InputConfig: Required. The input content for the list of requests.
InputConfig *ImportProductSetsInputConfig `json:"inputConfig,omitempty"`
// ForceSendFields is a list of field names (e.g. "InputConfig") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "InputConfig") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ImportProductSetsRequest) MarshalJSON() ([]byte, error) {
type NoMethod ImportProductSetsRequest
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ImportProductSetsResponse: Response message for the
// `ImportProductSets` method. This message is returned by the
// google.longrunning.Operations.GetOperation method in the returned
// google.longrunning.Operation.response field.
type ImportProductSetsResponse struct {
// ReferenceImages: The list of reference_images that are imported
// successfully.
ReferenceImages []*ReferenceImage `json:"referenceImages,omitempty"`
// Statuses: The rpc status for each ImportProductSet request, including
// both successes and errors. The number of statuses here matches the
// number of lines in the csv file, and statuses[i] stores the success
// or failure status of processing the i-th line of the csv, starting
// from line 0.
Statuses []*Status `json:"statuses,omitempty"`
// ForceSendFields is a list of field names (e.g. "ReferenceImages") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ReferenceImages") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *ImportProductSetsResponse) MarshalJSON() ([]byte, error) {
type NoMethod ImportProductSetsResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// InputConfig: The desired input location and metadata.
type InputConfig struct {
// Content: File content, represented as a stream of bytes. Note: As
// with all `bytes` fields, protobuffers use a pure binary
// representation, whereas JSON representations use base64. Currently,
// this field only works for BatchAnnotateFiles requests. It does not
// work for AsyncBatchAnnotateFiles requests.
Content string `json:"content,omitempty"`
// GcsSource: The Google Cloud Storage location to read the input from.
GcsSource *GcsSource `json:"gcsSource,omitempty"`
// MimeType: The type of the file. Currently only "application/pdf",
// "image/tiff" and "image/gif" are supported. Wildcards are not
// supported.
MimeType string `json:"mimeType,omitempty"`
// ForceSendFields is a list of field names (e.g. "Content") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Content") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *InputConfig) MarshalJSON() ([]byte, error) {
type NoMethod InputConfig
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// KeyValue: A product label represented as a key-value pair.
type KeyValue struct {
// Key: The key of the label attached to the product. Cannot be empty
// and cannot exceed 128 bytes.
Key string `json:"key,omitempty"`
// Value: The value of the label attached to the product. Cannot be
// empty and cannot exceed 128 bytes.
Value string `json:"value,omitempty"`
// ForceSendFields is a list of field names (e.g. "Key") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Key") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *KeyValue) MarshalJSON() ([]byte, error) {
type NoMethod KeyValue
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Landmark: A face-specific landmark (for example, a face feature).
type Landmark struct {
// Position: Face landmark position.
Position *Position `json:"position,omitempty"`
// Type: Face landmark type.
//
// Possible values:
// "UNKNOWN_LANDMARK" - Unknown face landmark detected. Should not be
// filled.
// "LEFT_EYE" - Left eye.
// "RIGHT_EYE" - Right eye.
// "LEFT_OF_LEFT_EYEBROW" - Left of left eyebrow.
// "RIGHT_OF_LEFT_EYEBROW" - Right of left eyebrow.
// "LEFT_OF_RIGHT_EYEBROW" - Left of right eyebrow.
// "RIGHT_OF_RIGHT_EYEBROW" - Right of right eyebrow.
// "MIDPOINT_BETWEEN_EYES" - Midpoint between eyes.
// "NOSE_TIP" - Nose tip.
// "UPPER_LIP" - Upper lip.
// "LOWER_LIP" - Lower lip.
// "MOUTH_LEFT" - Mouth left.
// "MOUTH_RIGHT" - Mouth right.
// "MOUTH_CENTER" - Mouth center.
// "NOSE_BOTTOM_RIGHT" - Nose, bottom right.
// "NOSE_BOTTOM_LEFT" - Nose, bottom left.
// "NOSE_BOTTOM_CENTER" - Nose, bottom center.
// "LEFT_EYE_TOP_BOUNDARY" - Left eye, top boundary.
// "LEFT_EYE_RIGHT_CORNER" - Left eye, right corner.
// "LEFT_EYE_BOTTOM_BOUNDARY" - Left eye, bottom boundary.
// "LEFT_EYE_LEFT_CORNER" - Left eye, left corner.
// "RIGHT_EYE_TOP_BOUNDARY" - Right eye, top boundary.
// "RIGHT_EYE_RIGHT_CORNER" - Right eye, right corner.
// "RIGHT_EYE_BOTTOM_BOUNDARY" - Right eye, bottom boundary.
// "RIGHT_EYE_LEFT_CORNER" - Right eye, left corner.
// "LEFT_EYEBROW_UPPER_MIDPOINT" - Left eyebrow, upper midpoint.
// "RIGHT_EYEBROW_UPPER_MIDPOINT" - Right eyebrow, upper midpoint.
// "LEFT_EAR_TRAGION" - Left ear tragion.
// "RIGHT_EAR_TRAGION" - Right ear tragion.
// "LEFT_EYE_PUPIL" - Left eye pupil.
// "RIGHT_EYE_PUPIL" - Right eye pupil.
// "FOREHEAD_GLABELLA" - Forehead glabella.
// "CHIN_GNATHION" - Chin gnathion.
// "CHIN_LEFT_GONION" - Chin left gonion.
// "CHIN_RIGHT_GONION" - Chin right gonion.
// "LEFT_CHEEK_CENTER" - Left cheek center.
// "RIGHT_CHEEK_CENTER" - Right cheek center.
Type string `json:"type,omitempty"`
// ForceSendFields is a list of field names (e.g. "Position") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Position") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Landmark) MarshalJSON() ([]byte, error) {
type NoMethod Landmark
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// LatLng: An object that represents a latitude/longitude pair. This is
// expressed as a pair of doubles to represent degrees latitude and
// degrees longitude. Unless specified otherwise, this object must
// conform to the WGS84 standard. Values must be within normalized
// ranges.
type LatLng struct {
// Latitude: The latitude in degrees. It must be in the range [-90.0,
// +90.0].
Latitude float64 `json:"latitude,omitempty"`
// Longitude: The longitude in degrees. It must be in the range [-180.0,
// +180.0].
Longitude float64 `json:"longitude,omitempty"`
// ForceSendFields is a list of field names (e.g. "Latitude") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Latitude") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *LatLng) MarshalJSON() ([]byte, error) {
type NoMethod LatLng
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *LatLng) UnmarshalJSON(data []byte) error {
type NoMethod LatLng
var s1 struct {
Latitude gensupport.JSONFloat64 `json:"latitude"`
Longitude gensupport.JSONFloat64 `json:"longitude"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Latitude = float64(s1.Latitude)
s.Longitude = float64(s1.Longitude)
return nil
}
// LatLongRect: Rectangle determined by min and max `LatLng` pairs.
type LatLongRect struct {
// MaxLatLng: Max lat/long pair.
MaxLatLng *LatLng `json:"maxLatLng,omitempty"`
// MinLatLng: Min lat/long pair.
MinLatLng *LatLng `json:"minLatLng,omitempty"`
// ForceSendFields is a list of field names (e.g. "MaxLatLng") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "MaxLatLng") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *LatLongRect) MarshalJSON() ([]byte, error) {
type NoMethod LatLongRect
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ListOperationsResponse: The response message for
// Operations.ListOperations.
type ListOperationsResponse struct {
// NextPageToken: The standard List next-page token.
NextPageToken string `json:"nextPageToken,omitempty"`
// Operations: A list of operations that matches the specified filter in
// the request.
Operations []*Operation `json:"operations,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "NextPageToken") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "NextPageToken") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ListOperationsResponse) MarshalJSON() ([]byte, error) {
type NoMethod ListOperationsResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ListProductSetsResponse: Response message for the `ListProductSets`
// method.
type ListProductSetsResponse struct {
// NextPageToken: Token to retrieve the next page of results, or empty
// if there are no more results in the list.
NextPageToken string `json:"nextPageToken,omitempty"`
// ProductSets: List of ProductSets.
ProductSets []*ProductSet `json:"productSets,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "NextPageToken") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "NextPageToken") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ListProductSetsResponse) MarshalJSON() ([]byte, error) {
type NoMethod ListProductSetsResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ListProductsInProductSetResponse: Response message for the
// `ListProductsInProductSet` method.
type ListProductsInProductSetResponse struct {
// NextPageToken: Token to retrieve the next page of results, or empty
// if there are no more results in the list.
NextPageToken string `json:"nextPageToken,omitempty"`
// Products: The list of Products.
Products []*Product `json:"products,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "NextPageToken") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "NextPageToken") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ListProductsInProductSetResponse) MarshalJSON() ([]byte, error) {
type NoMethod ListProductsInProductSetResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ListProductsResponse: Response message for the `ListProducts` method.
type ListProductsResponse struct {
// NextPageToken: Token to retrieve the next page of results, or empty
// if there are no more results in the list.
NextPageToken string `json:"nextPageToken,omitempty"`
// Products: List of products.
Products []*Product `json:"products,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "NextPageToken") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "NextPageToken") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ListProductsResponse) MarshalJSON() ([]byte, error) {
type NoMethod ListProductsResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ListReferenceImagesResponse: Response message for the
// `ListReferenceImages` method.
type ListReferenceImagesResponse struct {
// NextPageToken: The next_page_token returned from a previous List
// request, if any.
NextPageToken string `json:"nextPageToken,omitempty"`
// PageSize: The maximum number of items to return. Default 10, maximum
// 100.
PageSize int64 `json:"pageSize,omitempty"`
// ReferenceImages: The list of reference images.
ReferenceImages []*ReferenceImage `json:"referenceImages,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "NextPageToken") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "NextPageToken") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ListReferenceImagesResponse) MarshalJSON() ([]byte, error) {
type NoMethod ListReferenceImagesResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// LocalizedObjectAnnotation: Set of detected objects with bounding
// boxes.
type LocalizedObjectAnnotation struct {
// BoundingPoly: Image region to which this object belongs. This must be
// populated.
BoundingPoly *BoundingPoly `json:"boundingPoly,omitempty"`
// LanguageCode: The BCP-47 language code, such as "en-US" or "sr-Latn".
// For more information, see
// http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
LanguageCode string `json:"languageCode,omitempty"`
// Mid: Object ID that should align with EntityAnnotation mid.
Mid string `json:"mid,omitempty"`
// Name: Object name, expressed in its `language_code` language.
Name string `json:"name,omitempty"`
// Score: Score of the result. Range [0, 1].
Score float64 `json:"score,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingPoly") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingPoly") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *LocalizedObjectAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod LocalizedObjectAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *LocalizedObjectAnnotation) UnmarshalJSON(data []byte) error {
type NoMethod LocalizedObjectAnnotation
var s1 struct {
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Score = float64(s1.Score)
return nil
}
// LocationInfo: Detected entity location information.
type LocationInfo struct {
// LatLng: lat/long location coordinates.
LatLng *LatLng `json:"latLng,omitempty"`
// ForceSendFields is a list of field names (e.g. "LatLng") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "LatLng") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *LocationInfo) MarshalJSON() ([]byte, error) {
type NoMethod LocationInfo
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// NormalizedVertex: A vertex represents a 2D point in the image. NOTE:
// the normalized vertex coordinates are relative to the original image
// and range from 0 to 1.
type NormalizedVertex struct {
// X: X coordinate.
X float64 `json:"x,omitempty"`
// Y: Y coordinate.
Y float64 `json:"y,omitempty"`
// ForceSendFields is a list of field names (e.g. "X") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "X") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *NormalizedVertex) MarshalJSON() ([]byte, error) {
type NoMethod NormalizedVertex
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *NormalizedVertex) UnmarshalJSON(data []byte) error {
type NoMethod NormalizedVertex
var s1 struct {
X gensupport.JSONFloat64 `json:"x"`
Y gensupport.JSONFloat64 `json:"y"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.X = float64(s1.X)
s.Y = float64(s1.Y)
return nil
}
// ObjectAnnotation: Prediction for what the object in the bounding box
// is.
type ObjectAnnotation struct {
// LanguageCode: The BCP-47 language code, such as "en-US" or "sr-Latn".
// For more information, see
// http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
LanguageCode string `json:"languageCode,omitempty"`
// Mid: Object ID that should align with EntityAnnotation mid.
Mid string `json:"mid,omitempty"`
// Name: Object name, expressed in its `language_code` language.
Name string `json:"name,omitempty"`
// Score: Score of the result. Range [0, 1].
Score float64 `json:"score,omitempty"`
// ForceSendFields is a list of field names (e.g. "LanguageCode") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "LanguageCode") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ObjectAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod ObjectAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *ObjectAnnotation) UnmarshalJSON(data []byte) error {
type NoMethod ObjectAnnotation
var s1 struct {
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Score = float64(s1.Score)
return nil
}
// Operation: This resource represents a long-running operation that is
// the result of a network API call.
type Operation struct {
// Done: If the value is `false`, it means the operation is still in
// progress. If `true`, the operation is completed, and either `error`
// or `response` is available.
Done bool `json:"done,omitempty"`
// Error: The error result of the operation in case of failure or
// cancellation.
Error *Status `json:"error,omitempty"`
// Metadata: Service-specific metadata associated with the operation. It
// typically contains progress information and common metadata such as
// create time. Some services might not provide such metadata. Any
// method that returns a long-running operation should document the
// metadata type, if any.
Metadata googleapi.RawMessage `json:"metadata,omitempty"`
// Name: The server-assigned name, which is only unique within the same
// service that originally returns it. If you use the default HTTP
// mapping, the `name` should be a resource name ending with
// `operations/{unique_id}`.
Name string `json:"name,omitempty"`
// Response: The normal response of the operation in case of success. If
// the original method returns no data on success, such as `Delete`, the
// response is `google.protobuf.Empty`. If the original method is
// standard `Get`/`Create`/`Update`, the response should be the
// resource. For other methods, the response should have the type
// `XxxResponse`, where `Xxx` is the original method name. For example,
// if the original method name is `TakeSnapshot()`, the inferred
// response type is `TakeSnapshotResponse`.
Response googleapi.RawMessage `json:"response,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Done") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Done") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Operation) MarshalJSON() ([]byte, error) {
type NoMethod Operation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// OperationMetadata: Contains metadata for the BatchAnnotateImages
// operation.
type OperationMetadata struct {
// CreateTime: The time when the batch request was received.
CreateTime string `json:"createTime,omitempty"`
// State: Current state of the batch operation.
//
// Possible values:
// "STATE_UNSPECIFIED" - Invalid.
// "CREATED" - Request is received.
// "RUNNING" - Request is actively being processed.
// "DONE" - The batch processing is done.
// "CANCELLED" - The batch processing was cancelled.
State string `json:"state,omitempty"`
// UpdateTime: The time when the operation result was last updated.
UpdateTime string `json:"updateTime,omitempty"`
// ForceSendFields is a list of field names (e.g. "CreateTime") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CreateTime") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *OperationMetadata) MarshalJSON() ([]byte, error) {
type NoMethod OperationMetadata
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// OutputConfig: The desired output location and metadata.
type OutputConfig struct {
// BatchSize: The max number of response protos to put into each output
// JSON file on Google Cloud Storage. The valid range is [1, 100]. If
// not specified, the default value is 20. For example, for one pdf file
// with 100 pages, 100 response protos will be generated. If
// `batch_size` = 20, then 5 json files each containing 20 response
// protos will be written under the prefix `gcs_destination`.`uri`.
// Currently, batch_size only applies to GcsDestination, with potential
// future support for other output configurations.
BatchSize int64 `json:"batchSize,omitempty"`
// GcsDestination: The Google Cloud Storage location to write the
// output(s) to.
GcsDestination *GcsDestination `json:"gcsDestination,omitempty"`
// ForceSendFields is a list of field names (e.g. "BatchSize") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BatchSize") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *OutputConfig) MarshalJSON() ([]byte, error) {
type NoMethod OutputConfig
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Page: Detected page from OCR.
type Page struct {
// Blocks: List of blocks of text, images etc on this page.
Blocks []*Block `json:"blocks,omitempty"`
// Confidence: Confidence of the OCR results on the page. Range [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// Height: Page height. For PDFs the unit is points. For images
// (including TIFFs) the unit is pixels.
Height int64 `json:"height,omitempty"`
// Property: Additional information detected on the page.
Property *TextProperty `json:"property,omitempty"`
// Width: Page width. For PDFs the unit is points. For images (including
// TIFFs) the unit is pixels.
Width int64 `json:"width,omitempty"`
// ForceSendFields is a list of field names (e.g. "Blocks") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Blocks") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Page) MarshalJSON() ([]byte, error) {
type NoMethod Page
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *Page) UnmarshalJSON(data []byte) error {
type NoMethod Page
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
return nil
}
// Paragraph: Structural unit of text representing a number of words in
// certain order.
type Paragraph struct {
// BoundingBox: The bounding box for the paragraph. The vertices are in
// the order of top-left, top-right, bottom-right, bottom-left. When a
// rotation of the bounding box is detected the rotation is represented
// as around the top-left corner as defined when the text is read in the
// 'natural' orientation. For example: * when the text is horizontal it
// might look like: 0----1 | | 3----2 * when it's rotated 180 degrees
// around the top-left corner it becomes: 2----3 | | 1----0 and the
// vertex order will still be (0, 1, 2, 3).
BoundingBox *BoundingPoly `json:"boundingBox,omitempty"`
// Confidence: Confidence of the OCR results for the paragraph. Range
// [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// Property: Additional information detected for the paragraph.
Property *TextProperty `json:"property,omitempty"`
// Words: List of all words in this paragraph.
Words []*Word `json:"words,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingBox") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingBox") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Paragraph) MarshalJSON() ([]byte, error) {
type NoMethod Paragraph
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *Paragraph) UnmarshalJSON(data []byte) error {
type NoMethod Paragraph
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
return nil
}
// Position: A 3D position in the image, used primarily for Face
// detection landmarks. A valid Position must have both x and y
// coordinates. The position coordinates are in the same scale as the
// original image.
type Position struct {
// X: X coordinate.
X float64 `json:"x,omitempty"`
// Y: Y coordinate.
Y float64 `json:"y,omitempty"`
// Z: Z coordinate (or depth).
Z float64 `json:"z,omitempty"`
// ForceSendFields is a list of field names (e.g. "X") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "X") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Position) MarshalJSON() ([]byte, error) {
type NoMethod Position
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *Position) UnmarshalJSON(data []byte) error {
type NoMethod Position
var s1 struct {
X gensupport.JSONFloat64 `json:"x"`
Y gensupport.JSONFloat64 `json:"y"`
Z gensupport.JSONFloat64 `json:"z"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.X = float64(s1.X)
s.Y = float64(s1.Y)
s.Z = float64(s1.Z)
return nil
}
// Product: A Product contains ReferenceImages.
type Product struct {
// Description: User-provided metadata to be stored with this product.
// Must be at most 4096 characters long.
Description string `json:"description,omitempty"`
// DisplayName: The user-provided name for this Product. Must not be
// empty. Must be at most 4096 characters long.
DisplayName string `json:"displayName,omitempty"`
// Name: The resource name of the product. Format is:
// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`. This
// field is ignored when creating a product.
Name string `json:"name,omitempty"`
// ProductCategory: Immutable. The category for the product identified
// by the reference image. This should be one of "homegoods-v2",
// "apparel-v2", "toys-v2", "packagedgoods-v1" or "general-v1". The
// legacy categories "homegoods", "apparel", and "toys" are still
// supported, but these should not be used for new products.
ProductCategory string `json:"productCategory,omitempty"`
// ProductLabels: Key-value pairs that can be attached to a product. At
// query time, constraints can be specified based on the product_labels.
// Note that integer values can be provided as strings, e.g. "1199".
// Only strings with integer values can match a range-based restriction
// which is to be supported soon. Multiple values can be assigned to the
// same key. One product may have up to 500 product_labels. Notice that
// the total number of distinct product_labels over all products in one
// ProductSet cannot exceed 1M, otherwise the product search pipeline
// will refuse to work for that ProductSet.
ProductLabels []*KeyValue `json:"productLabels,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Description") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Description") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Product) MarshalJSON() ([]byte, error) {
type NoMethod Product
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ProductSearchParams: Parameters for a product search request.
type ProductSearchParams struct {
// BoundingPoly: The bounding polygon around the area of interest in the
// image. If it is not specified, system discretion will be applied.
BoundingPoly *BoundingPoly `json:"boundingPoly,omitempty"`
// Filter: The filtering expression. This can be used to restrict search
// results based on Product labels. We currently support an AND of OR of
// key-value expressions, where each expression within an OR must have
// the same key. An '=' should be used to connect the key and value. For
// example, "(color = red OR color = blue) AND brand = Google" is
// acceptable, but "(color = red OR brand = Google)" is not acceptable.
// "color: red" is not acceptable because it uses a ':' instead of an
// '='.
Filter string `json:"filter,omitempty"`
// ProductCategories: The list of product categories to search in.
// Currently, we only consider the first category, and either
// "homegoods-v2", "apparel-v2", "toys-v2", "packagedgoods-v1", or
// "general-v1" should be specified. The legacy categories "homegoods",
// "apparel", and "toys" are still supported but will be deprecated. For
// new products, please use "homegoods-v2", "apparel-v2", or "toys-v2"
// for better product search accuracy. It is recommended to migrate
// existing products to these categories as well.
ProductCategories []string `json:"productCategories,omitempty"`
// ProductSet: The resource name of a ProductSet to be searched for
// similar images. Format is:
// `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`.
ProductSet string `json:"productSet,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingPoly") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingPoly") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ProductSearchParams) MarshalJSON() ([]byte, error) {
type NoMethod ProductSearchParams
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ProductSearchResults: Results for a product search request.
type ProductSearchResults struct {
// IndexTime: Timestamp of the index which provided these results.
// Products added to the product set and products removed from the
// product set after this time are not reflected in the current results.
IndexTime string `json:"indexTime,omitempty"`
// ProductGroupedResults: List of results grouped by products detected
// in the query image. Each entry corresponds to one bounding polygon in
// the query image, and contains the matching products specific to that
// region. There may be duplicate product matches in the union of all
// the per-product results.
ProductGroupedResults []*GroupedResult `json:"productGroupedResults,omitempty"`
// Results: List of results, one for each product match.
Results []*Result `json:"results,omitempty"`
// ForceSendFields is a list of field names (e.g. "IndexTime") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "IndexTime") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ProductSearchResults) MarshalJSON() ([]byte, error) {
type NoMethod ProductSearchResults
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ProductSet: A ProductSet contains Products. A ProductSet can contain
// a maximum of 1 million reference images. If the limit is exceeded,
// periodic indexing will fail.
type ProductSet struct {
// DisplayName: The user-provided name for this ProductSet. Must not be
// empty. Must be at most 4096 characters long.
DisplayName string `json:"displayName,omitempty"`
// IndexError: Output only. If there was an error with indexing the
// product set, the field is populated. This field is ignored when
// creating a ProductSet.
IndexError *Status `json:"indexError,omitempty"`
// IndexTime: Output only. The time at which this ProductSet was last
// indexed. Query results will reflect all updates before this time. If
// this ProductSet has never been indexed, this timestamp is the default
// value "1970-01-01T00:00:00Z". This field is ignored when creating a
// ProductSet.
IndexTime string `json:"indexTime,omitempty"`
// Name: The resource name of the ProductSet. Format is:
// `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`.
// This field is ignored when creating a ProductSet.
Name string `json:"name,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "DisplayName") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "DisplayName") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ProductSet) MarshalJSON() ([]byte, error) {
type NoMethod ProductSet
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ProductSetPurgeConfig: Config to control which ProductSet contains
// the Products to be deleted.
type ProductSetPurgeConfig struct {
// ProductSetId: The ProductSet that contains the Products to delete. If
// a Product is a member of product_set_id in addition to other
// ProductSets, the Product will still be deleted.
ProductSetId string `json:"productSetId,omitempty"`
// ForceSendFields is a list of field names (e.g. "ProductSetId") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ProductSetId") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ProductSetPurgeConfig) MarshalJSON() ([]byte, error) {
type NoMethod ProductSetPurgeConfig
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Property: A `Property` consists of a user-supplied name/value pair.
type Property struct {
// Name: Name of the property.
Name string `json:"name,omitempty"`
// Uint64Value: Value of numeric properties.
Uint64Value uint64 `json:"uint64Value,omitempty,string"`
// Value: Value of the property.
Value string `json:"value,omitempty"`
// ForceSendFields is a list of field names (e.g. "Name") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Name") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Property) MarshalJSON() ([]byte, error) {
type NoMethod Property
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// PurgeProductsRequest: Request message for the `PurgeProducts` method.
type PurgeProductsRequest struct {
// DeleteOrphanProducts: If delete_orphan_products is true, all Products
// that are not in any ProductSet will be deleted.
DeleteOrphanProducts bool `json:"deleteOrphanProducts,omitempty"`
// Force: The default value is false. Override this value to true to
// actually perform the purge.
Force bool `json:"force,omitempty"`
// ProductSetPurgeConfig: Specify which ProductSet contains the Products
// to be deleted.
ProductSetPurgeConfig *ProductSetPurgeConfig `json:"productSetPurgeConfig,omitempty"`
// ForceSendFields is a list of field names (e.g.
// "DeleteOrphanProducts") to unconditionally include in API requests.
// By default, fields with empty or default values are omitted from API
// requests. However, any non-pointer, non-interface field appearing in
// ForceSendFields will be sent to the server regardless of whether the
// field is empty or not. This may be used to include empty fields in
// Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "DeleteOrphanProducts") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *PurgeProductsRequest) MarshalJSON() ([]byte, error) {
type NoMethod PurgeProductsRequest
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ReferenceImage: A `ReferenceImage` represents a product image and its
// associated metadata, such as bounding boxes.
type ReferenceImage struct {
// BoundingPolys: Optional. Bounding polygons around the areas of
// interest in the reference image. If this field is empty, the system
// will try to detect regions of interest. At most 10 bounding polygons
// will be used. The provided shape is converted into a non-rotated
// rectangle. Once converted, the small edge of the rectangle must be
// greater than or equal to 300 pixels. The aspect ratio must be 1:4 or
// less (i.e. 1:3 is ok; 1:5 is not).
BoundingPolys []*BoundingPoly `json:"boundingPolys,omitempty"`
// Name: The resource name of the reference image. Format is:
// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceIma
// ges/IMAGE_ID`. This field is ignored when creating a reference image.
Name string `json:"name,omitempty"`
// Uri: Required. The Google Cloud Storage URI of the reference image.
// The URI must start with `gs://`.
Uri string `json:"uri,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "BoundingPolys") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingPolys") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ReferenceImage) MarshalJSON() ([]byte, error) {
type NoMethod ReferenceImage
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// RemoveProductFromProductSetRequest: Request message for the
// `RemoveProductFromProductSet` method.
type RemoveProductFromProductSetRequest struct {
// Product: Required. The resource name for the Product to be removed
// from this ProductSet. Format is:
// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`
Product string `json:"product,omitempty"`
// ForceSendFields is a list of field names (e.g. "Product") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Product") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *RemoveProductFromProductSetRequest) MarshalJSON() ([]byte, error) {
type NoMethod RemoveProductFromProductSetRequest
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Result: Information about a product.
type Result struct {
// Image: The resource name of the image from the product that is the
// closest match to the query.
Image string `json:"image,omitempty"`
// Product: The Product.
Product *Product `json:"product,omitempty"`
// Score: A confidence level on the match, ranging from 0 (no
// confidence) to 1 (full confidence).
Score float64 `json:"score,omitempty"`
// ForceSendFields is a list of field names (e.g. "Image") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Image") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Result) MarshalJSON() ([]byte, error) {
type NoMethod Result
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *Result) UnmarshalJSON(data []byte) error {
type NoMethod Result
var s1 struct {
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Score = float64(s1.Score)
return nil
}
// SafeSearchAnnotation: Set of features pertaining to the image,
// computed by computer vision methods over safe-search verticals (for
// example, adult, spoof, medical, violence).
type SafeSearchAnnotation struct {
// Adult: Represents the adult content likelihood for the image. Adult
// content may contain elements such as nudity, pornographic images or
// cartoons, or sexual activities.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
Adult string `json:"adult,omitempty"`
// Medical: Likelihood that this is a medical image.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
Medical string `json:"medical,omitempty"`
// Racy: Likelihood that the request image contains racy content. Racy
// content may include (but is not limited to) skimpy or sheer clothing,
// strategically covered nudity, lewd or provocative poses, or close-ups
// of sensitive body areas.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
Racy string `json:"racy,omitempty"`
// Spoof: Spoof likelihood. The likelihood that an modification was made
// to the image's canonical version to make it appear funny or
// offensive.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
Spoof string `json:"spoof,omitempty"`
// Violence: Likelihood that this image contains violent content.
//
// Possible values:
// "UNKNOWN" - Unknown likelihood.
// "VERY_UNLIKELY" - It is very unlikely.
// "UNLIKELY" - It is unlikely.
// "POSSIBLE" - It is possible.
// "LIKELY" - It is likely.
// "VERY_LIKELY" - It is very likely.
Violence string `json:"violence,omitempty"`
// ForceSendFields is a list of field names (e.g. "Adult") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Adult") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *SafeSearchAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod SafeSearchAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Status: The `Status` type defines a logical error model that is
// suitable for different programming environments, including REST APIs
// and RPC APIs. It is used by gRPC (https://github.com/grpc). Each
// `Status` message contains three pieces of data: error code, error
// message, and error details. You can find out more about this error
// model and how to work with it in the API Design Guide
// (https://cloud.google.com/apis/design/errors).
type Status struct {
// Code: The status code, which should be an enum value of
// google.rpc.Code.
Code int64 `json:"code,omitempty"`
// Details: A list of messages that carry the error details. There is a
// common set of message types for APIs to use.
Details []googleapi.RawMessage `json:"details,omitempty"`
// Message: A developer-facing error message, which should be in
// English. Any user-facing error message should be localized and sent
// in the google.rpc.Status.details field, or localized by the client.
Message string `json:"message,omitempty"`
// ForceSendFields is a list of field names (e.g. "Code") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Code") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Status) MarshalJSON() ([]byte, error) {
type NoMethod Status
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Symbol: A single symbol representation.
type Symbol struct {
// BoundingBox: The bounding box for the symbol. The vertices are in the
// order of top-left, top-right, bottom-right, bottom-left. When a
// rotation of the bounding box is detected the rotation is represented
// as around the top-left corner as defined when the text is read in the
// 'natural' orientation. For example: * when the text is horizontal it
// might look like: 0----1 | | 3----2 * when it's rotated 180 degrees
// around the top-left corner it becomes: 2----3 | | 1----0 and the
// vertex order will still be (0, 1, 2, 3).
BoundingBox *BoundingPoly `json:"boundingBox,omitempty"`
// Confidence: Confidence of the OCR results for the symbol. Range [0,
// 1].
Confidence float64 `json:"confidence,omitempty"`
// Property: Additional information detected for the symbol.
Property *TextProperty `json:"property,omitempty"`
// Text: The actual UTF-8 representation of the symbol.
Text string `json:"text,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingBox") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingBox") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Symbol) MarshalJSON() ([]byte, error) {
type NoMethod Symbol
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *Symbol) UnmarshalJSON(data []byte) error {
type NoMethod Symbol
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
return nil
}
// TextAnnotation: TextAnnotation contains a structured representation
// of OCR extracted text. The hierarchy of an OCR extracted text
// structure is like this: TextAnnotation -> Page -> Block -> Paragraph
// -> Word -> Symbol Each structural component, starting from Page, may
// further have their own properties. Properties describe detected
// languages, breaks etc.. Please refer to the
// TextAnnotation.TextProperty message definition below for more detail.
type TextAnnotation struct {
// Pages: List of pages detected by OCR.
Pages []*Page `json:"pages,omitempty"`
// Text: UTF-8 text detected on the pages.
Text string `json:"text,omitempty"`
// ForceSendFields is a list of field names (e.g. "Pages") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Pages") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *TextAnnotation) MarshalJSON() ([]byte, error) {
type NoMethod TextAnnotation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// TextDetectionParams: Parameters for text detections. This is used to
// control TEXT_DETECTION and DOCUMENT_TEXT_DETECTION features.
type TextDetectionParams struct {
// EnableTextDetectionConfidenceScore: By default, Cloud Vision API only
// includes confidence score for DOCUMENT_TEXT_DETECTION result. Set the
// flag to true to include confidence score for TEXT_DETECTION as well.
EnableTextDetectionConfidenceScore bool `json:"enableTextDetectionConfidenceScore,omitempty"`
// ForceSendFields is a list of field names (e.g.
// "EnableTextDetectionConfidenceScore") to unconditionally include in
// API requests. By default, fields with empty or default values are
// omitted from API requests. However, any non-pointer, non-interface
// field appearing in ForceSendFields will be sent to the server
// regardless of whether the field is empty or not. This may be used to
// include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g.
// "EnableTextDetectionConfidenceScore") to include in API requests with
// the JSON null value. By default, fields with empty values are omitted
// from API requests. However, any field with an empty value appearing
// in NullFields will be sent to the server as null. It is an error if a
// field in this list has a non-empty value. This may be used to include
// null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *TextDetectionParams) MarshalJSON() ([]byte, error) {
type NoMethod TextDetectionParams
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// TextProperty: Additional information detected on the structural
// component.
type TextProperty struct {
// DetectedBreak: Detected start or end of a text segment.
DetectedBreak *DetectedBreak `json:"detectedBreak,omitempty"`
// DetectedLanguages: A list of detected languages together with
// confidence.
DetectedLanguages []*DetectedLanguage `json:"detectedLanguages,omitempty"`
// ForceSendFields is a list of field names (e.g. "DetectedBreak") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "DetectedBreak") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *TextProperty) MarshalJSON() ([]byte, error) {
type NoMethod TextProperty
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Vertex: A vertex represents a 2D point in the image. NOTE: the vertex
// coordinates are in the same scale as the original image.
type Vertex struct {
// X: X coordinate.
X int64 `json:"x,omitempty"`
// Y: Y coordinate.
Y int64 `json:"y,omitempty"`
// ForceSendFields is a list of field names (e.g. "X") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "X") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Vertex) MarshalJSON() ([]byte, error) {
type NoMethod Vertex
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// WebDetection: Relevant information for the image from the Internet.
type WebDetection struct {
// BestGuessLabels: The service's best guess as to the topic of the
// request image. Inferred from similar images on the open web.
BestGuessLabels []*WebLabel `json:"bestGuessLabels,omitempty"`
// FullMatchingImages: Fully matching images from the Internet. Can
// include resized copies of the query image.
FullMatchingImages []*WebImage `json:"fullMatchingImages,omitempty"`
// PagesWithMatchingImages: Web pages containing the matching images
// from the Internet.
PagesWithMatchingImages []*WebPage `json:"pagesWithMatchingImages,omitempty"`
// PartialMatchingImages: Partial matching images from the Internet.
// Those images are similar enough to share some key-point features. For
// example an original image will likely have partial matching for its
// crops.
PartialMatchingImages []*WebImage `json:"partialMatchingImages,omitempty"`
// VisuallySimilarImages: The visually similar image results.
VisuallySimilarImages []*WebImage `json:"visuallySimilarImages,omitempty"`
// WebEntities: Deduced entities from similar images on the Internet.
WebEntities []*WebEntity `json:"webEntities,omitempty"`
// ForceSendFields is a list of field names (e.g. "BestGuessLabels") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BestGuessLabels") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *WebDetection) MarshalJSON() ([]byte, error) {
type NoMethod WebDetection
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// WebDetectionParams: Parameters for web detection request.
type WebDetectionParams struct {
// IncludeGeoResults: Whether to include results derived from the geo
// information in the image.
IncludeGeoResults bool `json:"includeGeoResults,omitempty"`
// ForceSendFields is a list of field names (e.g. "IncludeGeoResults")
// to unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "IncludeGeoResults") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *WebDetectionParams) MarshalJSON() ([]byte, error) {
type NoMethod WebDetectionParams
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// WebEntity: Entity deduced from similar images on the Internet.
type WebEntity struct {
// Description: Canonical description of the entity, in English.
Description string `json:"description,omitempty"`
// EntityId: Opaque entity ID.
EntityId string `json:"entityId,omitempty"`
// Score: Overall relevancy score for the entity. Not normalized and not
// comparable across different image queries.
Score float64 `json:"score,omitempty"`
// ForceSendFields is a list of field names (e.g. "Description") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Description") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *WebEntity) MarshalJSON() ([]byte, error) {
type NoMethod WebEntity
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *WebEntity) UnmarshalJSON(data []byte) error {
type NoMethod WebEntity
var s1 struct {
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Score = float64(s1.Score)
return nil
}
// WebImage: Metadata for online images.
type WebImage struct {
// Score: (Deprecated) Overall relevancy score for the image.
Score float64 `json:"score,omitempty"`
// Url: The result image URL.
Url string `json:"url,omitempty"`
// ForceSendFields is a list of field names (e.g. "Score") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Score") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *WebImage) MarshalJSON() ([]byte, error) {
type NoMethod WebImage
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *WebImage) UnmarshalJSON(data []byte) error {
type NoMethod WebImage
var s1 struct {
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Score = float64(s1.Score)
return nil
}
// WebLabel: Label to provide extra metadata for the web detection.
type WebLabel struct {
// Label: Label for extra metadata.
Label string `json:"label,omitempty"`
// LanguageCode: The BCP-47 language code for `label`, such as "en-US"
// or "sr-Latn". For more information, see
// http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
LanguageCode string `json:"languageCode,omitempty"`
// ForceSendFields is a list of field names (e.g. "Label") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Label") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *WebLabel) MarshalJSON() ([]byte, error) {
type NoMethod WebLabel
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// WebPage: Metadata for web pages.
type WebPage struct {
// FullMatchingImages: Fully matching images on the page. Can include
// resized copies of the query image.
FullMatchingImages []*WebImage `json:"fullMatchingImages,omitempty"`
// PageTitle: Title for the web page, may contain HTML markups.
PageTitle string `json:"pageTitle,omitempty"`
// PartialMatchingImages: Partial matching images on the page. Those
// images are similar enough to share some key-point features. For
// example an original image will likely have partial matching for its
// crops.
PartialMatchingImages []*WebImage `json:"partialMatchingImages,omitempty"`
// Score: (Deprecated) Overall relevancy score for the web page.
Score float64 `json:"score,omitempty"`
// Url: The result web page URL.
Url string `json:"url,omitempty"`
// ForceSendFields is a list of field names (e.g. "FullMatchingImages")
// to unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "FullMatchingImages") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *WebPage) MarshalJSON() ([]byte, error) {
type NoMethod WebPage
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *WebPage) UnmarshalJSON(data []byte) error {
type NoMethod WebPage
var s1 struct {
Score gensupport.JSONFloat64 `json:"score"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Score = float64(s1.Score)
return nil
}
// Word: A word representation.
type Word struct {
// BoundingBox: The bounding box for the word. The vertices are in the
// order of top-left, top-right, bottom-right, bottom-left. When a
// rotation of the bounding box is detected the rotation is represented
// as around the top-left corner as defined when the text is read in the
// 'natural' orientation. For example: * when the text is horizontal it
// might look like: 0----1 | | 3----2 * when it's rotated 180 degrees
// around the top-left corner it becomes: 2----3 | | 1----0 and the
// vertex order will still be (0, 1, 2, 3).
BoundingBox *BoundingPoly `json:"boundingBox,omitempty"`
// Confidence: Confidence of the OCR results for the word. Range [0, 1].
Confidence float64 `json:"confidence,omitempty"`
// Property: Additional information detected for the word.
Property *TextProperty `json:"property,omitempty"`
// Symbols: List of symbols in the word. The order of the symbols
// follows the natural reading order.
Symbols []*Symbol `json:"symbols,omitempty"`
// ForceSendFields is a list of field names (e.g. "BoundingBox") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "BoundingBox") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Word) MarshalJSON() ([]byte, error) {
type NoMethod Word
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *Word) UnmarshalJSON(data []byte) error {
type NoMethod Word
var s1 struct {
Confidence gensupport.JSONFloat64 `json:"confidence"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Confidence = float64(s1.Confidence)
return nil
}
// method id "vision.files.annotate":
type FilesAnnotateCall struct {
s *Service
batchannotatefilesrequest *BatchAnnotateFilesRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Annotate: Service that performs image detection and annotation for a
// batch of files. Now only "application/pdf", "image/tiff" and
// "image/gif" are supported. This service will extract at most 5
// (customers can specify which 5 in AnnotateFileRequest.pages) frames
// (gif) or pages (pdf or tiff) from each file provided and perform
// detection and annotation for each image extracted.
func (r *FilesService) Annotate(batchannotatefilesrequest *BatchAnnotateFilesRequest) *FilesAnnotateCall {
c := &FilesAnnotateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.batchannotatefilesrequest = batchannotatefilesrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *FilesAnnotateCall) Fields(s ...googleapi.Field) *FilesAnnotateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *FilesAnnotateCall) Context(ctx context.Context) *FilesAnnotateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *FilesAnnotateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *FilesAnnotateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.batchannotatefilesrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/files:annotate")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.files.annotate" call.
// Exactly one of *BatchAnnotateFilesResponse or error will be non-nil.
// Any non-2xx status code is an error. Response headers are in either
// *BatchAnnotateFilesResponse.ServerResponse.Header or (if a response
// was returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *FilesAnnotateCall) Do(opts ...googleapi.CallOption) (*BatchAnnotateFilesResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &BatchAnnotateFilesResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Service that performs image detection and annotation for a batch of files. Now only \"application/pdf\", \"image/tiff\" and \"image/gif\" are supported. This service will extract at most 5 (customers can specify which 5 in AnnotateFileRequest.pages) frames (gif) or pages (pdf or tiff) from each file provided and perform detection and annotation for each image extracted.",
// "flatPath": "v1/files:annotate",
// "httpMethod": "POST",
// "id": "vision.files.annotate",
// "parameterOrder": [],
// "parameters": {},
// "path": "v1/files:annotate",
// "request": {
// "$ref": "BatchAnnotateFilesRequest"
// },
// "response": {
// "$ref": "BatchAnnotateFilesResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// method id "vision.files.asyncBatchAnnotate":
type FilesAsyncBatchAnnotateCall struct {
s *Service
asyncbatchannotatefilesrequest *AsyncBatchAnnotateFilesRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// AsyncBatchAnnotate: Run asynchronous image detection and annotation
// for a list of generic files, such as PDF files, which may contain
// multiple pages and multiple images per page. Progress and results can
// be retrieved through the `google.longrunning.Operations` interface.
// `Operation.metadata` contains `OperationMetadata` (metadata).
// `Operation.response` contains `AsyncBatchAnnotateFilesResponse`
// (results).
func (r *FilesService) AsyncBatchAnnotate(asyncbatchannotatefilesrequest *AsyncBatchAnnotateFilesRequest) *FilesAsyncBatchAnnotateCall {
c := &FilesAsyncBatchAnnotateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.asyncbatchannotatefilesrequest = asyncbatchannotatefilesrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *FilesAsyncBatchAnnotateCall) Fields(s ...googleapi.Field) *FilesAsyncBatchAnnotateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *FilesAsyncBatchAnnotateCall) Context(ctx context.Context) *FilesAsyncBatchAnnotateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *FilesAsyncBatchAnnotateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *FilesAsyncBatchAnnotateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.asyncbatchannotatefilesrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/files:asyncBatchAnnotate")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.files.asyncBatchAnnotate" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *FilesAsyncBatchAnnotateCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Run asynchronous image detection and annotation for a list of generic files, such as PDF files, which may contain multiple pages and multiple images per page. Progress and results can be retrieved through the `google.longrunning.Operations` interface. `Operation.metadata` contains `OperationMetadata` (metadata). `Operation.response` contains `AsyncBatchAnnotateFilesResponse` (results).",
// "flatPath": "v1/files:asyncBatchAnnotate",
// "httpMethod": "POST",
// "id": "vision.files.asyncBatchAnnotate",
// "parameterOrder": [],
// "parameters": {},
// "path": "v1/files:asyncBatchAnnotate",
// "request": {
// "$ref": "AsyncBatchAnnotateFilesRequest"
// },
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// method id "vision.images.annotate":
type ImagesAnnotateCall struct {
s *Service
batchannotateimagesrequest *BatchAnnotateImagesRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Annotate: Run image detection and annotation for a batch of images.
func (r *ImagesService) Annotate(batchannotateimagesrequest *BatchAnnotateImagesRequest) *ImagesAnnotateCall {
c := &ImagesAnnotateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.batchannotateimagesrequest = batchannotateimagesrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ImagesAnnotateCall) Fields(s ...googleapi.Field) *ImagesAnnotateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ImagesAnnotateCall) Context(ctx context.Context) *ImagesAnnotateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ImagesAnnotateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ImagesAnnotateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.batchannotateimagesrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/images:annotate")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.images.annotate" call.
// Exactly one of *BatchAnnotateImagesResponse or error will be non-nil.
// Any non-2xx status code is an error. Response headers are in either
// *BatchAnnotateImagesResponse.ServerResponse.Header or (if a response
// was returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ImagesAnnotateCall) Do(opts ...googleapi.CallOption) (*BatchAnnotateImagesResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &BatchAnnotateImagesResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Run image detection and annotation for a batch of images.",
// "flatPath": "v1/images:annotate",
// "httpMethod": "POST",
// "id": "vision.images.annotate",
// "parameterOrder": [],
// "parameters": {},
// "path": "v1/images:annotate",
// "request": {
// "$ref": "BatchAnnotateImagesRequest"
// },
// "response": {
// "$ref": "BatchAnnotateImagesResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// method id "vision.images.asyncBatchAnnotate":
type ImagesAsyncBatchAnnotateCall struct {
s *Service
asyncbatchannotateimagesrequest *AsyncBatchAnnotateImagesRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// AsyncBatchAnnotate: Run asynchronous image detection and annotation
// for a list of images. Progress and results can be retrieved through
// the `google.longrunning.Operations` interface. `Operation.metadata`
// contains `OperationMetadata` (metadata). `Operation.response`
// contains `AsyncBatchAnnotateImagesResponse` (results). This service
// will write image annotation outputs to json files in customer GCS
// bucket, each json file containing BatchAnnotateImagesResponse proto.
func (r *ImagesService) AsyncBatchAnnotate(asyncbatchannotateimagesrequest *AsyncBatchAnnotateImagesRequest) *ImagesAsyncBatchAnnotateCall {
c := &ImagesAsyncBatchAnnotateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.asyncbatchannotateimagesrequest = asyncbatchannotateimagesrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ImagesAsyncBatchAnnotateCall) Fields(s ...googleapi.Field) *ImagesAsyncBatchAnnotateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ImagesAsyncBatchAnnotateCall) Context(ctx context.Context) *ImagesAsyncBatchAnnotateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ImagesAsyncBatchAnnotateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ImagesAsyncBatchAnnotateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.asyncbatchannotateimagesrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/images:asyncBatchAnnotate")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.images.asyncBatchAnnotate" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *ImagesAsyncBatchAnnotateCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Run asynchronous image detection and annotation for a list of images. Progress and results can be retrieved through the `google.longrunning.Operations` interface. `Operation.metadata` contains `OperationMetadata` (metadata). `Operation.response` contains `AsyncBatchAnnotateImagesResponse` (results). This service will write image annotation outputs to json files in customer GCS bucket, each json file containing BatchAnnotateImagesResponse proto.",
// "flatPath": "v1/images:asyncBatchAnnotate",
// "httpMethod": "POST",
// "id": "vision.images.asyncBatchAnnotate",
// "parameterOrder": [],
// "parameters": {},
// "path": "v1/images:asyncBatchAnnotate",
// "request": {
// "$ref": "AsyncBatchAnnotateImagesRequest"
// },
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// method id "vision.locations.operations.get":
type LocationsOperationsGetCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Gets the latest state of a long-running operation. Clients can
// use this method to poll the operation result at intervals as
// recommended by the API service.
//
// - name: The name of the operation resource.
func (r *LocationsOperationsService) Get(name string) *LocationsOperationsGetCall {
c := &LocationsOperationsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *LocationsOperationsGetCall) Fields(s ...googleapi.Field) *LocationsOperationsGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *LocationsOperationsGetCall) IfNoneMatch(entityTag string) *LocationsOperationsGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *LocationsOperationsGetCall) Context(ctx context.Context) *LocationsOperationsGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *LocationsOperationsGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *LocationsOperationsGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.locations.operations.get" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *LocationsOperationsGetCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service.",
// "flatPath": "v1/locations/{locationsId}/operations/{operationsId}",
// "httpMethod": "GET",
// "id": "vision.locations.operations.get",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "The name of the operation resource.",
// "location": "path",
// "pattern": "^locations/[^/]+/operations/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1/{+name}",
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// method id "vision.operations.cancel":
type OperationsCancelCall struct {
s *Service
name string
canceloperationrequest *CancelOperationRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Cancel: Starts asynchronous cancellation on a long-running operation.
// The server makes a best effort to cancel the operation, but success
// is not guaranteed. If the server doesn't support this method, it
// returns `google.rpc.Code.UNIMPLEMENTED`. Clients can use
// Operations.GetOperation or other methods to check whether the
// cancellation succeeded or whether the operation completed despite
// cancellation. On successful cancellation, the operation is not
// deleted; instead, it becomes an operation with an Operation.error
// value with a google.rpc.Status.code of 1, corresponding to
// `Code.CANCELLED`.
//
// - name: The name of the operation resource to be cancelled.
func (r *OperationsService) Cancel(name string, canceloperationrequest *CancelOperationRequest) *OperationsCancelCall {
c := &OperationsCancelCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
c.canceloperationrequest = canceloperationrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *OperationsCancelCall) Fields(s ...googleapi.Field) *OperationsCancelCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *OperationsCancelCall) Context(ctx context.Context) *OperationsCancelCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *OperationsCancelCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *OperationsCancelCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.canceloperationrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+name}:cancel")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.operations.cancel" call.
// Exactly one of *Empty or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Empty.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *OperationsCancelCall) Do(opts ...googleapi.CallOption) (*Empty, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Empty{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether the cancellation succeeded or whether the operation completed despite cancellation. On successful cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`.",
// "flatPath": "v1/operations/{operationsId}:cancel",
// "httpMethod": "POST",
// "id": "vision.operations.cancel",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "The name of the operation resource to be cancelled.",
// "location": "path",
// "pattern": "^operations/.*$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1/{+name}:cancel",
// "request": {
// "$ref": "CancelOperationRequest"
// },
// "response": {
// "$ref": "Empty"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// method id "vision.operations.delete":
type OperationsDeleteCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Deletes a long-running operation. This method indicates that
// the client is no longer interested in the operation result. It does
// not cancel the operation. If the server doesn't support this method,
// it returns `google.rpc.Code.UNIMPLEMENTED`.
//
// - name: The name of the operation resource to be deleted.
func (r *OperationsService) Delete(name string) *OperationsDeleteCall {
c := &OperationsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *OperationsDeleteCall) Fields(s ...googleapi.Field) *OperationsDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *OperationsDeleteCall) Context(ctx context.Context) *OperationsDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *OperationsDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *OperationsDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("DELETE", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.operations.delete" call.
// Exactly one of *Empty or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Empty.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *OperationsDeleteCall) Do(opts ...googleapi.CallOption) (*Empty, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Empty{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Deletes a long-running operation. This method indicates that the client is no longer interested in the operation result. It does not cancel the operation. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`.",
// "flatPath": "v1/operations/{operationsId}",
// "httpMethod": "DELETE",
// "id": "vision.operations.delete",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "The name of the operation resource to be deleted.",
// "location": "path",
// "pattern": "^operations/.*$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1/{+name}",
// "response": {
// "$ref": "Empty"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// method id "vision.operations.get":
type OperationsGetCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Gets the latest state of a long-running operation. Clients can
// use this method to poll the operation result at intervals as
// recommended by the API service.
//
// - name: The name of the operation resource.
func (r *OperationsService) Get(name string) *OperationsGetCall {
c := &OperationsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *OperationsGetCall) Fields(s ...googleapi.Field) *OperationsGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *OperationsGetCall) IfNoneMatch(entityTag string) *OperationsGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *OperationsGetCall) Context(ctx context.Context) *OperationsGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *OperationsGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *OperationsGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.operations.get" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *OperationsGetCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service.",
// "flatPath": "v1/operations/{operationsId}",
// "httpMethod": "GET",
// "id": "vision.operations.get",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "The name of the operation resource.",
// "location": "path",
// "pattern": "^operations/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1/{+name}",
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// method id "vision.operations.list":
type OperationsListCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Lists operations that match the specified filter in the
// request. If the server doesn't support this method, it returns
// `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to
// override the binding to use different resource name schemes, such as
// `users/*/operations`. To override the binding, API services can add a
// binding such as "/v1/{name=users/*}/operations" to their service
// configuration. For backwards compatibility, the default name includes
// the operations collection id, however overriding users must ensure
// the name binding is the parent resource, without the operations
// collection id.
//
// - name: The name of the operation's parent resource.
func (r *OperationsService) List(name string) *OperationsListCall {
c := &OperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Filter sets the optional parameter "filter": The standard list
// filter.
func (c *OperationsListCall) Filter(filter string) *OperationsListCall {
c.urlParams_.Set("filter", filter)
return c
}
// PageSize sets the optional parameter "pageSize": The standard list
// page size.
func (c *OperationsListCall) PageSize(pageSize int64) *OperationsListCall {
c.urlParams_.Set("pageSize", fmt.Sprint(pageSize))
return c
}
// PageToken sets the optional parameter "pageToken": The standard list
// page token.
func (c *OperationsListCall) PageToken(pageToken string) *OperationsListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *OperationsListCall) Fields(s ...googleapi.Field) *OperationsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *OperationsListCall) IfNoneMatch(entityTag string) *OperationsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *OperationsListCall) Context(ctx context.Context) *OperationsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *OperationsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *OperationsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.operations.list" call.
// Exactly one of *ListOperationsResponse or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ListOperationsResponse.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *OperationsListCall) Do(opts ...googleapi.CallOption) (*ListOperationsResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ListOperationsResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to override the binding to use different resource name schemes, such as `users/*/operations`. To override the binding, API services can add a binding such as `\"/v1/{name=users/*}/operations\"` to their service configuration. For backwards compatibility, the default name includes the operations collection id, however overriding users must ensure the name binding is the parent resource, without the operations collection id.",
// "flatPath": "v1/operations",
// "httpMethod": "GET",
// "id": "vision.operations.list",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "filter": {
// "description": "The standard list filter.",
// "location": "query",
// "type": "string"
// },
// "name": {
// "description": "The name of the operation's parent resource.",
// "location": "path",
// "pattern": "^operations$",
// "required": true,
// "type": "string"
// },
// "pageSize": {
// "description": "The standard list page size.",
// "format": "int32",
// "location": "query",
// "type": "integer"
// },
// "pageToken": {
// "description": "The standard list page token.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1/{+name}",
// "response": {
// "$ref": "ListOperationsResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *OperationsListCall) Pages(ctx context.Context, f func(*ListOperationsResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "vision.projects.files.annotate":
type ProjectsFilesAnnotateCall struct {
s *Service
parent string
batchannotatefilesrequest *BatchAnnotateFilesRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Annotate: Service that performs image detection and annotation for a
// batch of files. Now only "application/pdf", "image/tiff" and
// "image/gif" are supported. This service will extract at most 5
// (customers can specify which 5 in AnnotateFileRequest.pages) frames
// (gif) or pages (pdf or tiff) from each file provided and perform
// detection and annotation for each image extracted.
//
// - parent: Optional. Target project and location to make a call.
// Format: `projects/{project-id}/locations/{location-id}`. If no
// parent is specified, a region will be chosen automatically.
// Supported location-ids: `us`: USA country only, `asia`: East asia
// areas, like Japan, Taiwan, `eu`: The European Union. Example:
// `projects/project-A/locations/eu`.
func (r *ProjectsFilesService) Annotate(parent string, batchannotatefilesrequest *BatchAnnotateFilesRequest) *ProjectsFilesAnnotateCall {
c := &ProjectsFilesAnnotateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
c.batchannotatefilesrequest = batchannotatefilesrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsFilesAnnotateCall) Fields(s ...googleapi.Field) *ProjectsFilesAnnotateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsFilesAnnotateCall) Context(ctx context.Context) *ProjectsFilesAnnotateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsFilesAnnotateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsFilesAnnotateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.batchannotatefilesrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+parent}/files:annotate")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.projects.files.annotate" call.
// Exactly one of *BatchAnnotateFilesResponse or error will be non-nil.
// Any non-2xx status code is an error. Response headers are in either
// *BatchAnnotateFilesResponse.ServerResponse.Header or (if a response
// was returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsFilesAnnotateCall) Do(opts ...googleapi.CallOption) (*BatchAnnotateFilesResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &BatchAnnotateFilesResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Service that performs image detection and annotation for a batch of files. Now only \"application/pdf\", \"image/tiff\" and \"image/gif\" are supported. This service will extract at most 5 (customers can specify which 5 in AnnotateFileRequest.pages) frames (gif) or pages (pdf or tiff) from each file provided and perform detection and annotation for each image extracted.",
// "flatPath": "v1/projects/{projectsId}/files:annotate",
// "httpMethod": "POST",
// "id": "vision.projects.files.annotate",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "parent": {
// "description": "Optional. Target project and location to make a call. Format: `projects/{project-id}/locations/{location-id}`. If no parent is specified, a region will be chosen automatically. Supported location-ids: `us`: USA country only, `asia`: East asia areas, like Japan, Taiwan, `eu`: The European Union. Example: `projects/project-A/locations/eu`.",
// "location": "path",
// "pattern": "^projects/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1/{+parent}/files:annotate",
// "request": {
// "$ref": "BatchAnnotateFilesRequest"
// },
// "response": {
// "$ref": "BatchAnnotateFilesResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// method id "vision.projects.files.asyncBatchAnnotate":
type ProjectsFilesAsyncBatchAnnotateCall struct {
s *Service
parent string
asyncbatchannotatefilesrequest *AsyncBatchAnnotateFilesRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// AsyncBatchAnnotate: Run asynchronous image detection and annotation
// for a list of generic files, such as PDF files, which may contain
// multiple pages and multiple images per page. Progress and results can
// be retrieved through the `google.longrunning.Operations` interface.
// `Operation.metadata` contains `OperationMetadata` (metadata).
// `Operation.response` contains `AsyncBatchAnnotateFilesResponse`
// (results).
//
// - parent: Optional. Target project and location to make a call.
// Format: `projects/{project-id}/locations/{location-id}`. If no
// parent is specified, a region will be chosen automatically.
// Supported location-ids: `us`: USA country only, `asia`: East asia
// areas, like Japan, Taiwan, `eu`: The European Union. Example:
// `projects/project-A/locations/eu`.
func (r *ProjectsFilesService) AsyncBatchAnnotate(parent string, asyncbatchannotatefilesrequest *AsyncBatchAnnotateFilesRequest) *ProjectsFilesAsyncBatchAnnotateCall {
c := &ProjectsFilesAsyncBatchAnnotateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
c.asyncbatchannotatefilesrequest = asyncbatchannotatefilesrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsFilesAsyncBatchAnnotateCall) Fields(s ...googleapi.Field) *ProjectsFilesAsyncBatchAnnotateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsFilesAsyncBatchAnnotateCall) Context(ctx context.Context) *ProjectsFilesAsyncBatchAnnotateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsFilesAsyncBatchAnnotateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsFilesAsyncBatchAnnotateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.asyncbatchannotatefilesrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+parent}/files:asyncBatchAnnotate")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.projects.files.asyncBatchAnnotate" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *ProjectsFilesAsyncBatchAnnotateCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Run asynchronous image detection and annotation for a list of generic files, such as PDF files, which may contain multiple pages and multiple images per page. Progress and results can be retrieved through the `google.longrunning.Operations` interface. `Operation.metadata` contains `OperationMetadata` (metadata). `Operation.response` contains `AsyncBatchAnnotateFilesResponse` (results).",
// "flatPath": "v1/projects/{projectsId}/files:asyncBatchAnnotate",
// "httpMethod": "POST",
// "id": "vision.projects.files.asyncBatchAnnotate",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "parent": {
// "description": "Optional. Target project and location to make a call. Format: `projects/{project-id}/locations/{location-id}`. If no parent is specified, a region will be chosen automatically. Supported location-ids: `us`: USA country only, `asia`: East asia areas, like Japan, Taiwan, `eu`: The European Union. Example: `projects/project-A/locations/eu`.",
// "location": "path",
// "pattern": "^projects/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1/{+parent}/files:asyncBatchAnnotate",
// "request": {
// "$ref": "AsyncBatchAnnotateFilesRequest"
// },
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// method id "vision.projects.images.annotate":
type ProjectsImagesAnnotateCall struct {
s *Service
parent string
batchannotateimagesrequest *BatchAnnotateImagesRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Annotate: Run image detection and annotation for a batch of images.
//
// - parent: Optional. Target project and location to make a call.
// Format: `projects/{project-id}/locations/{location-id}`. If no
// parent is specified, a region will be chosen automatically.
// Supported location-ids: `us`: USA country only, `asia`: East asia
// areas, like Japan, Taiwan, `eu`: The European Union. Example:
// `projects/project-A/locations/eu`.
func (r *ProjectsImagesService) Annotate(parent string, batchannotateimagesrequest *BatchAnnotateImagesRequest) *ProjectsImagesAnnotateCall {
c := &ProjectsImagesAnnotateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
c.batchannotateimagesrequest = batchannotateimagesrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsImagesAnnotateCall) Fields(s ...googleapi.Field) *ProjectsImagesAnnotateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsImagesAnnotateCall) Context(ctx context.Context) *ProjectsImagesAnnotateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsImagesAnnotateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsImagesAnnotateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.batchannotateimagesrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+parent}/images:annotate")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.projects.images.annotate" call.
// Exactly one of *BatchAnnotateImagesResponse or error will be non-nil.
// Any non-2xx status code is an error. Response headers are in either
// *BatchAnnotateImagesResponse.ServerResponse.Header or (if a response
// was returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsImagesAnnotateCall) Do(opts ...googleapi.CallOption) (*BatchAnnotateImagesResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &BatchAnnotateImagesResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Run image detection and annotation for a batch of images.",
// "flatPath": "v1/projects/{projectsId}/images:annotate",
// "httpMethod": "POST",
// "id": "vision.projects.images.annotate",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "parent": {
// "description": "Optional. Target project and location to make a call. Format: `projects/{project-id}/locations/{location-id}`. If no parent is specified, a region will be chosen automatically. Supported location-ids: `us`: USA country only, `asia`: East asia areas, like Japan, Taiwan, `eu`: The European Union. Example: `projects/project-A/locations/eu`.",
// "location": "path",
// "pattern": "^projects/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1/{+parent}/images:annotate",
// "request": {
// "$ref": "BatchAnnotateImagesRequest"
// },
// "response": {
// "$ref": "BatchAnnotateImagesResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// method id "vision.projects.images.asyncBatchAnnotate":
type ProjectsImagesAsyncBatchAnnotateCall struct {
s *Service
parent string
asyncbatchannotateimagesrequest *AsyncBatchAnnotateImagesRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// AsyncBatchAnnotate: Run asynchronous image detection and annotation
// for a list of images. Progress and results can be retrieved through
// the `google.longrunning.Operations` interface. `Operation.metadata`
// contains `OperationMetadata` (metadata). `Operation.response`
// contains `AsyncBatchAnnotateImagesResponse` (results). This service
// will write image annotation outputs to json files in customer GCS
// bucket, each json file containing BatchAnnotateImagesResponse proto.
//
// - parent: Optional. Target project and location to make a call.
// Format: `projects/{project-id}/locations/{location-id}`. If no
// parent is specified, a region will be chosen automatically.
// Supported location-ids: `us`: USA country only, `asia`: East asia
// areas, like Japan, Taiwan, `eu`: The European Union. Example:
// `projects/project-A/locations/eu`.
func (r *ProjectsImagesService) AsyncBatchAnnotate(parent string, asyncbatchannotateimagesrequest *AsyncBatchAnnotateImagesRequest) *ProjectsImagesAsyncBatchAnnotateCall {
c := &ProjectsImagesAsyncBatchAnnotateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
c.asyncbatchannotateimagesrequest = asyncbatchannotateimagesrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsImagesAsyncBatchAnnotateCall) Fields(s ...googleapi.Field) *ProjectsImagesAsyncBatchAnnotateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsImagesAsyncBatchAnnotateCall) Context(ctx context.Context) *ProjectsImagesAsyncBatchAnnotateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsImagesAsyncBatchAnnotateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsImagesAsyncBatchAnnotateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.asyncbatchannotateimagesrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+parent}/images:asyncBatchAnnotate")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.projects.images.asyncBatchAnnotate" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *ProjectsImagesAsyncBatchAnnotateCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Run asynchronous image detection and annotation for a list of images. Progress and results can be retrieved through the `google.longrunning.Operations` interface. `Operation.metadata` contains `OperationMetadata` (metadata). `Operation.response` contains `AsyncBatchAnnotateImagesResponse` (results). This service will write image annotation outputs to json files in customer GCS bucket, each json file containing BatchAnnotateImagesResponse proto.",
// "flatPath": "v1/projects/{projectsId}/images:asyncBatchAnnotate",
// "httpMethod": "POST",
// "id": "vision.projects.images.asyncBatchAnnotate",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "parent": {
// "description": "Optional. Target project and location to make a call. Format: `projects/{project-id}/locations/{location-id}`. If no parent is specified, a region will be chosen automatically. Supported location-ids: `us`: USA country only, `asia`: East asia areas, like Japan, Taiwan, `eu`: The European Union. Example: `projects/project-A/locations/eu`.",
// "location": "path",
// "pattern": "^projects/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1/{+parent}/images:asyncBatchAnnotate",
// "request": {
// "$ref": "AsyncBatchAnnotateImagesRequest"
// },
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// method id "vision.projects.locations.files.annotate":
type ProjectsLocationsFilesAnnotateCall struct {
s *Service
parent string
batchannotatefilesrequest *BatchAnnotateFilesRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Annotate: Service that performs image detection and annotation for a
// batch of files. Now only "application/pdf", "image/tiff" and
// "image/gif" are supported. This service will extract at most 5
// (customers can specify which 5 in AnnotateFileRequest.pages) frames
// (gif) or pages (pdf or tiff) from each file provided and perform
// detection and annotation for each image extracted.
//
// - parent: Optional. Target project and location to make a call.
// Format: `projects/{project-id}/locations/{location-id}`. If no
// parent is specified, a region will be chosen automatically.
// Supported location-ids: `us`: USA country only, `asia`: East asia
// areas, like Japan, Taiwan, `eu`: The European Union. Example:
// `projects/project-A/locations/eu`.
func (r *ProjectsLocationsFilesService) Annotate(parent string, batchannotatefilesrequest *BatchAnnotateFilesRequest) *ProjectsLocationsFilesAnnotateCall {
c := &ProjectsLocationsFilesAnnotateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
c.batchannotatefilesrequest = batchannotatefilesrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsFilesAnnotateCall) Fields(s ...googleapi.Field) *ProjectsLocationsFilesAnnotateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsFilesAnnotateCall) Context(ctx context.Context) *ProjectsLocationsFilesAnnotateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsFilesAnnotateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsFilesAnnotateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.batchannotatefilesrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+parent}/files:annotate")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.projects.locations.files.annotate" call.
// Exactly one of *BatchAnnotateFilesResponse or error will be non-nil.
// Any non-2xx status code is an error. Response headers are in either
// *BatchAnnotateFilesResponse.ServerResponse.Header or (if a response
// was returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsLocationsFilesAnnotateCall) Do(opts ...googleapi.CallOption) (*BatchAnnotateFilesResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &BatchAnnotateFilesResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Service that performs image detection and annotation for a batch of files. Now only \"application/pdf\", \"image/tiff\" and \"image/gif\" are supported. This service will extract at most 5 (customers can specify which 5 in AnnotateFileRequest.pages) frames (gif) or pages (pdf or tiff) from each file provided and perform detection and annotation for each image extracted.",
// "flatPath": "v1/projects/{projectsId}/locations/{locationsId}/files:annotate",
// "httpMethod": "POST",
// "id": "vision.projects.locations.files.annotate",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "parent": {
// "description": "Optional. Target project and location to make a call. Format: `projects/{project-id}/locations/{location-id}`. If no parent is specified, a region will be chosen automatically. Supported location-ids: `us`: USA country only, `asia`: East asia areas, like Japan, Taiwan, `eu`: The European Union. Example: `projects/project-A/locations/eu`.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1/{+parent}/files:annotate",
// "request": {
// "$ref": "BatchAnnotateFilesRequest"
// },
// "response": {
// "$ref": "BatchAnnotateFilesResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// method id "vision.projects.locations.files.asyncBatchAnnotate":
type ProjectsLocationsFilesAsyncBatchAnnotateCall struct {
s *Service
parent string
asyncbatchannotatefilesrequest *AsyncBatchAnnotateFilesRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// AsyncBatchAnnotate: Run asynchronous image detection and annotation
// for a list of generic files, such as PDF files, which may contain
// multiple pages and multiple images per page. Progress and results can
// be retrieved through the `google.longrunning.Operations` interface.
// `Operation.metadata` contains `OperationMetadata` (metadata).
// `Operation.response` contains `AsyncBatchAnnotateFilesResponse`
// (results).
//
// - parent: Optional. Target project and location to make a call.
// Format: `projects/{project-id}/locations/{location-id}`. If no
// parent is specified, a region will be chosen automatically.
// Supported location-ids: `us`: USA country only, `asia`: East asia
// areas, like Japan, Taiwan, `eu`: The European Union. Example:
// `projects/project-A/locations/eu`.
func (r *ProjectsLocationsFilesService) AsyncBatchAnnotate(parent string, asyncbatchannotatefilesrequest *AsyncBatchAnnotateFilesRequest) *ProjectsLocationsFilesAsyncBatchAnnotateCall {
c := &ProjectsLocationsFilesAsyncBatchAnnotateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
c.asyncbatchannotatefilesrequest = asyncbatchannotatefilesrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsFilesAsyncBatchAnnotateCall) Fields(s ...googleapi.Field) *ProjectsLocationsFilesAsyncBatchAnnotateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsFilesAsyncBatchAnnotateCall) Context(ctx context.Context) *ProjectsLocationsFilesAsyncBatchAnnotateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsFilesAsyncBatchAnnotateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsFilesAsyncBatchAnnotateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.asyncbatchannotatefilesrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+parent}/files:asyncBatchAnnotate")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.projects.locations.files.asyncBatchAnnotate" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *ProjectsLocationsFilesAsyncBatchAnnotateCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Run asynchronous image detection and annotation for a list of generic files, such as PDF files, which may contain multiple pages and multiple images per page. Progress and results can be retrieved through the `google.longrunning.Operations` interface. `Operation.metadata` contains `OperationMetadata` (metadata). `Operation.response` contains `AsyncBatchAnnotateFilesResponse` (results).",
// "flatPath": "v1/projects/{projectsId}/locations/{locationsId}/files:asyncBatchAnnotate",
// "httpMethod": "POST",
// "id": "vision.projects.locations.files.asyncBatchAnnotate",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "parent": {
// "description": "Optional. Target project and location to make a call. Format: `projects/{project-id}/locations/{location-id}`. If no parent is specified, a region will be chosen automatically. Supported location-ids: `us`: USA country only, `asia`: East asia areas, like Japan, Taiwan, `eu`: The European Union. Example: `projects/project-A/locations/eu`.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1/{+parent}/files:asyncBatchAnnotate",
// "request": {
// "$ref": "AsyncBatchAnnotateFilesRequest"
// },
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// method id "vision.projects.locations.images.annotate":
type ProjectsLocationsImagesAnnotateCall struct {
s *Service
parent string
batchannotateimagesrequest *BatchAnnotateImagesRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Annotate: Run image detection and annotation for a batch of images.
//
// - parent: Optional. Target project and location to make a call.
// Format: `projects/{project-id}/locations/{location-id}`. If no
// parent is specified, a region will be chosen automatically.
// Supported location-ids: `us`: USA country only, `asia`: East asia
// areas, like Japan, Taiwan, `eu`: The European Union. Example:
// `projects/project-A/locations/eu`.
func (r *ProjectsLocationsImagesService) Annotate(parent string, batchannotateimagesrequest *BatchAnnotateImagesRequest) *ProjectsLocationsImagesAnnotateCall {
c := &ProjectsLocationsImagesAnnotateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
c.batchannotateimagesrequest = batchannotateimagesrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsImagesAnnotateCall) Fields(s ...googleapi.Field) *ProjectsLocationsImagesAnnotateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsImagesAnnotateCall) Context(ctx context.Context) *ProjectsLocationsImagesAnnotateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsImagesAnnotateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsImagesAnnotateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.batchannotateimagesrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+parent}/images:annotate")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.projects.locations.images.annotate" call.
// Exactly one of *BatchAnnotateImagesResponse or error will be non-nil.
// Any non-2xx status code is an error. Response headers are in either
// *BatchAnnotateImagesResponse.ServerResponse.Header or (if a response
// was returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsLocationsImagesAnnotateCall) Do(opts ...googleapi.CallOption) (*BatchAnnotateImagesResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &BatchAnnotateImagesResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Run image detection and annotation for a batch of images.",
// "flatPath": "v1/projects/{projectsId}/locations/{locationsId}/images:annotate",
// "httpMethod": "POST",
// "id": "vision.projects.locations.images.annotate",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "parent": {
// "description": "Optional. Target project and location to make a call. Format: `projects/{project-id}/locations/{location-id}`. If no parent is specified, a region will be chosen automatically. Supported location-ids: `us`: USA country only, `asia`: East asia areas, like Japan, Taiwan, `eu`: The European Union. Example: `projects/project-A/locations/eu`.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1/{+parent}/images:annotate",
// "request": {
// "$ref": "BatchAnnotateImagesRequest"
// },
// "response": {
// "$ref": "BatchAnnotateImagesResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// method id "vision.projects.locations.images.asyncBatchAnnotate":
type ProjectsLocationsImagesAsyncBatchAnnotateCall struct {
s *Service
parent string
asyncbatchannotateimagesrequest *AsyncBatchAnnotateImagesRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// AsyncBatchAnnotate: Run asynchronous image detection and annotation
// for a list of images. Progress and results can be retrieved through
// the `google.longrunning.Operations` interface. `Operation.metadata`
// contains `OperationMetadata` (metadata). `Operation.response`
// contains `AsyncBatchAnnotateImagesResponse` (results). This service
// will write image annotation outputs to json files in customer GCS
// bucket, each json file containing BatchAnnotateImagesResponse proto.
//
// - parent: Optional. Target project and location to make a call.
// Format: `projects/{project-id}/locations/{location-id}`. If no
// parent is specified, a region will be chosen automatically.
// Supported location-ids: `us`: USA country only, `asia`: East asia
// areas, like Japan, Taiwan, `eu`: The European Union. Example:
// `projects/project-A/locations/eu`.
func (r *ProjectsLocationsImagesService) AsyncBatchAnnotate(parent string, asyncbatchannotateimagesrequest *AsyncBatchAnnotateImagesRequest) *ProjectsLocationsImagesAsyncBatchAnnotateCall {
c := &ProjectsLocationsImagesAsyncBatchAnnotateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
c.asyncbatchannotateimagesrequest = asyncbatchannotateimagesrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsImagesAsyncBatchAnnotateCall) Fields(s ...googleapi.Field) *ProjectsLocationsImagesAsyncBatchAnnotateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsImagesAsyncBatchAnnotateCall) Context(ctx context.Context) *ProjectsLocationsImagesAsyncBatchAnnotateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsImagesAsyncBatchAnnotateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsImagesAsyncBatchAnnotateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.asyncbatchannotateimagesrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+parent}/images:asyncBatchAnnotate")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.projects.locations.images.asyncBatchAnnotate" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *ProjectsLocationsImagesAsyncBatchAnnotateCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Run asynchronous image detection and annotation for a list of images. Progress and results can be retrieved through the `google.longrunning.Operations` interface. `Operation.metadata` contains `OperationMetadata` (metadata). `Operation.response` contains `AsyncBatchAnnotateImagesResponse` (results). This service will write image annotation outputs to json files in customer GCS bucket, each json file containing BatchAnnotateImagesResponse proto.",
// "flatPath": "v1/projects/{projectsId}/locations/{locationsId}/images:asyncBatchAnnotate",
// "httpMethod": "POST",
// "id": "vision.projects.locations.images.asyncBatchAnnotate",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "parent": {
// "description": "Optional. Target project and location to make a call. Format: `projects/{project-id}/locations/{location-id}`. If no parent is specified, a region will be chosen automatically. Supported location-ids: `us`: USA country only, `asia`: East asia areas, like Japan, Taiwan, `eu`: The European Union. Example: `projects/project-A/locations/eu`.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1/{+parent}/images:asyncBatchAnnotate",
// "request": {
// "$ref": "AsyncBatchAnnotateImagesRequest"
// },
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// method id "vision.projects.locations.operations.get":
type ProjectsLocationsOperationsGetCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Gets the latest state of a long-running operation. Clients can
// use this method to poll the operation result at intervals as
// recommended by the API service.
//
// - name: The name of the operation resource.
func (r *ProjectsLocationsOperationsService) Get(name string) *ProjectsLocationsOperationsGetCall {
c := &ProjectsLocationsOperationsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsOperationsGetCall) Fields(s ...googleapi.Field) *ProjectsLocationsOperationsGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ProjectsLocationsOperationsGetCall) IfNoneMatch(entityTag string) *ProjectsLocationsOperationsGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsOperationsGetCall) Context(ctx context.Context) *ProjectsLocationsOperationsGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsOperationsGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsOperationsGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.projects.locations.operations.get" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *ProjectsLocationsOperationsGetCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service.",
// "flatPath": "v1/projects/{projectsId}/locations/{locationsId}/operations/{operationsId}",
// "httpMethod": "GET",
// "id": "vision.projects.locations.operations.get",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "The name of the operation resource.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/operations/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1/{+name}",
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// method id "vision.projects.locations.productSets.addProduct":
type ProjectsLocationsProductSetsAddProductCall struct {
s *Service
name string
addproducttoproductsetrequest *AddProductToProductSetRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// AddProduct: Adds a Product to the specified ProductSet. If the
// Product is already present, no change is made. One Product can be
// added to at most 100 ProductSets. Possible errors: * Returns
// NOT_FOUND if the Product or the ProductSet doesn't exist.
//
// - name: The resource name for the ProductSet to modify. Format is:
// `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`.
func (r *ProjectsLocationsProductSetsService) AddProduct(name string, addproducttoproductsetrequest *AddProductToProductSetRequest) *ProjectsLocationsProductSetsAddProductCall {
c := &ProjectsLocationsProductSetsAddProductCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
c.addproducttoproductsetrequest = addproducttoproductsetrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsProductSetsAddProductCall) Fields(s ...googleapi.Field) *ProjectsLocationsProductSetsAddProductCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsProductSetsAddProductCall) Context(ctx context.Context) *ProjectsLocationsProductSetsAddProductCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsProductSetsAddProductCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsProductSetsAddProductCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.addproducttoproductsetrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+name}:addProduct")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.projects.locations.productSets.addProduct" call.
// Exactly one of *Empty or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Empty.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsLocationsProductSetsAddProductCall) Do(opts ...googleapi.CallOption) (*Empty, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Empty{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Adds a Product to the specified ProductSet. If the Product is already present, no change is made. One Product can be added to at most 100 ProductSets. Possible errors: * Returns NOT_FOUND if the Product or the ProductSet doesn't exist.",
// "flatPath": "v1/projects/{projectsId}/locations/{locationsId}/productSets/{productSetsId}:addProduct",
// "httpMethod": "POST",
// "id": "vision.projects.locations.productSets.addProduct",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "Required. The resource name for the ProductSet to modify. Format is: `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/productSets/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1/{+name}:addProduct",
// "request": {
// "$ref": "AddProductToProductSetRequest"
// },
// "response": {
// "$ref": "Empty"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// method id "vision.projects.locations.productSets.create":
type ProjectsLocationsProductSetsCreateCall struct {
s *Service
parent string
productset *ProductSet
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Create: Creates and returns a new ProductSet resource. Possible
// errors: * Returns INVALID_ARGUMENT if display_name is missing, or is
// longer than 4096 characters.
//
// - parent: The project in which the ProductSet should be created.
// Format is `projects/PROJECT_ID/locations/LOC_ID`.
func (r *ProjectsLocationsProductSetsService) Create(parent string, productset *ProductSet) *ProjectsLocationsProductSetsCreateCall {
c := &ProjectsLocationsProductSetsCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
c.productset = productset
return c
}
// ProductSetId sets the optional parameter "productSetId": A
// user-supplied resource id for this ProductSet. If set, the server
// will attempt to use this value as the resource id. If it is already
// in use, an error is returned with code ALREADY_EXISTS. Must be at
// most 128 characters long. It cannot contain the character `/`.
func (c *ProjectsLocationsProductSetsCreateCall) ProductSetId(productSetId string) *ProjectsLocationsProductSetsCreateCall {
c.urlParams_.Set("productSetId", productSetId)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsProductSetsCreateCall) Fields(s ...googleapi.Field) *ProjectsLocationsProductSetsCreateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsProductSetsCreateCall) Context(ctx context.Context) *ProjectsLocationsProductSetsCreateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsProductSetsCreateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsProductSetsCreateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.productset)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+parent}/productSets")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.projects.locations.productSets.create" call.
// Exactly one of *ProductSet or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *ProductSet.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *ProjectsLocationsProductSetsCreateCall) Do(opts ...googleapi.CallOption) (*ProductSet, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ProductSet{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Creates and returns a new ProductSet resource. Possible errors: * Returns INVALID_ARGUMENT if display_name is missing, or is longer than 4096 characters.",
// "flatPath": "v1/projects/{projectsId}/locations/{locationsId}/productSets",
// "httpMethod": "POST",
// "id": "vision.projects.locations.productSets.create",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "parent": {
// "description": "Required. The project in which the ProductSet should be created. Format is `projects/PROJECT_ID/locations/LOC_ID`.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+$",
// "required": true,
// "type": "string"
// },
// "productSetId": {
// "description": "A user-supplied resource id for this ProductSet. If set, the server will attempt to use this value as the resource id. If it is already in use, an error is returned with code ALREADY_EXISTS. Must be at most 128 characters long. It cannot contain the character `/`.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1/{+parent}/productSets",
// "request": {
// "$ref": "ProductSet"
// },
// "response": {
// "$ref": "ProductSet"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// method id "vision.projects.locations.productSets.delete":
type ProjectsLocationsProductSetsDeleteCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Permanently deletes a ProductSet. Products and
// ReferenceImages in the ProductSet are not deleted. The actual image
// files are not deleted from Google Cloud Storage.
//
// - name: Resource name of the ProductSet to delete. Format is:
// `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`.
func (r *ProjectsLocationsProductSetsService) Delete(name string) *ProjectsLocationsProductSetsDeleteCall {
c := &ProjectsLocationsProductSetsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsProductSetsDeleteCall) Fields(s ...googleapi.Field) *ProjectsLocationsProductSetsDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsProductSetsDeleteCall) Context(ctx context.Context) *ProjectsLocationsProductSetsDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsProductSetsDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsProductSetsDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("DELETE", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.projects.locations.productSets.delete" call.
// Exactly one of *Empty or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Empty.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsLocationsProductSetsDeleteCall) Do(opts ...googleapi.CallOption) (*Empty, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Empty{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Permanently deletes a ProductSet. Products and ReferenceImages in the ProductSet are not deleted. The actual image files are not deleted from Google Cloud Storage.",
// "flatPath": "v1/projects/{projectsId}/locations/{locationsId}/productSets/{productSetsId}",
// "httpMethod": "DELETE",
// "id": "vision.projects.locations.productSets.delete",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "Required. Resource name of the ProductSet to delete. Format is: `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/productSets/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1/{+name}",
// "response": {
// "$ref": "Empty"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// method id "vision.projects.locations.productSets.get":
type ProjectsLocationsProductSetsGetCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Gets information associated with a ProductSet. Possible errors:
// * Returns NOT_FOUND if the ProductSet does not exist.
//
// - name: Resource name of the ProductSet to get. Format is:
// `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`.
func (r *ProjectsLocationsProductSetsService) Get(name string) *ProjectsLocationsProductSetsGetCall {
c := &ProjectsLocationsProductSetsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsProductSetsGetCall) Fields(s ...googleapi.Field) *ProjectsLocationsProductSetsGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ProjectsLocationsProductSetsGetCall) IfNoneMatch(entityTag string) *ProjectsLocationsProductSetsGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsProductSetsGetCall) Context(ctx context.Context) *ProjectsLocationsProductSetsGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsProductSetsGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsProductSetsGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.projects.locations.productSets.get" call.
// Exactly one of *ProductSet or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *ProductSet.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *ProjectsLocationsProductSetsGetCall) Do(opts ...googleapi.CallOption) (*ProductSet, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ProductSet{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets information associated with a ProductSet. Possible errors: * Returns NOT_FOUND if the ProductSet does not exist.",
// "flatPath": "v1/projects/{projectsId}/locations/{locationsId}/productSets/{productSetsId}",
// "httpMethod": "GET",
// "id": "vision.projects.locations.productSets.get",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "Required. Resource name of the ProductSet to get. Format is: `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/productSets/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1/{+name}",
// "response": {
// "$ref": "ProductSet"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// method id "vision.projects.locations.productSets.import":
type ProjectsLocationsProductSetsImportCall struct {
s *Service
parent string
importproductsetsrequest *ImportProductSetsRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Import: Asynchronous API that imports a list of reference images to
// specified product sets based on a list of image information. The
// google.longrunning.Operation API can be used to keep track of the
// progress and results of the request. `Operation.metadata` contains
// `BatchOperationMetadata`. (progress) `Operation.response` contains
// `ImportProductSetsResponse`. (results) The input source of this
// method is a csv file on Google Cloud Storage. For the format of the
// csv file please see ImportProductSetsGcsSource.csv_file_uri.
//
// - parent: The project in which the ProductSets should be imported.
// Format is `projects/PROJECT_ID/locations/LOC_ID`.
func (r *ProjectsLocationsProductSetsService) Import(parent string, importproductsetsrequest *ImportProductSetsRequest) *ProjectsLocationsProductSetsImportCall {
c := &ProjectsLocationsProductSetsImportCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
c.importproductsetsrequest = importproductsetsrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsProductSetsImportCall) Fields(s ...googleapi.Field) *ProjectsLocationsProductSetsImportCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsProductSetsImportCall) Context(ctx context.Context) *ProjectsLocationsProductSetsImportCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsProductSetsImportCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsProductSetsImportCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.importproductsetsrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+parent}/productSets:import")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.projects.locations.productSets.import" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *ProjectsLocationsProductSetsImportCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Asynchronous API that imports a list of reference images to specified product sets based on a list of image information. The google.longrunning.Operation API can be used to keep track of the progress and results of the request. `Operation.metadata` contains `BatchOperationMetadata`. (progress) `Operation.response` contains `ImportProductSetsResponse`. (results) The input source of this method is a csv file on Google Cloud Storage. For the format of the csv file please see ImportProductSetsGcsSource.csv_file_uri.",
// "flatPath": "v1/projects/{projectsId}/locations/{locationsId}/productSets:import",
// "httpMethod": "POST",
// "id": "vision.projects.locations.productSets.import",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "parent": {
// "description": "Required. The project in which the ProductSets should be imported. Format is `projects/PROJECT_ID/locations/LOC_ID`.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1/{+parent}/productSets:import",
// "request": {
// "$ref": "ImportProductSetsRequest"
// },
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// method id "vision.projects.locations.productSets.list":
type ProjectsLocationsProductSetsListCall struct {
s *Service
parent string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Lists ProductSets in an unspecified order. Possible errors: *
// Returns INVALID_ARGUMENT if page_size is greater than 100, or less
// than 1.
//
// - parent: The project from which ProductSets should be listed. Format
// is `projects/PROJECT_ID/locations/LOC_ID`.
func (r *ProjectsLocationsProductSetsService) List(parent string) *ProjectsLocationsProductSetsListCall {
c := &ProjectsLocationsProductSetsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
return c
}
// PageSize sets the optional parameter "pageSize": The maximum number
// of items to return. Default 10, maximum 100.
func (c *ProjectsLocationsProductSetsListCall) PageSize(pageSize int64) *ProjectsLocationsProductSetsListCall {
c.urlParams_.Set("pageSize", fmt.Sprint(pageSize))
return c
}
// PageToken sets the optional parameter "pageToken": The
// next_page_token returned from a previous List request, if any.
func (c *ProjectsLocationsProductSetsListCall) PageToken(pageToken string) *ProjectsLocationsProductSetsListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsProductSetsListCall) Fields(s ...googleapi.Field) *ProjectsLocationsProductSetsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ProjectsLocationsProductSetsListCall) IfNoneMatch(entityTag string) *ProjectsLocationsProductSetsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsProductSetsListCall) Context(ctx context.Context) *ProjectsLocationsProductSetsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsProductSetsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsProductSetsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+parent}/productSets")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.projects.locations.productSets.list" call.
// Exactly one of *ListProductSetsResponse or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ListProductSetsResponse.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsLocationsProductSetsListCall) Do(opts ...googleapi.CallOption) (*ListProductSetsResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ListProductSetsResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Lists ProductSets in an unspecified order. Possible errors: * Returns INVALID_ARGUMENT if page_size is greater than 100, or less than 1.",
// "flatPath": "v1/projects/{projectsId}/locations/{locationsId}/productSets",
// "httpMethod": "GET",
// "id": "vision.projects.locations.productSets.list",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "pageSize": {
// "description": "The maximum number of items to return. Default 10, maximum 100.",
// "format": "int32",
// "location": "query",
// "type": "integer"
// },
// "pageToken": {
// "description": "The next_page_token returned from a previous List request, if any.",
// "location": "query",
// "type": "string"
// },
// "parent": {
// "description": "Required. The project from which ProductSets should be listed. Format is `projects/PROJECT_ID/locations/LOC_ID`.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1/{+parent}/productSets",
// "response": {
// "$ref": "ListProductSetsResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *ProjectsLocationsProductSetsListCall) Pages(ctx context.Context, f func(*ListProductSetsResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "vision.projects.locations.productSets.patch":
type ProjectsLocationsProductSetsPatchCall struct {
s *Service
name string
productset *ProductSet
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Patch: Makes changes to a ProductSet resource. Only display_name can
// be updated currently. Possible errors: * Returns NOT_FOUND if the
// ProductSet does not exist. * Returns INVALID_ARGUMENT if display_name
// is present in update_mask but missing from the request or longer than
// 4096 characters.
//
// - name: The resource name of the ProductSet. Format is:
// `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`.
// This field is ignored when creating a ProductSet.
func (r *ProjectsLocationsProductSetsService) Patch(name string, productset *ProductSet) *ProjectsLocationsProductSetsPatchCall {
c := &ProjectsLocationsProductSetsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
c.productset = productset
return c
}
// UpdateMask sets the optional parameter "updateMask": The FieldMask
// that specifies which fields to update. If update_mask isn't
// specified, all mutable fields are to be updated. Valid mask path is
// `display_name`.
func (c *ProjectsLocationsProductSetsPatchCall) UpdateMask(updateMask string) *ProjectsLocationsProductSetsPatchCall {
c.urlParams_.Set("updateMask", updateMask)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsProductSetsPatchCall) Fields(s ...googleapi.Field) *ProjectsLocationsProductSetsPatchCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsProductSetsPatchCall) Context(ctx context.Context) *ProjectsLocationsProductSetsPatchCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsProductSetsPatchCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsProductSetsPatchCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.productset)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("PATCH", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.projects.locations.productSets.patch" call.
// Exactly one of *ProductSet or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *ProductSet.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *ProjectsLocationsProductSetsPatchCall) Do(opts ...googleapi.CallOption) (*ProductSet, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ProductSet{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Makes changes to a ProductSet resource. Only display_name can be updated currently. Possible errors: * Returns NOT_FOUND if the ProductSet does not exist. * Returns INVALID_ARGUMENT if display_name is present in update_mask but missing from the request or longer than 4096 characters.",
// "flatPath": "v1/projects/{projectsId}/locations/{locationsId}/productSets/{productSetsId}",
// "httpMethod": "PATCH",
// "id": "vision.projects.locations.productSets.patch",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "The resource name of the ProductSet. Format is: `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`. This field is ignored when creating a ProductSet.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/productSets/[^/]+$",
// "required": true,
// "type": "string"
// },
// "updateMask": {
// "description": "The FieldMask that specifies which fields to update. If update_mask isn't specified, all mutable fields are to be updated. Valid mask path is `display_name`.",
// "format": "google-fieldmask",
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1/{+name}",
// "request": {
// "$ref": "ProductSet"
// },
// "response": {
// "$ref": "ProductSet"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// method id "vision.projects.locations.productSets.removeProduct":
type ProjectsLocationsProductSetsRemoveProductCall struct {
s *Service
name string
removeproductfromproductsetrequest *RemoveProductFromProductSetRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// RemoveProduct: Removes a Product from the specified ProductSet.
//
// - name: The resource name for the ProductSet to modify. Format is:
// `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`.
func (r *ProjectsLocationsProductSetsService) RemoveProduct(name string, removeproductfromproductsetrequest *RemoveProductFromProductSetRequest) *ProjectsLocationsProductSetsRemoveProductCall {
c := &ProjectsLocationsProductSetsRemoveProductCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
c.removeproductfromproductsetrequest = removeproductfromproductsetrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsProductSetsRemoveProductCall) Fields(s ...googleapi.Field) *ProjectsLocationsProductSetsRemoveProductCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsProductSetsRemoveProductCall) Context(ctx context.Context) *ProjectsLocationsProductSetsRemoveProductCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsProductSetsRemoveProductCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsProductSetsRemoveProductCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.removeproductfromproductsetrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+name}:removeProduct")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.projects.locations.productSets.removeProduct" call.
// Exactly one of *Empty or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Empty.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsLocationsProductSetsRemoveProductCall) Do(opts ...googleapi.CallOption) (*Empty, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Empty{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Removes a Product from the specified ProductSet.",
// "flatPath": "v1/projects/{projectsId}/locations/{locationsId}/productSets/{productSetsId}:removeProduct",
// "httpMethod": "POST",
// "id": "vision.projects.locations.productSets.removeProduct",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "Required. The resource name for the ProductSet to modify. Format is: `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/productSets/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1/{+name}:removeProduct",
// "request": {
// "$ref": "RemoveProductFromProductSetRequest"
// },
// "response": {
// "$ref": "Empty"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// method id "vision.projects.locations.productSets.products.list":
type ProjectsLocationsProductSetsProductsListCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Lists the Products in a ProductSet, in an unspecified order. If
// the ProductSet does not exist, the products field of the response
// will be empty. Possible errors: * Returns INVALID_ARGUMENT if
// page_size is greater than 100 or less than 1.
//
// - name: The ProductSet resource for which to retrieve Products.
// Format is:
// `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`.
func (r *ProjectsLocationsProductSetsProductsService) List(name string) *ProjectsLocationsProductSetsProductsListCall {
c := &ProjectsLocationsProductSetsProductsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// PageSize sets the optional parameter "pageSize": The maximum number
// of items to return. Default 10, maximum 100.
func (c *ProjectsLocationsProductSetsProductsListCall) PageSize(pageSize int64) *ProjectsLocationsProductSetsProductsListCall {
c.urlParams_.Set("pageSize", fmt.Sprint(pageSize))
return c
}
// PageToken sets the optional parameter "pageToken": The
// next_page_token returned from a previous List request, if any.
func (c *ProjectsLocationsProductSetsProductsListCall) PageToken(pageToken string) *ProjectsLocationsProductSetsProductsListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsProductSetsProductsListCall) Fields(s ...googleapi.Field) *ProjectsLocationsProductSetsProductsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ProjectsLocationsProductSetsProductsListCall) IfNoneMatch(entityTag string) *ProjectsLocationsProductSetsProductsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsProductSetsProductsListCall) Context(ctx context.Context) *ProjectsLocationsProductSetsProductsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsProductSetsProductsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsProductSetsProductsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+name}/products")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.projects.locations.productSets.products.list" call.
// Exactly one of *ListProductsInProductSetResponse or error will be
// non-nil. Any non-2xx status code is an error. Response headers are in
// either *ListProductsInProductSetResponse.ServerResponse.Header or (if
// a response was returned at all) in error.(*googleapi.Error).Header.
// Use googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsLocationsProductSetsProductsListCall) Do(opts ...googleapi.CallOption) (*ListProductsInProductSetResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ListProductsInProductSetResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Lists the Products in a ProductSet, in an unspecified order. If the ProductSet does not exist, the products field of the response will be empty. Possible errors: * Returns INVALID_ARGUMENT if page_size is greater than 100 or less than 1.",
// "flatPath": "v1/projects/{projectsId}/locations/{locationsId}/productSets/{productSetsId}/products",
// "httpMethod": "GET",
// "id": "vision.projects.locations.productSets.products.list",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "Required. The ProductSet resource for which to retrieve Products. Format is: `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/productSets/[^/]+$",
// "required": true,
// "type": "string"
// },
// "pageSize": {
// "description": "The maximum number of items to return. Default 10, maximum 100.",
// "format": "int32",
// "location": "query",
// "type": "integer"
// },
// "pageToken": {
// "description": "The next_page_token returned from a previous List request, if any.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1/{+name}/products",
// "response": {
// "$ref": "ListProductsInProductSetResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *ProjectsLocationsProductSetsProductsListCall) Pages(ctx context.Context, f func(*ListProductsInProductSetResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "vision.projects.locations.products.create":
type ProjectsLocationsProductsCreateCall struct {
s *Service
parent string
product *Product
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Create: Creates and returns a new product resource. Possible errors:
// * Returns INVALID_ARGUMENT if display_name is missing or longer than
// 4096 characters. * Returns INVALID_ARGUMENT if description is longer
// than 4096 characters. * Returns INVALID_ARGUMENT if product_category
// is missing or invalid.
//
// - parent: The project in which the Product should be created. Format
// is `projects/PROJECT_ID/locations/LOC_ID`.
func (r *ProjectsLocationsProductsService) Create(parent string, product *Product) *ProjectsLocationsProductsCreateCall {
c := &ProjectsLocationsProductsCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
c.product = product
return c
}
// ProductId sets the optional parameter "productId": A user-supplied
// resource id for this Product. If set, the server will attempt to use
// this value as the resource id. If it is already in use, an error is
// returned with code ALREADY_EXISTS. Must be at most 128 characters
// long. It cannot contain the character `/`.
func (c *ProjectsLocationsProductsCreateCall) ProductId(productId string) *ProjectsLocationsProductsCreateCall {
c.urlParams_.Set("productId", productId)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsProductsCreateCall) Fields(s ...googleapi.Field) *ProjectsLocationsProductsCreateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsProductsCreateCall) Context(ctx context.Context) *ProjectsLocationsProductsCreateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsProductsCreateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsProductsCreateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.product)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+parent}/products")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.projects.locations.products.create" call.
// Exactly one of *Product or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Product.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsLocationsProductsCreateCall) Do(opts ...googleapi.CallOption) (*Product, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Product{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Creates and returns a new product resource. Possible errors: * Returns INVALID_ARGUMENT if display_name is missing or longer than 4096 characters. * Returns INVALID_ARGUMENT if description is longer than 4096 characters. * Returns INVALID_ARGUMENT if product_category is missing or invalid.",
// "flatPath": "v1/projects/{projectsId}/locations/{locationsId}/products",
// "httpMethod": "POST",
// "id": "vision.projects.locations.products.create",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "parent": {
// "description": "Required. The project in which the Product should be created. Format is `projects/PROJECT_ID/locations/LOC_ID`.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+$",
// "required": true,
// "type": "string"
// },
// "productId": {
// "description": "A user-supplied resource id for this Product. If set, the server will attempt to use this value as the resource id. If it is already in use, an error is returned with code ALREADY_EXISTS. Must be at most 128 characters long. It cannot contain the character `/`.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1/{+parent}/products",
// "request": {
// "$ref": "Product"
// },
// "response": {
// "$ref": "Product"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// method id "vision.projects.locations.products.delete":
type ProjectsLocationsProductsDeleteCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Permanently deletes a product and its reference images.
// Metadata of the product and all its images will be deleted right
// away, but search queries against ProductSets containing the product
// may still work until all related caches are refreshed.
//
// - name: Resource name of product to delete. Format is:
// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`.
func (r *ProjectsLocationsProductsService) Delete(name string) *ProjectsLocationsProductsDeleteCall {
c := &ProjectsLocationsProductsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsProductsDeleteCall) Fields(s ...googleapi.Field) *ProjectsLocationsProductsDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsProductsDeleteCall) Context(ctx context.Context) *ProjectsLocationsProductsDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsProductsDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsProductsDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("DELETE", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.projects.locations.products.delete" call.
// Exactly one of *Empty or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Empty.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsLocationsProductsDeleteCall) Do(opts ...googleapi.CallOption) (*Empty, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Empty{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Permanently deletes a product and its reference images. Metadata of the product and all its images will be deleted right away, but search queries against ProductSets containing the product may still work until all related caches are refreshed.",
// "flatPath": "v1/projects/{projectsId}/locations/{locationsId}/products/{productsId}",
// "httpMethod": "DELETE",
// "id": "vision.projects.locations.products.delete",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "Required. Resource name of product to delete. Format is: `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/products/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1/{+name}",
// "response": {
// "$ref": "Empty"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// method id "vision.projects.locations.products.get":
type ProjectsLocationsProductsGetCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Gets information associated with a Product. Possible errors: *
// Returns NOT_FOUND if the Product does not exist.
//
// - name: Resource name of the Product to get. Format is:
// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`.
func (r *ProjectsLocationsProductsService) Get(name string) *ProjectsLocationsProductsGetCall {
c := &ProjectsLocationsProductsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsProductsGetCall) Fields(s ...googleapi.Field) *ProjectsLocationsProductsGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ProjectsLocationsProductsGetCall) IfNoneMatch(entityTag string) *ProjectsLocationsProductsGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsProductsGetCall) Context(ctx context.Context) *ProjectsLocationsProductsGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsProductsGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsProductsGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.projects.locations.products.get" call.
// Exactly one of *Product or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Product.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsLocationsProductsGetCall) Do(opts ...googleapi.CallOption) (*Product, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Product{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets information associated with a Product. Possible errors: * Returns NOT_FOUND if the Product does not exist.",
// "flatPath": "v1/projects/{projectsId}/locations/{locationsId}/products/{productsId}",
// "httpMethod": "GET",
// "id": "vision.projects.locations.products.get",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "Required. Resource name of the Product to get. Format is: `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/products/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1/{+name}",
// "response": {
// "$ref": "Product"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// method id "vision.projects.locations.products.list":
type ProjectsLocationsProductsListCall struct {
s *Service
parent string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Lists products in an unspecified order. Possible errors: *
// Returns INVALID_ARGUMENT if page_size is greater than 100 or less
// than 1.
//
// - parent: The project OR ProductSet from which Products should be
// listed. Format: `projects/PROJECT_ID/locations/LOC_ID`.
func (r *ProjectsLocationsProductsService) List(parent string) *ProjectsLocationsProductsListCall {
c := &ProjectsLocationsProductsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
return c
}
// PageSize sets the optional parameter "pageSize": The maximum number
// of items to return. Default 10, maximum 100.
func (c *ProjectsLocationsProductsListCall) PageSize(pageSize int64) *ProjectsLocationsProductsListCall {
c.urlParams_.Set("pageSize", fmt.Sprint(pageSize))
return c
}
// PageToken sets the optional parameter "pageToken": The
// next_page_token returned from a previous List request, if any.
func (c *ProjectsLocationsProductsListCall) PageToken(pageToken string) *ProjectsLocationsProductsListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsProductsListCall) Fields(s ...googleapi.Field) *ProjectsLocationsProductsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ProjectsLocationsProductsListCall) IfNoneMatch(entityTag string) *ProjectsLocationsProductsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsProductsListCall) Context(ctx context.Context) *ProjectsLocationsProductsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsProductsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsProductsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+parent}/products")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.projects.locations.products.list" call.
// Exactly one of *ListProductsResponse or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ListProductsResponse.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsLocationsProductsListCall) Do(opts ...googleapi.CallOption) (*ListProductsResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ListProductsResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Lists products in an unspecified order. Possible errors: * Returns INVALID_ARGUMENT if page_size is greater than 100 or less than 1.",
// "flatPath": "v1/projects/{projectsId}/locations/{locationsId}/products",
// "httpMethod": "GET",
// "id": "vision.projects.locations.products.list",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "pageSize": {
// "description": "The maximum number of items to return. Default 10, maximum 100.",
// "format": "int32",
// "location": "query",
// "type": "integer"
// },
// "pageToken": {
// "description": "The next_page_token returned from a previous List request, if any.",
// "location": "query",
// "type": "string"
// },
// "parent": {
// "description": "Required. The project OR ProductSet from which Products should be listed. Format: `projects/PROJECT_ID/locations/LOC_ID`",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1/{+parent}/products",
// "response": {
// "$ref": "ListProductsResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *ProjectsLocationsProductsListCall) Pages(ctx context.Context, f func(*ListProductsResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "vision.projects.locations.products.patch":
type ProjectsLocationsProductsPatchCall struct {
s *Service
name string
product *Product
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Patch: Makes changes to a Product resource. Only the `display_name`,
// `description`, and `labels` fields can be updated right now. If
// labels are updated, the change will not be reflected in queries until
// the next index time. Possible errors: * Returns NOT_FOUND if the
// Product does not exist. * Returns INVALID_ARGUMENT if display_name is
// present in update_mask but is missing from the request or longer than
// 4096 characters. * Returns INVALID_ARGUMENT if description is present
// in update_mask but is longer than 4096 characters. * Returns
// INVALID_ARGUMENT if product_category is present in update_mask.
//
// - name: The resource name of the product. Format is:
// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`. This
// field is ignored when creating a product.
func (r *ProjectsLocationsProductsService) Patch(name string, product *Product) *ProjectsLocationsProductsPatchCall {
c := &ProjectsLocationsProductsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
c.product = product
return c
}
// UpdateMask sets the optional parameter "updateMask": The FieldMask
// that specifies which fields to update. If update_mask isn't
// specified, all mutable fields are to be updated. Valid mask paths
// include `product_labels`, `display_name`, and `description`.
func (c *ProjectsLocationsProductsPatchCall) UpdateMask(updateMask string) *ProjectsLocationsProductsPatchCall {
c.urlParams_.Set("updateMask", updateMask)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsProductsPatchCall) Fields(s ...googleapi.Field) *ProjectsLocationsProductsPatchCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsProductsPatchCall) Context(ctx context.Context) *ProjectsLocationsProductsPatchCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsProductsPatchCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsProductsPatchCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.product)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("PATCH", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.projects.locations.products.patch" call.
// Exactly one of *Product or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Product.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsLocationsProductsPatchCall) Do(opts ...googleapi.CallOption) (*Product, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Product{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Makes changes to a Product resource. Only the `display_name`, `description`, and `labels` fields can be updated right now. If labels are updated, the change will not be reflected in queries until the next index time. Possible errors: * Returns NOT_FOUND if the Product does not exist. * Returns INVALID_ARGUMENT if display_name is present in update_mask but is missing from the request or longer than 4096 characters. * Returns INVALID_ARGUMENT if description is present in update_mask but is longer than 4096 characters. * Returns INVALID_ARGUMENT if product_category is present in update_mask.",
// "flatPath": "v1/projects/{projectsId}/locations/{locationsId}/products/{productsId}",
// "httpMethod": "PATCH",
// "id": "vision.projects.locations.products.patch",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "The resource name of the product. Format is: `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`. This field is ignored when creating a product.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/products/[^/]+$",
// "required": true,
// "type": "string"
// },
// "updateMask": {
// "description": "The FieldMask that specifies which fields to update. If update_mask isn't specified, all mutable fields are to be updated. Valid mask paths include `product_labels`, `display_name`, and `description`.",
// "format": "google-fieldmask",
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1/{+name}",
// "request": {
// "$ref": "Product"
// },
// "response": {
// "$ref": "Product"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// method id "vision.projects.locations.products.purge":
type ProjectsLocationsProductsPurgeCall struct {
s *Service
parent string
purgeproductsrequest *PurgeProductsRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Purge: Asynchronous API to delete all Products in a ProductSet or all
// Products that are in no ProductSet. If a Product is a member of the
// specified ProductSet in addition to other ProductSets, the Product
// will still be deleted. It is recommended to not delete the specified
// ProductSet until after this operation has completed. It is also
// recommended to not add any of the Products involved in the batch
// delete to a new ProductSet while this operation is running because
// those Products may still end up deleted. It's not possible to undo
// the PurgeProducts operation. Therefore, it is recommended to keep the
// csv files used in ImportProductSets (if that was how you originally
// built the Product Set) before starting PurgeProducts, in case you
// need to re-import the data after deletion. If the plan is to purge
// all of the Products from a ProductSet and then re-use the empty
// ProductSet to re-import new Products into the empty ProductSet, you
// must wait until the PurgeProducts operation has finished for that
// ProductSet. The google.longrunning.Operation API can be used to keep
// track of the progress and results of the request.
// `Operation.metadata` contains `BatchOperationMetadata`. (progress)
//
// - parent: The project and location in which the Products should be
// deleted. Format is `projects/PROJECT_ID/locations/LOC_ID`.
func (r *ProjectsLocationsProductsService) Purge(parent string, purgeproductsrequest *PurgeProductsRequest) *ProjectsLocationsProductsPurgeCall {
c := &ProjectsLocationsProductsPurgeCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
c.purgeproductsrequest = purgeproductsrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsProductsPurgeCall) Fields(s ...googleapi.Field) *ProjectsLocationsProductsPurgeCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsProductsPurgeCall) Context(ctx context.Context) *ProjectsLocationsProductsPurgeCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsProductsPurgeCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsProductsPurgeCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.purgeproductsrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+parent}/products:purge")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.projects.locations.products.purge" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *ProjectsLocationsProductsPurgeCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Asynchronous API to delete all Products in a ProductSet or all Products that are in no ProductSet. If a Product is a member of the specified ProductSet in addition to other ProductSets, the Product will still be deleted. It is recommended to not delete the specified ProductSet until after this operation has completed. It is also recommended to not add any of the Products involved in the batch delete to a new ProductSet while this operation is running because those Products may still end up deleted. It's not possible to undo the PurgeProducts operation. Therefore, it is recommended to keep the csv files used in ImportProductSets (if that was how you originally built the Product Set) before starting PurgeProducts, in case you need to re-import the data after deletion. If the plan is to purge all of the Products from a ProductSet and then re-use the empty ProductSet to re-import new Products into the empty ProductSet, you must wait until the PurgeProducts operation has finished for that ProductSet. The google.longrunning.Operation API can be used to keep track of the progress and results of the request. `Operation.metadata` contains `BatchOperationMetadata`. (progress)",
// "flatPath": "v1/projects/{projectsId}/locations/{locationsId}/products:purge",
// "httpMethod": "POST",
// "id": "vision.projects.locations.products.purge",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "parent": {
// "description": "Required. The project and location in which the Products should be deleted. Format is `projects/PROJECT_ID/locations/LOC_ID`.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1/{+parent}/products:purge",
// "request": {
// "$ref": "PurgeProductsRequest"
// },
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// method id "vision.projects.locations.products.referenceImages.create":
type ProjectsLocationsProductsReferenceImagesCreateCall struct {
s *Service
parent string
referenceimage *ReferenceImage
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Create: Creates and returns a new ReferenceImage resource. The
// `bounding_poly` field is optional. If `bounding_poly` is not
// specified, the system will try to detect regions of interest in the
// image that are compatible with the product_category on the parent
// product. If it is specified, detection is ALWAYS skipped. The system
// converts polygons into non-rotated rectangles. Note that the pipeline
// will resize the image if the image resolution is too large to process
// (above 50MP). Possible errors: * Returns INVALID_ARGUMENT if the
// image_uri is missing or longer than 4096 characters. * Returns
// INVALID_ARGUMENT if the product does not exist. * Returns
// INVALID_ARGUMENT if bounding_poly is not provided, and nothing
// compatible with the parent product's product_category is detected. *
// Returns INVALID_ARGUMENT if bounding_poly contains more than 10
// polygons.
//
// - parent: Resource name of the product in which to create the
// reference image. Format is
// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`.
func (r *ProjectsLocationsProductsReferenceImagesService) Create(parent string, referenceimage *ReferenceImage) *ProjectsLocationsProductsReferenceImagesCreateCall {
c := &ProjectsLocationsProductsReferenceImagesCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
c.referenceimage = referenceimage
return c
}
// ReferenceImageId sets the optional parameter "referenceImageId": A
// user-supplied resource id for the ReferenceImage to be added. If set,
// the server will attempt to use this value as the resource id. If it
// is already in use, an error is returned with code ALREADY_EXISTS.
// Must be at most 128 characters long. It cannot contain the character
// `/`.
func (c *ProjectsLocationsProductsReferenceImagesCreateCall) ReferenceImageId(referenceImageId string) *ProjectsLocationsProductsReferenceImagesCreateCall {
c.urlParams_.Set("referenceImageId", referenceImageId)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsProductsReferenceImagesCreateCall) Fields(s ...googleapi.Field) *ProjectsLocationsProductsReferenceImagesCreateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsProductsReferenceImagesCreateCall) Context(ctx context.Context) *ProjectsLocationsProductsReferenceImagesCreateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsProductsReferenceImagesCreateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsProductsReferenceImagesCreateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.referenceimage)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+parent}/referenceImages")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.projects.locations.products.referenceImages.create" call.
// Exactly one of *ReferenceImage or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *ReferenceImage.ServerResponse.Header or (if a response was returned
// at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsLocationsProductsReferenceImagesCreateCall) Do(opts ...googleapi.CallOption) (*ReferenceImage, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ReferenceImage{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Creates and returns a new ReferenceImage resource. The `bounding_poly` field is optional. If `bounding_poly` is not specified, the system will try to detect regions of interest in the image that are compatible with the product_category on the parent product. If it is specified, detection is ALWAYS skipped. The system converts polygons into non-rotated rectangles. Note that the pipeline will resize the image if the image resolution is too large to process (above 50MP). Possible errors: * Returns INVALID_ARGUMENT if the image_uri is missing or longer than 4096 characters. * Returns INVALID_ARGUMENT if the product does not exist. * Returns INVALID_ARGUMENT if bounding_poly is not provided, and nothing compatible with the parent product's product_category is detected. * Returns INVALID_ARGUMENT if bounding_poly contains more than 10 polygons.",
// "flatPath": "v1/projects/{projectsId}/locations/{locationsId}/products/{productsId}/referenceImages",
// "httpMethod": "POST",
// "id": "vision.projects.locations.products.referenceImages.create",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "parent": {
// "description": "Required. Resource name of the product in which to create the reference image. Format is `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/products/[^/]+$",
// "required": true,
// "type": "string"
// },
// "referenceImageId": {
// "description": "A user-supplied resource id for the ReferenceImage to be added. If set, the server will attempt to use this value as the resource id. If it is already in use, an error is returned with code ALREADY_EXISTS. Must be at most 128 characters long. It cannot contain the character `/`.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1/{+parent}/referenceImages",
// "request": {
// "$ref": "ReferenceImage"
// },
// "response": {
// "$ref": "ReferenceImage"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// method id "vision.projects.locations.products.referenceImages.delete":
type ProjectsLocationsProductsReferenceImagesDeleteCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Permanently deletes a reference image. The image metadata
// will be deleted right away, but search queries against ProductSets
// containing the image may still work until all related caches are
// refreshed. The actual image files are not deleted from Google Cloud
// Storage.
//
// - name: The resource name of the reference image to delete. Format
// is:
// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceI
// mages/IMAGE_ID`.
func (r *ProjectsLocationsProductsReferenceImagesService) Delete(name string) *ProjectsLocationsProductsReferenceImagesDeleteCall {
c := &ProjectsLocationsProductsReferenceImagesDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsProductsReferenceImagesDeleteCall) Fields(s ...googleapi.Field) *ProjectsLocationsProductsReferenceImagesDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsProductsReferenceImagesDeleteCall) Context(ctx context.Context) *ProjectsLocationsProductsReferenceImagesDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsProductsReferenceImagesDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsProductsReferenceImagesDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("DELETE", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.projects.locations.products.referenceImages.delete" call.
// Exactly one of *Empty or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Empty.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *ProjectsLocationsProductsReferenceImagesDeleteCall) Do(opts ...googleapi.CallOption) (*Empty, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Empty{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Permanently deletes a reference image. The image metadata will be deleted right away, but search queries against ProductSets containing the image may still work until all related caches are refreshed. The actual image files are not deleted from Google Cloud Storage.",
// "flatPath": "v1/projects/{projectsId}/locations/{locationsId}/products/{productsId}/referenceImages/{referenceImagesId}",
// "httpMethod": "DELETE",
// "id": "vision.projects.locations.products.referenceImages.delete",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "Required. The resource name of the reference image to delete. Format is: `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID`",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/products/[^/]+/referenceImages/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1/{+name}",
// "response": {
// "$ref": "Empty"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// method id "vision.projects.locations.products.referenceImages.get":
type ProjectsLocationsProductsReferenceImagesGetCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Gets information associated with a ReferenceImage. Possible
// errors: * Returns NOT_FOUND if the specified image does not exist.
//
// - name: The resource name of the ReferenceImage to get. Format is:
// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceI
// mages/IMAGE_ID`.
func (r *ProjectsLocationsProductsReferenceImagesService) Get(name string) *ProjectsLocationsProductsReferenceImagesGetCall {
c := &ProjectsLocationsProductsReferenceImagesGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsProductsReferenceImagesGetCall) Fields(s ...googleapi.Field) *ProjectsLocationsProductsReferenceImagesGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ProjectsLocationsProductsReferenceImagesGetCall) IfNoneMatch(entityTag string) *ProjectsLocationsProductsReferenceImagesGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsProductsReferenceImagesGetCall) Context(ctx context.Context) *ProjectsLocationsProductsReferenceImagesGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsProductsReferenceImagesGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsProductsReferenceImagesGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.projects.locations.products.referenceImages.get" call.
// Exactly one of *ReferenceImage or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *ReferenceImage.ServerResponse.Header or (if a response was returned
// at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsLocationsProductsReferenceImagesGetCall) Do(opts ...googleapi.CallOption) (*ReferenceImage, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ReferenceImage{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets information associated with a ReferenceImage. Possible errors: * Returns NOT_FOUND if the specified image does not exist.",
// "flatPath": "v1/projects/{projectsId}/locations/{locationsId}/products/{productsId}/referenceImages/{referenceImagesId}",
// "httpMethod": "GET",
// "id": "vision.projects.locations.products.referenceImages.get",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "Required. The resource name of the ReferenceImage to get. Format is: `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID`.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/products/[^/]+/referenceImages/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1/{+name}",
// "response": {
// "$ref": "ReferenceImage"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// method id "vision.projects.locations.products.referenceImages.list":
type ProjectsLocationsProductsReferenceImagesListCall struct {
s *Service
parent string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Lists reference images. Possible errors: * Returns NOT_FOUND if
// the parent product does not exist. * Returns INVALID_ARGUMENT if the
// page_size is greater than 100, or less than 1.
//
// - parent: Resource name of the product containing the reference
// images. Format is
// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`.
func (r *ProjectsLocationsProductsReferenceImagesService) List(parent string) *ProjectsLocationsProductsReferenceImagesListCall {
c := &ProjectsLocationsProductsReferenceImagesListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.parent = parent
return c
}
// PageSize sets the optional parameter "pageSize": The maximum number
// of items to return. Default 10, maximum 100.
func (c *ProjectsLocationsProductsReferenceImagesListCall) PageSize(pageSize int64) *ProjectsLocationsProductsReferenceImagesListCall {
c.urlParams_.Set("pageSize", fmt.Sprint(pageSize))
return c
}
// PageToken sets the optional parameter "pageToken": A token
// identifying a page of results to be returned. This is the value of
// `nextPageToken` returned in a previous reference image list request.
// Defaults to the first page if not specified.
func (c *ProjectsLocationsProductsReferenceImagesListCall) PageToken(pageToken string) *ProjectsLocationsProductsReferenceImagesListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsLocationsProductsReferenceImagesListCall) Fields(s ...googleapi.Field) *ProjectsLocationsProductsReferenceImagesListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ProjectsLocationsProductsReferenceImagesListCall) IfNoneMatch(entityTag string) *ProjectsLocationsProductsReferenceImagesListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsLocationsProductsReferenceImagesListCall) Context(ctx context.Context) *ProjectsLocationsProductsReferenceImagesListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsLocationsProductsReferenceImagesListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsLocationsProductsReferenceImagesListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+parent}/referenceImages")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"parent": c.parent,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.projects.locations.products.referenceImages.list" call.
// Exactly one of *ListReferenceImagesResponse or error will be non-nil.
// Any non-2xx status code is an error. Response headers are in either
// *ListReferenceImagesResponse.ServerResponse.Header or (if a response
// was returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *ProjectsLocationsProductsReferenceImagesListCall) Do(opts ...googleapi.CallOption) (*ListReferenceImagesResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ListReferenceImagesResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Lists reference images. Possible errors: * Returns NOT_FOUND if the parent product does not exist. * Returns INVALID_ARGUMENT if the page_size is greater than 100, or less than 1.",
// "flatPath": "v1/projects/{projectsId}/locations/{locationsId}/products/{productsId}/referenceImages",
// "httpMethod": "GET",
// "id": "vision.projects.locations.products.referenceImages.list",
// "parameterOrder": [
// "parent"
// ],
// "parameters": {
// "pageSize": {
// "description": "The maximum number of items to return. Default 10, maximum 100.",
// "format": "int32",
// "location": "query",
// "type": "integer"
// },
// "pageToken": {
// "description": "A token identifying a page of results to be returned. This is the value of `nextPageToken` returned in a previous reference image list request. Defaults to the first page if not specified.",
// "location": "query",
// "type": "string"
// },
// "parent": {
// "description": "Required. Resource name of the product containing the reference images. Format is `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`.",
// "location": "path",
// "pattern": "^projects/[^/]+/locations/[^/]+/products/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1/{+parent}/referenceImages",
// "response": {
// "$ref": "ListReferenceImagesResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *ProjectsLocationsProductsReferenceImagesListCall) Pages(ctx context.Context, f func(*ListReferenceImagesResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "vision.projects.operations.get":
type ProjectsOperationsGetCall struct {
s *Service
name string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Gets the latest state of a long-running operation. Clients can
// use this method to poll the operation result at intervals as
// recommended by the API service.
//
// - name: The name of the operation resource.
func (r *ProjectsOperationsService) Get(name string) *ProjectsOperationsGetCall {
c := &ProjectsOperationsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.name = name
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *ProjectsOperationsGetCall) Fields(s ...googleapi.Field) *ProjectsOperationsGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *ProjectsOperationsGetCall) IfNoneMatch(entityTag string) *ProjectsOperationsGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *ProjectsOperationsGetCall) Context(ctx context.Context) *ProjectsOperationsGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *ProjectsOperationsGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *ProjectsOperationsGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211128")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1/{+name}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"name": c.name,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "vision.projects.operations.get" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *ProjectsOperationsGetCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service.",
// "flatPath": "v1/projects/{projectsId}/operations/{operationsId}",
// "httpMethod": "GET",
// "id": "vision.projects.operations.get",
// "parameterOrder": [
// "name"
// ],
// "parameters": {
// "name": {
// "description": "The name of the operation resource.",
// "location": "path",
// "pattern": "^projects/[^/]+/operations/[^/]+$",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1/{+name}",
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-vision"
// ]
// }
}
| {
rs := &ProjectsLocationsProductSetsService{s: s}
rs.Products = NewProjectsLocationsProductSetsProductsService(s)
return rs
} |
decoding.py | import abc
import decimal
import io
from typing import (
Any,
)
from eth_utils import (
big_endian_to_int,
to_normalized_address,
to_tuple,
)
from eth_abi.base import (
BaseCoder,
parse_tuple_type_str,
parse_type_str,
)
from eth_abi.exceptions import (
DecodingError,
InsufficientDataBytes,
NonEmptyPaddingBytes,
)
from eth_abi.utils.numeric import (
TEN,
abi_decimal_context,
ceil32,
)
class ContextFramesBytesIO(io.BytesIO):
"""
A byte stream which can track a series of contextual frames in a stack. This
data structure is necessary to perform nested decodings using the
:py:class:``HeadTailDecoder`` since offsets present in head sections are
relative only to a particular encoded object. These offsets can only be
used to locate a position in a decoding stream if they are paired with a
contextual offset that establishes the position of the object in which they
are found.
For example, consider the encoding of a value for the following type::
type: (int,(int,int[]))
value: (1,(2,[3,3]))
There are two tuples in this type: one inner and one outer. The inner tuple
type contains a dynamic type ``int[]`` and, therefore, is itself dynamic.
This means that its value encoding will be placed in the tail section of the
outer tuple's encoding. Furthermore, the inner tuple's encoding will,
itself, contain a tail section with the encoding for ``[3,3]``. All
together, the encoded value of ``(1,(2,[3,3]))`` would look like this (the
data values are normally 32 bytes wide but have been truncated to remove the
redundant zeros at the beginnings of their encodings)::
offset data
--------------------------
^ 0 0x01
| 32 0x40 <-- Offset of object A in global frame (64)
-----|--------------------
Global frame ^ 64 0x02 <-- Beginning of object A (64 w/offset 0 = 64)
| | 96 0x40 <-- Offset of object B in frame of object A (64)
-----|-Object A's frame---
| | 128 0x02 <-- Beginning of object B (64 w/offset 64 = 128)
| | 160 0x03
v v 192 0x03
--------------------------
Note that the offset of object B is encoded as 64 which only specifies the
beginning of its encoded value relative to the beginning of object A's
encoding. Globally, object B is located at offset 128. In order to make
sense out of object B's offset, it needs to be positioned in the context of
its enclosing object's frame (object A).
"""
def __init__(self, *args, **kwargs):
|
def seek_in_frame(self, pos, *args, **kwargs):
"""
Seeks relative to the total offset of the current contextual frames.
"""
self.seek(self._total_offset + pos, *args, **kwargs)
def push_frame(self, offset):
"""
Pushes a new contextual frame onto the stack with the given offset and a
return position at the current cursor position then seeks to the new
total offset.
"""
self._frames.append((offset, self.tell()))
self._total_offset += offset
self.seek_in_frame(0)
def pop_frame(self):
"""
Pops the current contextual frame off of the stack and returns the
cursor to the frame's return position.
"""
try:
offset, return_pos = self._frames.pop()
except IndexError:
raise IndexError('no frames to pop')
self._total_offset -= offset
self.seek(return_pos)
class BaseDecoder(BaseCoder, metaclass=abc.ABCMeta):
"""
Base class for all decoder classes. Subclass this if you want to define a
custom decoder class. Subclasses must also implement
:any:`BaseCoder.from_type_str`.
"""
@abc.abstractmethod
def decode(self, stream: ContextFramesBytesIO) -> Any: # pragma: no cover
"""
Decodes the given stream of bytes into a python value. Should raise
:any:`exceptions.DecodingError` if a python value cannot be decoded
from the given byte stream.
"""
pass
def __call__(self, stream: ContextFramesBytesIO) -> Any:
return self.decode(stream)
class HeadTailDecoder(BaseDecoder):
is_dynamic = True
tail_decoder = None
def validate(self):
super().validate()
if self.tail_decoder is None:
raise ValueError("No `tail_decoder` set")
def decode(self, stream):
start_pos = decode_uint_256(stream)
stream.push_frame(start_pos)
value = self.tail_decoder(stream)
stream.pop_frame()
return value
class TupleDecoder(BaseDecoder):
decoders = None
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.decoders = tuple(
HeadTailDecoder(tail_decoder=d) if getattr(d, 'is_dynamic', False) else d
for d in self.decoders
)
self.is_dynamic = any(getattr(d, 'is_dynamic', False) for d in self.decoders)
def validate(self):
super().validate()
if self.decoders is None:
raise ValueError("No `decoders` set")
@to_tuple
def decode(self, stream):
for decoder in self.decoders:
yield decoder(stream)
@parse_tuple_type_str
def from_type_str(cls, abi_type, registry):
decoders = tuple(
registry.get_decoder(c.to_type_str())
for c in abi_type.components
)
return cls(decoders=decoders)
class SingleDecoder(BaseDecoder):
decoder_fn = None
def validate(self):
super().validate()
if self.decoder_fn is None:
raise ValueError("No `decoder_fn` set")
def validate_padding_bytes(self, value, padding_bytes):
raise NotImplementedError("Must be implemented by subclasses")
def decode(self, stream):
raw_data = self.read_data_from_stream(stream)
data, padding_bytes = self.split_data_and_padding(raw_data)
value = self.decoder_fn(data)
self.validate_padding_bytes(value, padding_bytes)
return value
def read_data_from_stream(self, stream):
raise NotImplementedError("Must be implemented by subclasses")
def split_data_and_padding(self, raw_data):
return raw_data, b''
class BaseArrayDecoder(BaseDecoder):
item_decoder = None
def __init__(self, **kwargs):
super().__init__(**kwargs)
# Use a head-tail decoder to decode dynamic elements
if self.item_decoder.is_dynamic:
self.item_decoder = HeadTailDecoder(
tail_decoder=self.item_decoder,
)
def validate(self):
super().validate()
if self.item_decoder is None:
raise ValueError("No `item_decoder` set")
@parse_type_str(with_arrlist=True)
def from_type_str(cls, abi_type, registry):
item_decoder = registry.get_decoder(abi_type.item_type.to_type_str())
array_spec = abi_type.arrlist[-1]
if len(array_spec) == 1:
# If array dimension is fixed
return SizedArrayDecoder(
array_size=array_spec[0],
item_decoder=item_decoder,
)
else:
# If array dimension is dynamic
return DynamicArrayDecoder(item_decoder=item_decoder)
class SizedArrayDecoder(BaseArrayDecoder):
array_size = None
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.is_dynamic = self.item_decoder.is_dynamic
@to_tuple
def decode(self, stream):
for _ in range(self.array_size):
yield self.item_decoder(stream)
class DynamicArrayDecoder(BaseArrayDecoder):
# Dynamic arrays are always dynamic, regardless of their elements
is_dynamic = True
@to_tuple
def decode(self, stream):
array_size = decode_uint_256(stream)
stream.push_frame(32)
for _ in range(array_size):
yield self.item_decoder(stream)
stream.pop_frame()
class FixedByteSizeDecoder(SingleDecoder):
decoder_fn = None
value_bit_size = None
data_byte_size = None
is_big_endian = None
def validate(self):
super().validate()
if self.value_bit_size is None:
raise ValueError("`value_bit_size` may not be None")
if self.data_byte_size is None:
raise ValueError("`data_byte_size` may not be None")
if self.decoder_fn is None:
raise ValueError("`decoder_fn` may not be None")
if self.is_big_endian is None:
raise ValueError("`is_big_endian` may not be None")
if self.value_bit_size % 8 != 0:
raise ValueError(
"Invalid value bit size: {0}. Must be a multiple of 8".format(
self.value_bit_size,
)
)
if self.value_bit_size > self.data_byte_size * 8:
raise ValueError("Value byte size exceeds data size")
def read_data_from_stream(self, stream):
data = stream.read(self.data_byte_size)
if len(data) != self.data_byte_size:
raise InsufficientDataBytes(
"Tried to read {0} bytes. Only got {1} bytes".format(
self.data_byte_size,
len(data),
)
)
return data
def split_data_and_padding(self, raw_data):
value_byte_size = self._get_value_byte_size()
padding_size = self.data_byte_size - value_byte_size
if self.is_big_endian:
padding_bytes = raw_data[:padding_size]
data = raw_data[padding_size:]
else:
data = raw_data[:value_byte_size]
padding_bytes = raw_data[value_byte_size:]
return data, padding_bytes
def validate_padding_bytes(self, value, padding_bytes):
value_byte_size = self._get_value_byte_size()
padding_size = self.data_byte_size - value_byte_size
if padding_bytes != b'\x00' * padding_size:
raise NonEmptyPaddingBytes(
"Padding bytes were not empty: {0}".format(repr(padding_bytes))
)
def _get_value_byte_size(self):
value_byte_size = self.value_bit_size // 8
return value_byte_size
class Fixed32ByteSizeDecoder(FixedByteSizeDecoder):
data_byte_size = 32
class BooleanDecoder(Fixed32ByteSizeDecoder):
value_bit_size = 8
is_big_endian = True
@staticmethod
def decoder_fn(data):
if data == b'\x00':
return False
elif data == b'\x01':
return True
else:
raise NonEmptyPaddingBytes(
"Boolean must be either 0x0 or 0x1. Got: {0}".format(repr(data))
)
@parse_type_str('bool')
def from_type_str(cls, abi_type, registry):
return cls()
class AddressDecoder(Fixed32ByteSizeDecoder):
value_bit_size = 20 * 8
is_big_endian = True
decoder_fn = staticmethod(to_normalized_address)
@parse_type_str('address')
def from_type_str(cls, abi_type, registry):
return cls()
#
# Unsigned Integer Decoders
#
class UnsignedIntegerDecoder(Fixed32ByteSizeDecoder):
decoder_fn = staticmethod(big_endian_to_int)
is_big_endian = True
@parse_type_str('uint')
def from_type_str(cls, abi_type, registry):
return cls(value_bit_size=abi_type.sub)
decode_uint_256 = UnsignedIntegerDecoder(value_bit_size=256)
#
# Signed Integer Decoders
#
class SignedIntegerDecoder(Fixed32ByteSizeDecoder):
is_big_endian = True
def decoder_fn(self, data):
value = big_endian_to_int(data)
if value >= 2 ** (self.value_bit_size - 1):
return value - 2 ** self.value_bit_size
else:
return value
def validate_padding_bytes(self, value, padding_bytes):
value_byte_size = self._get_value_byte_size()
padding_size = self.data_byte_size - value_byte_size
if value >= 0:
expected_padding_bytes = b'\x00' * padding_size
else:
expected_padding_bytes = b'\xff' * padding_size
if padding_bytes != expected_padding_bytes:
raise NonEmptyPaddingBytes(
"Padding bytes were not empty: {0}".format(repr(padding_bytes))
)
@parse_type_str('int')
def from_type_str(cls, abi_type, registry):
return cls(value_bit_size=abi_type.sub)
#
# Bytes1..32
#
class BytesDecoder(Fixed32ByteSizeDecoder):
is_big_endian = False
@staticmethod
def decoder_fn(data):
return data
@parse_type_str('bytes')
def from_type_str(cls, abi_type, registry):
return cls(value_bit_size=abi_type.sub * 8)
class BaseFixedDecoder(Fixed32ByteSizeDecoder):
frac_places = None
is_big_endian = True
def validate(self):
super().validate()
if self.frac_places is None:
raise ValueError("must specify `frac_places`")
if self.frac_places <= 0 or self.frac_places > 80:
raise ValueError("`frac_places` must be in range (0, 80]")
class UnsignedFixedDecoder(BaseFixedDecoder):
def decoder_fn(self, data):
value = big_endian_to_int(data)
with decimal.localcontext(abi_decimal_context):
decimal_value = decimal.Decimal(value) / TEN ** self.frac_places
return decimal_value
@parse_type_str('ufixed')
def from_type_str(cls, abi_type, registry):
value_bit_size, frac_places = abi_type.sub
return cls(value_bit_size=value_bit_size, frac_places=frac_places)
class SignedFixedDecoder(BaseFixedDecoder):
def decoder_fn(self, data):
value = big_endian_to_int(data)
if value >= 2 ** (self.value_bit_size - 1):
signed_value = value - 2 ** self.value_bit_size
else:
signed_value = value
with decimal.localcontext(abi_decimal_context):
decimal_value = decimal.Decimal(signed_value) / TEN ** self.frac_places
return decimal_value
def validate_padding_bytes(self, value, padding_bytes):
value_byte_size = self._get_value_byte_size()
padding_size = self.data_byte_size - value_byte_size
if value >= 0:
expected_padding_bytes = b'\x00' * padding_size
else:
expected_padding_bytes = b'\xff' * padding_size
if padding_bytes != expected_padding_bytes:
raise NonEmptyPaddingBytes(
"Padding bytes were not empty: {0}".format(repr(padding_bytes))
)
@parse_type_str('fixed')
def from_type_str(cls, abi_type, registry):
value_bit_size, frac_places = abi_type.sub
return cls(value_bit_size=value_bit_size, frac_places=frac_places)
#
# String and Bytes
#
class ByteStringDecoder(SingleDecoder):
is_dynamic = True
@staticmethod
def decoder_fn(data):
return data
@staticmethod
def read_data_from_stream(stream):
data_length = decode_uint_256(stream)
padded_length = ceil32(data_length)
data = stream.read(padded_length)
if len(data) < padded_length:
raise InsufficientDataBytes(
"Tried to read {0} bytes. Only got {1} bytes".format(
padded_length,
len(data),
)
)
padding_bytes = data[data_length:]
if padding_bytes != b'\x00' * (padded_length - data_length):
raise NonEmptyPaddingBytes(
"Padding bytes were not empty: {0}".format(repr(padding_bytes))
)
return data[:data_length]
def validate_padding_bytes(self, value, padding_bytes):
pass
@parse_type_str('bytes')
def from_type_str(cls, abi_type, registry):
return cls()
class StringDecoder(ByteStringDecoder):
@parse_type_str('string')
def from_type_str(cls, abi_type, registry):
return cls()
@staticmethod
def decoder_fn(data):
try:
value = data.decode("utf-8")
except UnicodeDecodeError as e:
raise DecodingError(
e.encoding,
e.object,
e.start,
e.end,
"The returned type for this function is string which is "
"expected to be a UTF8 encoded string of text. The returned "
"value could not be decoded as valid UTF8. This is indicative "
"of a broken application which is using incorrect return types for "
"binary data.") from e
return value
| super().__init__(*args, **kwargs)
self._frames = []
self._total_offset = 0 |
paramiko_expect.py | #
# Paramiko Expect
#
# Written by Fotis Gimian
# http://github.com/fgimian
#
# This library works with a Paramiko SSH channel to provide native SSH
# expect-like handling for servers. The library may be used to interact
# with commands like 'configure' or Cisco IOS devices or with interactive
# Unix scripts or commands.
#
# You must have Paramiko installed in order to use this library.
#
from __future__ import unicode_literals
import codecs
import sys
import re
import socket
import struct
import time
# Windows does not have termios
try:
import termios
import tty
has_termios = True
MAX_TIMEOUT = 2 ** (struct.Struct(str('i')).size * 8 - 1) - 1
except ImportError: # pragma: no cover
import threading
has_termios = False
MAX_TIMEOUT = threading.TIMEOUT_MAX
import select
def strip_ansi_codes(s):
return re.sub(r'\x1b\[([0-9,A-Z]{1,2}(;[0-9]{1,2})?(;[0-9]{3})?)?[m|K]?|\?(1049|2004)[hl]', '', s)
def default_output_func(msg):
sys.stdout.write(msg)
sys.stdout.flush()
class | (object):
"""
This class allows an expect-like interface to Paramiko which allows
coders to interact with applications and the shell of the connected
device.
:param client: A Paramiko SSHClient object
:param timeout: The connection timeout in seconds
:param newline: The newline character to send after each command
:param buffer_size: The amount of data (in bytes) that will be read at
a time after a command is run
:param display: Whether or not the output should be displayed in
real-time as it is being performed (especially useful
when debugging)
:param encoding: The character encoding to use.
:param lines_to_check: The number of last few lines of the output to
look at, while matching regular expression(s)
"""
def __init__(
self, client, timeout=60, newline='\r', buffer_size=1024,
display=False, encoding='utf-8', output_callback=default_output_func,
tty_width=80, tty_height=24, lines_to_check=1
):
self.channel = client.invoke_shell(width=tty_width, height=tty_height)
self.timeout = timeout
self.newline = newline
self.buffer_size = buffer_size
self.display = display
self.encoding = encoding
self.output_callback = output_callback
self.lines_to_check = lines_to_check
self.current_output = ''
self.current_output_clean = ''
self.current_send_string = ''
self.last_match = ''
# If the output is long, multi-byte encoded characters may be split
# across calls to recv, so decode incrementally.
self.decoder = codecs.getincrementaldecoder(self.encoding)()
def __del__(self):
self.close()
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.close()
def close(self):
"""Attempts to close the channel for clean completion."""
try:
self.channel.close()
except Exception:
pass
def expect(
self, re_strings='', timeout=None, output_callback=None, default_match_prefix='.*\n',
strip_ansi=True, ignore_decode_error=True, lines_to_check=None
):
"""
This function takes in a regular expression (or regular expressions)
that represent the last line of output from the server. The function
waits for one or more of the terms to be matched. The regexes are
matched using expression \n<regex>$ so you'll need to provide an
easygoing regex such as '.*server.*' if you wish to have a fuzzy
match.
:param re_strings: Either a regex string or list of regex strings
that we should expect; if this is not specified,
then EOF is expected (i.e. the shell is completely
closed after the exit command is issued)
:param timeout: Timeout in seconds. If this timeout is exceeded,
then an exception is raised.
:param output_callback: A function used to print ssh output. Printed to stdout
by default. A user-defined logger may be passed like
output_callback=lambda m: mylog.debug(m)
:param default_match_prefix: A prefix to all match regexes, defaults to '.*\n',
can set to '' on cases prompt is the first line,
or the command has no output.
:param strip_ansi: If True, will strip ansi control chars befores regex matching
default to True.
:param ignore_decode_error: If True, will ignore decode errors if any.
default to True.
:param lines_to_check: The number of last few lines of the output to
look at, while matching regular expression(s)
:return: An EOF returns -1, a regex metch returns 0 and a match in a
list of regexes returns the index of the matched string in
the list.
:raises: A socket.timeout exception is raised on timeout.
"""
output_callback = output_callback if output_callback else self.output_callback
# Set the channel timeout
timeout = timeout if timeout else self.timeout
self.channel.settimeout(timeout)
lines_to_check = lines_to_check if lines_to_check else self.lines_to_check
if ignore_decode_error:
self.decoder = codecs.getincrementaldecoder(self.encoding)('ignore')
# Create an empty output buffer
self.current_output = ''
# saves the current buffer to check for re_strings pattern
current_buffer_output_decoded = ''
# This function needs all regular expressions to be in the form of a
# list, so if the user provided a string, let's convert it to a 1
# item list.
if isinstance(re_strings, str) and len(re_strings) != 0:
re_strings = [re_strings]
# to avoid looping in recv_ready()
base_time = time.time()
# Loop until one of the expressions is matched or loop forever if
# nothing is expected (usually used for exit)
while (
len(re_strings) == 0 or
not [re_string
for re_string in re_strings
if re.match(default_match_prefix + re_string + '$',
current_buffer_output_decoded, re.DOTALL)]
):
current_buffer_output_decoded = ''
# avoids paramiko hang when recv is not ready yet
while not self.channel.recv_ready():
time.sleep(.009)
if time.time() >= (base_time + timeout):
print('EXCESS TIME RECV_READY TIMEOUT, did you expect() before a send()')
return -1
# Read some of the output
current_buffer = self.channel.recv(self.buffer_size)
# If we have an empty buffer, then the SSH session has been closed
if len(current_buffer) == 0:
break
# Convert the buffer to our chosen encoding
current_buffer_decoded = self.decoder.decode(current_buffer)
# Strip all ugly \r (Ctrl-M making) characters from the current
# read
current_buffer_decoded = current_buffer_decoded.replace('\r', '')
# Display the current buffer in realtime if requested to do so
# (good for debugging purposes)
if strip_ansi:
current_buffer_decoded = strip_ansi_codes(current_buffer_decoded)
if not current_buffer_decoded:
continue
if self.display:
output_callback(current_buffer_decoded)
# Add the currently read buffer to the output
self.current_output += current_buffer_decoded
current_buffer_output_decoded = '\n' + '\n'.join(self.current_output.splitlines()[-lines_to_check:])
# Grab the first pattern that was matched
if len(re_strings) != 0:
found_pattern = [(re_index, re_string)
for re_index, re_string in enumerate(re_strings)
if re.match(default_match_prefix + re_string + '$',
self.current_output, re.DOTALL)]
# Clean the output up by removing the sent command
self.current_output_clean = self.current_output
if len(self.current_send_string) != 0:
self.current_output_clean = (
self.current_output_clean.replace(
self.current_send_string + self.newline, ''
)
)
# Reset the current send string to ensure that multiple expect calls
# don't result in bad output cleaning
self.current_send_string = ''
# Clean the output up by removing the expect output from the end if
# requested and save the details of the matched pattern
if len(re_strings) != 0 and len(found_pattern) != 0:
self.current_output_clean = (
re.sub(
found_pattern[0][1] + '$', '', self.current_output_clean
)
)
self.last_match = found_pattern[0][1]
return found_pattern[0][0]
else:
# We would socket timeout before getting here, but for good
# measure, let's send back a -1
return -1
def send(self, send_string, newline=None):
"""Saves and sends the send string provided."""
self.current_send_string = send_string
# send_string, _ = codecs.getdecoder(self.encoding)(send_string)
newline = newline if newline is not None else self.newline
# don't send till send_ready
while not self.channel.send_ready():
time.sleep(.009)
self.channel.send(send_string)
self.channel.send(newline)
def tail(
self, line_prefix=None, callback=None, output_callback=None, stop_callback=lambda x: False,
timeout=None
):
"""
This function takes control of an SSH channel and displays line
by line of output as \n is recieved. This function is specifically
made for tail-like commands.
:param line_prefix: Text to append to the left of each line of output.
This is especially useful if you are using my
MultiSSH class to run tail commands over multiple
servers.
:param callback: You may optionally supply a callback function which
takes two paramaters. The first is the line prefix
and the second is current line of output. The
callback should return the string that is to be
displayed (including the \n character). This allows
users to grep the output or manipulate it as
required.
:param output_callback: A function used to print ssh output. Printed to stdout
by default. A user-defined logger may be passed like
output_callback=lambda m: mylog.debug(m)
:param stop_callback: A function usesd to stop the tail, when function retruns
True tail will stop, by default stop_callback=lambda x: False
:param timeout: how much time to wait for data, default to None which
mean almost forever.
"""
output_callback = output_callback if output_callback else self.output_callback
# Set the channel timeout to the maximum allowed value,
# setting this to None breaks the KeyboardInterrupt exception and
# won't allow us to Ctrl+C out of the script
timeout = timeout if timeout else MAX_TIMEOUT
self.channel.settimeout(timeout)
# Create an empty line buffer and a line counter
current_line = b''
line_counter = 0
line_feed_byte = '\n'.encode(self.encoding)
# Loop forever, Ctrl+C (KeyboardInterrupt) is used to break the tail
while True:
# Read the output one byte at a time so we can detect \n correctly
buffer = self.channel.recv(1)
# If we have an empty buffer, then the SSH session has been closed
if len(buffer) == 0:
break
# Add the currently read buffer to the current line output
current_line += buffer
# Display the last read line in realtime when we reach a \n
# character
if buffer == line_feed_byte:
current_line_decoded = self.decoder.decode(current_line)
if line_counter:
if callback:
output_callback(callback(line_prefix, current_line_decoded))
else:
if line_prefix:
output_callback(line_prefix)
output_callback(current_line_decoded)
if stop_callback(current_line_decoded):
break
line_counter += 1
current_line = b''
def take_control(self):
"""
This function is a better documented and touched up version of the
posix_shell function found in the interactive.py demo script that
ships with Paramiko.
"""
if has_termios:
# Get attributes of the shell you were in before going to the
# new one
original_tty = termios.tcgetattr(sys.stdin)
try:
tty.setraw(sys.stdin.fileno())
tty.setcbreak(sys.stdin.fileno())
# We must set the timeout to 0 so that we can bypass times when
# there is no available text to receive
self.channel.settimeout(0)
# Loop forever until the user exits (i.e. read buffer is empty)
while True:
select_read, select_write, select_exception = (
select.select([self.channel, sys.stdin], [], [])
)
# Read any output from the terminal and print it to the
# screen. With timeout set to 0, we just can ignore times
# when there's nothing to receive.
if self.channel in select_read:
try:
buffer = self.channel.recv(self.buffer_size)
if len(buffer) == 0:
break
sys.stdout.write(self.decoder.decode(buffer))
sys.stdout.flush()
except socket.timeout:
pass
# Send any keyboard input to the terminal one byte at a
# time
if sys.stdin in select_read:
buffer = sys.stdin.read(1)
if len(buffer) == 0:
break
self.channel.send(buffer)
finally:
# Restore the attributes of the shell you were in
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, original_tty)
else:
def writeall(sock):
while True:
buffer = sock.recv(self.buffer_size)
if len(buffer) == 0:
break
sys.stdout.write(self.decoder.decode(buffer))
sys.stdout.flush()
writer = threading.Thread(target=writeall, args=(self.channel,))
writer.start()
try:
while True:
buffer = sys.stdin.read(1)
if len(buffer) == 0:
break
self.channel.send(buffer)
# User has hit Ctrl+Z or F6
except EOFError:
pass
| SSHClientInteraction |
demo.go | package main
import (
"errors"
"fmt"
"math"
)
func main() {
_, err := IntFromInt64(math.MaxInt32 + 1)
if err != nil {
fmt.Println(err)
}
}
func ConvertInt64ToInt(i64 int64) int {
if math.MinInt32 <= i64 && i64 <= math.MaxInt32 {
return int(i64)
}
panic("can't convert int64 to int")
}
func IntFromInt64(i64 int64) (i int, err error) | {//这里
defer func() {
if err2 := recover(); err2 != nil {
i = 0//这里
err = errors.New("ttt")//这里
}
}()
i = ConvertInt64ToInt(i64)
return i, nil
}
|
|
vtrace_test.py | # Copyright 2018 Google LLC
#
# 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
#
# https://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.
"""Tests for V-trace.
For details and theory see:
"IMPALA: Scalable Distributed Deep-RL with
Importance Weighted Actor-Learner Architectures"
by Espeholt, Soyer, Munos et al.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
import numpy as np
import tensorflow as tf
import vtrace
def _shaped_arange(*shape):
"""Runs np.arange, converts to float and reshapes."""
return np.arange(np.prod(shape), dtype=np.float32).reshape(*shape)
def _softmax(logits):
"""Applies softmax non-linearity on inputs."""
return np.exp(logits) / np.sum(np.exp(logits), axis=-1, keepdims=True)
def _ground_truth_calculation(discounts, log_rhos, rewards, values,
bootstrap_value, clip_rho_threshold,
clip_pg_rho_threshold):
"""Calculates the ground truth for V-trace in Python/Numpy."""
vs = []
seq_len = len(discounts)
rhos = np.exp(log_rhos)
cs = np.minimum(rhos, 1.0)
clipped_rhos = rhos
if clip_rho_threshold:
clipped_rhos = np.minimum(rhos, clip_rho_threshold)
clipped_pg_rhos = rhos
if clip_pg_rho_threshold:
clipped_pg_rhos = np.minimum(rhos, clip_pg_rho_threshold)
# This is a very inefficient way to calculate the V-trace ground truth.
# We calculate it this way because it is close to the mathematical notation
# of
# V-trace.
# v_s = V(x_s)
# + \sum^{T-1}_{t=s} \gamma^{t-s}
# * \prod_{i=s}^{t-1} c_i
# * \rho_t (r_t + \gamma V(x_{t+1}) - V(x_t))
# Note that when we take the product over c_i, we write `s:t` as the
# notation
# of the paper is inclusive of the `t-1`, but Python is exclusive.
# Also note that np.prod([]) == 1.
values_t_plus_1 = np.concatenate(
[values, bootstrap_value[None, :]], axis=0)
for s in range(seq_len):
v_s = np.copy(values[s]) # Very important copy.
for t in range(s, seq_len):
v_s += (np.prod(discounts[s:t], axis=0) * np.prod(cs[s:t], axis=0)
* clipped_rhos[t] * (rewards[t] + discounts[t] *
values_t_plus_1[t + 1] - values[t]))
vs.append(v_s)
vs = np.stack(vs, axis=0)
pg_advantages = (clipped_pg_rhos * (rewards + discounts * np.concatenate(
[vs[1:], bootstrap_value[None, :]], axis=0) - values))
return vtrace.VTraceReturns(vs=vs, pg_advantages=pg_advantages)
class LogProbsFromLogitsAndActionsTest(tf.test.TestCase,
parameterized.TestCase):
@parameterized.named_parameters(('Batch1', 1), ('Batch2', 2))
def test_log_probs_from_logits_and_actions(self, batch_size):
"""Tests log_probs_from_logits_and_actions."""
seq_len = 7
num_actions = 3
policy_logits = _shaped_arange(seq_len, batch_size, num_actions) + 10 | action_log_probs_tensor = vtrace.log_probs_from_logits_and_actions(
policy_logits, actions)
# Ground Truth
# Using broadcasting to create a mask that indexes action logits
action_index_mask = actions[..., None] == np.arange(num_actions)
def index_with_mask(array, mask):
return array[mask].reshape(*array.shape[:-1])
# Note: Normally log(softmax) is not a good idea because it's not
# numerically stable. However, in this test we have well-behaved
# values.
ground_truth_v = index_with_mask(
np.log(_softmax(policy_logits)), action_index_mask)
with self.test_session() as session:
self.assertAllClose(ground_truth_v,
session.run(action_log_probs_tensor))
class VtraceTest(tf.test.TestCase, parameterized.TestCase):
@parameterized.named_parameters(('Batch1', 1), ('Batch5', 5))
def test_vtrace(self, batch_size):
"""Tests V-trace against ground truth data calculated in python."""
seq_len = 5
# Create log_rhos such that rho will span from near-zero to above the
# clipping thresholds. In particular, calculate log_rhos in
# [-2.5, 2.5),
# so that rho is in approx [0.08, 12.2).
log_rhos = _shaped_arange(seq_len, batch_size) / (batch_size * seq_len)
log_rhos = 5 * (log_rhos - 0.5) # [0.0, 1.0) -> [-2.5, 2.5).
values = {
'log_rhos': log_rhos,
# T, B where B_i: [0.9 / (i+1)] * T
'discounts': np.array([[0.9 / (b + 1) for b in range(batch_size)]
for _ in range(seq_len)]),
'rewards': _shaped_arange(seq_len, batch_size),
'values': _shaped_arange(seq_len, batch_size) / batch_size,
'bootstrap_value': _shaped_arange(batch_size) + 1.0,
'clip_rho_threshold': 3.7,
'clip_pg_rho_threshold': 2.2,
}
output = vtrace.from_importance_weights(**values)
with self.test_session() as session:
output_v = session.run(output)
ground_truth_v = _ground_truth_calculation(**values)
for a, b in zip(ground_truth_v, output_v):
self.assertAllClose(a, b)
@parameterized.named_parameters(('Batch1', 1), ('Batch2', 2))
def test_vtrace_from_logits(self, batch_size):
"""Tests V-trace calculated from logits."""
seq_len = 5
num_actions = 3
clip_rho_threshold = None # No clipping.
clip_pg_rho_threshold = None # No clipping.
# Intentionally leaving shapes unspecified to test if V-trace can
# deal with that.
placeholders = {
# T, B, NUM_ACTIONS
'behaviour_policy_logits': tf.placeholder(
dtype=tf.float32, shape=[None, None, None]),
# T, B, NUM_ACTIONS
'target_policy_logits': tf.placeholder(
dtype=tf.float32, shape=[None, None, None]),
'actions': tf.placeholder(dtype=tf.int32, shape=[None, None]),
'discounts': tf.placeholder(dtype=tf.float32, shape=[None, None]),
'rewards': tf.placeholder(dtype=tf.float32, shape=[None, None]),
'values': tf.placeholder(dtype=tf.float32, shape=[None, None]),
'bootstrap_value': tf.placeholder(dtype=tf.float32, shape=[None]),
}
from_logits_output = vtrace.from_logits(
clip_rho_threshold=clip_rho_threshold,
clip_pg_rho_threshold=clip_pg_rho_threshold,
**placeholders)
target_log_probs = vtrace.log_probs_from_logits_and_actions(
placeholders['target_policy_logits'], placeholders['actions'])
behaviour_log_probs = vtrace.log_probs_from_logits_and_actions(
placeholders['behaviour_policy_logits'], placeholders['actions'])
log_rhos = target_log_probs - behaviour_log_probs
ground_truth = (log_rhos, behaviour_log_probs, target_log_probs)
values = {
'behaviour_policy_logits': _shaped_arange(seq_len, batch_size,
num_actions),
'target_policy_logits': _shaped_arange(seq_len, batch_size,
num_actions),
'actions': np.random.randint(
0, num_actions - 1, size=(seq_len, batch_size)),
'discounts': np.array( # T, B where B_i: [0.9 / (i+1)] * T
[[0.9 / (b + 1) for b in range(batch_size)]
for _ in range(seq_len)]),
'rewards': _shaped_arange(seq_len, batch_size),
'values': _shaped_arange(seq_len, batch_size) / batch_size,
'bootstrap_value': _shaped_arange(batch_size) + 1.0, # B
}
feed_dict = {placeholders[k]: v for k, v in values.items()}
with self.test_session() as session:
from_logits_output_v = session.run(
from_logits_output, feed_dict=feed_dict)
(ground_truth_log_rhos, ground_truth_behaviour_action_log_probs,
ground_truth_target_action_log_probs) = session.run(
ground_truth, feed_dict=feed_dict)
# Calculate V-trace using the ground truth logits.
from_iw = vtrace.from_importance_weights(
log_rhos=ground_truth_log_rhos,
discounts=values['discounts'],
rewards=values['rewards'],
values=values['values'],
bootstrap_value=values['bootstrap_value'],
clip_rho_threshold=clip_rho_threshold,
clip_pg_rho_threshold=clip_pg_rho_threshold)
with self.test_session() as session:
from_iw_v = session.run(from_iw)
self.assertAllClose(from_iw_v.vs, from_logits_output_v.vs)
self.assertAllClose(from_iw_v.pg_advantages,
from_logits_output_v.pg_advantages)
self.assertAllClose(ground_truth_behaviour_action_log_probs,
from_logits_output_v.behaviour_action_log_probs)
self.assertAllClose(ground_truth_target_action_log_probs,
from_logits_output_v.target_action_log_probs)
self.assertAllClose(ground_truth_log_rhos,
from_logits_output_v.log_rhos)
def test_higher_rank_inputs_for_importance_weights(self):
"""Checks support for additional dimensions in inputs."""
placeholders = {
'log_rhos': tf.placeholder(
dtype=tf.float32, shape=[None, None, 1]),
'discounts': tf.placeholder(
dtype=tf.float32, shape=[None, None, 1]),
'rewards': tf.placeholder(
dtype=tf.float32, shape=[None, None, 42]),
'values': tf.placeholder(dtype=tf.float32, shape=[None, None, 42]),
'bootstrap_value': tf.placeholder(
dtype=tf.float32, shape=[None, 42])
}
output = vtrace.from_importance_weights(**placeholders)
self.assertEqual(output.vs.shape.as_list()[-1], 42)
def test_inconsistent_rank_inputs_for_importance_weights(self):
"""Test one of many possible errors in shape of inputs."""
placeholders = {
'log_rhos': tf.placeholder(
dtype=tf.float32, shape=[None, None, 1]),
'discounts': tf.placeholder(
dtype=tf.float32, shape=[None, None, 1]),
'rewards': tf.placeholder(
dtype=tf.float32, shape=[None, None, 42]),
'values': tf.placeholder(dtype=tf.float32, shape=[None, None, 42]),
# Should be [None, 42].
'bootstrap_value': tf.placeholder(dtype=tf.float32, shape=[None])
}
with self.assertRaisesRegexp(ValueError, 'must have rank 2'):
vtrace.from_importance_weights(**placeholders)
if __name__ == '__main__':
tf.test.main() | actions = np.random.randint(
0, num_actions - 1, size=(seq_len, batch_size), dtype=np.int32)
|
test_cli.py | # -*- coding: utf-8 -*- | ----------------------------------
Tests for `cli` module.
"""
# thirdparty libraies
import pytest
# This package
from ar_too import cli
class TestCli:
def test_cli(self, cli_runner):
result = cli_runner.invoke(cli.cli, ['--help'])
assert result.exit_code == 0
assert result.output.startswith('Usage:') |
"""
test_cli |
skills.js | /* Skill Bar */
function | (dataElement, barElement, cssProperty, barPercent) {
var listData = [];
$(dataElement).each(function() {
listData.push($(this).html());
});
var listMax = Math.max.apply(Math, listData);
$(barElement).each(function(index) {
$(this).css(cssProperty, (listData[index] / listMax) * barPercent + "%");
});
}
setBarWidth(".style-1 span", ".style-1 em", "width", 142);
/*Zoom prevent*/
$(document).keydown(function(event) {
if (event.ctrlKey==true && (event.which == '61' || event.which == '107' || event.which == '173' || event.which == '109' || event.which == '187' || event.which == '189' ) ) {
event.preventDefault();
}
});
$(window).bind('mousewheel DOMMouseScroll', function (event) {
if (event.ctrlKey == true) {
event.preventDefault();
}
}); | setBarWidth |
client_test.go | // Copyright 2019 eBay Inc.
// Primary authors: Simon Fell, Diego Ongaro,
// Raymond Kroeker, and Sathish Kandasamy.
//
// 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
// https://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 logspecclient
import (
"context"
"strings"
"testing"
"time"
"github.com/ebay/beam/blog"
"github.com/ebay/beam/discovery"
"github.com/ebay/beam/logspec"
"github.com/ebay/beam/util/parallel"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc/connectivity"
)
// Ensures that Log satisfies the intended interfaces.
var (
_ blog.BeamLog = (*Log)(nil)
_ blog.Disconnector = (*Log)(nil)
)
func TestDiscard_success(t *testing.T) {
test := func(mode string) func(t *testing.T) {
return func(t *testing.T) {
assert := assert.New(t)
server, log, cleanup := setup(t)
defer cleanup()
switch mode {
case "ok":
case "redirect":
server.startClock()
server.next.redirect = 3
case "unknown":
server.startClock()
server.next.unknown = true
}
err := log.Discard(context.Background(), 3)
require.NoError(t, err)
assert.Equal(uint64(3), server.startIndex)
assert.Equal(0, server.next.redirect)
assert.False(server.next.unknown)
}
}
t.Run("ok", test("ok"))
t.Run("redirect", test("redirect"))
t.Run("unknown", test("unknown"))
}
func TestDiscard_expired(t *testing.T) {
assert := assert.New(t)
server, log, cleanup := setup(t)
defer cleanup()
ctx, cancel := context.WithCancel(context.Background())
cancel()
err := log.Discard(ctx, 3)
assert.Equal(ctx.Err(), err)
assert.Equal(uint64(1), server.startIndex)
}
func TestDiscard_closed(t *testing.T) {
assert := assert.New(t)
server, log, cleanup := setup(t)
cleanup()
err := log.Discard(context.Background(), 3)
assert.True(blog.IsClosedError(err))
assert.Equal(uint64(1), server.startIndex)
}
func TestRead_success(t *testing.T) {
test := func(mode string) func(t *testing.T) {
return func(t *testing.T) {
assert := assert.New(t)
server, log, cleanup := setup(t)
defer cleanup()
server.append([][]byte{[]byte("hello"), []byte("world")})
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
entriesCh := make(chan []blog.Entry)
switch mode {
case "ok":
case "redirect":
server.startClock()
server.next.redirect = 3
case "unknown":
server.startClock()
server.next.unknown = true
}
var allEntries []blog.Entry
wait := parallel.Go(func() {
for entries := range entriesCh {
allEntries = append(allEntries, entries...)
if len(allEntries) >= 2 {
cancel()
}
}
})
err := log.Read(ctx, 1, entriesCh)
wait()
assert.Error(ctx.Err())
assert.Equal(ctx.Err(), err)
if assert.Len(allEntries, 2) {
assert.Equal(blog.Index(1), allEntries[0].Index)
assert.Equal("hello", string(allEntries[0].Data))
assert.False(allEntries[0].Skip)
assert.Equal(blog.Index(2), allEntries[1].Index)
assert.Equal("world", string(allEntries[1].Data))
assert.False(allEntries[1].Skip)
}
assert.Equal(0, server.next.redirect)
assert.False(server.next.unknown)
}
}
t.Run("ok", test("ok"))
t.Run("redirect", test("redirect"))
t.Run("unknown", test("unknown"))
}
func TestRead_truncated(t *testing.T) {
assert := assert.New(t)
server, log, cleanup := setup(t)
defer cleanup()
server.append([][]byte{[]byte("hello"), []byte("world")})
entriesCh := make(chan []blog.Entry, 4)
err := log.Read(context.Background(), 0, entriesCh)
assert.True(blog.IsTruncatedError(err))
}
func TestRead_expired(t *testing.T) {
assert := assert.New(t)
server, log, cleanup := setup(t)
defer cleanup()
ctx, cancel := context.WithCancel(context.Background())
cancel()
server.append([][]byte{[]byte("hello"), []byte("world")})
entriesCh := make(chan []blog.Entry, 4)
err := log.Read(ctx, 1, entriesCh)
assert.Equal(ctx.Err(), err)
}
func TestRead_closed(t *testing.T) {
assert := assert.New(t)
server, log, cleanup := setup(t)
server.append([][]byte{[]byte("hello"), []byte("world")})
cleanup()
entriesCh := make(chan []blog.Entry, 4)
err := log.Read(context.Background(), 1, entriesCh)
assert.True(blog.IsClosedError(err))
}
func TestRead_closedMidstream(t *testing.T) {
assert := assert.New(t)
server, log, cleanup := setup(t)
defer cleanup()
server.append([][]byte{[]byte("hello"), []byte("world")})
var allEntries []blog.Entry
entriesCh := make(chan []blog.Entry)
wait := parallel.Go(func() {
for entries := range entriesCh {
allEntries = append(allEntries, entries...)
if len(allEntries) >= 2 {
cleanup()
}
}
})
err := log.Read(context.Background(), 1, entriesCh)
wait()
assert.True(blog.IsClosedError(err))
}
// TestRead_panicsOnBadIndex checks that Read() will panic in the event the
// Log service sent us data with an unexpected log index.
func TestRead_panicsOnBadIndex(t *testing.T) {
type testcase struct {
name string
entries [][]*logspec.Entry
expPanic string
}
testcases := []testcase{{
name: "rewind",
entries: [][]*logspec.Entry{{
{Index: 1},
{Index: 2},
{Index: 3},
{Index: 2},
}},
expPanic: `
received invalid log index from Log service server: tcp://{server}
expected log index 4, but got 2
log store read started at log index 1
ReadReply from Log service has entries:
idx=1 skip=false data=[]
idx=2 skip=false data=[]
idx=3 skip=false data=[]
idx=2 skip=false data=[]
`,
}, {
name: "hole",
entries: [][]*logspec.Entry{{
{Index: 1},
{Index: 2},
{Index: 4},
}},
expPanic: `
received invalid log index from Log service server: tcp://{server}
expected log index 3, but got 4
log store read started at log index 1
ReadReply from Log service has entries:
idx=1 skip=false data=[]
idx=2 skip=false data=[]
idx=4 skip=false data=[]
`,
}, {
name: "repeat",
entries: [][]*logspec.Entry{{
{Index: 1},
{Index: 2},
{Index: 2},
}},
expPanic: `
received invalid log index from Log service server: tcp://{server}
expected log index 3, but got 2
log store read started at log index 1
ReadReply from Log service has entries:
idx=1 skip=false data=[]
idx=2 skip=false data=[]
idx=2 skip=false data=[]
`,
}, {
name: "rewind_2_msgs",
entries: [][]*logspec.Entry{{
{Index: 1},
{Index: 2},
{Index: 3},
}, {
{Index: 2},
}},
expPanic: `
received invalid log index from Log service server: tcp://{server}
expected log index 4, but got 2
log store read started at log index 1
ReadReply from Log service has entries:
idx=2 skip=false data=[]
`,
}, {
name: "hole_2_msgs",
entries: [][]*logspec.Entry{{
{Index: 1},
{Index: 2},
}, {
{Index: 4},
{Index: 5},
}},
expPanic: `
received invalid log index from Log service server: tcp://{server}
expected log index 3, but got 4
log store read started at log index 1
ReadReply from Log service has entries:
idx=4 skip=false data=[]
idx=5 skip=false data=[]
`,
}, {
name: "repeat_2_msg",
entries: [][]*logspec.Entry{{
{Index: 1},
{Index: 2},
}, {
{Index: 2},
{Index: 3},
}},
expPanic: `
received invalid log index from Log service server: tcp://{server}
expected log index 3, but got 2
log store read started at log index 1
ReadReply from Log service has entries:
idx=2 skip=false data=[]
idx=3 skip=false data=[]
`}}
for _, test := range testcases {
t.Run(test.name, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
server, log, cleanup := setup(t)
defer cleanup()
server.append([][]byte{[]byte("hello")})
server.read = func(_ *mockServer, stream logspec.Log_ReadServer, idx uint64) error {
for _, entries := range test.entries {
stream.Send(&logspec.ReadReply{
Reply: &logspec.ReadReply_Ok{
Ok: &logspec.ReadReply_OK{
Entries: entries,
},
},
})
}
return nil
}
resCh := make(chan []logspec.Entry, 10)
expPanic := strings.Replace(test.expPanic,
"{server}", server.listener.Addr().String(), -1)
assert.PanicsWithValue(t, strings.TrimPrefix(expPanic, "\n"), func() {
log.Read(ctx, 1, resCh)
})
// Verify that anything that made it onto resCh is valid.
nextIdx := uint64(1)
for c := range resCh {
for _, e := range c {
assert.Equal(t, nextIdx, e.Index)
nextIdx++
}
}
})
}
}
func TestInfo_success(t *testing.T) {
test := func(mode string) func(t *testing.T) {
return func(t *testing.T) {
assert := assert.New(t)
server, log, cleanup := setup(t)
defer cleanup()
switch mode {
case "ok":
case "redirect":
server.startClock()
server.next.redirect = 3
case "unknown":
server.startClock()
server.next.unknown = true
}
info, err := log.Info(context.Background())
require.NoError(t, err)
assert.Equal(uint64(1), info.FirstIndex)
assert.Equal(0, server.next.redirect)
assert.False(server.next.unknown)
}
}
t.Run("ok", test("ok"))
t.Run("redirect", test("redirect"))
t.Run("unknown", test("unknown"))
}
func TestInfo_expired(t *testing.T) {
assert := assert.New(t)
_, log, cleanup := setup(t)
defer cleanup()
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err := log.Info(ctx)
assert.Equal(ctx.Err(), err)
}
func TestInfo_closed(t *testing.T) {
assert := assert.New(t)
_, log, cleanup := setup(t)
cleanup()
_, err := log.Info(context.Background())
assert.True(blog.IsClosedError(err))
}
func TestInfoStream_success(t *testing.T) {
test := func(mode string) func(t *testing.T) {
return func(t *testing.T) {
assert := assert.New(t)
server, log, cleanup := setup(t)
defer cleanup()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
infoCh := make(chan *blog.Info)
switch mode {
case "ok":
case "redirect":
server.startClock()
server.next.redirect = 3
case "unknown":
server.startClock()
server.next.unknown = true
}
var infos []*blog.Info
wait := parallel.Go(func() {
for info := range infoCh {
infos = append(infos, info)
if len(infos) >= 3 {
cancel()
}
server.append([][]byte{[]byte("hi")})
}
})
err := log.InfoStream(ctx, infoCh)
wait()
assert.Error(ctx.Err())
assert.Equal(ctx.Err(), err)
if assert.Len(infos, 3) {
assert.Equal(blog.Index(0), infos[0].LastIndex)
assert.Equal(blog.Index(1), infos[1].LastIndex)
assert.Equal(blog.Index(2), infos[2].LastIndex)
}
assert.Equal(0, server.next.redirect)
assert.False(server.next.unknown)
}
}
t.Run("ok", test("ok"))
t.Run("redirect", test("redirect"))
t.Run("unknown", test("unknown"))
}
func TestInfoStream_expired(t *testing.T) {
assert := assert.New(t)
_, log, cleanup := setup(t)
defer cleanup()
ctx, cancel := context.WithCancel(context.Background())
cancel()
infoCh := make(chan *blog.Info, 4)
err := log.InfoStream(ctx, infoCh)
assert.Equal(ctx.Err(), err)
}
func TestInfoStream_closed(t *testing.T) {
assert := assert.New(t)
_, log, cleanup := setup(t)
cleanup()
infoCh := make(chan *blog.Info, 4)
err := log.InfoStream(context.Background(), infoCh)
assert.True(blog.IsClosedError(err))
}
func TestInfoStream_closedMidstream(t *testing.T) {
assert := assert.New(t)
_, log, cleanup := setup(t)
defer cleanup()
infoCh := make(chan *blog.Info)
wait := parallel.Go(func() {
for range infoCh {
cleanup()
}
})
err := log.InfoStream(context.Background(), infoCh)
wait()
assert.True(blog.IsClosedError(err))
}
// Tests that connectAnyLocked selects servers randomly and assigns endpoint
// strings back to the clientConn.
func Test_connectAnyLocked_random(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel() // clean up any background dialers left over
endpoints := []*discovery.Endpoint{
{Network: "unknown", Host: "example.com", Port: "80"},
{Network: "unknown", Host: "example.com", Port: "81"},
{Network: "unknown", Host: "example.com", Port: "82"},
{Network: "unknown", Host: "example.com", Port: "83"},
{Network: "unknown", Host: "example.com", Port: "84"},
}
counts := make(map[string]int, len(endpoints))
for _, endpoint := range endpoints {
counts[endpoint.String()] = 0
}
zeros := len(endpoints)
for i := 0; i < 100; i++ {
log := &Log{ctx: ctx, logger: logrus.NewEntry(logrus.New())}
address := connectAddress(ctx, t, log, endpoints)
count, found := counts[address]
if !found {
assert.FailNow(t, "Unexpected address",
"address: %v", address)
}
counts[address]++
if count == 0 |
}
assert.Fail(t, "connectAnyLocked isn't very random",
"counts %v", counts)
}
func Test_connectAnyLocked_ignoresLastEndpoint(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel() // clean up any background dialers left over
endpoints := []*discovery.Endpoint{
{Network: "unknown", Host: "example.com", Port: "80"},
{Network: "unknown", Host: "example.com", Port: "81"},
{Network: "unknown", Host: "example.com", Port: "82"},
{Network: "unknown", Host: "example.com", Port: "83"},
{Network: "unknown", Host: "example.com", Port: "84"},
}
counts := make(map[string]int, len(endpoints))
for _, endpoint := range endpoints {
counts[endpoint.String()] = 0
}
log := &Log{ctx: ctx, logger: logrus.NewEntry(logrus.New())}
prev := ""
for i := 0; i < 100; i++ {
address := connectAddress(ctx, t, log, endpoints)
_, found := counts[address]
if !found {
assert.FailNow(t, "Unexpected address",
"address: %v", address)
}
counts[address]++
if address == prev {
assert.FailNow(t, "connectAnyLocked shouldn't have selected last used endpoint")
}
prev = address
}
for endpoint, count := range counts {
assert.True(t, count > 0, "endpoint %s was never used", endpoint)
}
}
func Test_connectAnyLocked_HandleDuplicatedEndpoints(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel() // clean up any background dialers left over
endpoints := []*discovery.Endpoint{
{Network: "unknown", Host: "example.com", Port: "80"},
{Network: "unknown", Host: "example.com", Port: "80"},
}
log := &Log{ctx: ctx, logger: logrus.NewEntry(logrus.New())}
log.locked.lastEndpoint = endpoints[1].String()
// endpoints has 2 entries that are the same, and are the failed endpoint
// this is a broken configuration, but shouldn't cause connectAnyLocked to barf.
address := connectAddress(ctx, t, log, endpoints)
assert.Equal(t, endpoints[0].String(), address)
}
// Used in Test_connectAnyLocked_* and Test_disconnectFrom_flagsEndpointAsFailed
func connectAddress(ctx context.Context, t *testing.T, log *Log, endpoints []*discovery.Endpoint) string {
assert := assert.New(t)
log.servers = discovery.NewStaticLocator(endpoints)
log.lock.Lock()
log.connectAnyLocked()
client := log.locked.client
log.lock.Unlock()
// This loop waits until client.conn has failed (the dialer for the "unknown"
// Network won't succeed).
i := 0
for {
state := client.conn.GetState()
if state == connectivity.TransientFailure {
break
}
i++
if i == 100 { // give up
assert.Equal(connectivity.TransientFailure.String(), state.String())
break
}
ctx, cancel := context.WithTimeout(ctx, time.Millisecond)
client.conn.WaitForStateChange(ctx, state)
cancel()
}
// Since the net.Dialer failed, the address must be set already.
return client.server()
}
| {
zeros--
if zeros == 0 {
return
}
} |
release_cmd.go | package main
import (
"context"
"fmt"
"io"
"github.com/spf13/cobra"
"github.com/weaveworks/flux"
"github.com/weaveworks/flux/job"
"github.com/weaveworks/flux/update"
)
type controllerReleaseOpts struct {
*rootOpts
namespace string
controllers []string
allControllers bool
image string
allImages bool
exclude []string
dryRun bool
interactive bool
outputOpts
cause update.Cause
// Deprecated
services []string
}
func newControllerRelease(parent *rootOpts) *controllerReleaseOpts {
return &controllerReleaseOpts{rootOpts: parent}
}
func (opts *controllerReleaseOpts) Command() *cobra.Command {
cmd := &cobra.Command{
Use: "release",
Short: "Release a new version of a controller.",
Example: makeExample(
"fluxctl release -n default --controller=deployment/foo --update-image=library/hello:v2",
"fluxctl release --all --update-image=library/hello:v2",
"fluxctl release --controller=default:deployment/foo --update-all-images",
),
RunE: opts.RunE,
}
AddOutputFlags(cmd, &opts.outputOpts)
AddCauseFlags(cmd, &opts.cause)
cmd.Flags().StringVarP(&opts.namespace, "namespace", "n", "default", "Controller namespace")
cmd.Flags().StringSliceVarP(&opts.controllers, "controller", "c", []string{}, "List of controllers to release <namespace>:<kind>/<name>")
cmd.Flags().BoolVar(&opts.allControllers, "all", false, "Release all controllers")
cmd.Flags().StringVarP(&opts.image, "update-image", "i", "", "Update a specific image")
cmd.Flags().BoolVar(&opts.allImages, "update-all-images", false, "Update all images to latest versions")
cmd.Flags().StringSliceVar(&opts.exclude, "exclude", []string{}, "List of controllers to exclude")
cmd.Flags().BoolVar(&opts.dryRun, "dry-run", false, "Do not release anything; just report back what would have been done")
cmd.Flags().BoolVar(&opts.interactive, "interactive", false, "Select interactively which containers to update")
// Deprecated
cmd.Flags().StringSliceVarP(&opts.services, "service", "s", []string{}, "Service to release")
cmd.Flags().MarkHidden("service")
return cmd
}
func (opts *controllerReleaseOpts) RunE(cmd *cobra.Command, args []string) error {
if len(opts.services) > 0 {
return errorServiceFlagDeprecated
}
if len(args) != 0 {
return errorWantedNoArgs
}
if err := checkExactlyOne("--update-image=<image> or --update-all-images", opts.image != "", opts.allImages); err != nil {
return err
}
if len(opts.controllers) <= 0 && !opts.allControllers {
return newUsageError("please supply either --all, or at least one --controller=<controller>")
}
var controllers []update.ResourceSpec
if opts.allControllers {
controllers = []update.ResourceSpec{update.ResourceSpecAll}
} else {
for _, controller := range opts.controllers {
id, err := flux.ParseResourceIDOptionalNamespace(opts.namespace, controller)
if err != nil {
return err
}
controllers = append(controllers, update.MakeResourceSpec(id))
}
} | image update.ImageSpec
err error
)
switch {
case opts.image != "":
image, err = update.ParseImageSpec(opts.image)
if err != nil {
return err
}
case opts.allImages:
image = update.ImageSpecLatest
}
var kind update.ReleaseKind = update.ReleaseKindExecute
if opts.dryRun || opts.interactive {
kind = update.ReleaseKindPlan
}
var excludes []flux.ResourceID
for _, exclude := range opts.exclude {
s, err := flux.ParseResourceIDOptionalNamespace(opts.namespace, exclude)
if err != nil {
return err
}
excludes = append(excludes, s)
}
if kind == update.ReleaseKindPlan {
fmt.Fprintf(cmd.OutOrStderr(), "Submitting dry-run release...\n")
} else {
fmt.Fprintf(cmd.OutOrStderr(), "Submitting release ...\n")
}
ctx := context.Background()
spec := update.ReleaseSpec{
ServiceSpecs: controllers,
ImageSpec: image,
Kind: kind,
Excludes: excludes,
}
jobID, err := opts.API.UpdateManifests(ctx, update.Spec{
Type: update.Images,
Cause: opts.cause,
Spec: spec,
})
if err != nil {
return err
}
if opts.interactive {
result, err := awaitJob(ctx, opts.API, jobID)
if err != nil {
return err
}
spec, err := promptSpec(cmd.OutOrStdout(), result, opts.verbosity)
if err != nil {
fmt.Fprintln(cmd.OutOrStderr(), err.Error())
return nil
}
fmt.Fprintf(cmd.OutOrStderr(), "Submitting selected release...\n")
jobID, err = opts.API.UpdateManifests(ctx, update.Spec{
Type: update.Containers,
Cause: opts.cause,
Spec: spec,
})
opts.dryRun = false
}
return await(ctx, cmd.OutOrStdout(), cmd.OutOrStderr(), opts.API, jobID, !opts.dryRun, opts.verbosity)
}
func promptSpec(out io.Writer, result job.Result, verbosity int) (update.ContainerSpecs, error) {
menu := update.NewMenu(out, result.Result, verbosity)
containerSpecs, err := menu.Run()
return update.ContainerSpecs{
Kind: update.ReleaseKindExecute,
ContainerSpecs: containerSpecs,
SkipMismatches: false,
}, err
} |
var ( |
wasm.rs | use std::ops::{Add, AddAssign, Sub, SubAssign};
use std::time::Duration;
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Hash)]
pub struct Instant(Duration);
impl Ord for Instant {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.partial_cmp(other)
.expect("an instant should never be NaN or Inf.")
}
}
impl Eq for Instant {}
impl Instant {
#[inline]
pub fn now() -> Self {
Instant(duration_from_f64(now()))
}
#[inline]
pub fn duration_since(&self, earlier: Instant) -> Duration {
assert!(
earlier.0 <= self.0,
"`earlier` cannot be later than `self`."
);
self.0 - earlier.0
}
#[inline]
pub fn elapsed(&self) -> Duration {
Self::now().duration_since(*self)
}
/// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
/// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
/// otherwise.
#[inline]
pub fn checked_add(&self, duration: Duration) -> Option<Instant> {
self.0.checked_add(duration).map(Instant)
}
/// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
/// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
/// otherwise.
#[inline]
pub fn checked_sub(&self, duration: Duration) -> Option<Instant> {
self.0.checked_sub(duration).map(Instant)
}
/// Returns the amount of time elapsed from another instant to this one, or None if that
/// instant is later than this one.
#[inline]
pub fn checked_duration_since(&self, earlier: Instant) -> Option<Duration> {
if earlier.0 > self.0 {
None
} else {
Some(self.0 - earlier.0)
}
}
/// Returns the amount of time elapsed from another instant to this one, or zero duration if
/// that instant is later than this one.
#[inline]
pub fn saturating_duration_since(&self, earlier: Instant) -> Duration {
self.checked_duration_since(earlier).unwrap_or_default()
}
}
impl Add<Duration> for Instant {
type Output = Self;
#[inline]
fn add(self, rhs: Duration) -> Self {
Instant(self.0 + rhs)
}
}
impl AddAssign<Duration> for Instant {
#[inline]
fn add_assign(&mut self, rhs: Duration) {
self.0 += rhs
}
}
impl Sub<Duration> for Instant {
type Output = Self;
#[inline]
fn sub(self, rhs: Duration) -> Self {
Instant(self.0 - rhs)
}
}
impl Sub<Instant> for Instant {
type Output = Duration;
#[inline]
fn sub(self, rhs: Instant) -> Duration {
self.duration_since(rhs)
}
}
impl SubAssign<Duration> for Instant {
#[inline]
fn sub_assign(&mut self, rhs: Duration) { | self.0 -= rhs
}
}
fn duration_from_f64(millis: f64) -> Duration {
Duration::from_millis(millis.trunc() as u64)
+ Duration::from_nanos((millis.fract() * 1.0e6) as u64)
}
#[cfg(all(feature = "stdweb", not(feature = "wasm-bindgen")))]
#[allow(unused_results)] // Needed because the js macro triggers it.
pub fn now() -> f64 {
use stdweb::unstable::TryInto;
// https://developer.mozilla.org/en-US/docs/Web/API/Performance/now
#[cfg(not(feature = "inaccurate"))]
let v = js! { return performance.now(); };
#[cfg(feature = "inaccurate")]
let v = js! { return Date.now(); };
v.try_into().unwrap()
}
#[cfg(feature = "wasm-bindgen")]
pub fn now() -> f64 {
#[cfg(not(feature = "inaccurate"))]
let now = {
use wasm_bindgen_rs::prelude::*;
use wasm_bindgen_rs::JsCast;
js_sys::Reflect::get(&js_sys::global(), &JsValue::from_str("performance"))
.expect("failed to get performance from global object")
.unchecked_into::<web_sys::Performance>()
.now()
};
#[cfg(feature = "inaccurate")]
let now = js_sys::Date::now();
now
}
// The JS now function is in a module so it won't have to be renamed
#[cfg(not(any(feature = "wasm-bindgen", feature = "stdweb")))]
mod js {
extern "C" {
#[cfg(not(target_os = "emscripten"))]
pub fn now() -> f64;
#[cfg(target_os = "emscripten")]
pub fn _emscripten_get_now() -> f64;
}
}
// Make the unsafe extern function "safe" so it can be called like the other 'now' functions
#[cfg(not(any(feature = "wasm-bindgen", feature = "stdweb")))]
pub fn now() -> f64 {
#[cfg(not(target_os = "emscripten"))]
return unsafe { js::now() };
#[cfg(target_os = "emscripten")]
return unsafe { js::_emscripten_get_now() };
} | |
slider_view.rs | use direction::{Direction, Orientation};
use event::{Callback, Event, EventResult, Key, MouseButton, MouseEvent};
use std::rc::Rc;
use theme::ColorStyle;
use vec::Vec2;
use view::View;
use With;
use {Cursive, Printer};
/// A horizontal or vertical slider.
pub struct SliderView {
orientation: Orientation,
on_change: Option<Rc<Fn(&mut Cursive, usize)>>,
on_enter: Option<Rc<Fn(&mut Cursive, usize)>>,
value: usize,
max_value: usize,
dragging: bool,
}
impl SliderView {
/// Creates a new `SliderView` in the given orientation.
///
/// The view will have a fixed length of `max_value`,
/// with one tick per block.
pub fn new(orientation: Orientation, max_value: usize) -> Self {
SliderView {
orientation,
value: 0,
max_value,
on_change: None,
on_enter: None,
dragging: false,
}
}
/// Creates a new vertical `SliderView`.
pub fn vertical(max_value: usize) -> Self {
Self::new(Orientation::Vertical, max_value)
}
/// Creates a new horizontal `SliderView`.
pub fn horizontal(max_value: usize) -> Self {
Self::new(Orientation::Horizontal, max_value)
}
/// Sets the current value.
///
/// Returns an event result with a possible callback,
/// if `on_change` was set..
pub fn set_value(&mut self, value: usize) -> EventResult {
self.value = value;
self.get_change_result()
}
/// Sets the current value.
///
/// Chainable variant.
pub fn value(self, value: usize) -> Self {
self.with(|s| {
s.set_value(value);
})
}
/// Sets a callback to be called when the slider is moved.
pub fn on_change<F>(mut self, callback: F) -> Self
where
F: Fn(&mut Cursive, usize) + 'static,
{
self.on_change = Some(Rc::new(callback));
self
}
/// Sets a callback to be called when the <Enter> key is pressed.
pub fn | <F>(mut self, callback: F) -> Self
where
F: Fn(&mut Cursive, usize) + 'static,
{
self.on_enter = Some(Rc::new(callback));
self
}
fn get_change_result(&self) -> EventResult {
EventResult::Consumed(self.on_change.clone().map(|cb| {
let value = self.value;
Callback::from_fn(move |s| {
cb(s, value);
})
}))
}
fn slide_plus(&mut self) -> EventResult {
if self.value + 1 < self.max_value {
self.value += 1;
self.get_change_result()
} else {
EventResult::Ignored
}
}
fn slide_minus(&mut self) -> EventResult {
if self.value > 0 {
self.value -= 1;
self.get_change_result()
} else {
EventResult::Ignored
}
}
fn req_size(&self) -> Vec2 {
self.orientation.make_vec(self.max_value, 1)
}
}
impl View for SliderView {
fn draw(&self, printer: &Printer) {
match self.orientation {
Orientation::Vertical => {
printer.print_vline((0, 0), self.max_value, "|")
}
Orientation::Horizontal => {
printer.print_hline((0, 0), self.max_value, "-")
}
}
let color = if printer.focused {
ColorStyle::highlight()
} else {
ColorStyle::highlight_inactive()
};
printer.with_color(color, |printer| {
printer.print(self.orientation.make_vec(self.value, 0), " ");
});
}
fn required_size(&mut self, _: Vec2) -> Vec2 {
self.req_size()
}
fn on_event(&mut self, event: Event) -> EventResult {
match event {
Event::Key(Key::Left)
if self.orientation == Orientation::Horizontal =>
{
self.slide_minus()
}
Event::Key(Key::Right)
if self.orientation == Orientation::Horizontal =>
{
self.slide_plus()
}
Event::Key(Key::Up)
if self.orientation == Orientation::Vertical =>
{
self.slide_minus()
}
Event::Key(Key::Down)
if self.orientation == Orientation::Vertical =>
{
self.slide_plus()
}
Event::Key(Key::Enter) if self.on_enter.is_some() => {
let value = self.value;
let cb = self.on_enter.clone().unwrap();
EventResult::with_cb(move |s| {
cb(s, value);
})
}
Event::Mouse {
event: MouseEvent::Hold(MouseButton::Left),
position,
offset,
}
if self.dragging =>
{
let position = position.saturating_sub(offset);
let position = self.orientation.get(&position);
let position = ::std::cmp::min(
position,
self.max_value.saturating_sub(1),
);
self.value = position;
self.get_change_result()
}
Event::Mouse {
event: MouseEvent::Press(MouseButton::Left),
position,
offset,
}
if position.fits_in_rect(offset, self.req_size()) =>
{
if let Some(position) = position.checked_sub(offset) {
self.dragging = true;
self.value = self.orientation.get(&position);
}
self.get_change_result()
}
Event::Mouse {
event: MouseEvent::Release(MouseButton::Left),
..
} => {
self.dragging = false;
EventResult::Ignored
}
_ => EventResult::Ignored,
}
}
fn take_focus(&mut self, _: Direction) -> bool {
true
}
}
| on_enter |
influxSender.js | /**
* Send Google Analytics data to InfluxDB
* Copyright (c) 2016, Steffen Konerow
* Released under the MIT License
* Inspired by gaToGraphite by Peter Hedenskog
*/
'use strict';
var influx = require('influx')
function | (host, port, user, pass, database) {
this.client = influx({
host : host,
port : port, // optional, default 8086
protocol : 'http', // optional, default 'http'
username : user,
password : pass,
database : database
})
}
InfluxSender.prototype.send = function(series,points, cb) {
this.client.writeSeries(series,points,cb);
};
module.exports = InfluxSender;
| InfluxSender |
evr.py |
""" Sahana Eden Evacuees Registry Model
@copyright: 2015-2017 (c) Sahana Software Foundation
@license: MIT
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.
"""
__all__ = ("S3EVRCaseModel",
"evr_rheader",
"evr_AddGroupMembers",
)
from gluon import *
from ..s3 import *
# =============================================================================
class S3EVRCaseModel(S3Model):
names = ("evr_case",
"evr_medical_details",
)
def model(self):
T = current.T
settings = current.deployment_settings
define_table = self.define_table
person_id = self.pr_person_id
# ---------------------------------------------------------------------
# Case Data
#
enable_evr_organisation = settings.get_evr_link_to_organisation()
organisation_label = settings.get_hrm_organisation_label()
org_organisation_represent = self.org_OrganisationRepresent()
org_widget = S3HierarchyWidget(lookup="org_organisation",
represent=org_organisation_represent,
multiple=False,
leafonly=False,)
tablename = "evr_case"
define_table(tablename,
person_id(ondelete = "CASCADE"),
self.org_organisation_id(
empty = not settings.get_hrm_org_required(),
label = organisation_label,
requires = self.org_organisation_requires(required=True),
comment = DIV(_class="tooltip",
_title="%s|%s" % (T("Designed Organisation"),
T("Organisation designed to take care of evacuee"))),
widget = org_widget,
readable = enable_evr_organisation,
writable = enable_evr_organisation,
),
Field("fiscal_code", "string", length=16,
label = T("Fiscal Code"),
comment = DIV(_class="tooltip",
_title="%s|%s" % (T("Fiscal Code"),
T("Insert the fiscal code with no spaces")
)
),
),
s3_comments(),
*s3_meta_fields())
# If fiscal code is present, it's unique
# fiscal_code = db.evr_case.fiscal_code
# fiscal_code.requires = IS_EMPTY_OR(
# IS_NOT_IN_DB(db(db.evr_case.deleted != True),
# fiscal_code),
# null=''
# )
self.configure(tablename,
onaccept = self.evr_case_onaccept,
)
# ---------------------------------------------------------------------
# Medical Details
#
# @todo: use string-codes for option fields for better
# maintainability/interoperability
#
evr_therapy_opts = {1: T("Vital Long-Term Medication"),
2: T("Dialysis"),
3: T("Chronic Oxygen Supply"),
4: T("Intermittend Ventilator Support"),
5: T("Ventilator Dependend"),
6: T("Cardiac Assist Device"),
}
evr_allergy_opts = {1: T("Drug"),
2: T("Food"),
3: T("Olive Tree"),
4: T("Grass"),
5: T("Dust"),
6: T("Other"),
}
evr_disability_opts = {1: T("Visually Impaired"),
2: T("Blind"),
3: T("Hearing-Impaired"),
4: T("Deaf"),
5: T("Deaf-Mute"),
6: T("Deaf-Blind"),
7: T("Aphasic"),
8: T("Mobility-Impaired"),
9: T("Paralysed"),
10: T("Amputated"),
11: T("Other Physical Disability"),
12: T("Mentally Disabled"),
}
evr_aids_appliances_opts = {1: ("Guide Dog"),
2: ("Wheelchair"),
3: ("Walking stick"),
4: ("Crutch"),
5: ("Tripod"),
6: ("Artificial limb"),
7: ("Catheter"),
8: ("Sanity Napkin"),
}
def med_multiopt_field(fieldname, options, label=None):
""" Simple generator for option fields """
return Field(fieldname, "list:integer",
label = label,
represent = S3Represent(options = options,
multiple = True),
requires = IS_IN_SET(options, multiple = True),
widget = S3MultiSelectWidget(filter = False,
selectedList = 3,
noneSelectedText = "Select",
)
)
evr_source_opts = {1: "Self",
2: "Mother",
3: "Father",
4: "Uncle",
5: "Grandfather",
6: "Grandmother",
7: "Official",
8: "Attendant",
9: "Neighbour",
10: "Teacher",
11: "Priest",
12: "Other",
}
tablename = "evr_medical_details"
define_table(tablename,
person_id(),
med_multiopt_field("therapy",
evr_therapy_opts,
label = T("Therapy"),
),
Field("therapy_comment"),
Field("pregnancy", "boolean",
label = T("Pregnancy"),
),
med_multiopt_field("allergy",
evr_allergy_opts,
label = T("Allergies"),
),
Field("diet",
label = T("Food intolerance"),
),
med_multiopt_field("disability",
evr_disability_opts,
label = T("Disabilities"),
),
Field("self_sufficient", "boolean",
label = T("Self-Sufficient"),
),
med_multiopt_field("aids_appliances",
evr_aids_appliances_opts,
label = T("Aids and Appliances"),
),
Field("declared_by_name",
label = T("Declared by (Name)"),
),
Field("declared_by_relationship", "integer",
label = T("Declared by (Relationship)"),
represent=S3Represent(options=evr_source_opts),
requires = IS_IN_SET(evr_source_opts,
zero=None),
),
Field("declared_by_phone",
label = T("Declared by (Phone)"),
requires = IS_NULL_OR(IS_PHONE_NUMBER()),
),
Field("declared_by_email",
label = T("Declared by (Email)"),
requires = IS_NULL_OR(IS_EMAIL()),
),
Field("has_attendant", "boolean",
label = T("Has Attendant"),
),
Field("attendant_name",
label = T("Attendant (Name)"),
),
Field("attendant_phone",
label = T("Attendant (Phone)"),
requires = IS_NULL_OR(IS_PHONE_NUMBER()),
),
Field("attendant_email",
label = T("Attendant (Email)"),
requires = IS_NULL_OR(IS_EMAIL()),
),
s3_comments(),
*s3_meta_fields())
# ---------------------------------------------------------------------
# Socio-economic Background
#
tablename = "evr_background"
define_table(tablename,
person_id(),
Field("legal_measure",
label = T("Legal measure / Home warrant"),
comment = DIV(_class="tooltip",
_title="%s|%s" % (T("Legal measure / Home warrant"),
T("Evacuee subject to special or legal measures/penalities")
)
),
),
Field("diet_restrictions",
label = T("Food Restrictions")
),
Field("social_welfare",
label = T("Social Welfare"),
comment = DIV(_class="tooltip",
_title="%s|%s" % (T("Social Welfare"),
T("Evacuee subject to Social Welfare")
)
),
),
Field("interpreter",
label = T("Interpreter / Cultural Mediator Required"),
comment = DIV(_class="tooltip",
_title="%s|%s" % (T("Interpreter / Cultural Mediator"),
T("Specific language interpreter and/or cultural mediator required")
)
),
),
Field("home_help", "boolean",
label = T("Home Help"),
comment = DIV(_class="tooltip",
_title="%s|%s" % (T("Home Help"),
T("Evacuee requiring dedicated assistance at home")
)
),
),
Field("distance_from_shelter", "integer",
label = T("Working Distance from Shelter (km)")
),
Field("job_lost_by_event", "boolean",
label = T("Job lost by event")
),
Field("domestic_animal", "boolean",
label = T("With Domestic Animals")
),
Field("car_available", "boolean",
label = T("Car available")
),
s3_comments(),
*s3_meta_fields())
# -------------------------------------------------------------------------
@staticmethod
def evr_case_onaccept(form):
"""
After DB I/O, check the correctness of fiscal code (ITALY)
@ToDo: The function should be made a deployment_setting when anyone else wishes to use this module
"""
# Initialization
fiscal_code = form.vars.fiscal_code
if fiscal_code == "" or fiscal_code == None:
return
fiscal_code = fiscal_code.upper()
MALE = 3
CONSONANTS = "BCDFGHJKLMNPQRSTVWXYZ"
VOWELS = "AEIOU"
MONTHS = "ABCDEHLMPRST"
T = current.T
ptable = current.s3db.pr_person
query = (form.vars.person_id == ptable.id)
row = current.db(query).select(ptable.first_name,
ptable.last_name,
ptable.date_of_birth,
ptable.gender,
limitby = (0, 1)
).first()
name = row.first_name.upper()
surname = row.last_name.upper()
date_of_birth = row.date_of_birth
year = date_of_birth.year
month = date_of_birth.month
day = date_of_birth.day
gender = row.gender
# Check surname
cons = ""
for c in surname:
if c in CONSONANTS:
cons += c
vow = ""
for c in surname:
if c in VOWELS:
vow += c
chars = cons + vow
if len(chars) < 3:
chars += ["X", "X"]
if fiscal_code[:3] != chars[0:3].upper():
current.response.warning = T("Warning: fiscal code isn't \
consistent with personal data")
return
# Check name
cons = ""
for c in name:
if c in CONSONANTS:
cons += c
if len(cons) > 3:
chars = cons[0] + cons[2] + cons[3]
else:
vow = ""
for c in name:
if c in VOWELS:
vow += c
chars = cons + vow
if len(chars) < 3:
chars += ["X", "X"]
if fiscal_code[3:6] != chars[0:3].upper():
current.response.warning = T("Warning: fiscal code isn't \
consistent with personal data")
return
# Check date of birth and gender
year = str(year)[2:4] # Convert to string and take only the last two elements
if fiscal_code[6:8] != year or \
fiscal_code[8] != MONTHS[month - 1]:
current.response.warning = T("Warning: fiscal code isn't \
consistent with personal data")
return
if gender == MALE:
birthday_in_cf = fiscal_code[9:11]
if not birthday_in_cf.isdigit():
current.response.warning = T("Warning: fiscal code isn't \
consistent with personal data")
return
else:
birthday_in_cf = int(birthday_in_cf)
if birthday_in_cf != day:
current.response.warning = T("Warning: fiscal code isn't \
consistent with personal data")
return
else: # if gender == FEMALE
if fiscal_code[9:11] != str(day + 40):
current.response.warning = T("Warning: fiscal code isn't \
consistent with personal data")
return
return
# =============================================================================
def evr_rheader(r):
"""
EVR Resource Headers
@param r: the S3Request
"""
T = current.T
settings = current.deployment_settings
if r.representation != "html" or not r.record:
return None
resourcename = r.name
rheader_fields = None
if resourcename == "person":
tabs = [(T("Person"), None),
(T("Addresses"), "address"),
(T("Contact Data"), "contacts"),
(T("Groups"), "group_membership"),
# these can be hidden since inline in the main form,
# but can enabled to verify the functionality:
#(T("Identity Documents"), "identity"),
#(T("Case Details"), "case"),
(T("Images"), "image"),
(T("Medical Information"), "medical_details"),
(T("Socio-Economic Background"), "background"),
]
if settings.get_evr_show_physical_description():
tabs.append((T("Physical Description"), "physical_description"))
if settings.has_module("cr"):
tabs.append((T("Shelter Registration"), "shelter_registration"))
rheader_fields = [["first_name", "last_name"],
["date_of_birth"],
]
# Show profile picture in rheader
itable = current.s3db.pr_image
query = (itable.pe_id == r.record.pe_id) & \
(itable.profile == True)
image = current.db(query).select(itable.image,
limitby=(0, 1)).first()
if image:
image = itable.image.represent(image.image)
else:
image = A(IMG(_src=URL(c="static", f="img", args="blank-user.gif"),
_height=60,
_title=T("No image available")),
_class="th",
_href=URL(f="person", args=[r.id, "image", "create"]),
)
return DIV(DIV(image, _style="float:left"),
S3ResourceHeader(rheader_fields, tabs)(r))
elif resourcename == "group":
tabs = [("Group Details", None),
(T("Contact Data"), "contact"),
(T("Members"), "group_membership"),
]
# Show "Add Members" tab only when we action it explicitly
# (=> from action-button in the group members list)
if r.method == "add_members":
tabs.append((T("Add Members"), "add_members"))
rheader_fields = [["name"],
["description"],
]
return S3ResourceHeader(rheader_fields, tabs)(r)
return None
# =============================================================================
class evr_AddGroupMembers(S3Method):
"""
Custom method to select multiple persons from a filtered list
and add them to a group
"""
# -------------------------------------------------------------------------
def apply_method(self, r, **attr):
"""
Entry point for REST controller
@param r: the S3Request
@param attr: dictionary of parameters for the method handler
@return: output object to send to the view
"""
# Add button "Add Members" to members tab
if r.http in ("GET", "POST"):
if r.representation == "html" and r.id or \
r.representation == "aadata":
return self.add_members(r, **attr)
else:
r.error(415, current.ERROR.BAD_FORMAT)
else:
r.error(405, current.ERROR.BAD_METHOD)
# -------------------------------------------------------------------------
def add_members(self, r, **attr):
"""
Add-members action: renders a filtered multi-select datatable
form, and creates group_memberships on POST
@param r: the S3Request
@param attr: dictionary of parameters for the method handler
@return: output object to send to the view
"""
T = current.T
db = current.db
s3db = current.s3db
unaffiliated = ((S3FieldSelector("group_membership.id") == None) & \
(S3FieldSelector("case.id") != None))
if r.http == "POST":
# Form submission
group_id = r.id
added = 0
post_vars = r.post_vars
if all([name in post_vars
for name in ("add", "selected", "mode")]):
# Get selection
selected = post_vars.selected
if selected:
selected = selected.split(",")
else:
selected = []
# Handle exclusion filter
if post_vars.mode == "Exclusive":
if "filterURL" in post_vars:
filters = S3URLQuery.parse_url(post_vars.filterURL)
else:
filters = None
query = unaffiliated & \
(~(S3FieldSelector("id").belongs(selected)))
resource = s3db.resource("pr_person",
filter=query,
vars=filters)
rows = resource.select(["id"], as_rows=True)
selected = [str(row.id) for row in rows]
# Avoid duplicates
gtable = s3db.pr_group_membership
query = (gtable.group_id == group_id) & \
(gtable.person_id.belongs(selected)) & \
(gtable.deleted != True)
rows = db(query).select(gtable.person_id)
skip = set(row.person_id for row in rows)
# Add new group members
for record_id in selected:
try:
person_id = int(record_id.strip())
except ValueError:
continue
if person_id in skip:
continue
gtable.insert(group_id = group_id,
person_id = person_id,
)
added += 1
# Confirmation message (in session because we redirect)
session = current.session
if not selected:
session.warning = T("No Persons Selected!")
else:
session.confirmation = T("%(number)s Members added to Group") % \
dict(number=added)
# Go back to list of existing group members
redirect(r.url(method = "",
id = group_id,
component = "group_membership"))
else:
resource = s3db.resource("pr_person", vars=r.get_vars)
resource.add_filter(unaffiliated)
get_config = resource.get_config
# Filter widgets
filter_widgets = get_config("filter_widgets", [])
filter_widgets.append(S3DateFilter("created_on",
label = T("Registered on"),
)
)
# List fields
list_fields = ["id",
"first_name",
"last_name",
"gender",
"date_of_birth",
]
response = current.response
# Data table boundaries
get_vars = self.request.get_vars
if "displayStart" in get_vars:
start = int(get_vars["displayStart"])
else:
start = None
if "pageLength" in get_vars:
display_length = int(get_vars["pageLength"])
else:
display_length = response.s3.ROWSPERPAGE
limit = 4 * display_length
# Apply datatable filter and sorting
totalrows = resource.count()
filter, orderby, left = resource.datatable_filter(list_fields, get_vars)
if not orderby:
# Most recently created records on top
orderby = "pr_person.created_on desc"
resource.add_filter(filter)
# Retrieve the data
data = resource.select(list_fields,
start=start,
limit=limit,
orderby=orderby,
left=left,
count=True,
represent=True)
filteredrows = data["numrows"]
# Generate the datatable
dt = S3DataTable(data["rfields"], data["rows"])
dt_id = "datatable"
# Bulk Action
dt_bulk_actions = [(T("Add as Group Members"), "add")]
if r.representation == "html":
# Page load
# Custom open-button, no delete-option
resource.configure(deletable = False)
open_url = URL(f = "person", args = ["[id]"])
S3CRUD.action_buttons(r,
deletable = False,
read_url = open_url,
update_url = open_url)
# Need no export formats (as this is a form)
response.s3.no_formats = True
# Data table (items)
items = dt.html(totalrows,
filteredrows,
dt_id,
dt_ajax_url=URL(c="evr",
f="group",
args=["add_members"],
vars={},
extension="aadata",
),
dt_bulk_actions=dt_bulk_actions,
dt_pageLength=display_length,
dt_pagination="true",
dt_searching="false",
)
resource.configure(deletable = False)
# Filter form
if filter_widgets:
# Where to retrieve filtered data from:
_vars = resource.crud._remove_filters(r.get_vars)
filter_submit_url = r.url(vars=_vars)
# Where to retrieve updated filter options from:
filter_ajax_url = URL(f="person",
args=["filter.options"],
vars={},
)
# Define filter form
filter_clear = get_config("filter_clear", True)
filter_submit = get_config("filter_submit", True)
filter_form = S3FilterForm(filter_widgets,
clear=filter_clear,
submit=filter_submit,
ajax=True,
url=filter_submit_url,
ajaxurl=filter_ajax_url,
_class="filter-form",
_id="datatable-filter-form",
)
# Render filter form
fresource = s3db.resource(resource.tablename)
alias = resource.alias if r.component else None
ff = filter_form.html(fresource,
r.get_vars,
target="datatable",
alias=alias)
else:
ff = ""
output = dict(items = items,
title = T("Add Members to Group"),
addheader = "%s:" % T("Select People to add them to the Group"),
list_filter_form = ff,
)
response.view = "list_filter.html"
return output
else:
# Ajax refresh
if "draw" in get_vars:
echo = int(get_vars.draw)
else:
echo = None
items = dt.json(totalrows,
filteredrows,
dt_id,
echo,
dt_bulk_actions=dt_bulk_actions,
)
response.headers["Content-Type"] = "application/json"
return items
# END ========================================================================= | # -*- coding: utf-8 -*- |
|
simple-refiner.component.ts | import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import {
faCaretDown,
faChevronDown,
faChevronUp
} from '@fortawesome/free-solid-svg-icons';
// Porcelain
import { SimpleOption } from '../refiners/IOption';
import { SimpleRefiner } from '../refiners/IRefiner';
import { blockInitialAnimation } from '../shared/animations/blockInitialAnimation.trigger';
import { optionsInOut } from '../shared/animations/slideInOut.trigger';
import { defaultOptionShowCount } from './defaultOptionShowCount';
@Component({
selector: 'porcelain-simple-refiner',
templateUrl: './simple-refiner.component.html',
styleUrls: ['./simple-refiner.component.scss']
})
export class | implements OnInit {
// Inputs
@Input() refiner: SimpleRefiner;
@Input('showCount') _showCount: number;
@Input('isOpen') _isOpen: boolean;
@Input('isExpanded') _isExpanded: boolean;
// Getters
get showCount() {
return this._showCount || this.refiner.showCount || defaultOptionShowCount;
}
set showCount(newCount: number) {
this._showCount = newCount;
}
get isOpen() {
return this._isOpen;
}
set isOpen(newIsOpenValue: boolean) {
this._isOpen = newIsOpenValue;
}
get isExpanded(): boolean {
return this._isExpanded;
}
set isExpanded(newIsExpandedValue: boolean) {
this._isExpanded = newIsExpandedValue;
}
// Outputs
@Output() onRefinerChange: EventEmitter<any> = new EventEmitter();
// Icons
faChevronDown = faCaretDown;
contractIcon = faChevronUp;
expandIcon = faChevronDown;
// State
value: object | SimpleOption;
constructor() {}
ngOnInit() {
// Pick the `isOpen` value;
let isOpen = true;
if (this.refiner && typeof this.refiner.isOpen === 'boolean') {
isOpen = this.refiner.isOpen;
}
if (typeof this._isOpen === 'boolean') {
isOpen = this._isOpen;
}
this.isOpen = !!isOpen;
// Pick the `showCount` value
let showCount = defaultOptionShowCount;
if (this.refiner && typeof this.refiner.showCount === 'number') {
showCount = this.refiner.showCount;
}
if (typeof this._showCount === 'number') {
showCount = this._showCount;
}
this.showCount = showCount;
// Pick the `isExpanded` value
let isExpanded = false;
if (this.refiner && typeof this.refiner.isExpanded === 'boolean') {
isExpanded = this.refiner.isExpanded;
}
if (typeof this._isExpanded === 'boolean') {
isExpanded = this._isExpanded;
}
this._isExpanded = !!isExpanded;
// Sets up the dictionary used for value state
this.selectNone();
// Options can be selected on load through Option.isSelected boolean
if (this.refiner.options) {
for (let optionSlug in this.refiner.options) {
let option = this.refiner.options[optionSlug];
if (
option instanceof SimpleOption ||
option.hasOwnProperty('isSelected')
) {
if (option.slug !== optionSlug) {
console.error(option);
}
// !! ensures a boolean value
this.value[optionSlug] = !!option.isSelected;
}
}
}
// Options should be selected on load through the refiner.selected array of selected optionSlugs
if (this.refiner.selected) {
for (let optionSlug of this.refiner.selected) {
this.value[optionSlug] = true;
}
}
}
toggleExpanded(): void {
this._isExpanded = !this._isExpanded;
}
toggleOpen(): void {
this._isOpen = !this._isOpen;
}
countTail(): number {
return Object.keys(this.refiner.options).length - this._showCount;
}
canExpand(): boolean {
return this.refiner.type === 'simple'
? Object.keys(this.refiner.options).length > this._showCount
: false;
}
getExpandedOptionKeys(): string[] {
return this._isExpanded
? Object.keys(this.refiner.options)
: Object.keys(this.refiner.options).slice(0, this._showCount);
}
optionHasBadge(option: string | SimpleOption): boolean {
if (typeof option === 'string') {
return false;
} else {
return option.badge && option.badge !== '';
}
}
getOptionLabel(option: string | SimpleOption): string {
if (typeof option === 'string') {
return option;
} else {
return option.label;
}
}
getOptionBadge(option: SimpleOption) {
if (typeof option.badge === 'number')
return option.badge.toLocaleString();
else return option.badge;
}
getValue(): string[] {
return Object.keys(this.value).filter(key => this.value[key]);
}
canSelectNone(): boolean {
return Object.keys(this.value).every(
paramName => this.value[paramName] === true
);
}
selectNone() {
this.setAll(false);
}
canSelectAll(): boolean {
return !this.canSelectNone();
}
selectAll() {
return this.setAll(true);
}
setAll(value: any) {
if (this.refiner.type === 'simple') {
this.value = {};
for (let optionKey in this.refiner.options) {
this.value[optionKey] = value;
}
} else {
this.value = value;
}
this.onSelectionChange();
}
onSelectionChange() {
this.onRefinerChange.emit([this.refiner.slug, this.getValue()]);
}
}
| SimpleRefinerComponent |
app.js | /*
Instalar express
npm install express --save
Instalar nodemoon (para no estar ejecutando a cada rato)
npm install nodemon --save (Esto NO es necesario si ya esta instalado a nivel de sistema)
Ejecutar aplicacion con nodemon
nodemon ./app.js
npx nodemon ./app.js (si NO esta instlado en el sistema)
*/
const { response } = require('express');
const express = require('express');
const app = express(); //Devuelve un objeto de tipo app o servidor
/*app.get('/', (req, res) => {
res.send(`This a ${req.method} request!`);
});
app.post('/about', (req, res) => {
res.send(`This a ${req.method} request!`);
});
app.put('/contact', (req, res) => {
res.send(`This a ${req.method} request!`);
});
app.delete('/test', (req, res) => {
res.send(`This a ${req.method} request!`);
});*/
/*app.get('/user1', (req, res) => {
res.send(`{"username":"Fabian","lastname":"Murillo"}`);
});
app.get('/user', (req, res) => {
res.json({
username: 'Fabian',
lastname: 'Murillo'
});
});
*/
//Middleware para que la aplicacion permita recibir JSON de entrada
app.use(express.json());
//Es una especie de Middleware/Request para CUALQUIER/TODO un grupo de URLS
app.all('/user', (req, res, next) => {
console.log(`Por aquí pasó y filtró antes de continuar con lo siguiente.`);
next();
});
app.get('/user', (req, res) => {
//res.send(`This a ${req.method} request!`);
res.json({
username: 'Fabian',
lastname: 'Murillo' | });
app.post('/user', (req, res) => {
console.log(req.body); //Recibe lo que se envia por BODY
//res.send(`This a ${req.method} request!`);
res.json(req.body);
});
app.delete('/user/:userId', (req, res) => {
console.log(req.params);
//res.send(`This a ${req.method} request!`);
let userId = req.params.userId; //Recibe lo que se envia por URL
res.send(`User ${userId} deleted!`);
});
app.put('/user/:userId', (req, res) => {
console.log(req.params);
console.log(req.body);
//res.send(`This a ${req.method} request!`);
let userId = req.params.userId; //Recibe lo que se envia por URL
res.send(`User with id ${userId} updated!`);
});
app.listen(3000, () => {
console.log(`Server running on port 3000!`);
}); | }); |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.