text
stringlengths
1
1.05M
#! /bin/bash # Copyright 2016 Vimal Manohar # Apache 2.0. cmd=run.pl nj=4 frame_shift=0.01 frame_overlap=0.015 . utils/parse_options.sh if [ $# -ne 1 ]; then echo "This script writes a file utt2num_frames with the " echo "number of frames in each utterance as measured based on the " echo "duration of the utterances (in utt2dur) and the specified " echo "frame_shift and frame_overlap." echo "Usage: $0 <data>" exit 1 fi data=$1 if [ -s $data/utt2num_frames ]; then echo "$0: $data/utt2num_frames already present!" exit 0; fi if [ ! -f $data/feats.scp ]; then utils/data/get_utt2dur.sh $data awk -v fs=$frame_shift -v fovlp=$frame_overlap \ '{print $1" "int( ($2 - fovlp) / fs)}' $data/utt2dur > $data/utt2num_frames exit 0 fi utils/split_data.sh --per-utt $data $nj || exit 1 $cmd JOB=1:$nj $data/log/utt2num_frames/get_utt2num_frames.JOB.log \ feat-to-len scp:$data/split${nj}utt/JOB/feats.scp ark,t:$data/split${nj}utt/JOB/utt2num_frames || exit 1 for n in `seq $nj`; do cat $data/split${nj}utt/$n/utt2num_frames done > $data/utt2num_frames echo "$0: Computed and wrote $data/utt2num_frames"
<filename>server/models/user/index.js const getUser = require('./getUser') const updateUser = require('./updateUser') const updatePassword = require('./updatePassword') const updateProfileImage = require('./updateProfileImage') module.exports = { getUser, updateUser, updatePassword, updateProfileImage, }
/* * Copyright (C) 2012 Sony Mobile Communications AB * * This file is part of ApkAnalyser. * * 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 andreflect.gui.action; import gui.actions.AbstractCanceableAction; import java.awt.event.ActionEvent; import javax.swing.Icon; import javax.swing.JOptionPane; import analyser.gui.MainFrame; import analyser.gui.Selection; import analyser.logic.RefContext; import andreflect.ApkClassContext; import andreflect.xml.XmlResourceChecker; public class XmlFindLabelAction extends AbstractCanceableAction { private static final long serialVersionUID = 731223167037250146L; protected XmlFindLabelAction(String actionName, Icon actionIcon) { super(actionName, actionIcon); } protected static XmlFindLabelAction m_inst = null; public static XmlFindLabelAction getInstance(MainFrame mainFrame) { if (m_inst == null) { m_inst = new XmlFindLabelAction("Find label in apk", null); m_inst.setMainFrame(mainFrame); } return m_inst; } @Override public String getWorkDescription() { return "Find label"; } @Override public void handleThrowable(Throwable t) { t.printStackTrace(); getMainFrame().showError("Error finding label", t); } @Override public void run(ActionEvent e) throws Throwable { Object oRef = Selection.getRefContextOfSeletedObject(); if (oRef == null || !(oRef instanceof RefContext)) { return; } RefContext cRef = (RefContext) oRef; /* Collection<Reference> refs = MainFrame.getInstance().getResolver().getMidletResources(); for (Reference ref : refs){ if (((RefContext)ref).getContext().getContextDescription().equals(ApkClassContext.DESCRIPTION)){ ApkClassContext apkContext = (ApkClassContext)((RefContext)ref).getContext(); XmlResourceChecker checker = apkContext.getXmlParser().getResourceChecker(); checker.showFindLabel( apkContext, (MainFrame)getMainFrame(), this); } } */ String output = (String) JOptionPane.showInputDialog( getMainFrame(), "", "Find label (case insensitive)", JOptionPane.QUESTION_MESSAGE, null, null, "sony\\s*ericsson"); if (output != null && output.trim().length() > 0) { if (cRef.getContext().getContextDescription().equals(ApkClassContext.DESCRIPTION)) { ApkClassContext apkContext = (ApkClassContext) cRef.getContext(); XmlResourceChecker checker = apkContext.getXmlParser().getResourceChecker(); checker.showFindLabel(output, apkContext, (MainFrame) getMainFrame(), this); } } } }
<reponame>houwenbiao/BaseProject<filename>utils/src/main/java/com/qtimes/utils/android/NullUtil.java<gh_stars>0 package com.qtimes.utils.android; import android.text.TextUtils; import android.util.Log; import com.qtimes.utils.BuildConfig; /** * 专门检测是否为空的util * 检测到Null会在log中打印出来,并提示相应的行数 * 请及时解决。 * author: liutao * date: 2016/7/26. */ public class NullUtil { public static String tagPrefix = "NullUtil";//log前缀 public static boolean debug = BuildConfig.DEBUG; public static boolean isNull(Object... objects) { if (debug) { return isNullDeubug(objects); } else { return isNullRelease(objects); } } private static boolean isNullDeubug(Object... objects) { if (objects == null) { return true; } for (int i = 0, len = objects.length; i < len; i++) { Object o = objects[i]; if (null == o) { String tag = getTag(getCallerStackTraceElement()); Log.e(tag, "index = " + i + " is Null"); return true; } } return false; } private static boolean isNullRelease(Object... objects) { if (objects == null) { return true; } for (Object o : objects) { if (null == o) { return true; } } return false; } private static String getTag(StackTraceElement element) { try { String tag = "%s.%s(Line:%d)"; // 占位符 String callerClazzName = element.getClassName(); // 获取到类名 callerClazzName = callerClazzName.substring(callerClazzName.lastIndexOf(".") + 1); tag = String.format(tag, callerClazzName, element.getMethodName(), element.getLineNumber()); // 替换 tag = TextUtils.isEmpty(tagPrefix) ? tag : tagPrefix + ":" + tag; return tag; } catch (Exception e) { return tagPrefix; } } /** * 获取线程状态 * * @return */ private static StackTraceElement getCallerStackTraceElement() { return Thread.currentThread().getStackTrace()[5]; } }
gunicorn -w 4 -b 172.19.189.121:5003 --access-logfile ./logs/log magnet:app
<filename>examples/dsg-ssr/src/pages/index.js import React from "react" import { Link } from "gatsby" import Layout from "../components/layout" const Index = () => ( <Layout> <header> <h1>Examples</h1> <p> For the examples explanation, take a look at{" "} <a href="https://github.com/Kentico/kontent-gatsby-packages/tree/master/examples/dsg-ssr#readme"> GitHub example README </a> </p> </header> <section> <ul> <li> <Link to="/dsg-listing">DSG listing-detail</Link> </li> <li> <Link to="/ssr-listing">SSG listing-detail</Link> </li> </ul> </section> </Layout> ) export default Index
#!/usr/bin/env bash python3 -m pip install --upgrade setuptools wheel python3 setup.py sdist bdist_wheel python3 -m pip install --upgrade twine twine upload dist/*
#!/bin/bash #Zalo ai challenge complete training run #check data availablity and get if required python3 utils/get_data.py --data=./data --data_src=https://dl.challenge.zalo.ai/landmark/train_val2018.zip #train python3 finetune.py --data=./data/TrainVal/ --mode=train_then_finetune --net=nasnetmobile --dense_layers=1 --workers=2 \ --train_lr=0.001 --train_epochs=6 --train_steps_per_epoch=800 \ --finetune_lr2=0.001 --finetune_epochs2=200 --finetune_steps_per_epoch2=800 \ --freeze=295 --dropout0=0.5
# frontend from terminal function frontend() { # get the open command local open_cmd if [[ $(uname -s) == 'Darwin' ]]; then open_cmd='open' else open_cmd='xdg-open' fi # no keyword provided, simply show how call methods if [[ $# -le 1 ]]; then echo "Please provide a search-content and a search-term for app.\nEx:\nfrontend <search-content> <search-term>\n" return 1 fi # check whether the search engine is supported if [[ ! $1 =~ '(jquery|mdn|compass|html5please|caniuse|aurajs|dartlang|qunit|fontello|bootsnipp|cssflow|codepen|unheap|bem|smacss|angularjs|reactjs|emberjs)' ]]; then echo "Search valid search content $1 not supported." echo "Valid contents: (formats 'frontend <search-content>' or '<search-content>')" echo "* jquery" echo "* mdn" echo "* compass" echo "* html5please" echo "* caniuse" echo "* aurajs" echo "* dartlang" echo "* lodash" echo "* qunit" echo "* fontello" echo "* bootsnipp" echo "* cssflow" echo "* codepen" echo "* unheap" echo "* bem" echo "* smacss" echo "* angularjs" echo "* reactjs" echo "* emberjs" echo "" return 1 fi local url="http://" local query="" case "$1" in "jquery") url="${url}api.jquery.com" url="${url}/?s=$2" ;; "mdn") url="${url}developer.mozilla.org" url="${url}/search?q=$2" ;; "compass") url="${url}compass-style.org" url="${url}/search?q=$2" ;; "html5please") url="${url}html5please.com" url="${url}/#$2" ;; "caniuse") url="${url}caniuse.com" url="${url}/#search=$2" ;; "aurajs") url="${url}aurajs.com" url="${url}/api/#stq=$2" ;; "dartlang") url="${url}api.dartlang.org/apidocs/channels/stable/dartdoc-viewer" url="${url}/dart-$2" ;; "qunit") url="${url}api.qunitjs.com" url="${url}/?s=$2" ;; "fontello") url="${url}fontello.com" url="${url}/#search=$2" ;; "bootsnipp") url="${url}bootsnipp.com" url="${url}/search?q=$2" ;; "cssflow") url="${url}cssflow.com" url="${url}/search?q=$2" ;; "codepen") url="${url}codepen.io" url="${url}/search?q=$2" ;; "unheap") url="${url}www.unheap.com" url="${url}/?s=$2" ;; "bem") url="${url}google.com" url="${url}/search?as_q=$2&as_sitesearch=bem.info" ;; "smacss") url="${url}google.com" url="${url}/search?as_q=$2&as_sitesearch=smacss.com" ;; "angularjs") url="${url}google.com" url="${url}/search?as_q=$2&as_sitesearch=angularjs.org" ;; "reactjs") url="${url}google.com" url="${url}/search?as_q=$2&as_sitesearch=facebook.github.io/react" ;; "emberjs") url="${url}emberjs.com" url="${url}/api/#stq=$2&stp=1" ;; *) echo "INVALID PARAM!" return ;; esac echo "$url" $open_cmd "$url" } # javascript alias jquery='frontend jquery' alias mdn='frontend mdn' # pre processors frameworks alias compass='frontend compass' # important links alias html5please='frontend html5please' alias caniuse='frontend caniuse' # components and libraries alias aurajs='frontend aurajs' alias dartlang='frontend dartlang' alias lodash='frontend lodash' #tests alias qunit='frontend qunit' #fonts alias fontello='frontend fontello' # snippets alias bootsnipp='frontend bootsnipp' alias cssflow='frontend cssflow' alias codepen='frontend codepen' alias unheap='frontend unheap' # css architecture alias bem='frontend bem' alias smacss='frontend smacss' # frameworks alias angularjs='frontend angularjs' alias reactjs='frontend reactjs' alias emberjs='frontend emberjs'
#!/bin/sh make -C /Users/lbajo/ros2_mod_ws/build/trajectory_msgs -f /Users/lbajo/ros2_mod_ws/build/trajectory_msgs/CMakeScripts/trajectory_msgs__rosidl_typesupport_introspection_cpp_cmakeRulesBuildPhase.make$CONFIGURATION all
<filename>src/utils/index.ts<gh_stars>0 export { default as runNetworkQuery } from './networkQueryRunner';
<gh_stars>1-10 from xml.dom.minidom import parseString from . import TestReader from reader.importer.Perseus import PerseusTextImporter from reader.utils.work_helpers import get_work_page_info from reader.models import WorkAlias class TestWorkHelpers(TestReader): def setUp(self): self.importer = PerseusTextImporter() def test_get_work_page_info(self): # Import a work for us to use book_xml = self.load_test_resource('j.vit_gk_portion.xml') book_doc = parseString(book_xml) self.importer.import_xml_document(book_doc) WorkAlias.populate_alias_from_work(self.importer.work) # Get the work information data = get_work_page_info(title=self.importer.work.title_slug, division_0=1) self.assertEquals(data['title'], 'Josephi vita 1')
<reponame>m-wrona/hevicado 'use strict'; describe('calendar-base-spec:', function () { //prepare module for testing beforeEach(angular.mock.module('chronos')); describe('CalendarCtrl-spec:', function () { var ctrlScope; var mockCalendarService, mockUsersService; var mockUiNotification; var mockState, mockStateParams; var calendarPromise, userPromise; beforeEach(function () { toUTCDate = function (value) { return typeof value != 'string' ? value : Date.parse(value); }; toLocalDate = function (value) { return typeof value == 'string' ? Date.parse(value) : new Date(value); }; }); //prepare controller for testing beforeEach(inject(function ($controller, $injector, _$rootScope_, CALENDAR_EVENTS) { //prepare controller for testing ctrlScope = _$rootScope_.$new(); //mock dependencies mockCalendarService = jasmine.createSpyObj('mockCalendarService', ['events', 'init', 'cancel', 'save']); calendarPromise = { success: function (f) { calendarPromise.onSuccess = f; return calendarPromise; }, error: function (f) { calendarPromise.onError = f; return calendarPromise; } }; mockCalendarService.events.andReturn(calendarPromise); mockCalendarService.cancel.andReturn(calendarPromise); mockCalendarService.save.andReturn(calendarPromise); mockUsersService = jasmine.createSpyObj('mockUsersService', ['get']); userPromise = { success: function (f) { userPromise.onSuccess = f; return userPromise; }, error: function (f) { userPromise.onError = f; return userPromise; } }; mockUsersService.get.andReturn(userPromise); //mock others mockUiNotification = jasmine.createSpyObj('mockUiNotification', ['text', 'error']); mockUiNotification.text = function (title, msg) { mockUiNotification.title = title; mockUiNotification.msg = msg; return mockUiNotification; }; var mockLog = jasmine.createSpyObj('mockLog', ['debug', 'info', 'error']); mockState = jasmine.createSpyObj('$state', ['go']); mockState.current = { daysAmount: 1, data: { addVisitState: 'mock-state.new-visit', editVisitState: 'mock-state.edit-visit' } }; mockStateParams = {doctorId: "doctor-123"}; //inject mocks $controller('CalendarCtrl', { $scope: ctrlScope, $log: mockLog, $state: mockState, $stateParams: mockStateParams, CalendarService: mockCalendarService, EventUtils: $injector.get('EventUtils'), uiNotification: mockUiNotification, UsersService: mockUsersService }); })); describe('calendar initialization-spec:', function () { it('should initialize weekly view by shifting time table to beginning of the week', function () { //given controller is initialized expect(ctrlScope).toBeDefined(); //and one week display period time mockState.current.daysAmount = 7; //and current user var currentUserId = "doctor-123"; //and current date mockStateParams.currentDate = Date.today().set({ year: 2014, month: 9, day: 3 }); //when initializing calendar ctrlScope.init(); //then calendar is prepared for displaying data of chosen user expect(ctrlScope.doctorId).toBe(currentUserId); expect(mockCalendarService.init).toHaveBeenCalledWith(currentUserId); //and calendar time table is set for current week expect(ctrlScope.days.length).toBe(mockState.current.daysAmount); expect(ctrlScope.days[0].toString('yyyy-MM-dd')).toBe('2014-09-29'); expect(ctrlScope.days[6].toString('yyyy-MM-dd')).toBe('2014-10-05'); //and events started to be loading expect(mockCalendarService.events.mostRecentCall.args[0].toString('yyyy-MM-dd')).toEqual('2014-09-29'); expect(mockCalendarService.events.mostRecentCall.args[1].toString('yyyy-MM-dd')).toEqual('2014-10-05'); }); it('should initialize weekly view by leaving current Monday', function () { //given controller is initialized expect(ctrlScope).toBeDefined(); //and one week display period time mockState.current.daysAmount = 7; //and current user var currentUserId = "doctor-123"; //and current date is Monday mockStateParams.currentDate = Date.today().set({ year: 2014, month: 9, day: 15 }); //when initializing calendar ctrlScope.init(); //then calendar is prepared for displaying data of chosen user expect(ctrlScope.doctorId).toBe(currentUserId); expect(mockCalendarService.init).toHaveBeenCalledWith(currentUserId); //and calendar time table is set for current week expect(ctrlScope.days.length).toBe(mockState.current.daysAmount); expect(ctrlScope.days[0].toString('yyyy-MM-dd')).toBe('2014-10-13'); expect(ctrlScope.days[6].toString('yyyy-MM-dd')).toBe('2014-10-19'); //and events started to be loading expect(mockCalendarService.events.mostRecentCall.args[0].toString('yyyy-MM-dd')).toEqual('2014-10-13'); expect(mockCalendarService.events.mostRecentCall.args[1].toString('yyyy-MM-dd')).toEqual('2014-10-19'); }); it('should initialize monthly view by shifting time table to beginning of the month', function () { //given controller is initialized expect(ctrlScope).toBeDefined(); //and one month display period time mockState.current.daysAmount = 31; //and current user var currentUserId = "doctor-123"; //and current date mockStateParams.currentDate = Date.today().set({ year: 2014, month: 9, day: 13 }); //when initializing calendar ctrlScope.init(); //then calendar is prepared for displaying data of chosen user expect(ctrlScope.doctorId).toBe(currentUserId); expect(mockCalendarService.init).toHaveBeenCalledWith(currentUserId); //and calendar time table is set for beginning of the current month expect(ctrlScope.days.length).toBe(35); expect(ctrlScope.days[0].toString('yyyy-MM-dd')).toBe('2014-09-29'); expect(ctrlScope.days[34].toString('yyyy-MM-dd')).toBe('2014-11-02'); //and events started to be loading expect(mockCalendarService.events.mostRecentCall.args[0].toString('yyyy-MM-dd')).toEqual('2014-09-29'); expect(mockCalendarService.events.mostRecentCall.args[1].toString('yyyy-MM-dd')).toEqual('2014-11-02'); }); it('should initialize daily view', function () { //given controller is initialized expect(ctrlScope).toBeDefined(); //and one day display period time mockState.current.daysAmount = 1; //and current user var currentUserId = "doctor-123"; //and current date mockStateParams.currentDate = Date.today().set({ year: 2014, month: 9, day: 13 }); //when initializing calendar ctrlScope.init(); //then calendar is prepared for displaying data of chosen user expect(ctrlScope.doctorId).toBe(currentUserId); expect(mockCalendarService.init).toHaveBeenCalledWith(currentUserId); //and calendar time table is set for one day only expect(ctrlScope.days.length).toBe(mockState.current.daysAmount); expect(ctrlScope.days[0].toString('yyyy-MM-dd')).toBe('2014-10-13'); //and events started to be loading expect(mockCalendarService.events.mostRecentCall.args[0].toString('yyyy-MM-dd')).toEqual('2014-10-13'); expect(mockCalendarService.events.mostRecentCall.args[1].toString('yyyy-MM-dd')).toEqual('2014-10-13'); }); it('should initialize time table based on current date parameter', function () { //given controller is initialized expect(ctrlScope).toBeDefined(); //and one week display period time mockState.current.daysAmount = 7; //and current user var currentUserId = "doctor-123"; //and current date mockStateParams.currentDate = Date.today().set({ year: 2014, month: 9, day: 3 }); //and current date parameter is present mockStateParams.currentDate = Date.today().set({ year: 2014, month: 9, day: 10 }); //when initializing calendar ctrlScope.init(); //then calendar is prepared for displaying data of chosen user expect(ctrlScope.doctorId).toBe(currentUserId); expect(mockCalendarService.init).toHaveBeenCalledWith(currentUserId); //and calendar time table is set for current week expect(ctrlScope.days.length).toBe(mockState.current.daysAmount); expect(ctrlScope.days[0].toString('yyyy-MM-dd')).toBe('2014-10-06'); expect(ctrlScope.days[6].toString('yyyy-MM-dd')).toBe('2014-10-12'); //and events started to be loading expect(mockCalendarService.events.mostRecentCall.args[0].toString('yyyy-MM-dd')).toEqual('2014-10-06'); expect(mockCalendarService.events.mostRecentCall.args[1].toString('yyyy-MM-dd')).toEqual('2014-10-12'); }); }); describe('calendar data loading-spec:', function () { it('should load data for view', function () { //given controller is initialized expect(ctrlScope).toBeDefined(); ctrlScope.onEventsLoad = function () { ctrlScope.eventLoaded = true; }; //and one day display period time mockState.current.daysAmount = 1; //and current date mockStateParams.currentDate = Date.today().set({ year: 2014, month: 9, day: 13 }); //when loading data for chosen view ctrlScope.init(); //and back-end responded successfully var events = [ { title: 'sample-event', start: mockStateParams.currentDate.clone(), end: mockStateParams.currentDate.clone().add(1).hour() } ]; calendarPromise.onSuccess(events); //then calendar time table is set for one day only expect(ctrlScope.days.length).toBe(mockState.current.daysAmount); expect(ctrlScope.days[0].toString('yyyy-MM-dd')).toBe('2014-10-13'); //and events are loaded expect(mockCalendarService.events.mostRecentCall.args[0].toString('yyyy-MM-dd HH:mm:ss')).toEqual('2014-10-13 00:00:00'); expect(mockCalendarService.events.mostRecentCall.args[1].toString('yyyy-MM-dd HH:mm:ss')).toEqual('2014-10-13 23:59:59'); expect(ctrlScope.eventLoaded).toBe(true); }); it('should inform user when data couldn\'t be loaded', function () { //given controller is initialized expect(ctrlScope).toBeDefined(); //and one day display period time mockState.current.daysAmount = 1; //and current date mockStateParams.currentDate = Date.today().set({ year: 2014, month: 9, day: 13 }); //when loading data for chosen view ctrlScope.init(); //and back-end responded with failure calendarPromise.onError('ERROR'); //then user is informed properly expect(mockUiNotification.error).toHaveBeenCalled(); expect(mockUiNotification.title).toBe('Error'); expect(mockUiNotification.msg).toBe('Couldn\'t load events'); }); it('should refresh data of calendar view', function () { //given controller is initialized expect(ctrlScope).toBeDefined(); //and one day display period time mockState.current.daysAmount = 1; //and current date mockStateParams.currentDate = Date.today().set({ year: 2014, month: 9, day: 13 }); ctrlScope.beginDate = mockStateParams.currentDate; ctrlScope.currentDate = mockStateParams.currentDate; ctrlScope.endDate = mockStateParams.currentDate; ctrlScope.days = [mockStateParams.currentDate]; //when calendar is refreshed ctrlScope.refresh(); //then calendar time table is set for one day only expect(ctrlScope.days.length).toBe(mockState.current.daysAmount); expect(ctrlScope.days[0].toString('yyyy-MM-dd')).toBe('2014-10-13'); //and events are loaded again expect(mockCalendarService.events.mostRecentCall.args[0].toString('yyyy-MM-dd HH:mm:ss')).toEqual('2014-10-13 00:00:00'); expect(mockCalendarService.events.mostRecentCall.args[1].toString('yyyy-MM-dd HH:mm:ss')).toEqual('2014-10-13 23:59:59'); }); it('should load info about calendar owner', function () { //given controller is initialized expect(ctrlScope).toBeDefined(); //and one day display period time mockState.current.daysAmount = 1; //and current date mockStateParams.currentDate = Date.today().set({ year: 2014, month: 9, day: 13 }); //and calendar owner var currentUserId = "doctor-123"; var doctor = { id: currentUserId, first_name: 'Zbigniew', last_name: 'Religa' }; //when calendar is initialized ctrlScope.init(); //and back-end responded successfully userPromise.onSuccess(doctor); //then calendar is prepared for displaying data of chosen user expect(ctrlScope.doctorId).toBe(currentUserId); expect(mockCalendarService.init).toHaveBeenCalledWith(currentUserId); //and info about doctor is loaded expect(ctrlScope.doctor).toBe(doctor); }); it('should inform user when info about calendar owner couldn\'t be loaded', function () { //given controller is initialized expect(ctrlScope).toBeDefined(); //and one day display period time mockState.current.daysAmount = 1; //and current date mockStateParams.currentDate = Date.today().set({ year: 2014, month: 9, day: 13 }); //and calendar owner var currentUserId = "doctor-123"; var doctor = { id: currentUserId, first_name: 'Zbigniew', last_name: 'Religa' }; //when calendar is initialized ctrlScope.init(); //and back-end responded with failure userPromise.onError('Error'); //then calendar is prepared for displaying data of chosen user expect(ctrlScope.doctorId).toBe(currentUserId); expect(mockCalendarService.init).toHaveBeenCalledWith(currentUserId); //and user is informed about failed info loading expect(ctrlScope.doctor).not.toBeDefined(); expect(mockUiNotification.error).toHaveBeenCalled(); expect(mockUiNotification.title).toBe('Error'); expect(mockUiNotification.msg).toBe('Doctor\'s info not loaded - part of functionality may not workking properly'); }); }); describe('calendar navigation for weekly view-spec:', function () { it('should navigate to next week in week view', function () { //given controller is initialized expect(ctrlScope).toBeDefined(); //and one week view mockState.current.daysAmount = 7; //and current time table mockStateParams.currentDate = Date.today().set({ year: 2014, month: 9, day: 14 }); ctrlScope.init(); //when moving to next week ctrlScope.week(1); //then new time table is set expect(ctrlScope.days.length).toBe(mockState.current.daysAmount); expect(ctrlScope.days[0].toString('yyyy-MM-dd')).toBe('2014-10-20'); expect(ctrlScope.days[6].toString('yyyy-MM-dd')).toBe('2014-10-26'); //and events for new time table are loaded expect(mockCalendarService.events.mostRecentCall.args[0].toString('yyyy-MM-dd')).toEqual('2014-10-20'); expect(mockCalendarService.events.mostRecentCall.args[1].toString('yyyy-MM-dd')).toEqual('2014-10-26'); }); it('should navigate to previous week in week view', function () { //given controller is initialized expect(ctrlScope).toBeDefined(); //and one week view mockState.current.daysAmount = 7; //and current time table mockStateParams.currentDate = Date.today().set({ year: 2014, month: 9, day: 14 }); ctrlScope.init(); //when moving to previous week ctrlScope.week(-1); //then new time table is set expect(ctrlScope.days.length).toBe(mockState.current.daysAmount); expect(ctrlScope.days[0].toString('yyyy-MM-dd')).toBe('2014-10-06'); expect(ctrlScope.days[6].toString('yyyy-MM-dd')).toBe('2014-10-12'); //and events for new time table are loaded expect(mockCalendarService.events.mostRecentCall.args[0].toString('yyyy-MM-dd')).toEqual('2014-10-06'); expect(mockCalendarService.events.mostRecentCall.args[1].toString('yyyy-MM-dd')).toEqual('2014-10-12'); }); it('should navigate to next month in weekly view', function () { //given controller is initialized expect(ctrlScope).toBeDefined(); //and one week view mockState.current.daysAmount = 7; //and current time table mockStateParams.currentDate = Date.today().set({ year: 2014, month: 9, day: 14 }); ctrlScope.init(); //when moving to next month ctrlScope.month(1); //then new time table is set expect(ctrlScope.days.length).toBe(mockState.current.daysAmount); expect(ctrlScope.days[0].toString('yyyy-MM-dd')).toBe('2014-11-10'); expect(ctrlScope.days[6].toString('yyyy-MM-dd')).toBe('2014-11-16'); //and events for new time table are loaded expect(mockCalendarService.events.mostRecentCall.args[0].toString('yyyy-MM-dd')).toEqual('2014-11-10'); expect(mockCalendarService.events.mostRecentCall.args[1].toString('yyyy-MM-dd')).toEqual('2014-11-16'); }); it('should navigate to previous month in weekly view', function () { //given controller is initialized expect(ctrlScope).toBeDefined(); //and one week view mockState.current.daysAmount = 7; //and current time table mockStateParams.currentDate = Date.today().set({ year: 2014, month: 9, day: 14 }); ctrlScope.init(); //when moving to previous month ctrlScope.month(-1); //then new time table is set expect(ctrlScope.days.length).toBe(mockState.current.daysAmount); expect(ctrlScope.days[0].toString('yyyy-MM-dd')).toBe('2014-09-08'); expect(ctrlScope.days[6].toString('yyyy-MM-dd')).toBe('2014-09-14'); //and events for new time table are loaded expect(mockCalendarService.events.mostRecentCall.args[0].toString('yyyy-MM-dd')).toEqual('2014-09-08'); expect(mockCalendarService.events.mostRecentCall.args[1].toString('yyyy-MM-dd')).toEqual('2014-09-14'); }); it('should navigate to next year in weekly view', function () { //given controller is initialized expect(ctrlScope).toBeDefined(); //and one week view mockState.current.daysAmount = 7; //and current time table mockStateParams.currentDate = Date.today().set({ year: 2014, month: 9, day: 14 }); ctrlScope.init(); //when moving to next year ctrlScope.year(1); //then new time table is set expect(ctrlScope.days.length).toBe(mockState.current.daysAmount); expect(ctrlScope.days[0].toString('yyyy-MM-dd')).toBe('2015-10-12'); expect(ctrlScope.days[6].toString('yyyy-MM-dd')).toBe('2015-10-18'); //and events for new time table are loaded expect(mockCalendarService.events.mostRecentCall.args[0].toString('yyyy-MM-dd')).toEqual('2015-10-12'); expect(mockCalendarService.events.mostRecentCall.args[1].toString('yyyy-MM-dd')).toEqual('2015-10-18'); }); it('should navigate to previous year in weekly view', function () { //given controller is initialized expect(ctrlScope).toBeDefined(); //and one week view mockState.current.daysAmount = 7; //and current time table mockStateParams.currentDate = Date.today().set({ year: 2014, month: 9, day: 14 }); ctrlScope.init(); //when moving to next year ctrlScope.year(-1); //then new time table is set expect(ctrlScope.days.length).toBe(mockState.current.daysAmount); expect(ctrlScope.days[0].toString('yyyy-MM-dd')).toBe('2013-10-14'); expect(ctrlScope.days[6].toString('yyyy-MM-dd')).toBe('2013-10-20'); //and events for new time table are loaded expect(mockCalendarService.events.mostRecentCall.args[0].toString('yyyy-MM-dd')).toEqual('2013-10-14'); expect(mockCalendarService.events.mostRecentCall.args[1].toString('yyyy-MM-dd')).toEqual('2013-10-20'); }); }); describe('calendar navigation for monthly view-spec:', function () { it('should navigate to next month in monthly view', function () { //given controller is initialized expect(ctrlScope).toBeDefined(); //and one month view mockState.current.daysAmount = 31; //and current time table mockStateParams.currentDate = Date.today().set({ year: 2014, month: 9, day: 14 }); ctrlScope.init(); //when moving to next month ctrlScope.month(1); //then new time table is set expect(ctrlScope.days.length).toBe(35); expect(ctrlScope.days[0].toString('yyyy-MM-dd')).toBe('2014-10-27'); expect(ctrlScope.days[34].toString('yyyy-MM-dd')).toBe('2014-11-30'); //and events for new time table are loaded expect(mockCalendarService.events.mostRecentCall.args[0].toString('yyyy-MM-dd')).toEqual('2014-10-27'); expect(mockCalendarService.events.mostRecentCall.args[1].toString('yyyy-MM-dd')).toEqual('2014-11-30'); }); it('should navigate to previous month in monthly view', function () { //given controller is initialized expect(ctrlScope).toBeDefined(); //and one month view mockState.current.daysAmount = 31; //and current time table mockStateParams.currentDate = Date.today().set({ year: 2014, month: 9, day: 14 }); ctrlScope.init(); //when moving to previous month ctrlScope.month(-1); //then new time table is set expect(ctrlScope.days.length).toBe(35); expect(ctrlScope.days[0].toString('yyyy-MM-dd')).toBe('2014-09-01'); expect(ctrlScope.days[34].toString('yyyy-MM-dd')).toBe('2014-10-05'); //and events for new time table are loaded expect(mockCalendarService.events.mostRecentCall.args[0].toString('yyyy-MM-dd')).toEqual('2014-09-01'); expect(mockCalendarService.events.mostRecentCall.args[1].toString('yyyy-MM-dd')).toEqual('2014-10-05'); }); it('should navigate to previous year in monthly view', function () { //given controller is initialized expect(ctrlScope).toBeDefined(); //and one month view mockState.current.daysAmount = 31; //and current time table mockStateParams.currentDate = Date.today().set({ year: 2014, month: 9, day: 14 }); ctrlScope.init(); //when moving to previous year ctrlScope.year(-1); //then new time table is set expect(ctrlScope.days.length).toBe(35); expect(ctrlScope.days[0].toString('yyyy-MM-dd')).toBe('2013-09-30'); expect(ctrlScope.days[34].toString('yyyy-MM-dd')).toBe('2013-11-03'); //and events for new time table are loaded expect(mockCalendarService.events.mostRecentCall.args[0].toString('yyyy-MM-dd')).toEqual('2013-09-30'); expect(mockCalendarService.events.mostRecentCall.args[1].toString('yyyy-MM-dd')).toEqual('2013-11-03'); }); it('should navigate to next year in monthly view', function () { //given controller is initialized expect(ctrlScope).toBeDefined(); //and one month view mockState.current.daysAmount = 31; //and current time table mockStateParams.currentDate = Date.today().set({ year: 2014, month: 9, day: 14 }); ctrlScope.init(); //when moving to next year ctrlScope.year(1); //then new time table is set expect(ctrlScope.days.length).toBe(35); expect(ctrlScope.days[0].toString('yyyy-MM-dd')).toBe('2015-09-28'); expect(ctrlScope.days[34].toString('yyyy-MM-dd')).toBe('2015-11-01'); //and events for new time table are loaded expect(mockCalendarService.events.mostRecentCall.args[0].toString('yyyy-MM-dd')).toEqual('2015-09-28'); expect(mockCalendarService.events.mostRecentCall.args[1].toString('yyyy-MM-dd')).toEqual('2015-11-01'); }); }); describe('calendar navigation for daily view-spec:', function () { it('should navigate to next day in daily view', function () { //given controller is initialized expect(ctrlScope).toBeDefined(); //and one day view mockState.current.daysAmount = 1; //and current time table mockStateParams.currentDate = Date.today().set({ year: 2014, month: 9, day: 14 }); ctrlScope.init(); //when moving to next day ctrlScope.day(1); //then new time table is set expect(ctrlScope.days.length).toBe(mockState.current.daysAmount); expect(ctrlScope.days[0].toString('yyyy-MM-dd')).toBe('2014-10-15'); //and events for new time table are loaded expect(mockCalendarService.events.mostRecentCall.args[0].toString('yyyy-MM-dd')).toEqual('2014-10-15'); expect(mockCalendarService.events.mostRecentCall.args[1].toString('yyyy-MM-dd')).toEqual('2014-10-15'); }); it('should navigate to previous day in daily view', function () { //given controller is initialized expect(ctrlScope).toBeDefined(); //and one day view mockState.current.daysAmount = 1; //and current time table mockStateParams.currentDate = Date.today().set({ year: 2014, month: 9, day: 14 }); ctrlScope.init(); //when moving to previous day ctrlScope.day(-1); //then new time table is set expect(ctrlScope.days.length).toBe(mockState.current.daysAmount); expect(ctrlScope.days[0].toString('yyyy-MM-dd')).toBe('2014-10-13'); //and events for new time table are loaded expect(mockCalendarService.events.mostRecentCall.args[0].toString('yyyy-MM-dd')).toEqual('2014-10-13'); expect(mockCalendarService.events.mostRecentCall.args[1].toString('yyyy-MM-dd')).toEqual('2014-10-13'); }); it('should navigate to next month in daily view', function () { //given controller is initialized expect(ctrlScope).toBeDefined(); //and one day view mockState.current.daysAmount = 1; //and current time table mockStateParams.currentDate = Date.today().set({ year: 2014, month: 9, day: 14 }); ctrlScope.init(); //when moving to next month ctrlScope.month(1); //then new time table is set expect(ctrlScope.days.length).toBe(mockState.current.daysAmount); expect(ctrlScope.days[0].toString('yyyy-MM-dd')).toBe('2014-11-14'); //and events for new time table are loaded expect(mockCalendarService.events.mostRecentCall.args[0].toString('yyyy-MM-dd')).toEqual('2014-11-14'); expect(mockCalendarService.events.mostRecentCall.args[1].toString('yyyy-MM-dd')).toEqual('2014-11-14'); }); it('should navigate to previous month in daily view', function () { //given controller is initialized expect(ctrlScope).toBeDefined(); //and one day view mockState.current.daysAmount = 1; //and current time table mockStateParams.currentDate = Date.today().set({ year: 2014, month: 9, day: 14 }); ctrlScope.init(); //when moving to previous month ctrlScope.month(-1); //then new time table is set expect(ctrlScope.days.length).toBe(mockState.current.daysAmount); expect(ctrlScope.days[0].toString('yyyy-MM-dd')).toBe('2014-09-14'); //and events for new time table are loaded expect(mockCalendarService.events.mostRecentCall.args[0].toString('yyyy-MM-dd')).toEqual('2014-09-14'); expect(mockCalendarService.events.mostRecentCall.args[1].toString('yyyy-MM-dd')).toEqual('2014-09-14'); }); it('should navigate to next year in daily view', function () { //given controller is initialized expect(ctrlScope).toBeDefined(); //and one day view mockState.current.daysAmount = 1; //and current time table mockStateParams.currentDate = Date.today().set({ year: 2014, month: 9, day: 14 }); ctrlScope.init(); //when moving to next year ctrlScope.year(1); //then new time table is set expect(ctrlScope.days.length).toBe(mockState.current.daysAmount); expect(ctrlScope.days[0].toString('yyyy-MM-dd')).toBe('2015-10-14'); //and events for new time table are loaded expect(mockCalendarService.events.mostRecentCall.args[0].toString('yyyy-MM-dd')).toEqual('2015-10-14'); expect(mockCalendarService.events.mostRecentCall.args[1].toString('yyyy-MM-dd')).toEqual('2015-10-14'); }); it('should navigate to previous year in daily view', function () { //given controller is initialized expect(ctrlScope).toBeDefined(); //and one day view mockState.current.daysAmount = 1; //and current time table mockStateParams.currentDate = Date.today().set({ year: 2014, month: 9, day: 14 }); ctrlScope.init(); //when moving to previous year ctrlScope.year(-1); //then new time table is set expect(ctrlScope.days.length).toBe(mockState.current.daysAmount); expect(ctrlScope.days[0].toString('yyyy-MM-dd')).toBe('2013-10-14'); //and events for new time table are loaded expect(mockCalendarService.events.mostRecentCall.args[0].toString('yyyy-MM-dd')).toEqual('2013-10-14'); expect(mockCalendarService.events.mostRecentCall.args[1].toString('yyyy-MM-dd')).toEqual('2013-10-14'); }); }); describe('calendar menu-spec:', function () { it('should show mini-calendar', function () { //given controller is initialized expect(ctrlScope).toBeDefined(); //and one week display period time mockState.current.daysAmount = 7; //and current user var currentUserId = "doctor-123"; //and current date mockStateParams.currentDate = Date.today().set({ year: 2014, month: 9, day: 3 }); //and calendar is initialized ctrlScope.init(); expect(ctrlScope.datePickerOpened).not.toBeDefined(); //when showing mini-calendar var event = jasmine.createSpyObj('$event', ['preventDefault', 'stopPropagation']); ctrlScope.showDatePicker(event); //then mini-calendar is shown expect(ctrlScope.datePickerOpened).toBe(true); expect(event.preventDefault).toHaveBeenCalled(); expect(event.stopPropagation).toHaveBeenCalled(); }); it('should hide mini-calendar', function () { //given controller is initialized expect(ctrlScope).toBeDefined(); //and one week display period time mockState.current.daysAmount = 7; //and current user var currentUserId = "doctor-123"; //and current date mockStateParams.currentDate = Date.today().set({ year: 2014, month: 9, day: 3 }); //and calendar is initialized ctrlScope.init(); expect(ctrlScope.datePickerOpened).not.toBeDefined(); //and mini-calendar is shown var event = jasmine.createSpyObj('$event', ['preventDefault', 'stopPropagation']); ctrlScope.showDatePicker(event); expect(ctrlScope.datePickerOpened).toBe(true); //when calling show date picker once again ctrlScope.showDatePicker(event); //then mini-calendar is hidden expect(ctrlScope.datePickerOpened).toBe(false); }); it('should reset current data param when data is changed using mini-calendar', function () { //given controller is initialized expect(ctrlScope).toBeDefined(); //and one week display period time mockState.current.daysAmount = 7; //and current user var currentUserId = "doctor-123"; //and current date mockStateParams.currentDate = Date.today().set({ year: 2014, month: 9, day: 3 }); //and calendar is initialized ctrlScope.init(); expect(ctrlScope.datePickerOpened).not.toBeDefined(); //and mini-calendar is shown var event = jasmine.createSpyObj('$event', ['preventDefault', 'stopPropagation']); ctrlScope.showDatePicker(event); expect(ctrlScope.datePickerOpened).toBe(true); //when date is chosen using mini-calendar ctrlScope.currentDate = Date.today().set({ year: 2014, month: 9, day: 10 }); ctrlScope.onDatePickerDateChange(); //then mini-calendar is hidden expect(ctrlScope.datePickerOpened).toBe(false); //and loading of data has started expect(mockCalendarService.events.mostRecentCall.args[0].toString('yyyy-MM-dd')).toEqual('2014-10-06'); expect(mockCalendarService.events.mostRecentCall.args[1].toString('yyyy-MM-dd')).toEqual('2014-10-12'); }); }); }); });
#!/bin/bash ./build.sh && \ ./push.sh && \ ./deploy.sh
package ddbt.lib.store import scala.reflect._ import ddbt.Utils.ind import scala.collection.mutable.HashMap class Container[E<:Entry]()(implicit cE:ClassTag[E])
func testExample() { // Test case 1: Factorial of 0 should be 1 XCTAssertEqual(factorial(0), 1, "Factorial of 0 should be 1") // Test case 2: Factorial of 1 should be 1 XCTAssertEqual(factorial(1), 1, "Factorial of 1 should be 1") // Test case 3: Factorial of 5 should be 120 XCTAssertEqual(factorial(5), 120, "Factorial of 5 should be 120") // Test case 4: Factorial of 10 should be 3628800 XCTAssertEqual(factorial(10), 3628800, "Factorial of 10 should be 3628800") // Test case 5: Factorial of 12 should be 479001600 XCTAssertEqual(factorial(12), 479001600, "Factorial of 12 should be 479001600") }
<reponame>Olalaye/MegEngine # -*- coding: utf-8 -*- # MegEngine is Licensed under the Apache License, Version 2.0 (the "License") # # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import os import platform import re import subprocess import tempfile import lit.formats import lit.util from lit.llvm import llvm_config from lit.llvm.subst import ToolSubst from lit.llvm.subst import FindTool # Configuration file for the 'lit' test runner. # name: The name of this test suite. config.name = 'MLIR_TEST' config.test_format = lit.formats.ShTest(not llvm_config.use_lit_shell) # suffixes: A list of file extensions to treat as test files. config.suffixes = ['.mlir'] # test_source_root: The root path where tests are located. config.test_source_root = os.path.join(os.path.dirname(__file__), '../ir') # test_exec_root: The root path where tests should be run. config.test_exec_root = config.test_source_root # llvm_config.use_default_substitutions() # Tweak the PATH to include the tools dir. llvm_config.with_environment('PATH', config.llvm_tools_dir, append_path=True) tool_dirs = [ os.path.join(config.mgb_obj_root, 'tools/mlir'), os.path.join(config.mgb_obj_root, 'tools/mlir/mgb-opt'), os.path.join(config.mgb_obj_root, 'tools/mlir/mgb-file-check'), config.llvm_tools_dir] tool_names = [ 'mgb-opt', 'mlir-tblgen', 'mlir-translate', 'mgb-file-check', ] tools = [ToolSubst(s, unresolved='ignore') for s in tool_names] llvm_config.add_tool_substitutions(tools, tool_dirs) lit.llvm.initialize(lit_config, config)
<filename>src/patches/gooseupdate.js import { join } from 'path'; import Inquirer from 'inquirer'; import replaceInFile from '../lib/replaceInFile.js'; export default async ({ asarExtractPath }) => { let { branch } = await Inquirer.prompt([ { type: 'checkbox', name: 'branch', message: 'GooseUpdate mods', choices: [ 'smartcord', 'betterdiscord', { name: 'goosemod', checked: true } ] } ]); branch = branch.join('+'); replaceInFile(join(asarExtractPath, 'app_bootstrap', 'Constants.js'), `const UPDATE_ENDPOINT = settings.get('UPDATE_ENDPOINT') || API_ENDPOINT`, `const UPDATE_ENDPOINT = settings.get('UPDATE_ENDPOINT') || 'https://updates.goosemod.com/${branch}'`); replaceInFile(join(asarExtractPath, 'app_bootstrap', 'Constants.js'), `const NEW_UPDATE_ENDPOINT = settings.get('NEW_UPDATE_ENDPOINT') || 'https://discord.com/api/updates/'`, `const NEW_UPDATE_ENDPOINT = settings.get('NEW_UPDATE_ENDPOINT') || 'https://updates.goosemod.com/${branch}/'`); replaceInFile(join(asarExtractPath, 'common', 'Settings.js'), `return defaultValue`, `return key === 'SKIP_HOST_UPDATE' ? true : defaultValue`); };
def search_elem(my_list1, my_list2, elem): for list in [my_list1, my_list2]: found = False for val in list: if val == elem: found = True break if found: return True return False found = search_elem(my_list1, my_list2, elem) print(found)
#include "File.h" #include "../Container/AsciiString.h" #include "../OSDefine.h" #include <cassert> #include <cstdlib> #include <cstdio> #include <cwchar> #if defined(OSUnix) #include <sys/stat.h> #include <unistd.h> #include <dirent.h> #include <libgen.h> #define FileRemoveA remove #define FileRemoveW(string) remove((const char*)string) #define FileRenameA rename #define FileRenameW(oldName, newName) rename((const char*)oldName, (const char*)newName) #define FileDirectoryCreateA(string) mkdir(string, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) #define FileDirectoryCreateW(string) FileDirectoryCreateA((const char*)string) #define WorkingDirectoryCurrentA getcwd #define WorkingDirectoryCurrentW(string, size) (wchar_t*)WorkingDirectoryCurrentA((char*)string, size) #define WorkingDirectoryChangeA chdir #define WorkingDirectoryChangeW(string) WorkingDirectoryChangeA((const char*)string) #elif defined(OSWindows) #include <direct.h> #define FileRemoveA remove #define FileRemoveW _wremove #define FileRenameA rename #define FileRenameW _wrename #define FileDirectoryCreateA _mkdir #define FileDirectoryCreateW _wmkdir #define WorkingDirectoryCurrentA _getcwd #define WorkingDirectoryCurrentW _wgetcwd #define WorkingDirectoryChangeA _chdir #define WorkingDirectoryChangeW _wchdir #include <Windows.h> #endif #include "Text.h" BF::FileActionResult BF::File::CheckFile() { if (!DoesFileExist(Path)) { return BF::FileActionResult::FileNotFound; } return BF::FileActionResult::Successful; } BF::File::File() { SetFilePath((wchar_t*)nullptr); } BF::File::File(const char* filePath) { SetFilePath(filePath); } BF::File::File(const wchar_t* filePath) { SetFilePath(filePath); } BF::FileActionResult BF::File::Open(const char* filePath, FileOpenMode fileOpenMode) { const char* readMode = nullptr; switch (fileOpenMode) { case BF::FileOpenMode::Read: readMode = FileReadMode; break; case BF::FileOpenMode::Write: readMode = FileWriteMode; break; } assert(readMode != nullptr); FileMarker = fopen(filePath, readMode); return FileMarker ? FileActionResult::Successful : FileActionResult::FileOpenFailure; } BF::FileActionResult BF::File::Open(const wchar_t* filePath, FileOpenMode fileOpenMode) { #if defined(OSUnix) File::Open((const char*)filePath, fileOpenMode); #elif defined(OSWindows) const wchar_t* readMode = nullptr; switch (fileOpenMode) { case BF::FileOpenMode::Read: readMode = FileReadModeW; break; case BF::FileOpenMode::Write: readMode = FileWriteModeW; break; } assert(readMode != nullptr); FileMarker = _wfopen(filePath, readMode); return FileMarker ? FileActionResult::Successful : FileActionResult::FileOpenFailure; #endif } BF::FileActionResult BF::File::Close() { int closeResult = fclose(FileMarker); switch (closeResult) { case 0: return FileActionResult::Successful; default: return FileActionResult::FileCloseFailure; } } BF::ErrorCode BF::File::Remove() { return BF::File::Remove(Path); } BF::ErrorCode BF::File::Remove(const char* filePath) { int removeResult = FileRemoveA(filePath); ErrorCode errorCode = ConvertErrorCode(removeResult); return errorCode; } BF::ErrorCode BF::File::Remove(const wchar_t* filePath) { int removeResult = FileRemoveW(filePath); ErrorCode errorCode = ConvertErrorCode(removeResult); return errorCode; } BF::ErrorCode BF::File::Rename(const char* name) { wchar_t nameW[FileNameMaxSize]; mbstowcs(nameW, name, FileNameMaxSize - 1); return File::Rename(Path, nameW); } BF::ErrorCode BF::File::Rename(const char* oldName, const char* newName) { int renameResult = FileRenameA(oldName, newName); ErrorCode errorCode = ConvertErrorCode(renameResult); return errorCode; } BF::ErrorCode BF::File::Rename(const wchar_t* name) { return File::Rename(Path, name); } BF::ErrorCode BF::File::Rename(const wchar_t* oldName, const wchar_t* newName) { int renameResult = FileRenameW(oldName, newName); bool wasSuccesful = renameResult == 0; if (!wasSuccesful) { return GetCurrentError(); } return ErrorCode::Successful; } BF::FileActionResult BF::File::Copy(const char* sourceFilePath, const char* destinationFilePath, char* swapBuffer, size_t swapBufferSize) { if (!sourceFilePath || !destinationFilePath) { return FileActionResult::EmptyPath; } FILE* fileSource = fopen(sourceFilePath, FileReadMode); FILE* fileDestination = fopen(destinationFilePath, FileWriteMode); bool fileOpenSuccesful = fileSource && fileDestination; if (!fileOpenSuccesful) { return FileActionResult::FileOpenFailure; } while (!feof(fileSource)) { size_t readBytes = fread(swapBuffer, sizeof(char), swapBufferSize, fileSource); size_t writtenBytes = fwrite(swapBuffer, sizeof(char), readBytes, fileDestination); } fclose(fileSource); fclose(fileDestination); return FileActionResult::Successful; } BF::ErrorCode BF::File::DirectoryCreate(const char* directoryName) { int creationResult = FileDirectoryCreateA(directoryName); bool wasSuccesful = creationResult == 0; if (!wasSuccesful) { return GetCurrentError(); } return ErrorCode::Successful; } BF::ErrorCode BF::File::DirectoryCreate(const wchar_t* directoryName) { int creationResult = FileDirectoryCreateW(directoryName); bool wasSuccesful = creationResult == 0; if (!wasSuccesful) { return GetCurrentError(); } return ErrorCode::Successful; } BF::ErrorCode BF::File::WorkingDirectoryGet(char* workingDirectory, size_t workingDirectorySize) { char* workingDirectoryResult = WorkingDirectoryCurrentA(workingDirectory, workingDirectorySize); bool wasSuccesful = workingDirectoryResult != nullptr; if (!wasSuccesful) { return GetCurrentError(); } return ErrorCode::Successful; } BF::ErrorCode BF::File::WorkingDirectoryGet(wchar_t* workingDirectory, size_t workingDirectorySize) { wchar_t* workingDirectoryResult = WorkingDirectoryCurrentW(workingDirectory, workingDirectorySize); bool wasSuccesful = workingDirectoryResult != nullptr; if (!wasSuccesful) { return GetCurrentError(); } return ErrorCode::Successful; } BF::ErrorCode BF::File::WorkingDirectoryChange(const char* directoryName) { int creationResult = WorkingDirectoryChangeA(directoryName); bool wasSuccesful = creationResult == 0; if (!wasSuccesful) { return GetCurrentError(); } return ErrorCode::Successful; } BF::ErrorCode BF::File::WorkingDirectoryChange(const wchar_t* directoryName) { int creationResult = WorkingDirectoryChangeW(directoryName); bool wasSuccesful = creationResult == 0; if (!wasSuccesful) { return GetCurrentError(); } return ErrorCode::Successful; } BF::ErrorCode BF::File::DirectoryDelete(const char* directoryName) { int creationResult = FileRemoveA(directoryName); bool wasSuccesful = creationResult == 0; if (!wasSuccesful) { return GetCurrentError(); } return ErrorCode::Successful; } BF::ErrorCode BF::File::DirectoryDelete(const wchar_t* directoryName) { int creationResult = FileRemoveW(directoryName); bool wasSuccesful = creationResult == 0; if (!wasSuccesful) { return GetCurrentError(); } return ErrorCode::Successful; } void BF::File::SetFilePath(const char* filePath) { if (!filePath) { SetFilePath((wchar_t*)nullptr); return; } wchar_t filePathW[PathMaxSize]; Text::AsciiToUnicode(filePath, PathMaxSize, filePathW,PathMaxSize); SetFilePath(filePathW); } void BF::File::SetFilePath(const wchar_t* filePath) { FileMarker = nullptr; if (filePath == nullptr) { Path[0] = '\0'; Drive[0] = '\0'; Directory[0] = '\0'; FileName[0] = '\0'; Extension[0] = '\0'; return; } Text::Copy(Path, filePath, PathMaxSize); PathSplitt(filePath, Drive, Directory, FileName, Extension); } void BF::File::PathSwapFile(const wchar_t* currnetPath, wchar_t* targetPath, const wchar_t* newFileName) { const size_t index = Text::FindLast(currnetPath, PathMaxSize, '/'); const bool found = index != -1; if (found) { size_t copyedBytes = Text::Copy(targetPath, currnetPath, index + 1); Text::Copy(targetPath + copyedBytes, newFileName, 260 - copyedBytes); } } void BF::File::FilesInFolder(const char* folderPath, wchar_t*** list, size_t& listSize) { wchar_t folderPathW[PathMaxSize]; size_t writtenBytes = mbstowcs(folderPathW, folderPath, PathMaxSize); #if defined(OSUnix) DIR* directory = opendir(folderPath); if (directory) { struct dirent* directoryInfo = nullptr; while (directoryInfo = readdir(directory)) { ++listSize; } rewinddir(directory); (*list) = (wchar_t**)malloc(listSize * sizeof(wchar_t*)); for (size_t index = 0; directoryInfo = readdir(directory); index++) { bool isFile = directoryInfo->d_type == DT_REG || true; if (isFile) { const char* fileName = directoryInfo->d_name; size_t length = strlen(fileName); wchar_t* newString = (wchar_t*)malloc((length + 1) * sizeof(wchar_t)); wchar_t** target = &(*list)[index]; if (!newString) { return; // Error: OutOfMemory } (*target) = newString; size_t writtenBytes = mbstowcs(*target, fileName, 255); } } closedir(directory); } #elif defined(OSWindows) WIN32_FIND_DATA dataCursour; HANDLE hFind = 0; memset(&dataCursour, 0, sizeof(WIN32_FIND_DATA)); hFind = FindFirstFile(folderPathW, &dataCursour); // "/*.*"; bool foundData = hFind != INVALID_HANDLE_VALUE; if (!foundData) { return; } ++listSize; for (; FindNextFile(hFind, &dataCursour); listSize++); memset(&dataCursour, 0, sizeof(WIN32_FIND_DATA)); (*list) = (wchar_t**)malloc(listSize * sizeof(wchar_t*)); hFind = FindFirstFile(folderPathW, &dataCursour); // Expected "." Folder size_t fileIndex = 0; do { size_t length = wcslen(dataCursour.cFileName); wchar_t* filePathSource = dataCursour.cFileName; wchar_t* newString = (wchar_t*)malloc((length + 1) * sizeof(wchar_t)); if (!newString) { return; // Error: OutOfMemory } memcpy(newString, filePathSource, sizeof(wchar_t) * length); newString[length] = L'\0'; (*list)[fileIndex] = newString; fileIndex++; } while (FindNextFile(hFind, &dataCursour)); FindClose(hFind); #endif } void BF::File::PathSplitt(const char* fullPath, char* drive, char* directory, char* fileName, char* extension) { PathSplitt ( fullPath, PathMaxSize, drive, DriveMaxSize, directory, DirectoryMaxSize, fileName, FileNameMaxSize, extension, ExtensionMaxSize ); } void BF::File::PathSplitt ( const char* fullPath, size_t fullPathMaxSize, char* drive, size_t driveMaxSize, char* directory, size_t directoryMaxSize, char* fileName, size_t fileNameMaxSize, char* extension, size_t extensionMaxSize ) { #if defined(OSUnix) char directoryNameCache[PathMaxSize]; char baseNameCache[FileNameMaxSize]; strncpy(baseNameCache, fullPath, FileNameMaxSize); char* dirNameResult = dirname(directoryNameCache); char* baseNameResult = basename(baseNameCache); strncpy(directory, dirNameResult, DirectoryMaxSize); strncpy(fileName, baseNameResult, FileNameMaxSize); for (size_t i = 0; fileName[i] != '\0'; i++) { bool isDot = fileName[i] == '.'; if (isDot) { strcpy(extension, fileName + i); fileName[i] = '\0'; break; } } #elif defined(OSWindows) char fileNameCache[FileNameMaxSize]; _splitpath_s ( fullPath, drive, driveMaxSize, directory, directoryMaxSize, fileName, fileNameMaxSize, extension, extensionMaxSize ); for (size_t i = 0; fileName[i] != '\0'; i++) { bool isDot = fileName[i] == '.'; if (isDot) { Text::Copy(fileNameCache, extension + i, FileNameMaxSize); Text::Copy(extension, fileNameCache, FileNameMaxSize); break; } } #endif } void BF::File::PathSplitt(const wchar_t* fullPath, wchar_t* drive, wchar_t* directory, wchar_t* fileName, wchar_t* extension) { PathSplitt ( fullPath, PathMaxSize, drive, DriveMaxSize, directory, DirectoryMaxSize, fileName, FileNameMaxSize, extension, ExtensionMaxSize ); } void BF::File::PathSplitt(const wchar_t* fullPath, size_t fullPathMaxSize, wchar_t* drive, size_t driveMaxSize, wchar_t* directory, size_t directoryMaxSize, wchar_t* fileName, size_t fileNameMaxSize, wchar_t* extension, size_t extensionMaxSize) { #if defined(OSUnix) PathSplitt ( (const char*)fullPath, PathMaxSize, (char*)drive, DriveMaxSize, (char*)directory, DirectoryMaxSize, (char*)fileName, FileNameMaxSize, (char*)extension, ExtensionMaxSize ); #elif defined(OSWindows) wchar_t extensionCache[FileNameMaxSize]; _wsplitpath_s ( fullPath, drive, driveMaxSize, directory, directoryMaxSize, fileName, fileNameMaxSize, extension, extensionMaxSize ); for (size_t i = 0; extension[i] != '\0'; i++) { bool isDot = extension[i] == '.'; if (isDot) { Text::Copy(extensionCache, extension + i + 1, FileNameMaxSize); Text::Copy(extension, extensionCache, FileNameMaxSize); break; } } #endif } bool BF::File::DoesFileExist() { FileActionResult fileActionResult = Open(Path, FileOpenMode::Read); if (fileActionResult == FileActionResult::Successful) { Close(); return true; } else { return false; } } bool BF::File::DoesFileExist(const char* filePath) { FILE* file = fopen(filePath, "rb"); if (file) { fclose(file); return true; } return false; } bool BF::File::DoesFileExist(const wchar_t* filePath) { File file(filePath); return file.DoesFileExist(); } void BF::File::GetFileExtension(const char* filePath, char* fileExtension) { char dummyBuffer[PathMaxSize]; PathSplitt(filePath, dummyBuffer, dummyBuffer, dummyBuffer, fileExtension); } bool BF::File::ExtensionEquals(const char* extension) { return Text::CompareIgnoreCase(Extension, extension, ExtensionMaxSize); } bool BF::File::ExtensionEquals(const wchar_t* extension) { return Text::CompareIgnoreCase(Extension, extension, ExtensionMaxSize); }
package edu.unitn.pbam.androidproject.model.dao; import android.database.Cursor; import edu.unitn.pbam.androidproject.model.DList; import edu.unitn.pbam.androidproject.model.DList.Type; public interface DListDao extends ModelDao<DList> { public Cursor getByType(Type t); }
<gh_stars>1-10 /** * Copyright 2020 The AMP HTML 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 {Entity, PrimaryColumn} from 'typeorm'; @Entity() export class Release { constructor(name: string) { this.name = name; } @PrimaryColumn('varchar', {length: 13}) name: string; //TODO(ajwhatson): fill out table here. See https://typeorm.io/#/undefined/column-data-types }
#!/bin/bash function DecryptString() { echo "${1}" | /usr/bin/openssl enc -aes256 -d -a -A -S "${2}" -k "${3}" } EncryptedString="U2FsdGVkX1+1nTgI0CtcIWeucYoiUzsRzEiQKmbBKDQ=" Salt="b59d3808d02b5c21" Passphrase="21899c3d8247dce72ad190d9" jamfpro_username="jamfproadmin" jamfpro_password=$(DecryptString "${EncryptedString}" "${Salt}" "${Passphrase}") jamfpro_url="https://jamf.pro.server.here:8443" curl -su "$jamfpro_username":"$jamfpro_password" -H "Accept: text/xml" "$jamfpro_url"/JSSResource/computers
#!/bin/bash # The arguments that are passed by Jenkins system TEST_ARG="" JDK_VERSION="8" TASK_NAME="" LOG_LEVEL="" BRANCH="default" JEREPO="" JEREVISION=0 JEREVISIONARG="" HGPATH="" PRE="" # Jenkins VM and Test VM JENKINSVMIP="slc04ark" JENKINSVMUSERNAME="jenkins" JENKINSVM="${JENKINSVMUSERNAME}@${JENKINSVMIP}" TESTVM=`hostname -s` TESTVMUSERNAME="tests" TESTVMUSERPASSWORD="123456" # The user name used to get the je repository JEREPUSER="adqian" # Some basic direcotory/path/filename BASEDIR="/scratch/tests" REMOTEBASEDIR="/scratch/tests" JENKINSBASEDIR="/scratch/jenkins/jobs" CHANGESETFILE="jenkins_changeset.txt" ENVINFOFILE="location_of_environment_and_log.txt" while getopts "O:j:t:R:b:r:l:h:p:" OPTION do case $OPTION in O) TEST_ARG=$OPTARG ;; j) JDK_VERSION=$OPTARG ;; t) TASK_NAME=$OPTARG ;; R) JEREPO=$OPTARG ;; b) BRANCH=$OPTARG ;; r) JEREVISION=$OPTARG ;; l) LOG_LEVEL=$OPTARG ;; h) HGPATH=$OPTARG ;; p) PRE=$OPTARG esac done if [ "${JEREPO}" == "" ]; then echo "JE repository must be specified" exit 1 fi if [ "${JEREVISION}" != "0" ]; then JEREVISIONARG=" -u ${JEREVISION}" fi if [ "${HGPATH}" != "" ]; then HGPATH="${HGPATH}/" fi # 1.Only je_unit_aix needs to be handled specially if [ "${TASK_NAME}" == "je_unit_aix" ]; then JDK_VERSION="AIX" BASEDIR="/scratch/nosql" TESTVMUSERNAME="nosql" TESTVMUSERPASSWORD="q" fi echo "Task name: $TASK_NAME" echo "Test args: $TEST_ARG" echo "JE repo: ssh://${JEREPUSER}@${JEREPO}" echo "JE branch: $BRANCH" echo "JE revision(0 means the top): $JEREVISION" # hg clone je if [ "${TASK_NAME}" == "je_unit_aix" ]; then ssh tests@slc04arq "rm -rf ${REMOTEBASEDIR}/${TASK_NAME} && mkdir -p ${REMOTEBASEDIR}/${TASK_NAME}" echo "hg clone -b ${BRANCH} ${JEREVISIONARG} ssh://${JEREPUSER}@${JEREPO}" ssh tests@slc04arq "cd ${REMOTEBASEDIR}/${TASK_NAME} && ${HGPATH}hg clone -b ${BRANCH} ${JEREVISIONARG} ssh://${JEREPUSER}@${JEREPO} ./je" ssh tests@slc04arq "cd ${REMOTEBASEDIR}/${TASK_NAME}/je && ${HGPATH}hg log -l 1 -v > ./jenkins_changeset.txt" BUILD_VER=`ssh tests@slc04arq "cd ${REMOTEBASEDIR}/${TASK_NAME}/je && ${HGPATH}hg parent"` rm -rf ${BASEDIR}/${TASK_NAME} scp -r tests@slc04arq:${REMOTEBASEDIR}/${TASK_NAME} ${BASEDIR} else rm -rf ${BASEDIR}/${TASK_NAME} && mkdir -p ${BASEDIR}/${TASK_NAME} echo "hg clone -b ${BRANCH} ${JEREVISIONARG} ssh://${JEREPUSER}@${JEREPO}" cd ${BASEDIR}/${TASK_NAME} && ${HGPATH}hg clone -b ${BRANCH} ${JEREVISIONARG} ssh://${JEREPUSER}@${JEREPO} ./je cd je && ${HGPATH}hg log -l 1 -v > ./${CHANGESETFILE} && cd .. BUILD_VER=`cd ${BASEDIR}/${TASK_NAME}/je && ${HGPATH}hg parent` fi if [ X$JDK_VERSION == X"8" ] ; then export JAVA_HOME=${BASEDIR}/app/Java_8 elif [ X$JDK_VERSION == X"7" ] ; then export JAVA_HOME=${BASEDIR}/app/Java_7 elif [ X$JDK_VERSION == X"6" ] ; then export JAVA_HOME=${BASEDIR}/app/Java_6 elif [ X$JDK_VERSION == X"AIX" ] ; then export JAVA_HOME=${BASEDIR}/app/ibm-java-ppc64-80 else export JAVA_HOME=${BASEDIR}/app/Java_5 fi export ANT_HOME=${BASEDIR}/app/ant export PATH=$ANT_HOME/bin:$JAVA_HOME/bin:$PATH ROOT_DIR=${BASEDIR}/${TASK_NAME} ANT_VERN=`ant -version` echo " " echo "=========================================================" echo " " java -version ant -version echo "JAVA_HOME=$JAVA_HOME " echo "ANT_HOME=$ANT_HOME " echo "Code branch: $BRANCH $BUILD_VER " echo " " echo "=========================================================" echo " " if [ X$LOG_LEVEL == X"INFO" ]; then echo "com.sleepycat.je.util.ConsoleHandler.level=INFO" > ${ROOT_DIR}/je/logging.properties fi if [ X$PRE == X"TRUE" ]; then echo " je.rep.preserveRecordVersion=true" >> ${ROOT_DIR}/je/test/je.properties fi if [ X$TASK_NAME == X"je_unit_jdk7_no_embedded_ln" ]; then echo "je.tree.maxEmbeddedLN=0" >> ${ROOT_DIR}/je/test/je.properties fi if [ "${TASK_NAME}" == "je_unit_aix" ]; then TEST_ARG="-Dproxy.host=www-proxy -Dproxy.port=80 -Djvm=${JAVA_HOME}/bin/java" fi cd ${ROOT_DIR}/je && ant -lib ${BASEDIR}/app/ant/lib/junit-4.10.jar test $TEST_ARG # Back up the result of this time test run #echo "ssh -l ${JENKINSVMUSERNAME} ${JENKINSVMIP} 'cat ${JENKINSBASEDIR}/${TASK_NAME}/nextBuildNumber'" BUILDID=`ssh -l ${JENKINSVMUSERNAME} ${JENKINSVMIP} "cat ${JENKINSBASEDIR}/${TASK_NAME}/nextBuildNumber"` BUILDID=`expr $BUILDID - 1` LOGLOCATION=${BASEDIR}/log_archive/${TASK_NAME}/$BUILDID mkdir -p $LOGLOCATION cd $LOGLOCATION cp -r ${ROOT_DIR}/je $LOGLOCATION # Generate the test environment information echo "Host: ${TESTVM}.us.oracle.com" >> ${ROOT_DIR}/je/${ENVINFOFILE} echo "Directory: `pwd`" >> ${ROOT_DIR}/je/${ENVINFOFILE} echo "Username: ${TESTVMUSERNAME}" >> ${ROOT_DIR}/je/${ENVINFOFILE} echo "Password: ${TESTVMUSERPASSWORD}" >> ${ROOT_DIR}/je/${ENVINFOFILE} ssh -l ${JENKINSVMUSERNAME} ${JENKINSVMIP} "rm -rf ${JENKINSBASEDIR}/${TASK_NAME}/workspace/*" cd ${ROOT_DIR}/je && scp ./${CHANGESETFILE} ./${ENVINFOFILE} ${JENKINSVM}:${JENKINSBASEDIR}/${TASK_NAME}/workspace/ cd ${ROOT_DIR}/je && scp -r build/test/data/ ${JENKINSVM}:${JENKINSBASEDIR}/${TASK_NAME}/workspace/
import { meta, route, val } from "plumier" export class User { /** * Property need to have at least one decorator for type conversion to work * use @meta.property() for that */ @meta.property() email: string @meta.property() name: string /** * Data type array need to specified explicitly */ @meta.type(x => [String]) emails: string[] } export class UsersController { /** * Request body will be checked match with User data type, * if provided property value with different data type, * will returned http status 422 with proper error message */ @route.post("") save(data: User) { return {} } /** * query parameter receive input match with its data type * Valid query * /users/get?num=123 * /users/get?str=lorem+ipsum * /users/get?bo=true (true, false, yes, no, 1, 0, on, off) * /users/get?dt=2021-1-1 or use ISO 8601 */ @route.get() get(num:number, str:string, bo:boolean, dt:Date){ return {} } }
/* * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The OpenAirInterface Software Alliance licenses this file to You 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. *------------------------------------------------------------------------------- * For more information about the OpenAirInterface (OAI) Software Alliance: * <EMAIL> */ #include <stdio.h> #include <string.h> #include <unistd.h> #include <pthread.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/sctp.h> #include <arpa/inet.h> #include "sctp_primitives_client.h" #include "s1ap_common.h" #include "s1ap_eNB.h" #include "s1ap_mme.h" #include "s1ap_ies_defs.h" #include "s1ap_eNB_encoder.h" #include "s1ap_eNB_decoder.h" int recv_callback ( uint32_t assocId, uint32_t stream, uint8_t * buffer, uint32_t length) { free (buffer); return 0; } int sctp_connected ( void *args, uint32_t assocId, uint32_t instreams, uint32_t outstreams) { return 0; } int main ( int argc, char *argv[]) { asn_enc_rval_t retVal; int i; for (i = 0; i < nb_eNB; i++) { sctp_connect_to_remote_host (ip_addr, 36412, NULL, sctp_connected, recv_callback); } while (1) { sleep (1); } sctp_terminate (); return (0); }
import { ISerialisable } from '../../serialisation/interfaces/ISerialisable'; export interface IValidatable extends ISerialisable { readonly isValid: boolean; readonly errorMessages: string[]; validate(): Promise<boolean>; }
python /scratch/sz2257/sgan/scripts/train_basketball_teampos.py \ --dataset_name '01.04.2016.TOR.at.CLE-partial' \ --dataset_dir /scratch/sz2257/basketball-partial \ --delim tab \ --d_type 'local' \ --pred_len 8 \ --encoder_h_dim_g 32 \ --encoder_h_dim_d 64 \ --decoder_h_dim 32 \ --embedding_dim 16 \ --bottleneck_dim 32 \ --mlp_dim 128 \ --pos_embedding 16 \ --team_embedding 4 \ --num_layers 1 \ --noise_type gaussian \ --noise_mix_type global \ --pool_every_timestep 0 \ --l2_loss_weight 1 \ --batch_norm 0 \ --dropout 0 \ --tp_dropout 0 \ --batch_size 128 \ --g_learning_rate 1e-3 \ --g_steps 1 \ --d_learning_rate 1e-3 \ --d_steps 2 \ --checkpoint_every 10 \ --print_every 50 \ --num_iterations 20000 \ --num_epochs 200 \ --pooling_type 'none' \ --clipping_threshold_g 1.5 \ --best_k 10 \ --checkpoint_name 'basketball_lstm' \ --restore_from_checkpoint 0 \ --interaction_activation none \ --model baseline # --output_dir ./results \
#!/bin/bash set -x REMOTE=$1 PR_HEAD_SHA=$2 PR_BASE_SHA=$3 git init . git config remote.origin.url $REMOTE git fetch --tags --progress $REMOTE +refs/heads/*:refs/remotes/origin/* git checkout --force "${3}" git merge ${2} git submodule update --init --recursive --jobs=6
import jwt from "jsonwebtoken"; import jwkToPem from "jwk-to-pem"; import fetch from "node-fetch"; import util from "util"; import { SecurityContext, SecurityIdentity } from "@webiny/api-security/types"; import Error from "@webiny/error"; import { ContextPlugin } from "@webiny/handler/plugins/ContextPlugin"; const verify = util.promisify<string, string, Record<string, any>>(jwt.verify); // All JWTs are split into 3 parts by two periods const isJwt = token => token.split(".").length === 3; type Context = SecurityContext; export interface AuthenticatorConfig { // Okta issuer endpoint issuer: string; // Okta client ID clientId: string; // Create an identity object using the verified idToken getIdentity(params: { token: { [key: string]: any } }): SecurityIdentity; } const jwksCache = new Map<string, Record<string, any>[]>(); export const createAuthenticator = (config: AuthenticatorConfig) => { const getJWKs = async () => { const key = config.issuer; if (!jwksCache.has(key)) { const response = await fetch(`${config.issuer}/v1/keys`).then(res => res.json()); jwksCache.set(key, response.keys); } return jwksCache.get(key); }; const oktaAuthenticator = async idToken => { if (typeof idToken === "string" && isJwt(idToken)) { try { const jwks = await getJWKs(); const { header } = jwt.decode(idToken, { complete: true }); const jwk = jwks.find(key => key.kid === header.kid); if (!jwk) { return; } const token = await verify(idToken, jwkToPem(jwk)); if (!token.jti.startsWith("ID.")) { throw new Error("idToken is invalid!", "SECURITY_OKTA_INVALID_TOKEN"); } return token; } catch (err) { console.log("OktaAuthenticationPlugin", err); throw new Error(err.message, "SECURITY_OKTA_INVALID_TOKEN"); } } }; return new ContextPlugin<Context>(({ security }) => { security.addAuthenticator(async idToken => { const token = await oktaAuthenticator(idToken); if (!token) { return; } return config.getIdentity({ token }); }); }); };
SELECT AVG(Salary) FROM Employees WHERE Department = 'Marketing'
<reponame>3Xpl0it3r/loki-operator<gh_stars>1-10 package loki_test import ( crfakeclients "github.com/l0calh0st/loki-operator/pkg/client/clientset/versioned/fake" crinformers "github.com/l0calh0st/loki-operator/pkg/client/informers/externalversions" "github.com/l0calh0st/loki-operator/pkg/controller" "github.com/l0calh0st/loki-operator/pkg/controller/loki" "github.com/l0calh0st/loki-operator/pkg/operator/fake" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/informers" k8sfake "k8s.io/client-go/kubernetes/fake" "k8s.io/client-go/testing" "time" ) var noResyncPeriod = func() time.Duration { return 0 } type fakeController struct { controller controller.Controller fakeWatcher *watch.FakeWatcher crClient *crfakeclients.Clientset crInformerFactory crinformers.SharedInformerFactory } func newFakeController() *fakeController { kubeClient := k8sfake.NewSimpleClientset() crClient := crfakeclients.NewSimpleClientset() watcher := watch.NewFakeWithChanSize(10, false) crClient.PrependWatchReactor("lokis", testing.DefaultWatchReactor(watcher, nil)) crInformerFactory := crinformers.NewSharedInformerFactory(crClient, noResyncPeriod()) kubeInformerFactory := informers.NewSharedInformerFactory(kubeClient, noResyncPeriod()) return &fakeController{ controller: loki.NewFakeController(kubeClient, kubeInformerFactory, crClient, crInformerFactory, fake.NewOperator()), fakeWatcher: watcher, crClient: crClient, crInformerFactory: crInformerFactory, } }
import React from 'react'; import { WhatWeDoStyle, RotatedText, Hr, MainContent, RotatedTextContainer, WhatWeDoContainerStyle } from './WhatWeDo.style'; import { PrimaryText, PrimaryBriefText } from 'sections/LandingScreenSection/LandingScreenSection.style'; import ArrowIcon from 'components/ArrowIcon/ArrowIcon'; import Cards from 'sections/Cards/Cards'; export default function WhatWeDo() { return ( <WhatWeDoContainerStyle id="companies"> <WhatWeDoStyle> <RotatedTextContainer> <RotatedText>What we do</RotatedText> </RotatedTextContainer> <MainContent> <Hr /> <PrimaryText>You’re in great company</PrimaryText> <PrimaryBriefText>Gidara seeks to connect young talented musicians with world class producers, managers etc</PrimaryBriefText> <div className="arrow_holder"> <ArrowIcon fill="#fff" borderColor="black" background="black" rotateDeg={90} /> <ArrowIcon fill="#fff" borderColor="black" background="black" rotateDeg={-90} marginLeft="3" /> </div> <Cards /> </MainContent> </WhatWeDoStyle> </WhatWeDoContainerStyle> ); }
#include "headers/drawIssue.h" void prepareWindow() { SDL_RenderClear(gameTools.renderer); if(!state.endGame) loadBackground(); } void presentWindow() { SDL_RenderPresent(gameTools.renderer); } void blit(SDL_Texture *texture, int xPos, int yPos , int w , int h) { SDL_Rect dest; dest.x = xPos; dest.y = yPos; dest.w = w; dest.h = h; SDL_RenderCopy(gameTools.renderer, texture, NULL, &dest); }
package com.netcracker.ncstore.controller; import com.netcracker.ncstore.dto.request.OrderGetRequest; import com.netcracker.ncstore.dto.request.OrderInfoGetRequest; import com.netcracker.ncstore.dto.response.OrderGetResponse; import com.netcracker.ncstore.dto.response.OrderInfoResponse; import com.netcracker.ncstore.service.web.order.IOrderWebService; import lombok.extern.slf4j.Slf4j; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.security.Principal; import java.util.List; import java.util.UUID; /** * Order controller is responsible for any actions with orders */ @RestController @RequestMapping(value = "/orders") @Slf4j public class OrderController { private final IOrderWebService orderWebService; public OrderController(final IOrderWebService orderWebService) { this.orderWebService = orderWebService; } @GetMapping public ResponseEntity<List<OrderGetResponse>> getOrdersWithPagination(@RequestParam final int page, @RequestParam final int size, final Principal principal) { log.info("REQUEST: to get orders for user with email " + principal.getName() + " on page: " + page + " with size: " + size); OrderGetRequest request = new OrderGetRequest(page, size, principal.getName()); List<OrderGetResponse> response = orderWebService.getOrders(request); log.info("RESPONSE: to get orders for user with email " + principal.getName() + " on page: " + page + " with size: " + size); return ResponseEntity. ok(). contentType(MediaType.APPLICATION_JSON). body(response); } @GetMapping(value = "/{orderId}") public ResponseEntity<OrderInfoResponse> getOrder(@PathVariable final UUID orderId, Principal principal) { log.info("REQUEST: to get order with UUID " + orderId + " requested by user with email " + principal.getName()); OrderInfoGetRequest request = new OrderInfoGetRequest(orderId, principal.getName()); OrderInfoResponse response = orderWebService.getSpecificOrder(request); log.info("RESPONSE: to get order with UUID " + orderId + " requested by user with email " + principal.getName()); return ResponseEntity. ok(). contentType(MediaType.APPLICATION_JSON). body(response); } }
<gh_stars>1-10 package mindustry.world.meta.values; import arc.scene.ui.layout.Table; import arc.util.Strings; import mindustry.world.meta.StatValue; public class StringValue implements StatValue{ private final String value; public StringValue(String value, Object... args){ this.value = Strings.format(value, args); } @Override public void display(Table table){ table.add(value); } }
# This shell script executes Slurm jobs for thresholding # predictions of convolutional # neural network with adaptive threshold on BirdVox-70k full audio # with logmelspec input. # Augmentation kind: all. # Test unit: unit05. # Trial ID: 9. sbatch 045_aug-all_test-unit05_predict-unit05_trial-9.sbatch sbatch 045_aug-all_test-unit05_predict-unit02_trial-9.sbatch sbatch 045_aug-all_test-unit05_predict-unit03_trial-9.sbatch
<reponame>xfyre/tapestry-5<gh_stars>0 // 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 org.apache.tapestry5.corelib.components; import org.apache.tapestry5.*; import org.apache.tapestry5.corelib.components.SelectTest.Platform; import org.apache.tapestry5.corelib.data.BlankOption; import org.apache.tapestry5.corelib.data.SecureOption; import org.apache.tapestry5.dom.XMLMarkupModel; import org.apache.tapestry5.internal.InternalComponentResources; import org.apache.tapestry5.internal.OptionGroupModelImpl; import org.apache.tapestry5.internal.OptionModelImpl; import org.apache.tapestry5.internal.SelectModelImpl; import org.apache.tapestry5.internal.TapestryInternalUtils; import org.apache.tapestry5.internal.URLEventContext; import org.apache.tapestry5.internal.services.ContextValueEncoderImpl; import org.apache.tapestry5.internal.services.MarkupWriterImpl; import org.apache.tapestry5.internal.services.StringValueEncoder; import org.apache.tapestry5.internal.test.InternalBaseTestCase; import org.apache.tapestry5.internal.util.Holder; import org.apache.tapestry5.ioc.Messages; import org.apache.tapestry5.ioc.internal.util.CollectionFactory; import org.apache.tapestry5.ioc.services.TypeCoercer; import org.apache.tapestry5.services.ContextValueEncoder; import org.apache.tapestry5.services.Request; import org.apache.tapestry5.services.ValueEncoderSource; import org.apache.tapestry5.util.EnumSelectModel; import org.apache.tapestry5.util.EnumValueEncoder; import org.easymock.EasyMock; import org.easymock.IAnswer; import org.easymock.IArgumentMatcher; import org.testng.annotations.Test; import java.io.BufferedInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; /** * Mostly, this is about how the Select component renders its {@link SelectModel}. The real nuts and bolts are tested in * the integration tests. */ public class SelectTest extends InternalBaseTestCase { @Test public void empty_model() { ValidationTracker tracker = mockValidationTracker(); Select select = new Select(); train_getInput(tracker, select, null); replay(); select.setModel(new SelectModelImpl(null, null)); select.setValidationTracker(tracker); select.options(null); verify(); } private String fix(Object input) { return input.toString().replaceAll("\r\n", "\n"); } private String read(String file) throws Exception { InputStream is = getClass().getResourceAsStream(file); Reader reader = new InputStreamReader(new BufferedInputStream(is)); StringBuilder builder = new StringBuilder(); char[] buffer = new char[1000]; while (true) { int length = reader.read(buffer); if (length < 0) break; builder.append(buffer, 0, length); } reader.close(); return fix(builder); } @Test public void just_options() throws Exception { ValidationTracker tracker = mockValidationTracker(); List<OptionModel> options = TapestryInternalUtils.toOptionModels("fred=Fred Flintstone,barney=Barney Rubble"); Select select = new Select(); train_getInput(tracker, select, null); replay(); select.setModel(new SelectModelImpl(null, options)); select.setValueEncoder(new StringValueEncoder()); select.setValue("barney"); select.setValidationTracker(tracker); MarkupWriter writer = new MarkupWriterImpl(new XMLMarkupModel()); writer.element("select"); select.options(writer); writer.end(); assertEquals(writer.toString(), read("just_options.txt")); verify(); } @Test public void just_options_with_blank_label_enabled() throws Exception { ValidationTracker tracker = mockValidationTracker(); List<OptionModel> options = TapestryInternalUtils.toOptionModels("fred=Fred Flintstone,barney=Barney Rubble"); Select select = new Select(); train_getInput(tracker, select, null); replay(); select.setModel(new SelectModelImpl(null, options)); select.setValueEncoder(new StringValueEncoder()); select.setValue("barney"); select.setValidationTracker(tracker); select.setBlankOption(BlankOption.ALWAYS, "Make a selection"); MarkupWriter writer = new MarkupWriterImpl(new XMLMarkupModel()); writer.element("select"); select.options(writer); writer.end(); assertEquals(writer.toString(), read("blank_label.txt")); verify(); } @Test public void current_selection_from_validation_tracker() throws Exception { ValidationTracker tracker = mockValidationTracker(); List<OptionModel> options = TapestryInternalUtils.toOptionModels("fred=Fred Flintstone,barney=Barney Rubble"); Select select = new Select(); train_getInput(tracker, select, "fred"); replay(); select.setModel(new SelectModelImpl(null, options)); select.setValueEncoder(new StringValueEncoder()); select.setValue("barney"); select.setValidationTracker(tracker); MarkupWriter writer = new MarkupWriterImpl(new XMLMarkupModel()); writer.element("select"); select.options(writer); writer.end(); // fred will be selected, not barney, because the validation tracker // takes precendence. assertEquals(writer.toString(), read("current_selection_from_validation_tracker.txt")); verify(); } @Test public void output_with_raw_enabled() throws Exception { ValidationTracker tracker = mockValidationTracker(); List<OptionModel> options = TapestryInternalUtils.toOptionModels("bold=<b>Bold</b>,italic=<i>Italic</i>"); Select select = new Select(); train_getInput(tracker, select, null); replay(); select.setModel(new SelectModelImpl(null, options)); select.setValueEncoder(new StringValueEncoder()); select.setValue("barney"); select.setValidationTracker(tracker); select.setRaw(true); MarkupWriter writer = new MarkupWriterImpl(new XMLMarkupModel()); writer.element("select"); select.options(writer); writer.end(); assertEquals(writer.toString(), read("output_with_raw_enabled.txt")); verify(); } @Test public void option_attributes() throws Exception { ValidationTracker tracker = mockValidationTracker(); // Extra cast needed for Sun compiler, not Eclipse compiler. List<OptionModel> options = Arrays.asList((OptionModel) new OptionModelImpl("Fred", "fred") { @Override public Map<String, String> getAttributes() { return Collections.singletonMap("class", "pixie"); } }); Select select = new Select(); train_getInput(tracker, select, null); replay(); select.setModel(new SelectModelImpl(null, options)); select.setValueEncoder(new StringValueEncoder()); select.setValue("barney"); select.setValidationTracker(tracker); MarkupWriter writer = new MarkupWriterImpl(new XMLMarkupModel()); writer.element("select"); select.options(writer); writer.end(); assertEquals(writer.toString(), read("option_attributes.txt")); verify(); } @Test public void disabled_option() throws Exception { ValidationTracker tracker = mockValidationTracker(); // Extra cast needed for Sun compiler, not Eclipse compiler. List<OptionModel> options = Arrays.asList((OptionModel) new OptionModelImpl("Fred", "fred") { @Override public boolean isDisabled() { return true; } @Override public Map<String, String> getAttributes() { return Collections.singletonMap("class", "pixie"); } }); Select select = new Select(); train_getInput(tracker, select, null); replay(); select.setModel(new SelectModelImpl(null, options)); select.setValueEncoder(new StringValueEncoder()); select.setValue("barney"); select.setValidationTracker(tracker); MarkupWriter writer = new MarkupWriterImpl(new XMLMarkupModel()); writer.element("select"); select.options(writer); writer.end(); assertEquals(writer.toString(), read("disabled_option.txt")); verify(); } @Test public void option_groups() throws Exception { ValidationTracker tracker = mockValidationTracker(); OptionGroupModel husbands = new OptionGroupModelImpl("Husbands", false, TapestryInternalUtils.toOptionModels("Fred,Barney")); OptionGroupModel wives = new OptionGroupModelImpl("Wives", true, TapestryInternalUtils.toOptionModels("Wilma,Betty")); List<OptionGroupModel> groupModels = CollectionFactory.newList(husbands, wives); Select select = new Select(); train_getInput(tracker, select, null); replay(); select.setModel(new SelectModelImpl(groupModels, null)); select.setValueEncoder(new StringValueEncoder()); select.setValue("Fred"); select.setValidationTracker(tracker); MarkupWriter writer = new MarkupWriterImpl(new XMLMarkupModel()); writer.element("select"); select.options(writer); writer.end(); assertEquals(writer.toString(), read("option_groups.txt")); verify(); } @Test public void option_groups_precede_ungroup_options() throws Exception { ValidationTracker tracker = mockValidationTracker(); OptionGroupModel husbands = new OptionGroupModelImpl("Husbands", false, TapestryInternalUtils.toOptionModels("Fred,Barney")); Select select = new Select(); train_getInput(tracker, select, null); replay(); select.setModel(new SelectModelImpl(Collections.singletonList(husbands), TapestryInternalUtils .toOptionModels("Wilma,Betty"))); select.setValueEncoder(new StringValueEncoder()); select.setValue("Fred"); select.setValidationTracker(tracker); MarkupWriter writer = new MarkupWriterImpl(new XMLMarkupModel()); writer.element("select"); select.options(writer); writer.end(); assertEquals(writer.toString(), read("option_groups_precede_ungroup_options.txt")); verify(); } @Test public void option_group_attributes() throws Exception { ValidationTracker tracker = mockValidationTracker(); Map<String, String> attributes = Collections.singletonMap("class", "pixie"); OptionGroupModel husbands = new OptionGroupModelImpl("Husbands", false, TapestryInternalUtils.toOptionModels("Fred,Barney"), attributes); Select select = new Select(); train_getInput(tracker, select, null); replay(); select.setModel(new SelectModelImpl(Collections.singletonList(husbands), null)); select.setValueEncoder(new StringValueEncoder()); select.setValue("Fred"); select.setValidationTracker(tracker); MarkupWriter writer = new MarkupWriterImpl(new XMLMarkupModel()); writer.element("select"); select.options(writer); writer.end(); assertEquals(writer.toString(), read("option_group_attributes.txt")); verify(); } enum Platform { WINDOWS, MAC, LINUX; } /** * TAP5-2204: When secure parameter is "always" there should be no * validation error if the model is NOT null. */ @Test public void submitted_option_found_when_secure_always() throws ValidationException { checkSubmittedOption(true, SecureOption.ALWAYS, null); } /** * TAP5-2204: When secure parameter is "always" there should be a * validation error if the model is null. */ @Test public void submitted_option_not_found_when_secure_always() throws ValidationException { checkSubmittedOption(false, SecureOption.ALWAYS, "is null when validating"); } /** * TAP5-2204: When secure parameter is "never" there should be no * validation error if the model is NOT null. */ @Test public void submitted_option_ok_when_secure_never() throws ValidationException { checkSubmittedOption(true, SecureOption.NEVER, null); } /** * TAP5-2204: When secure parameter is "never" there should be no * validation error if the model is null. */ @Test public void submitted_option_ok_when_secure_never_no_model() throws ValidationException { checkSubmittedOption(false, SecureOption.NEVER, null); } /** * TAP5-2204: When secure parameter is "auto" there should be no * validation error if the model is NOT null. */ @Test public void submitted_option_found_when_secure_auto() throws ValidationException { checkSubmittedOption(true, SecureOption.AUTO, null); } /** * TAP5-2204: When secure parameter is "auto" there should be no * validation error if the model is null. */ @Test public void submitted_option_ok_when_secure_auto() throws ValidationException { checkSubmittedOption(false, SecureOption.AUTO, null); } /** * Utility for testing the "secure" option with various values and model * states. This avoids a lot of redundant test setup code. * * @param withModel whether there should be a model to test against * @param secureOption which "secure" option to test * @param expectedError the expected error message, nor null if no error * @throws ValidationException */ private void checkSubmittedOption(boolean withModel, SecureOption secureOption, String expectedError) throws ValidationException { ValueEncoder<Platform> encoder = getService(ValueEncoderSource.class).getValueEncoder(Platform.class); ValidationTracker tracker = mockValidationTracker(); Request request = mockRequest(); Messages messages = mockMessages(); FieldValidationSupport fvs = mockFieldValidationSupport(); TypeCoercer typeCoercer = mockTypeCoercer(); InternalComponentResources resources = mockInternalComponentResources(); Binding selectModelBinding = mockBinding(); expect(request.getParameter("xyz")).andReturn("MAC"); expect(messages.contains(EasyMock.anyObject(String.class))).andReturn(false).anyTimes(); expect(resources.getBinding("model")).andReturn(selectModelBinding); final Holder<SelectModel> modelHolder = Holder.create(); expect(typeCoercer.coerce(EasyMock.or(EasyMock.isA(SelectModel.class), EasyMock.isNull()), EasyMock.eq(SelectModel.class))) .andAnswer(new IAnswer<SelectModel>() { @Override public SelectModel answer() throws Throwable { return modelHolder.get(); } }); expect(selectModelBinding.get()).andAnswer(new IAnswer<SelectModel>() { @Override public SelectModel answer() throws Throwable { return modelHolder.get(); } }); Select select = new Select(); tracker.recordInput(select, "MAC"); // when not failing we will expect to call the fvs.validate method if (expectedError == null) { fvs.validate(Platform.MAC, resources, null); } else { tracker.recordError(EasyMock.eq(select), EasyMock.contains(expectedError)); } replay(); if (withModel) { modelHolder.put(new EnumSelectModel(Platform.class, messages)); } set(select, "encoder", encoder); set(select, "model", modelHolder.get()); set(select, "request", request); set(select, "secure", secureOption); set(select, "beanValidationDisabled", true); // Disable BeanValidationContextSupport set(select, "tracker", tracker); set(select, "fieldValidationSupport", fvs); set(select, "typeCoercer", typeCoercer); set(select, "resources", resources); select.processSubmission("xyz"); if (expectedError == null) { assertEquals(get(select, "value"), Platform.MAC); } verify(); } /** This a test for TAP5-2184 */ @Test public void submitted_option_matches_against_value_encoded_option_model_value() throws ValidationException { ValueEncoder<Integer> encoder = getService(ValueEncoderSource.class).getValueEncoder(Integer.class); ValidationTracker tracker = mockValidationTracker(); Request request = mockRequest(); Messages messages = mockMessages(); FieldValidationSupport fvs = mockFieldValidationSupport(); TypeCoercer typeCoercer = mockTypeCoercer(); InternalComponentResources resources = mockInternalComponentResources(); Binding selectModelBinding = mockBinding(); expect(request.getParameter("xyz")).andReturn("5"); expect(messages.contains(EasyMock.anyObject(String.class))).andReturn(false).anyTimes(); expect(resources.getBinding("model")).andReturn(selectModelBinding); final Holder<SelectModel> modelHolder = Holder.create(); expect(typeCoercer.coerce(EasyMock.or(EasyMock.isA(SelectModel.class), EasyMock.isNull()), EasyMock.eq(SelectModel.class) )) .andAnswer(new IAnswer<SelectModel>() { @Override public SelectModel answer() throws Throwable { return modelHolder.get(); } }); expect(selectModelBinding.get()).andAnswer(new IAnswer<SelectModel>() { @Override public SelectModel answer() throws Throwable { return modelHolder.get(); } }); Select select = new Select(); tracker.recordInput(select, "5"); fvs.validate(5, resources, null); replay(); // TAP5-2184 is triggered by the automatic String->SelectModel coercion, because the OptionModel // values are Strings even if the desired property type is not (Integer, here). Select has a little // hack to run the model values through the ValueEncoder for comparison. modelHolder.put(getService(TypeCoercer.class).coerce("1,5,10,20", SelectModel.class)); set(select, "encoder", encoder); set(select, "model", modelHolder.get()); set(select, "request", request); set(select, "secure", SecureOption.ALWAYS); set(select, "beanValidationDisabled", true); // Disable BeanValidationContextSupport set(select, "tracker", tracker); set(select, "fieldValidationSupport", fvs); set(select, "typeCoercer", typeCoercer); set(select, "resources", resources); select.processSubmission("xyz"); verify(); assertEquals(get(select, "value"), 5); } @Test public void context_that_needs_to_be_encoded() throws Exception { ValueEncoderSource valueEncoderSource = mockValueEncoderSource(); TypeCoercer typeCoercer = getService(TypeCoercer.class); ContextValueEncoder contextValueEncoder = new ContextValueEncoderImpl(valueEncoderSource); ValueEncoder<Platform> platformEncoder = new ValueEncoder<SelectTest.Platform>() { @Override public Platform toValue(String clientValue) { return Platform.valueOf(clientValue.substring(10)); } @Override public String toClient(Platform value) { return "Platform: "+value.name(); } }; InternalComponentResources resources = mockInternalComponentResources(); expect(valueEncoderSource.getValueEncoder(Platform.class)).andReturn(platformEncoder).anyTimes(); expect(valueEncoderSource.getValueEncoder(String.class)).andReturn(new StringValueEncoder()).anyTimes(); expect(resources.triggerContextEvent(EasyMock.eq(EventConstants.VALUE_CHANGED), eqEventContext(null, Platform.LINUX), EasyMock.isA(ComponentEventCallback.class))).andReturn(true); Select select = new Select(); set(select, "resources", resources); set(select, "encoder", new StringValueEncoder()); set(select, "typeCoercer", typeCoercer); replay(); select.onChange(new URLEventContext(contextValueEncoder, new String[]{platformEncoder.toClient(Platform.LINUX)}), null); verify(); } private static EventContext eqEventContext(final Object ... expectedContext) { EasyMock.reportMatcher(new IArgumentMatcher() { @Override public boolean matches(Object argument) { EventContext context = (EventContext) argument; for (int i = 0; i < expectedContext.length; i++) { Object expected = expectedContext[i]; Class expectedClass = expected == null ? Object.class : expected.getClass(); if (!TapestryInternalUtils.isEqual(context.get(expectedClass, i), expected)) { return false; } } return true; } @Override public void appendTo(StringBuffer buffer) { buffer.append("expected event context ["); for (int i = 0; i < expectedContext.length; i++) { if (i != 0) { buffer.append(", "); } buffer.append(expectedContext[i]); } buffer.append("]"); } }); return null; } }
<filename>runescape-api/src/main/java/net/runelite/rs/api/RSObjectComposition.java package net.runelite.rs.api; import net.runelite.api.ObjectComposition; import net.runelite.mapping.Import; public interface RSObjectComposition extends ObjectComposition { @Import("id") @Override int getId(); @Import("name") @Override String getName(); @Import("actions") @Override String[] getActions(); @Import("mapSceneId") @Override int getMapSceneId(); @Import("mapIconId") @Override int getMapIconId(); @Import("transforms") @Override int[] getImpostorIds(); @Import("transform") @Override RSObjectComposition getImpostor(); @Import("params") RSIterableNodeHashTable getParams(); @Import("params") void setParams(RSIterableNodeHashTable params); }
class ApplicationController < ActionController::Base protect_from_forgery respond_to :html end
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class ContentController extends Controller { public function showOffer(){ return view('Frontend.Layouts.User.offerFront'); } public function showBlog1(){ return view('Frontend.Layouts.User.offerBlog1'); } public function showBlog2(){ return view('Frontend.Layouts.User.offerBlog2'); } }
<filename>allrichstore/Tools/QBClass/QBViewClass/CustomCell/IconAndTitleCell.h // // IconAndTitleCell.h // MeiYiQuan // // Created by 任强宾 on 16/10/5. // Copyright © 2016年 任强宾. All rights reserved. // #import <UIKit/UIKit.h> @interface IconAndTitleCell : UITableViewCell - (void)configCellIconName:(NSString *)iconName cellTitle:(NSString *)cellTitle showLine:(BOOL)isShowLine; @end
#!/bin/sh # quit on errors: set -o errexit # quit on unbound symbols: set -o nounset DIR=`dirname "$0"` cd $DIR export FLASK_APP=app.py # Create the database flask db init flask db create flask fixtures loans
if [ ! -d /usr/local/app/tars/app_log ]; then mkdir -p /data/log/tars mkdir -p /usr/local/app/tars mkdir -p /data/tars/app_log ln -s /data/tars/app_log /usr/local/app/tars/app_log fi if [ ! -d /usr/local/app/tars/remote_app_log ]; then mkdir -p /data/tars/remote_app_log ln -s /data/tars/remote_app_log /usr/local/app/tars/remote_app_log fi cd /usr/local/app/tars/ chmod +x tarsnode/util/*.sh ./tarsnode/util/start.sh
import React, { FC, useState } from 'react'; import { AiOutlineClose, FiCircle } from 'react-icons/all'; import { Board } from '../../components'; import UseGameState from '../useGameState'; import { Container, ContainerPlay, ContainerTitle, TitleMain, ContainerRocket, ContainerFields, ContainerBoard, ContainerBackground, ContainerSteps, ContainerTextSteps, TextSteps, ContainerInformationGame, ContainerTexts, TextWinner, ButtonReset, } from './style'; /* ------------------------------------------- */ /* function to get the text O or X */ /* ------------------------------------------- */ const getLabel = (value: any) => { if (!value) return null; return value > 0 ? ( <FiCircle id="O" name="O" color="red" size={40} /> ) : ( <AiOutlineClose id="X" name="X" color="black" size={40} /> ); }; /* ------------------------------------------- */ /* function to get initial state of the board */ /* ------------------------------------------- */ const getInitialState = () => { const state: any = {}; for (let r = 0; r < 3; r++) { for (let c = 0; c < 3; c++) { state[`${r}-${c}`] = null; } } return state; }; /* -------------------------------------------- */ /* function that gets the row and column index */ /* -------------------------------------------- */ const getKeyFromIndex = (index: number) => { const row = Math.floor(index / 3); const column = index % 3; return `${row}-${column}`; }; const Game: FC = () => { const { computeMove, stepNumber, resetStep } = UseGameState(); const [values, setValues] = useState(getInitialState); const [player, setPlayer] = useState(1); const [winner, setWinner] = useState<number | any>(null); function getWinner(v: any) { for (let r = 0; r < 3; r++) { for (let c = 0; c < 3; c++) { const sumRow = v[`${r}-${c}`] + v[`${r}-${c + 1}`] + v[`${r}-${c + 2}`]; if (sumRow === 3 || sumRow === -3) { return sumRow; } const sumCol = v[`${r}-${c}`] + v[`${r + 1}-${c}`] + v[`${r + 2}-${c}`]; if (sumCol === 3 || sumCol === -3) { return sumCol; } const sumDiagonal = v[`${r}-${c}`] + v[`${r + 1}-${c + 1}`] + v[`${r + 2}-${c + 2}`]; if (sumDiagonal === 3 || sumDiagonal === -3) { return sumDiagonal; } const sumReverseDiagonal = v[`${r}-${c}`] + v[`${r + 1}-${c - 1}`] + v[`${r + 2}-${c - 2}`]; if (sumReverseDiagonal === 3 || sumReverseDiagonal === -3) { return sumReverseDiagonal; } } } return null; } const handleClick = async (key: number) => { if (winner || values[key]) { return; } const newValues = { ...values, [key]: player, }; setValues(newValues); setPlayer(player * -1); const newWinner = getWinner(newValues); if (newWinner) { setWinner(newWinner > 0 ? 1 : -1); } computeMove(); }; const reset = () => { setWinner(null); setValues(getInitialState); setPlayer(1); resetStep(); return true; }; const draw = Object.values(values).filter(Boolean).length === 9 && !winner; return ( <Container> <ContainerPlay> <ContainerTitle> <TitleMain>TIC-TAC-LIVEN</TitleMain> <ContainerRocket role="img" aria-label="rocket"> 🚀 </ContainerRocket> </ContainerTitle> <ContainerFields> <ContainerBoard> <Board getLabel={getLabel} values={values} handleClick={(key: number) => handleClick(key)} getKeyFromIndex={(index: number) => getKeyFromIndex(index) } /> </ContainerBoard> <ContainerSteps> <ContainerTextSteps> <TextSteps>Current step: </TextSteps> <TextSteps isBold>{stepNumber}</TextSteps> </ContainerTextSteps> </ContainerSteps> {(winner || draw) && ( <> <ContainerBackground /> <ContainerInformationGame> <ContainerTexts> {winner ? ( <> <TextWinner isBold> The winner is: </TextWinner> <TextWinner> {winner >= 0 ? 'O' : 'X'} </TextWinner> </> ) : ( <TextWinner isBold> There was a tie </TextWinner> )} </ContainerTexts> <ButtonReset type="reset" onClick={reset}> Restart </ButtonReset> </ContainerInformationGame> </> )} </ContainerFields> <ButtonReset type="reset" onClick={reset}> Restart </ButtonReset> </ContainerPlay> </Container> ); }; export default Game;
package test.bootstrap.boot; import org.junit.Test; import com.wpisen.trace.agent.bootstrap.DevelopBootMain; import java.lang.instrument.Instrumentation; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.io.File; public class DevelopBootMainTest { @Test public void successTest() throws Exception { ///Users/wpisen/git/trace-agent/ String home=new File(System.getProperty("user.dir")).getParentFile().toString(); Instrumentation inst = (Instrumentation) Proxy.newProxyInstance(AgentBootMainTest.class.getClassLoader(), new Class[] { Instrumentation.class }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return null; } }); home=home.replaceAll("\\\\","/"); StringBuilder sbuilder = new StringBuilder(); sbuilder.append("open=true"); sbuilder.append(",appId=test_team"); sbuilder.append(",proKey=test0123"); sbuilder.append(",proSecret=00215"); sbuilder.append(",trace.open=true"); sbuilder.append(",trace.upload.way=logfile"); sbuilder.append(",trace.upload.path=http://log.yunhou.com/trace/upload"); sbuilder.append(",dev.base="+home+"/agent-base/target/classes/"); sbuilder.append(",dev.collects="+home+"/agent-collects/target/classes/&"+home+"/agent-collect-servlet/target/classes/"); sbuilder.append(",stack.includes=com.*&org.*"); DevelopBootMain.premain(sbuilder.toString(), inst); } }
<reponame>mariokyprianou/React-Native /* * Jira Ticket: * Created Date: Tue, 27th Apr 2021, 08:35:32 am * Author: <NAME> * Email: <EMAIL> * Copyright (c) 2021 The Distance */ import React from 'react'; import {View} from 'react-native'; import {ScaleHook} from 'react-native-design-to-component'; import useTheme from '../../hooks/theme/UseTheme'; import TrainerIcon from '../Infographics/TrainerIcon'; import useDictionary from '../../hooks/localisation/useDictionary'; import LinearGradient from 'react-native-linear-gradient'; export default function TrainerIconCard({ fatLossPercentage, fitnessPercentage, musclePercentage, wellnessPercentage, }) { // ** ** ** ** ** SETUP ** ** ** ** ** const { getHeight, getWidth, getScaledHeight, getScaledWidth, radius, } = ScaleHook(); const {colors} = useTheme(); const {dictionary} = useDictionary(); const {MeetYourIconsDict} = dictionary; // ** ** ** ** ** STYLES ** ** ** ** ** const styles = { container: { width: getScaledWidth(335), height: getHeight(107), flexDirection: 'row', alignItems: 'center', justifyContent: 'space-around', borderRadius: radius(12), }, }; // ** ** ** ** ** FUNCTIONS ** ** ** ** ** // ** ** ** ** ** RENDER ** ** ** ** ** return ( <LinearGradient style={styles.container} start={{x: 0, y: 0}} end={{x: 0, y: 1}} colors={[colors.white80, colors.white30]}> <TrainerIcon text={MeetYourIconsDict.FatLoss} percentage={fatLossPercentage} /> <TrainerIcon text={MeetYourIconsDict.Fitness} percentage={fitnessPercentage} /> <TrainerIcon text={MeetYourIconsDict.Muscle} percentage={musclePercentage} /> <TrainerIcon text={MeetYourIconsDict.Wellness} percentage={wellnessPercentage} /> </LinearGradient> ); }
<gh_stars>0 count = 3 # Case with booleans case when count == 0 puts "nobody" when count ==1 puts "1 person" when (2..5).include?(count) puts "several people" else puts "many people" end # Case with comparisons case count when 0 puts "nobody" when 1 puts "1 person" when 2..5 puts "several people" else puts "many people" end
<reponame>sackio/fstk 'use strict'; var FSTK = require('../lib/fstk.js') , Belt = require('jsbelt') , FS = require('fs') , OS = require('os') , Path = require('path') , Async = require('async') , _ = require('underscore') , Child_Process = require('child_process') , Winston = require('winston') ; var create_dummy_directory = function(dir){ dir = _.defaults(dir || {}, { 'contents': {} , 'directory_count': Belt.random_int(1, 2) , 'file_count': Belt.random_int(1, 2) , 'files': {} , 'directories': {} , 'path': Path.join(OS.tmpdir(), Belt.uuid()) }); var uuid; for (var i = 0; i < dir.directory_count; i++){ uuid = Belt.uuid(); FS.mkdirSync(Path.join(dir.path, uuid)); dir.contents[uuid] = { 'type': 'directory' , 'path': Path.join(dir.path, uuid) }; dir.directories[uuid] = { 'type': 'directory' , 'path': Path.join(dir.path, uuid) }; } for (i = 0; i < dir.file_count; i++){ uuid = Belt.uuid(); FS.writeFileSync(Path.join(dir.path, uuid), 'test file'); dir.contents[uuid] = { 'type': 'file' , 'path': Path.join(dir.path, uuid) }; dir.files[uuid] = { 'type': 'file' , 'path': Path.join(dir.path, uuid) }; } return dir; }; var create_file_tree = function(){ var tree = { 'contents': {} , 'files': {} , 'directories': {} , 'path': Path.join(OS.tmpdir(), Belt.uuid()) }; FS.mkdirSync(tree.path); tree.contents = create_dummy_directory({'path': tree.path}); tree.files = _.extend(tree.files, tree.contents.files); tree.directories = _.extend(tree.directories, tree.contents.directories); _.each(tree.contents.directories, function(d){ d.subdir = create_dummy_directory({'path': d.path}); tree.files = _.extend(tree.files, d.subdir.files); tree.directories = _.extend(tree.directories, d.subdir.directories); return _.each(d.subdir.directories, function(d2){ d2.subdir = create_dummy_directory({'path': d2.path}); tree.files = _.extend(tree.files, d2.subdir.files); tree.directories = _.extend(tree.directories, d2.subdir.directories); return _.each(d2.subdir.directories, function(d3){ d3.subdir = create_dummy_directory({'path': d3.path}); tree.files = _.extend(tree.files, d3.subdir.files); tree.directories = _.extend(tree.directories, d3.subdir.directories); return; }); }); }); return tree; }; var gb = {} , log = new Winston.Logger() ; log.add(Winston.transports.Console, {'level': 'debug', 'colorize': true, 'timestamp': false}); exports['fstk'] = { 'filename': function(test) { test.expect(1); test.ok(FSTK.filename('/path/file.foo') === 'file'); test.done(); }, 'replaceExt': function(test) { test.expect(1); test.ok(FSTK.replaceExt('/path/file.foo', 'bar') === '/path/file.bar'); test.done(); }, 'fileType': function(test) { test.expect(3); test.ok(FSTK.fileType('/path/file.mov') === 'video'); test.ok(FSTK.fileType('/path/file.mp3') === 'audio'); test.ok(FSTK.fileType('/path/file.png') === 'image'); test.done(); }, 'subPaths': function(test) { test.expect(2); test.ok(Belt.deepEqual(FSTK.subPaths('/path/to/file.foo'), ['/', '/path', '/path/to', '/path/to/file.foo'])); test.ok(Belt.deepEqual(FSTK.subPaths('path/to/file.foo'), ['path', 'path/to', 'path/to/file.foo'])); test.done(); }, 'stat & exists': function(test) { var globals = {}; return Async.waterfall([ function(cb){ console.log('Creating temp files and directories'); globals.directory = Path.join(OS.tmpdir(), '/' + Belt.uuid()); globals.file = Path.join(OS.tmpdir(), '/' + Belt.uuid() + '.json'); globals.link = Path.join(OS.tmpdir(), '/' + Belt.uuid() + '.link'); FS.mkdirSync(globals.directory); FS.writeFileSync(globals.file, 'this is the test file'); FS.symlinkSync(globals.file, globals.link); return cb(); } , function(cb){ return FSTK.stat(globals.directory, Belt.cs(cb, globals, 'directory_stat', 1, 0)); } , function(cb){ return FSTK.stat(globals.file, Belt.cs(cb, globals, 'file_stat', 1, 0)); } , function(cb){ return FSTK.stat(globals.link, Belt.cs(cb, globals, 'link_stat', 1, 0)); } , function(cb){ return FSTK.stat(globals.directory, {'fast_stat': true}, Belt.cs(cb, globals, 'fast_directory_stat', 1, 0)); } , function(cb){ return FSTK.stat(globals.file, {'fast_stat': true}, Belt.cs(cb, globals, 'fast_file_stat', 1, 0)); } , function(cb){ return FSTK.stat(globals.link, {'fast_stat': true}, Belt.cs(cb, globals, 'fast_link_stat', 1, 0)); } , function(cb){ test.ok(globals.directory_stat.isDirectory); test.ok(!globals.directory_stat.isFile); test.ok(!globals.directory_stat.isBlockDevice); test.ok(!globals.directory_stat.isCharacterDevice); test.ok(!globals.directory_stat.isFIFO); test.ok(!globals.directory_stat.isSocket); test.ok(!globals.directory_stat.isSymbolicLink); test.ok(!globals.directory_stat.mime); test.ok(!globals.file_stat.isDirectory); test.ok(globals.file_stat.isFile); test.ok(!globals.file_stat.isBlockDevice); test.ok(!globals.file_stat.isCharacterDevice); test.ok(!globals.file_stat.isFIFO); test.ok(!globals.file_stat.isSocket); test.ok(!globals.file_stat.isSymbolicLink); test.ok(globals.file_stat.mime === 'application/json'); test.ok(!globals.link_stat.isDirectory); test.ok(!globals.link_stat.isFile); test.ok(!globals.link_stat.isBlockDevice); test.ok(!globals.link_stat.isCharacterDevice); test.ok(!globals.link_stat.isFIFO); test.ok(!globals.link_stat.isSocket); test.ok(globals.link_stat.isSymbolicLink); test.ok(globals.fast_directory_stat.isDirectory === true); test.ok(globals.fast_directory_stat.isFile === undefined); test.ok(globals.fast_directory_stat.isBlockDevice === undefined); test.ok(globals.fast_directory_stat.isCharacterDevice === undefined); test.ok(globals.fast_directory_stat.isFIFO === undefined); test.ok(globals.fast_directory_stat.isSocket === undefined); test.ok(globals.fast_directory_stat.isSymbolicLink === undefined); test.ok(!globals.fast_directory_stat.mime); test.ok(globals.fast_file_stat.isDirectory === false); test.ok(globals.fast_file_stat.isFile === undefined); test.ok(globals.fast_file_stat.isBlockDevice === undefined); test.ok(globals.fast_file_stat.isCharacterDevice === undefined); test.ok(globals.fast_file_stat.isFIFO === undefined); test.ok(globals.fast_file_stat.isSocket === undefined); test.ok(globals.fast_file_stat.isSymbolicLink === undefined); test.ok(!globals.fast_file_stat.mime); test.ok(globals.fast_link_stat.isDirectory === false); test.ok(globals.fast_link_stat.isFile === undefined); test.ok(globals.fast_link_stat.isBlockDevice === undefined); test.ok(globals.fast_link_stat.isCharacterDevice === undefined); test.ok(globals.fast_link_stat.isFIFO === undefined); test.ok(globals.fast_link_stat.isSocket === undefined); test.ok(globals.fast_link_stat.isSymbolicLink === undefined); test.ok(!globals.fast_link_stat.mime); return cb(); } , function(cb){ return FSTK.exists(globals.link, Belt.cs(cb, globals, 'exists_1', 0)); } , function(cb){ return FSTK.exists(globals.directory, Belt.cs(cb, globals, 'exists_2', 0)); } , function(cb){ return FSTK.exists(globals.file, Belt.cs(cb, globals, 'exists_3', 0)); } , function(cb){ return FSTK.exists('/a/completely/fake/path/to/nowhere.json', Belt.cs(cb, globals, 'exists_4', 0)); } , function(cb){ test.ok(globals.exists_1); test.ok(globals.exists_2); test.ok(globals.exists_3); test.ok(!globals.exists_4); return cb(); } ], function(err){ if (err) console.error(err); test.ok(!err); FS.rmdirSync(globals.directory); FS.unlinkSync(globals.file); FS.unlinkSync(globals.link); test.done(); }); }, 'statDir': function(test) { var globals = {}; return Async.waterfall([ function(cb){ console.log('Creating nested temp directory'); globals.directory = Path.join(OS.tmpdir(), '/' + Belt.uuid()); FS.mkdirSync(globals.directory); globals.contents = Belt.sequence(Belt.uuid, 100); for (var i = 0; i < 50; i++){ FS.writeFileSync(Path.join(globals.directory, globals.contents[i]), 'this is a file'); globals.contents[i] = {'path': Path.join(globals.directory, globals.contents[i]), 'type': 'file'}; } for (i = 50; i < 75; i++){ FS.mkdirSync(Path.join(globals.directory, globals.contents[i])); globals.contents[i] = {'path': Path.join(globals.directory, globals.contents[i]), 'type': 'directory'}; } for (i = 75; i < 100; i++){ FS.symlinkSync( globals.contents[i - 50].path , Path.join(globals.directory, globals.contents[i])); globals.contents[i] = { 'path': Path.join(globals.directory, globals.contents[i]) , 'realpath': globals.contents[i - 50].path , 'type': 'link'}; } return cb(); } , function(cb){ return FSTK.transformDir(globals.directory, function(p, _cb){ return _cb(null, 'hello'); } , Belt.cs(cb, globals, 'transformed_paths', 1, 0)); } , function(cb){ return FSTK.statDir(globals.directory, Belt.cs(cb, globals, 'stat_dir', 1, 0)); } , function(cb){ test.ok(Belt.deepEqual(Belt.sequence(function(){ return 'hello'; }, globals.contents.length), globals.transformed_paths)); test.ok(globals.stat_dir.directory && globals.stat_dir.directory.realpath === globals.directory); test.ok(globals.stat_dir.directory.isDirectory); _.each(globals.contents, function(c){ var file_stat = _.find(globals.stat_dir.files, function(f){ return f.path === c.path; }); test.ok(file_stat); if (c.type === 'link'){ test.ok(file_stat.isSymbolicLink); test.ok(!file_stat.isDirectory); } if (c.type === 'directory'){ test.ok(!file_stat.isSymbolicLink); test.ok(file_stat.isDirectory); test.ok(!file_stat.isFile); } if (c.type === 'file'){ test.ok(!file_stat.isSymbolicLink); test.ok(!file_stat.isDirectory); test.ok(file_stat.isFile); } }); return cb(); } ], function(err){ if (err) console.error(err); test.ok(!err); test.done(); }); }, 'transformFile': function(test) { var globals = {}; return Async.waterfall([ function(cb){ globals.path = Path.join(OS.tmpdir(), Belt.uuid()); FS.writeFileSync(globals.path, 'this is a test file'); return FSTK.transformFile(globals.path , function(b, _cb){ return _cb(null, 'transformed file'); }, Belt.cw(cb, 0)); } , function(cb){ var body = FS.readFileSync(globals.path); test.ok(body.toString() === 'transformed file'); return cb(); } , function(cb){ globals.new_path = Path.join(OS.tmpdir(), Belt.uuid()); return FSTK.transformFile(globals.path , function(b, _cb){ return _cb(null, 'new transformed file'); } , {'destination': globals.new_path}, Belt.cw(cb)); } , function(cb){ var body = FS.readFileSync(globals.new_path); test.ok(body.toString() === 'new transformed file'); body = FS.readFileSync(globals.path); test.ok(body.toString() === 'transformed file'); return cb(); } ], function(err){ if (err) console.error(err); test.ok(!err); test.done(); }); }, 'gzipFiles': function(test) { var globals = {}; return Async.waterfall([ function(cb){ globals.path = Path.join(OS.tmpdir(), Belt.uuid()); return FSTK.writeGzipFile(globals.path, 'this is a test file', Belt.cw(cb, 0)); } , function(cb){ var body = FS.readFileSync(globals.path); test.ok(body.toString() !== 'this is a test file'); return FSTK.readGzipFile(globals.path, Belt.cs(cb, globals, 'body', 1, 0)); } , function(cb){ test.ok(globals.body.toString() === 'this is a test file'); return cb(); } ], function(err){ if (err) console.error(err); test.ok(!err); test.done(); }); }, 'jsonFiles': function(test) { var globals = {}; return Async.waterfall([ function(cb){ globals.path = Path.join(OS.tmpdir(), Belt.uuid()); globals.json = {'this': {'is': ['json', 1, 2, 3]}}; return FSTK.writeJSON(globals.path, globals.json, Belt.cw(cb, 0)); } , function(cb){ var body = FS.readFileSync(globals.path); //test.ok(body.toString() === Belt.stringify(globals.json)); return FSTK.readJSON(globals.path, Belt.cs(cb, globals, 'body', 1, 0)); } , function(cb){ //test.ok(Belt.deepEqual(globals.json, globals.body)); return cb(); } , function(cb){ return FSTK.updateJSON(globals.path, 'this.is', 'updated', Belt.cw(cb, 0)); } , function(cb){ return FSTK.readJSON(globals.path, Belt.cs(cb, globals, 'body', 1, 0)); } , function(cb){ test.ok(globals.body.this.is === 'updated'); return cb(); } , function(cb){ return FSTK.updateJSON(globals.path, function(){ this.this = 'updated_again'; return; }, Belt.cw(cb, 0)); } , function(cb){ return FSTK.readJSON(globals.path, Belt.cs(cb, globals, 'body', 1, 0)); } , function(cb){ test.ok(globals.body.this === 'updated_again'); return cb(); } ], function(err){ if (err) console.error(err); test.ok(!err); test.done(); }); }, 'mkdir & rmdir': function(test) { var globals = {}; return Async.waterfall([ function(cb){ globals.path = Path.join(OS.tmpdir(), '/path/deep/exists/not/yet'); return FSTK.mkdir(globals.path, Belt.cw(cb, 0)); } , function(cb){ return FSTK.exists(globals.path, function(exists){ test.ok(exists); return cb(); }); } , function(cb){ return FSTK.exists(Path.join(OS.tmpdir(), '/path/deep/exists'), function(exists){ test.ok(exists); return cb(); }); } , function(cb){ return FSTK.exists(Path.join(OS.tmpdir(), '/path'), function(exists){ test.ok(exists); return cb(); }); } , function(cb){ return FSTK.rmdir(globals.path, Belt.cw(cb, 0)); } , function(cb){ return FSTK.exists(globals.path, function(exists){ test.ok(!exists); return cb(); }); } , function(cb){ return FSTK.rmdir(globals.path, Belt.cw(cb, 0)); } , function(cb){ return FSTK.rmdir(Path.join(OS.tmpdir(), '/path'), Belt.cw(cb, 0)); } ], function(err){ if (err) console.error(err); test.ok(!err); test.done(); }); }, 'rm': function(test) { var globals = {}; return Async.waterfall([ function(cb){ globals.path = Path.join(OS.tmpdir(), '/random/path/to/' + Belt.uuid()); globals.file_path = Path.join(globals.path, '/' + Belt.uuid()); globals.file_path2 = Path.join(OS.tmpdir(), '/random', '/' + Belt.uuid()); return FSTK.mkdir(globals.path, Belt.cw(cb, 0)); } , function(cb){ return FSTK.exists(globals.path, function(exists){ test.ok(exists); return cb(); }); } , function(cb){ return FSTK.exists(Path.join(OS.tmpdir(), '/random/path/to'), function(exists){ test.ok(exists); return cb(); }); } , function(cb){ FS.writeFileSync(globals.file_path, 'this is a test'); FS.writeFileSync(globals.file_path2, 'this is a test'); return cb(); } , function(cb){ return FSTK.exists(globals.file_path, function(exists){ test.ok(exists); return cb(); }); } , function(cb){ return FSTK.exists(globals.file_path2, function(exists){ test.ok(exists); return cb(); }); } , function(cb){ return FSTK.rm(globals.file_path2, Belt.cw(cb, 0)); } , function(cb){ return FSTK.exists(globals.file_path2, function(exists){ test.ok(!exists); return cb(); }); } , function(cb){ return FSTK.rm(Path.join(OS.tmpdir(), '/random'), Belt.cw(cb, 0)); } , function(cb){ return FSTK.exists(Path.join(OS.tmpdir(), '/random'), function(exists){ test.ok(!exists); return cb(); }); } ], function(err){ if (err) console.error(err); test.ok(!err); test.done(); }); }, 'write files': function(test) { var globals = {}; return Async.waterfall([ function(cb){ globals.path = Path.join(OS.tmpdir(), '/' + Belt.uuid(), '/' + Belt.uuid(), '/' + Belt.uuid()); return FSTK.writeFile(globals.path, 'this is a test', Belt.cw(cb, 0)); } , function(cb){ var body = FS.readFileSync(globals.path); test.ok(body.toString() === 'this is a test'); return cb(); } ], function(err){ if (err) console.error(err); test.ok(!err); test.done(); }); }, 'watch files': function(test) { var globals = {}; return Async.waterfall([ function(cb){ globals.path = Path.join(OS.tmpdir(), '/' + Belt.uuid(), '/' + Belt.uuid(), '/' + Belt.uuid()); return FSTK.writeFile(globals.path, 'this is a test', Belt.cw(cb, 0)); } , function(cb){ return FSTK.watchFile(globals.path, Belt.cs(cb, globals, 'watch', 1, 0)); } , function(cb){ test.ok(globals.watch.file.toString() === 'this is a test'); FS.writeFileSync(globals.path, 'now it is modified'); return setTimeout(function(){ return globals.watch.get(Belt.cs(cb, globals, 'file', 0)); }, 1000); } , function(cb){ test.ok(globals.file.toString() === 'now it is modified'); return cb(); } , function(cb){ return globals.watch.set(new Buffer('modifying the file'), cb); } , function(cb){ return globals.watch.get(Belt.cs(cb, globals, 'file', 0)); } , function(cb){ test.ok(globals.file.toString() === 'modifying the file'); return cb(); } ], function(err){ if (err) console.error(err); test.ok(!err); test.done(); }); }, 'watch json': function(test) { var globals = {}; return Async.waterfall([ function(cb){ globals.path = Path.join(OS.tmpdir(), '/' + Belt.uuid(), '/' + Belt.uuid(), '/' + Belt.uuid()); globals.json = {'this': {'is': ['the', 'json', 1, 2, 3]}}; return FSTK.watchJSON(globals.path, {'data': globals.json}, Belt.cs(cb, globals, 'watch', 1, 0)); } , function(cb){ return globals.watch.get(Belt.cs(cb, globals, 'file', 0)); } , function(cb){ //test.ok(Belt.deepEqual(globals.file, globals.json)); return cb(); } , function(cb){ globals.new_json = {'this': {'be the': ['new']}}; return globals.watch.set(globals.new_json, Belt.cs(cb, globals, 'file', 0)); } , function(cb){ return globals.watch.get(Belt.cs(cb, globals, 'file', 0)); } , function(cb){ test.ok(Belt.deepEqual(globals.file, globals.new_json)); return cb(); } , function(cb){ globals.new_json = {'this': {'be the': 3}}; return globals.watch.pset('this.be the', 3, Belt.cs(cb, globals, 'file', 0)); } , function(cb){ return globals.watch.get(Belt.cs(cb, globals, 'file', 0)); } , function(cb){ //test.ok(Belt.deepEqual(globals.file, globals.new_json)); return cb(); } ], function(err){ if (err) console.error(err); test.ok(!err); test.done(); }); }, 'dirTree & dirPart': function(test) { var globals = {} , tree_level_test = function(tree_directory, dir_tree_directory){ test.ok(_.keys(dir_tree_directory.files).length === _.keys(tree_directory.files).length); test.ok(_.keys(dir_tree_directory.directories).length === _.keys(tree_directory.directories).length); test.ok(!_.any(_.difference(_.pluck(_.values(dir_tree_directory.files), 'path'), _.pluck(_.values(tree_directory.files), 'path')))); test.ok(!_.any(_.difference(_.pluck(_.values(dir_tree_directory.directories), 'path'), _.pluck(_.values(tree_directory.directories), 'path')))); return _.each(dir_tree_directory.directories, function(d){ return tree_level_test(_.find(tree_directory.directories, function(f){ return f.path === d.path; }), d); }); }; return Async.waterfall([ function(cb){ globals.tree = create_file_tree(); return cb(); } , function(cb){ return FSTK.dirTree(globals.tree.path, Belt.cs(cb, globals, 'dirTree', 1, 0)); } , function(cb){ return FSTK.dirPart(globals.tree.path, Belt.cs(cb, globals, 'dirPart', 1, 0)); } , function(cb){ FS.writeFileSync(Path.join(OS.tmpdir(), '/tree.json'), JSON.stringify(globals.dirTree, null, 2)); FS.writeFileSync(Path.join(OS.tmpdir(), '/part.json'), JSON.stringify(globals.dirPart, null, 2)); tree_level_test(globals.tree.contents, globals.dirTree); return cb(); } , function(cb){ return cb(); } ], function(err){ if (err) console.error(err); test.ok(!err); test.done(); }); }, 'flattenDir & emptyDir': function(test) { var globals = {}; return Async.waterfall([ function(cb){ globals.tree = create_file_tree(); return cb(); } , function(cb){ return FSTK.statDir(globals.tree.path, Belt.cs(cb, globals, 'orig_stat', 1, 0)); } , function(cb){ return FSTK.flattenDir(globals.tree.path, Belt.cw(cb, 0)); } , function(cb){ return FSTK.statDir(globals.tree.path, Belt.cs(cb, globals, 'stat', 1, 0)); } , function(cb){ return FSTK.dirPart(globals.tree.path, Belt.cs(cb, globals, 'part', 1, 0)); } , function(cb){ test.ok(globals.stat.files.length === _.keys(globals.tree.files).length); test.ok(globals.orig_stat.files.length !== _.keys(globals.tree.files).length); test.ok(!_.any(globals.part.directories)); return cb(); } , function(cb){ globals.tree = create_file_tree(); return cb(); } , function(cb){ return FSTK.dirPart(globals.tree.path, Belt.cs(cb, globals, 'orig_stat', 1, 0)); } , function(cb){ return FSTK.emptyDir(globals.tree.path, Belt.cw(cb, 0)); } , function(cb){ return FSTK.dirPart(globals.tree.path, Belt.cs(cb, globals, 'stat', 1, 0)); } , function(cb){ test.ok(globals.stat.directories.length === globals.orig_stat.directories.length); test.ok(globals.stat.files.length !== globals.orig_stat.files.length); test.ok(!_.any(globals.stat.files)); return cb(); } , function(cb){ var files = []; for (var i = 0; i < 2000; i++){ var path = FSTK.tempfile(); test.ok(path); test.ok(!_.some(files, function(f){ return f === path; })); files.push(path); } return cb(); } , function(cb){ return FSTK.getURL('http://nytimes.com', Belt.cs(cb, globals, 'path', 1, 0)); } , function(cb){ globals.file = FS.readFileSync(globals.path).toString(); test.ok(globals.file.match(/<\/html>/)); test.ok(globals.file.match(/<html/)); return cb(); } , function(cb){ return FSTK.getURL('http://i.imgur.com/IBPVml1.jpg', Belt.cs(cb, globals, 'path', 1, 0)); } , function(cb){ test.ok(FS.existsSync(globals.path)); return cb(); } , function(cb){ globals.path = FSTK.tempfile(); FS.writeFileSync(globals.path, 'This is a test file'); globals.new_path = FSTK.tempfile(); test.ok(FS.existsSync(globals.path)); test.ok(!FS.existsSync(globals.new_path)); return FSTK.mv(globals.path, globals.new_path, Belt.cw(cb, 0)); } , function(cb){ test.ok(!FS.existsSync(globals.path)); test.ok(FS.existsSync(globals.new_path)); return cb(); } , function(cb){ globals.path = FSTK.tempfile(); globals.sub_path = Path.join(globals.path, '/asubpath.txt'); globals.sub_path2 = Path.join(globals.path, '/subpath2'); globals.sub_path3 = Path.join(globals.sub_path2, '/nested.txt'); FS.mkdirSync(globals.path); FS.mkdirSync(globals.sub_path2); FS.writeFileSync(globals.sub_path, 'This is a test file'); FS.writeFileSync(globals.sub_path3, 'This is a test file'); globals.new_path = FSTK.tempfile(); test.ok(FS.existsSync(globals.path)); test.ok(FS.existsSync(globals.sub_path)); test.ok(FS.existsSync(globals.sub_path2)); test.ok(FS.existsSync(globals.sub_path3)); test.ok(!FS.existsSync(globals.new_path)); return FSTK.mv(globals.path, globals.new_path, Belt.cw(cb, 0)); } , function(cb){ test.ok(!FS.existsSync(globals.path)); test.ok(!FS.existsSync(globals.sub_path)); test.ok(!FS.existsSync(globals.sub_path2)); test.ok(!FS.existsSync(globals.sub_path3)); test.ok(FS.existsSync(globals.new_path)); return cb(); } ], function(err){ if (err) console.error(err); test.ok(!err); test.done(); }); } , 'safePath': function(test){ var test_name = 'safePath'; //log.debug(test_name); //log.profile(test_name); //Yessir.test = test; test.ok(FSTK.safePath('/') === false); test.ok(FSTK.safePath('/etc') === false); test.ok(FSTK.safePath('/some.json') === false); test.ok(FSTK.safePath('./'), Path.resolve('./')); test.ok(FSTK.safePath('.'), Path.resolve('.')); test.ok(FSTK.safePath('..'), Path.resolve('..')); test.ok(FSTK.safePath('') === false); test.ok(FSTK.safePath() === false); test.ok(FSTK.safePath(false) === false); test.ok(FSTK.safePath(null) === false); test.ok(FSTK.safePath('etc')); test.ok(FSTK.safePath('/etc/file')); //log.profile(test_name); return test.done(); } , 'recursiveChecksum': function(test){ var test_name = 'recursiveChecksum'; log.debug(test_name); log.profile(test_name); return FSTK.recursiveChecksum('/mnt/F/documents/code', function(err, files, errs){ test.ok(!err, err); console.log(err); log.info(files.length); log.info(errs.length); log.profile(test_name); return test.done(); }); } };
// Code generated by ogen, DO NOT EDIT. package api import ( "bytes" "context" "fmt" "io" "math" "math/bits" "net" "net/http" "net/url" "regexp" "sort" "strconv" "strings" "sync" "time" "github.com/go-faster/errors" "github.com/go-faster/jx" "github.com/google/uuid" "github.com/ogen-go/ogen/conv" ht "github.com/ogen-go/ogen/http" "github.com/ogen-go/ogen/json" "github.com/ogen-go/ogen/otelogen" "github.com/ogen-go/ogen/uri" "github.com/ogen-go/ogen/validate" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/metric" "go.opentelemetry.io/otel/trace" ) // No-op definition for keeping imports. var ( _ = context.Background() _ = fmt.Stringer(nil) _ = strings.Builder{} _ = errors.Is _ = sort.Ints _ = http.MethodGet _ = io.Copy _ = json.Marshal _ = bytes.NewReader _ = strconv.ParseInt _ = time.Time{} _ = conv.ToInt32 _ = uuid.UUID{} _ = uri.PathEncoder{} _ = url.URL{} _ = math.Mod _ = bits.LeadingZeros64 _ = validate.Int{} _ = ht.NewRequest _ = net.IP{} _ = otelogen.Version _ = trace.TraceIDFromHex _ = otel.GetTracerProvider _ = metric.NewNoopMeterProvider _ = regexp.MustCompile _ = jx.Null _ = sync.Pool{} ) func (s *ErrorStatusCode) Error() string { return fmt.Sprintf("code %d: %+v", s.StatusCode, s.Response) } // Input for addStickerToSet. // Ref: #/components/schemas/addStickerToSet type AddStickerToSet struct { // User identifier of sticker set owner. UserID int `json:"user_id"` // Sticker set name. Name string `json:"name"` // PNG image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, // and either width or height must be exactly 512px. Pass a file_id as a String to send a file that // already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file // from the Internet, or upload a new one using multipart/form-data. More info on Sending Files ». PNGSticker OptString `json:"png_sticker"` // TGS animation with the sticker, uploaded using multipart/form-data. See https://core.telegram. // org/animated_stickers#technical-requirements for technical requirements. TgsSticker OptString `json:"tgs_sticker"` // One or more emoji corresponding to the sticker. Emojis string `json:"emojis"` MaskPosition OptMaskPosition `json:"mask_position"` } // This object represents an animation file (GIF or H.264/MPEG-4 AVC video without sound). // Ref: #/components/schemas/Animation type Animation struct { // Identifier for this file, which can be used to download or reuse the file. FileID string `json:"file_id"` // Unique identifier for this file, which is supposed to be the same over time and for different bots. // Can't be used to download or reuse the file. FileUniqueID string `json:"file_unique_id"` // Video width as defined by sender. Width int `json:"width"` // Video height as defined by sender. Height int `json:"height"` // Duration of the video in seconds as defined by sender. Duration int `json:"duration"` Thumb OptPhotoSize `json:"thumb"` // Original animation filename as defined by sender. FileName OptString `json:"file_name"` // MIME type of the file as defined by sender. MimeType OptString `json:"mime_type"` // File size in bytes. FileSize OptInt `json:"file_size"` } // Input for answerCallbackQuery. // Ref: #/components/schemas/answerCallbackQuery type AnswerCallbackQuery struct { // Unique identifier for the query to be answered. CallbackQueryID string `json:"callback_query_id"` // Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters. Text OptString `json:"text"` // If True, an alert will be shown by the client instead of a notification at the top of the chat // screen. Defaults to false. ShowAlert OptBool `json:"show_alert"` // URL that will be opened by the user's client. If you have created a Game and accepted the // conditions via @Botfather, specify the URL that opens your game — note that this will only work // if the query comes from a callback_game button.Otherwise, you may use links like t. // me/your_bot?start=XXXX that open your bot with a parameter. URL OptURL `json:"url"` // The maximum amount of time in seconds that the result of the callback query may be cached // client-side. Telegram apps will support caching starting in version 3.14. Defaults to 0. CacheTime OptInt `json:"cache_time"` } // Input for answerInlineQuery. // Ref: #/components/schemas/answerInlineQuery type AnswerInlineQuery struct { // Unique identifier for the answered query. InlineQueryID string `json:"inline_query_id"` // A JSON-serialized array of results for the inline query. Results []InlineQueryResult `json:"results"` // The maximum amount of time in seconds that the result of the inline query may be cached on the // server. Defaults to 300. CacheTime OptInt `json:"cache_time"` // Pass True, if results may be cached on the server side only for the user that sent the query. By // default, results may be returned to any user who sends the same query. IsPersonal OptBool `json:"is_personal"` // Pass the offset that a client should send in the next query with the same text to receive more // results. Pass an empty string if there are no more results or if you don't support pagination. // Offset length can't exceed 64 bytes. NextOffset OptString `json:"next_offset"` // If passed, clients will display a button with specified text that switches the user to a private // chat with the bot and sends the bot a start message with the parameter switch_pm_parameter. SwitchPmText OptString `json:"switch_pm_text"` // Deep-linking parameter for the /start message sent to the bot when user presses the switch button. // 1-64 characters, only A-Z, a-z, 0-9, _ and - are allowed.Example: An inline bot that sends YouTube // videos can ask the user to connect the bot to their YouTube account to adapt search results // accordingly. To do this, it displays a 'Connect your YouTube account' button above the results, or // even before showing any. The user presses the button, switches to a private chat with the bot and, // in doing so, passes a start parameter that instructs the bot to return an OAuth link. Once done, // the bot can offer a switch_inline button so that the user can easily return to the chat where they // wanted to use the bot's inline capabilities. SwitchPmParameter OptString `json:"switch_pm_parameter"` } // Input for answerPreCheckoutQuery. // Ref: #/components/schemas/answerPreCheckoutQuery type AnswerPreCheckoutQuery struct { // Unique identifier for the query to be answered. PreCheckoutQueryID string `json:"pre_checkout_query_id"` // Specify True if everything is alright (goods are available, etc.) and the bot is ready to proceed // with the order. Use False if there are any problems. Ok bool `json:"ok"` // Required if ok is False. Error message in human readable form that explains the reason for failure // to proceed with the checkout (e.g. "Sorry, somebody just bought the last of our amazing black // T-shirts while you were busy filling out your payment details. Please choose a different color or // garment!"). Telegram will display this message to the user. ErrorMessage OptString `json:"error_message"` } // Input for answerShippingQuery. // Ref: #/components/schemas/answerShippingQuery type AnswerShippingQuery struct { // Unique identifier for the query to be answered. ShippingQueryID string `json:"shipping_query_id"` // Specify True if delivery to the specified address is possible and False if there are any problems // (for example, if delivery to the specified address is not possible). Ok bool `json:"ok"` // Required if ok is True. A JSON-serialized array of available shipping options. ShippingOptions []ShippingOption `json:"shipping_options"` // Required if ok is False. Error message in human readable form that explains why it is impossible // to complete the order (e.g. "Sorry, delivery to your desired address is unavailable'). Telegram // will display this message to the user. ErrorMessage OptString `json:"error_message"` } // Input for approveChatJoinRequest. // Ref: #/components/schemas/approveChatJoinRequest type ApproveChatJoinRequest struct { ChatID ID `json:"chat_id"` // Unique identifier of the target user. UserID int `json:"user_id"` } // This object represents an audio file to be treated as music by the Telegram clients. // Ref: #/components/schemas/Audio type Audio struct { // Identifier for this file, which can be used to download or reuse the file. FileID string `json:"file_id"` // Unique identifier for this file, which is supposed to be the same over time and for different bots. // Can't be used to download or reuse the file. FileUniqueID string `json:"file_unique_id"` // Duration of the audio in seconds as defined by sender. Duration int `json:"duration"` // Performer of the audio as defined by sender or by audio tags. Performer OptString `json:"performer"` // Title of the audio as defined by sender or by audio tags. Title OptString `json:"title"` // Original filename as defined by sender. FileName OptString `json:"file_name"` // MIME type of the file as defined by sender. MimeType OptString `json:"mime_type"` // File size in bytes. FileSize OptInt `json:"file_size"` Thumb OptPhotoSize `json:"thumb"` } // Input for banChatMember. // Ref: #/components/schemas/banChatMember type BanChatMember struct { ChatID ID `json:"chat_id"` // Unique identifier of the target user. UserID int `json:"user_id"` // Date when the user will be unbanned, unix time. If user is banned for more than 366 days or less // than 30 seconds from the current time they are considered to be banned forever. Applied for // supergroups and channels only. UntilDate OptInt `json:"until_date"` // Pass True to delete all messages from the chat for the user that is being removed. If False, the // user will be able to see messages in the group that were sent before the user was removed. Always // True for supergroups and channels. RevokeMessages OptBool `json:"revoke_messages"` } // This object represents a bot command. // Ref: #/components/schemas/BotCommand type BotCommand struct { // Text of the command, 1-32 characters. Can contain only lowercase English letters, digits and // underscores. Command string `json:"command"` // Description of the command, 3-256 characters. Description string `json:"description"` } // This object represents the scope to which bot commands are applied. 7 scopes are supported:. // Ref: #/components/schemas/BotCommandScope // BotCommandScope represents sum type. type BotCommandScope struct { Type BotCommandScopeType // switch on this field BotCommandScopeDefault BotCommandScopeDefault BotCommandScopeAllPrivateChats BotCommandScopeAllPrivateChats BotCommandScopeAllGroupChats BotCommandScopeAllGroupChats BotCommandScopeAllChatAdministrators BotCommandScopeAllChatAdministrators BotCommandScopeChat BotCommandScopeChat BotCommandScopeChatAdministrators BotCommandScopeChatAdministrators BotCommandScopeChatMember BotCommandScopeChatMember } // BotCommandScopeType is oneOf type of BotCommandScope. type BotCommandScopeType string // Possible values for BotCommandScopeType. const ( BotCommandScopeDefaultBotCommandScope BotCommandScopeType = "BotCommandScopeDefault" BotCommandScopeAllPrivateChatsBotCommandScope BotCommandScopeType = "BotCommandScopeAllPrivateChats" BotCommandScopeAllGroupChatsBotCommandScope BotCommandScopeType = "BotCommandScopeAllGroupChats" BotCommandScopeAllChatAdministratorsBotCommandScope BotCommandScopeType = "BotCommandScopeAllChatAdministrators" BotCommandScopeChatBotCommandScope BotCommandScopeType = "BotCommandScopeChat" BotCommandScopeChatAdministratorsBotCommandScope BotCommandScopeType = "BotCommandScopeChatAdministrators" BotCommandScopeChatMemberBotCommandScope BotCommandScopeType = "BotCommandScopeChatMember" ) // IsBotCommandScopeDefault reports whether BotCommandScope is BotCommandScopeDefault. func (s BotCommandScope) IsBotCommandScopeDefault() bool { return s.Type == BotCommandScopeDefaultBotCommandScope } // IsBotCommandScopeAllPrivateChats reports whether BotCommandScope is BotCommandScopeAllPrivateChats. func (s BotCommandScope) IsBotCommandScopeAllPrivateChats() bool { return s.Type == BotCommandScopeAllPrivateChatsBotCommandScope } // IsBotCommandScopeAllGroupChats reports whether BotCommandScope is BotCommandScopeAllGroupChats. func (s BotCommandScope) IsBotCommandScopeAllGroupChats() bool { return s.Type == BotCommandScopeAllGroupChatsBotCommandScope } // IsBotCommandScopeAllChatAdministrators reports whether BotCommandScope is BotCommandScopeAllChatAdministrators. func (s BotCommandScope) IsBotCommandScopeAllChatAdministrators() bool { return s.Type == BotCommandScopeAllChatAdministratorsBotCommandScope } // IsBotCommandScopeChat reports whether BotCommandScope is BotCommandScopeChat. func (s BotCommandScope) IsBotCommandScopeChat() bool { return s.Type == BotCommandScopeChatBotCommandScope } // IsBotCommandScopeChatAdministrators reports whether BotCommandScope is BotCommandScopeChatAdministrators. func (s BotCommandScope) IsBotCommandScopeChatAdministrators() bool { return s.Type == BotCommandScopeChatAdministratorsBotCommandScope } // IsBotCommandScopeChatMember reports whether BotCommandScope is BotCommandScopeChatMember. func (s BotCommandScope) IsBotCommandScopeChatMember() bool { return s.Type == BotCommandScopeChatMemberBotCommandScope } // SetBotCommandScopeDefault sets BotCommandScope to BotCommandScopeDefault. func (s *BotCommandScope) SetBotCommandScopeDefault(v BotCommandScopeDefault) { s.Type = BotCommandScopeDefaultBotCommandScope s.BotCommandScopeDefault = v } // GetBotCommandScopeDefault returns BotCommandScopeDefault and true boolean if BotCommandScope is BotCommandScopeDefault. func (s BotCommandScope) GetBotCommandScopeDefault() (v BotCommandScopeDefault, ok bool) { if !s.IsBotCommandScopeDefault() { return v, false } return s.BotCommandScopeDefault, true } // NewBotCommandScopeDefaultBotCommandScope returns new BotCommandScope from BotCommandScopeDefault. func NewBotCommandScopeDefaultBotCommandScope(v BotCommandScopeDefault) BotCommandScope { var s BotCommandScope s.SetBotCommandScopeDefault(v) return s } // SetBotCommandScopeAllPrivateChats sets BotCommandScope to BotCommandScopeAllPrivateChats. func (s *BotCommandScope) SetBotCommandScopeAllPrivateChats(v BotCommandScopeAllPrivateChats) { s.Type = BotCommandScopeAllPrivateChatsBotCommandScope s.BotCommandScopeAllPrivateChats = v } // GetBotCommandScopeAllPrivateChats returns BotCommandScopeAllPrivateChats and true boolean if BotCommandScope is BotCommandScopeAllPrivateChats. func (s BotCommandScope) GetBotCommandScopeAllPrivateChats() (v BotCommandScopeAllPrivateChats, ok bool) { if !s.IsBotCommandScopeAllPrivateChats() { return v, false } return s.BotCommandScopeAllPrivateChats, true } // NewBotCommandScopeAllPrivateChatsBotCommandScope returns new BotCommandScope from BotCommandScopeAllPrivateChats. func NewBotCommandScopeAllPrivateChatsBotCommandScope(v BotCommandScopeAllPrivateChats) BotCommandScope { var s BotCommandScope s.SetBotCommandScopeAllPrivateChats(v) return s } // SetBotCommandScopeAllGroupChats sets BotCommandScope to BotCommandScopeAllGroupChats. func (s *BotCommandScope) SetBotCommandScopeAllGroupChats(v BotCommandScopeAllGroupChats) { s.Type = BotCommandScopeAllGroupChatsBotCommandScope s.BotCommandScopeAllGroupChats = v } // GetBotCommandScopeAllGroupChats returns BotCommandScopeAllGroupChats and true boolean if BotCommandScope is BotCommandScopeAllGroupChats. func (s BotCommandScope) GetBotCommandScopeAllGroupChats() (v BotCommandScopeAllGroupChats, ok bool) { if !s.IsBotCommandScopeAllGroupChats() { return v, false } return s.BotCommandScopeAllGroupChats, true } // NewBotCommandScopeAllGroupChatsBotCommandScope returns new BotCommandScope from BotCommandScopeAllGroupChats. func NewBotCommandScopeAllGroupChatsBotCommandScope(v BotCommandScopeAllGroupChats) BotCommandScope { var s BotCommandScope s.SetBotCommandScopeAllGroupChats(v) return s } // SetBotCommandScopeAllChatAdministrators sets BotCommandScope to BotCommandScopeAllChatAdministrators. func (s *BotCommandScope) SetBotCommandScopeAllChatAdministrators(v BotCommandScopeAllChatAdministrators) { s.Type = BotCommandScopeAllChatAdministratorsBotCommandScope s.BotCommandScopeAllChatAdministrators = v } // GetBotCommandScopeAllChatAdministrators returns BotCommandScopeAllChatAdministrators and true boolean if BotCommandScope is BotCommandScopeAllChatAdministrators. func (s BotCommandScope) GetBotCommandScopeAllChatAdministrators() (v BotCommandScopeAllChatAdministrators, ok bool) { if !s.IsBotCommandScopeAllChatAdministrators() { return v, false } return s.BotCommandScopeAllChatAdministrators, true } // NewBotCommandScopeAllChatAdministratorsBotCommandScope returns new BotCommandScope from BotCommandScopeAllChatAdministrators. func NewBotCommandScopeAllChatAdministratorsBotCommandScope(v BotCommandScopeAllChatAdministrators) BotCommandScope { var s BotCommandScope s.SetBotCommandScopeAllChatAdministrators(v) return s } // SetBotCommandScopeChat sets BotCommandScope to BotCommandScopeChat. func (s *BotCommandScope) SetBotCommandScopeChat(v BotCommandScopeChat) { s.Type = BotCommandScopeChatBotCommandScope s.BotCommandScopeChat = v } // GetBotCommandScopeChat returns BotCommandScopeChat and true boolean if BotCommandScope is BotCommandScopeChat. func (s BotCommandScope) GetBotCommandScopeChat() (v BotCommandScopeChat, ok bool) { if !s.IsBotCommandScopeChat() { return v, false } return s.BotCommandScopeChat, true } // NewBotCommandScopeChatBotCommandScope returns new BotCommandScope from BotCommandScopeChat. func NewBotCommandScopeChatBotCommandScope(v BotCommandScopeChat) BotCommandScope { var s BotCommandScope s.SetBotCommandScopeChat(v) return s } // SetBotCommandScopeChatAdministrators sets BotCommandScope to BotCommandScopeChatAdministrators. func (s *BotCommandScope) SetBotCommandScopeChatAdministrators(v BotCommandScopeChatAdministrators) { s.Type = BotCommandScopeChatAdministratorsBotCommandScope s.BotCommandScopeChatAdministrators = v } // GetBotCommandScopeChatAdministrators returns BotCommandScopeChatAdministrators and true boolean if BotCommandScope is BotCommandScopeChatAdministrators. func (s BotCommandScope) GetBotCommandScopeChatAdministrators() (v BotCommandScopeChatAdministrators, ok bool) { if !s.IsBotCommandScopeChatAdministrators() { return v, false } return s.BotCommandScopeChatAdministrators, true } // NewBotCommandScopeChatAdministratorsBotCommandScope returns new BotCommandScope from BotCommandScopeChatAdministrators. func NewBotCommandScopeChatAdministratorsBotCommandScope(v BotCommandScopeChatAdministrators) BotCommandScope { var s BotCommandScope s.SetBotCommandScopeChatAdministrators(v) return s } // SetBotCommandScopeChatMember sets BotCommandScope to BotCommandScopeChatMember. func (s *BotCommandScope) SetBotCommandScopeChatMember(v BotCommandScopeChatMember) { s.Type = BotCommandScopeChatMemberBotCommandScope s.BotCommandScopeChatMember = v } // GetBotCommandScopeChatMember returns BotCommandScopeChatMember and true boolean if BotCommandScope is BotCommandScopeChatMember. func (s BotCommandScope) GetBotCommandScopeChatMember() (v BotCommandScopeChatMember, ok bool) { if !s.IsBotCommandScopeChatMember() { return v, false } return s.BotCommandScopeChatMember, true } // NewBotCommandScopeChatMemberBotCommandScope returns new BotCommandScope from BotCommandScopeChatMember. func NewBotCommandScopeChatMemberBotCommandScope(v BotCommandScopeChatMember) BotCommandScope { var s BotCommandScope s.SetBotCommandScopeChatMember(v) return s } // Represents the scope of bot commands, covering all group and supergroup chat administrators. // Ref: #/components/schemas/BotCommandScopeAllChatAdministrators type BotCommandScopeAllChatAdministrators struct { // Scope type, must be all_chat_administrators. Type string `json:"type"` } // Represents the scope of bot commands, covering all group and supergroup chats. // Ref: #/components/schemas/BotCommandScopeAllGroupChats type BotCommandScopeAllGroupChats struct { // Scope type, must be all_group_chats. Type string `json:"type"` } // Represents the scope of bot commands, covering all private chats. // Ref: #/components/schemas/BotCommandScopeAllPrivateChats type BotCommandScopeAllPrivateChats struct { // Scope type, must be all_private_chats. Type string `json:"type"` } // Represents the scope of bot commands, covering a specific chat. // Ref: #/components/schemas/BotCommandScopeChat type BotCommandScopeChat struct { // Scope type, must be chat. Type string `json:"type"` ChatID ID `json:"chat_id"` } // Represents the scope of bot commands, covering all administrators of a specific group or // supergroup chat. // Ref: #/components/schemas/BotCommandScopeChatAdministrators type BotCommandScopeChatAdministrators struct { // Scope type, must be chat_administrators. Type string `json:"type"` ChatID ID `json:"chat_id"` } // Represents the scope of bot commands, covering a specific member of a group or supergroup chat. // Ref: #/components/schemas/BotCommandScopeChatMember type BotCommandScopeChatMember struct { // Scope type, must be chat_member. Type string `json:"type"` ChatID ID `json:"chat_id"` // Unique identifier of the target user. UserID int `json:"user_id"` } // Represents the default scope of bot commands. Default commands are used if no commands with a // narrower scope are specified for the user. // Ref: #/components/schemas/BotCommandScopeDefault type BotCommandScopeDefault struct { // Scope type, must be default. Type string `json:"type"` } // A placeholder, currently holds no information. Use BotFather to set up your game. // Ref: #/components/schemas/CallbackGame type CallbackGame struct{} // This object represents a chat. // Ref: #/components/schemas/Chat type Chat struct { // Unique identifier for this chat. This number may have more than 32 significant bits and some // programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 // significant bits, so a signed 64-bit integer or double-precision float type are safe for storing // this identifier. ID int `json:"id"` // Type of chat, can be either “private”, “group”, “supergroup” or “channel”. Type string `json:"type"` // Title, for supergroups, channels and group chats. Title OptString `json:"title"` // Username, for private chats, supergroups and channels if available. Username OptString `json:"username"` // First name of the other party in a private chat. FirstName OptString `json:"first_name"` // Last name of the other party in a private chat. LastName OptString `json:"last_name"` Photo OptChatPhoto `json:"photo"` // Bio of the other party in a private chat. Returned only in getChat. Bio OptString `json:"bio"` // Description, for groups, supergroups and channel chats. Returned only in getChat. Description OptString `json:"description"` // Primary invite link, for groups, supergroups and channel chats. Returned only in getChat. InviteLink OptString `json:"invite_link"` PinnedMessage *Message `json:"pinned_message"` Permissions OptChatPermissions `json:"permissions"` // For supergroups, the minimum allowed delay between consecutive messages sent by each unprivileged // user; in seconds. Returned only in getChat. SlowModeDelay OptInt `json:"slow_mode_delay"` // The time after which all messages sent to the chat will be automatically deleted; in seconds. // Returned only in getChat. MessageAutoDeleteTime OptInt `json:"message_auto_delete_time"` // For supergroups, name of group sticker set. Returned only in getChat. StickerSetName OptString `json:"sticker_set_name"` // True, if the bot can change the group sticker set. Returned only in getChat. CanSetStickerSet OptBool `json:"can_set_sticker_set"` // Unique identifier for the linked chat, i.e. the discussion group identifier for a channel and vice // versa; for supergroups and channel chats. This identifier may be greater than 32 bits and some // programming languages may have difficulty/silent defects in interpreting it. But it is smaller // than 52 bits, so a signed 64 bit integer or double-precision float type are safe for storing this // identifier. Returned only in getChat. LinkedChatID OptInt `json:"linked_chat_id"` Location OptChatLocation `json:"location"` } // Represents a location to which a chat is connected. // Ref: #/components/schemas/ChatLocation type ChatLocation struct { Location Location `json:"location"` // Location address; 1-64 characters, as defined by the chat owner. Address string `json:"address"` } // Describes actions that a non-administrator user is allowed to take in a chat. // Ref: #/components/schemas/ChatPermissions type ChatPermissions struct { // True, if the user is allowed to send text messages, contacts, locations and venues. CanSendMessages OptBool `json:"can_send_messages"` // True, if the user is allowed to send audios, documents, photos, videos, video notes and voice // notes, implies can_send_messages. CanSendMediaMessages OptBool `json:"can_send_media_messages"` // True, if the user is allowed to send polls, implies can_send_messages. CanSendPolls OptBool `json:"can_send_polls"` // True, if the user is allowed to send animations, games, stickers and use inline bots, implies // can_send_media_messages. CanSendOtherMessages OptBool `json:"can_send_other_messages"` // True, if the user is allowed to add web page previews to their messages, implies // can_send_media_messages. CanAddWebPagePreviews OptBool `json:"can_add_web_page_previews"` // True, if the user is allowed to change the chat title, photo and other settings. Ignored in public // supergroups. CanChangeInfo OptBool `json:"can_change_info"` // True, if the user is allowed to invite new users to the chat. CanInviteUsers OptBool `json:"can_invite_users"` // True, if the user is allowed to pin messages. Ignored in public supergroups. CanPinMessages OptBool `json:"can_pin_messages"` } // This object represents a chat photo. // Ref: #/components/schemas/ChatPhoto type ChatPhoto struct { // File identifier of small (160x160) chat photo. This file_id can be used only for photo download // and only for as long as the photo is not changed. SmallFileID string `json:"small_file_id"` // Unique file identifier of small (160x160) chat photo, which is supposed to be the same over time // and for different bots. Can't be used to download or reuse the file. SmallFileUniqueID string `json:"small_file_unique_id"` // File identifier of big (640x640) chat photo. This file_id can be used only for photo download and // only for as long as the photo is not changed. BigFileID string `json:"big_file_id"` // Unique file identifier of big (640x640) chat photo, which is supposed to be the same over time and // for different bots. Can't be used to download or reuse the file. BigFileUniqueID string `json:"big_file_unique_id"` } // This object represents a phone contact. // Ref: #/components/schemas/Contact type Contact struct { // Contact's phone number. PhoneNumber string `json:"phone_number"` // Contact's first name. FirstName string `json:"first_name"` // Contact's last name. LastName OptString `json:"last_name"` // Contact's user identifier in Telegram. This number may have more than 32 significant bits and some // programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 // significant bits, so a 64-bit integer or double-precision float type are safe for storing this // identifier. UserID OptInt `json:"user_id"` // Additional data about the contact in the form of a vCard. Vcard OptString `json:"vcard"` } // Input for copyMessage. // Ref: #/components/schemas/copyMessage type CopyMessage struct { ChatID ID `json:"chat_id"` FromChatID ID `json:"from_chat_id"` // Message identifier in the chat specified in from_chat_id. MessageID int `json:"message_id"` // New caption for media, 0-1024 characters after entities parsing. If not specified, the original // caption is kept. Caption OptString `json:"caption"` // Mode for parsing entities in the new caption. See formatting options for more details. ParseMode OptString `json:"parse_mode"` // A JSON-serialized list of special entities that appear in the new caption, which can be specified // instead of parse_mode. CaptionEntities []MessageEntity `json:"caption_entities"` // Sends the message silently. Users will receive a notification with no sound. DisableNotification OptBool `json:"disable_notification"` // If the message is a reply, ID of the original message. ReplyToMessageID OptInt `json:"reply_to_message_id"` // Pass True, if the message should be sent even if the specified replied-to message is not found. AllowSendingWithoutReply OptBool `json:"allow_sending_without_reply"` // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply // keyboard, instructions to remove reply keyboard or to force a reply from the user. ReplyMarkup OptCopyMessageReplyMarkup `json:"reply_markup"` } // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply // keyboard, instructions to remove reply keyboard or to force a reply from the user. // CopyMessageReplyMarkup represents sum type. type CopyMessageReplyMarkup struct { Type CopyMessageReplyMarkupType // switch on this field InlineKeyboardMarkup InlineKeyboardMarkup ReplyKeyboardMarkup ReplyKeyboardMarkup ReplyKeyboardRemove ReplyKeyboardRemove ForceReply ForceReply } // CopyMessageReplyMarkupType is oneOf type of CopyMessageReplyMarkup. type CopyMessageReplyMarkupType string // Possible values for CopyMessageReplyMarkupType. const ( InlineKeyboardMarkupCopyMessageReplyMarkup CopyMessageReplyMarkupType = "InlineKeyboardMarkup" ReplyKeyboardMarkupCopyMessageReplyMarkup CopyMessageReplyMarkupType = "ReplyKeyboardMarkup" ReplyKeyboardRemoveCopyMessageReplyMarkup CopyMessageReplyMarkupType = "ReplyKeyboardRemove" ForceReplyCopyMessageReplyMarkup CopyMessageReplyMarkupType = "ForceReply" ) // IsInlineKeyboardMarkup reports whether CopyMessageReplyMarkup is InlineKeyboardMarkup. func (s CopyMessageReplyMarkup) IsInlineKeyboardMarkup() bool { return s.Type == InlineKeyboardMarkupCopyMessageReplyMarkup } // IsReplyKeyboardMarkup reports whether CopyMessageReplyMarkup is ReplyKeyboardMarkup. func (s CopyMessageReplyMarkup) IsReplyKeyboardMarkup() bool { return s.Type == ReplyKeyboardMarkupCopyMessageReplyMarkup } // IsReplyKeyboardRemove reports whether CopyMessageReplyMarkup is ReplyKeyboardRemove. func (s CopyMessageReplyMarkup) IsReplyKeyboardRemove() bool { return s.Type == ReplyKeyboardRemoveCopyMessageReplyMarkup } // IsForceReply reports whether CopyMessageReplyMarkup is ForceReply. func (s CopyMessageReplyMarkup) IsForceReply() bool { return s.Type == ForceReplyCopyMessageReplyMarkup } // SetInlineKeyboardMarkup sets CopyMessageReplyMarkup to InlineKeyboardMarkup. func (s *CopyMessageReplyMarkup) SetInlineKeyboardMarkup(v InlineKeyboardMarkup) { s.Type = InlineKeyboardMarkupCopyMessageReplyMarkup s.InlineKeyboardMarkup = v } // GetInlineKeyboardMarkup returns InlineKeyboardMarkup and true boolean if CopyMessageReplyMarkup is InlineKeyboardMarkup. func (s CopyMessageReplyMarkup) GetInlineKeyboardMarkup() (v InlineKeyboardMarkup, ok bool) { if !s.IsInlineKeyboardMarkup() { return v, false } return s.InlineKeyboardMarkup, true } // NewInlineKeyboardMarkupCopyMessageReplyMarkup returns new CopyMessageReplyMarkup from InlineKeyboardMarkup. func NewInlineKeyboardMarkupCopyMessageReplyMarkup(v InlineKeyboardMarkup) CopyMessageReplyMarkup { var s CopyMessageReplyMarkup s.SetInlineKeyboardMarkup(v) return s } // SetReplyKeyboardMarkup sets CopyMessageReplyMarkup to ReplyKeyboardMarkup. func (s *CopyMessageReplyMarkup) SetReplyKeyboardMarkup(v ReplyKeyboardMarkup) { s.Type = ReplyKeyboardMarkupCopyMessageReplyMarkup s.ReplyKeyboardMarkup = v } // GetReplyKeyboardMarkup returns ReplyKeyboardMarkup and true boolean if CopyMessageReplyMarkup is ReplyKeyboardMarkup. func (s CopyMessageReplyMarkup) GetReplyKeyboardMarkup() (v ReplyKeyboardMarkup, ok bool) { if !s.IsReplyKeyboardMarkup() { return v, false } return s.ReplyKeyboardMarkup, true } // NewReplyKeyboardMarkupCopyMessageReplyMarkup returns new CopyMessageReplyMarkup from ReplyKeyboardMarkup. func NewReplyKeyboardMarkupCopyMessageReplyMarkup(v ReplyKeyboardMarkup) CopyMessageReplyMarkup { var s CopyMessageReplyMarkup s.SetReplyKeyboardMarkup(v) return s } // SetReplyKeyboardRemove sets CopyMessageReplyMarkup to ReplyKeyboardRemove. func (s *CopyMessageReplyMarkup) SetReplyKeyboardRemove(v ReplyKeyboardRemove) { s.Type = ReplyKeyboardRemoveCopyMessageReplyMarkup s.ReplyKeyboardRemove = v } // GetReplyKeyboardRemove returns ReplyKeyboardRemove and true boolean if CopyMessageReplyMarkup is ReplyKeyboardRemove. func (s CopyMessageReplyMarkup) GetReplyKeyboardRemove() (v ReplyKeyboardRemove, ok bool) { if !s.IsReplyKeyboardRemove() { return v, false } return s.ReplyKeyboardRemove, true } // NewReplyKeyboardRemoveCopyMessageReplyMarkup returns new CopyMessageReplyMarkup from ReplyKeyboardRemove. func NewReplyKeyboardRemoveCopyMessageReplyMarkup(v ReplyKeyboardRemove) CopyMessageReplyMarkup { var s CopyMessageReplyMarkup s.SetReplyKeyboardRemove(v) return s } // SetForceReply sets CopyMessageReplyMarkup to ForceReply. func (s *CopyMessageReplyMarkup) SetForceReply(v ForceReply) { s.Type = ForceReplyCopyMessageReplyMarkup s.ForceReply = v } // GetForceReply returns ForceReply and true boolean if CopyMessageReplyMarkup is ForceReply. func (s CopyMessageReplyMarkup) GetForceReply() (v ForceReply, ok bool) { if !s.IsForceReply() { return v, false } return s.ForceReply, true } // NewForceReplyCopyMessageReplyMarkup returns new CopyMessageReplyMarkup from ForceReply. func NewForceReplyCopyMessageReplyMarkup(v ForceReply) CopyMessageReplyMarkup { var s CopyMessageReplyMarkup s.SetForceReply(v) return s } // Input for createChatInviteLink. // Ref: #/components/schemas/createChatInviteLink type CreateChatInviteLink struct { ChatID ID `json:"chat_id"` // Invite link name; 0-32 characters. Name OptString `json:"name"` // Point in time (Unix timestamp) when the link will expire. ExpireDate OptInt `json:"expire_date"` // Maximum number of users that can be members of the chat simultaneously after joining the chat via // this invite link; 1-99999. MemberLimit OptInt `json:"member_limit"` // True, if users joining the chat via the link need to be approved by chat administrators. If True, // member_limit can't be specified. CreatesJoinRequest OptBool `json:"creates_join_request"` } // Input for createNewStickerSet. // Ref: #/components/schemas/createNewStickerSet type CreateNewStickerSet struct { // User identifier of created sticker set owner. UserID int `json:"user_id"` // Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only // english letters, digits and underscores. Must begin with a letter, can't contain consecutive // underscores and must end in “_by_<bot username>”. <bot_username> is case insensitive. 1-64 // characters. Name string `json:"name"` // Sticker set title, 1-64 characters. Title string `json:"title"` // PNG image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, // and either width or height must be exactly 512px. Pass a file_id as a String to send a file that // already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file // from the Internet, or upload a new one using multipart/form-data. More info on Sending Files ». PNGSticker OptString `json:"png_sticker"` // TGS animation with the sticker, uploaded using multipart/form-data. See https://core.telegram. // org/animated_stickers#technical-requirements for technical requirements. TgsSticker OptString `json:"tgs_sticker"` // One or more emoji corresponding to the sticker. Emojis string `json:"emojis"` // Pass True, if a set of mask stickers should be created. ContainsMasks OptBool `json:"contains_masks"` MaskPosition OptMaskPosition `json:"mask_position"` } // Input for declineChatJoinRequest. // Ref: #/components/schemas/declineChatJoinRequest type DeclineChatJoinRequest struct { ChatID ID `json:"chat_id"` // Unique identifier of the target user. UserID int `json:"user_id"` } // Input for deleteChatPhoto. // Ref: #/components/schemas/deleteChatPhoto type DeleteChatPhoto struct { ChatID ID `json:"chat_id"` } // Input for deleteChatStickerSet. // Ref: #/components/schemas/deleteChatStickerSet type DeleteChatStickerSet struct { ChatID ID `json:"chat_id"` } // Input for deleteMessage. // Ref: #/components/schemas/deleteMessage type DeleteMessage struct { ChatID ID `json:"chat_id"` // Identifier of the message to delete. MessageID int `json:"message_id"` } // Input for deleteMyCommands. // Ref: #/components/schemas/deleteMyCommands type DeleteMyCommands struct { Scope OptBotCommandScope `json:"scope"` // A two-letter ISO 639-1 language code. If empty, commands will be applied to all users from the // given scope, for whose language there are no dedicated commands. LanguageCode OptString `json:"language_code"` } // Input for deleteStickerFromSet. // Ref: #/components/schemas/deleteStickerFromSet type DeleteStickerFromSet struct { // File identifier of the sticker. Sticker string `json:"sticker"` } // Input for deleteWebhook. // Ref: #/components/schemas/deleteWebhook type DeleteWebhook struct { // Pass True to drop all pending updates. DropPendingUpdates OptBool `json:"drop_pending_updates"` } // This object represents an animated emoji that displays a random value. // Ref: #/components/schemas/Dice type Dice struct { // Emoji on which the dice throw animation is based. Emoji string `json:"emoji"` // Value of the dice, 1-6 for “”, “” and “” base emoji, 1-5 for “” and “” base // emoji, 1-64 for “” base emoji. Value int `json:"value"` } // This object represents a general file (as opposed to photos, voice messages and audio files). // Ref: #/components/schemas/Document type Document struct { // Identifier for this file, which can be used to download or reuse the file. FileID string `json:"file_id"` // Unique identifier for this file, which is supposed to be the same over time and for different bots. // Can't be used to download or reuse the file. FileUniqueID string `json:"file_unique_id"` Thumb OptPhotoSize `json:"thumb"` // Original filename as defined by sender. FileName OptString `json:"file_name"` // MIME type of the file as defined by sender. MimeType OptString `json:"mime_type"` // File size in bytes. FileSize OptInt `json:"file_size"` } // Input for editChatInviteLink. // Ref: #/components/schemas/editChatInviteLink type EditChatInviteLink struct { ChatID ID `json:"chat_id"` // The invite link to edit. InviteLink string `json:"invite_link"` // Invite link name; 0-32 characters. Name OptString `json:"name"` // Point in time (Unix timestamp) when the link will expire. ExpireDate OptInt `json:"expire_date"` // Maximum number of users that can be members of the chat simultaneously after joining the chat via // this invite link; 1-99999. MemberLimit OptInt `json:"member_limit"` // True, if users joining the chat via the link need to be approved by chat administrators. If True, // member_limit can't be specified. CreatesJoinRequest OptBool `json:"creates_join_request"` } // Input for editMessageCaption. // Ref: #/components/schemas/editMessageCaption type EditMessageCaption struct { ChatID OptID `json:"chat_id"` // Required if inline_message_id is not specified. Identifier of the message to edit. MessageID OptInt `json:"message_id"` // Required if chat_id and message_id are not specified. Identifier of the inline message. InlineMessageID OptString `json:"inline_message_id"` // New caption of the message, 0-1024 characters after entities parsing. Caption OptString `json:"caption"` // Mode for parsing entities in the message caption. See formatting options for more details. ParseMode OptString `json:"parse_mode"` // A JSON-serialized list of special entities that appear in the caption, which can be specified // instead of parse_mode. CaptionEntities []MessageEntity `json:"caption_entities"` ReplyMarkup OptInlineKeyboardMarkup `json:"reply_markup"` } // Input for editMessageLiveLocation. // Ref: #/components/schemas/editMessageLiveLocation type EditMessageLiveLocation struct { ChatID OptID `json:"chat_id"` // Required if inline_message_id is not specified. Identifier of the message to edit. MessageID OptInt `json:"message_id"` // Required if chat_id and message_id are not specified. Identifier of the inline message. InlineMessageID OptString `json:"inline_message_id"` // Latitude of new location. Latitude float64 `json:"latitude"` // Longitude of new location. Longitude float64 `json:"longitude"` // The radius of uncertainty for the location, measured in meters; 0-1500. HorizontalAccuracy OptFloat64 `json:"horizontal_accuracy"` // Direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. Heading OptInt `json:"heading"` // Maximum distance for proximity alerts about approaching another chat member, in meters. Must be // between 1 and 100000 if specified. ProximityAlertRadius OptInt `json:"proximity_alert_radius"` ReplyMarkup OptInlineKeyboardMarkup `json:"reply_markup"` } // Input for editMessageMedia. // Ref: #/components/schemas/editMessageMedia type EditMessageMedia struct { ChatID OptID `json:"chat_id"` // Required if inline_message_id is not specified. Identifier of the message to edit. MessageID OptInt `json:"message_id"` // Required if chat_id and message_id are not specified. Identifier of the inline message. InlineMessageID OptString `json:"inline_message_id"` Media InputMedia `json:"media"` ReplyMarkup OptInlineKeyboardMarkup `json:"reply_markup"` } // Input for editMessageReplyMarkup. // Ref: #/components/schemas/editMessageReplyMarkup type EditMessageReplyMarkup struct { ChatID OptID `json:"chat_id"` // Required if inline_message_id is not specified. Identifier of the message to edit. MessageID OptInt `json:"message_id"` // Required if chat_id and message_id are not specified. Identifier of the inline message. InlineMessageID OptString `json:"inline_message_id"` ReplyMarkup OptInlineKeyboardMarkup `json:"reply_markup"` } // Input for editMessageText. // Ref: #/components/schemas/editMessageText type EditMessageText struct { ChatID OptID `json:"chat_id"` // Required if inline_message_id is not specified. Identifier of the message to edit. MessageID OptInt `json:"message_id"` // Required if chat_id and message_id are not specified. Identifier of the inline message. InlineMessageID OptString `json:"inline_message_id"` // New text of the message, 1-4096 characters after entities parsing. Text string `json:"text"` // Mode for parsing entities in the message text. See formatting options for more details. ParseMode OptString `json:"parse_mode"` // A JSON-serialized list of special entities that appear in message text, which can be specified // instead of parse_mode. Entities []MessageEntity `json:"entities"` // Disables link previews for links in this message. DisableWebPagePreview OptBool `json:"disable_web_page_preview"` ReplyMarkup OptInlineKeyboardMarkup `json:"reply_markup"` } // Contains data required for decrypting and authenticating EncryptedPassportElement. See the // Telegram Passport Documentation for a complete description of the data decryption and // authentication processes. // Ref: #/components/schemas/EncryptedCredentials type EncryptedCredentials struct { // Base64-encoded encrypted JSON-serialized data with unique user's payload, data hashes and secrets // required for EncryptedPassportElement decryption and authentication. Data string `json:"data"` // Base64-encoded data hash for data authentication. Hash string `json:"hash"` // Base64-encoded secret, encrypted with the bot's public RSA key, required for data decryption. Secret string `json:"secret"` } // Contains information about documents or other Telegram Passport elements shared with the bot by // the user. // Ref: #/components/schemas/EncryptedPassportElement type EncryptedPassportElement struct { // Element type. One of “personal_details”, “passport”, “driver_license”, // “identity_card”, “internal_passport”, “address”, “utility_bill”, // “bank_statement”, “rental_agreement”, “passport_registration”, // “temporary_registration”, “phone_number”, “email”. Type string `json:"type"` // Base64-encoded encrypted Telegram Passport element data provided by the user, available for // “personal_details”, “passport”, “driver_license”, “identity_card”, // “internal_passport” and “address” types. Can be decrypted and verified using the // accompanying EncryptedCredentials. Data OptString `json:"data"` // User's verified phone number, available only for “phone_number” type. PhoneNumber OptString `json:"phone_number"` // User's verified email address, available only for “email” type. Email OptString `json:"email"` // Array of encrypted files with documents provided by the user, available for “utility_bill”, // “bank_statement”, “rental_agreement”, “passport_registration” and // “temporary_registration” types. Files can be decrypted and verified using the accompanying // EncryptedCredentials. Files []PassportFile `json:"files"` FrontSide OptPassportFile `json:"front_side"` ReverseSide OptPassportFile `json:"reverse_side"` Selfie OptPassportFile `json:"selfie"` // Array of encrypted files with translated versions of documents provided by the user. Available if // requested for “passport”, “driver_license”, “identity_card”, “internal_passport”, // “utility_bill”, “bank_statement”, “rental_agreement”, “passport_registration” and // “temporary_registration” types. Files can be decrypted and verified using the accompanying // EncryptedCredentials. Translation []PassportFile `json:"translation"` // Base64-encoded element hash for using in PassportElementErrorUnspecified. Hash string `json:"hash"` } // Ref: #/components/schemas/Error type Error struct { Ok bool `json:"ok"` ErrorCode int `json:"error_code"` Description string `json:"description"` Parameters OptResponse `json:"parameters"` } // ErrorStatusCode wraps Error with StatusCode. type ErrorStatusCode struct { StatusCode int Response Error } // Input for exportChatInviteLink. // Ref: #/components/schemas/exportChatInviteLink type ExportChatInviteLink struct { ChatID ID `json:"chat_id"` } // Upon receiving a message with this object, Telegram clients will display a reply interface to the // user (act as if the user has selected the bot's message and tapped 'Reply'). This can be extremely // useful if you want to create user-friendly step-by-step interfaces without having to sacrifice // privacy mode. // Ref: #/components/schemas/ForceReply type ForceReply struct { // Shows reply interface to the user, as if they manually selected the bot's message and tapped // 'Reply'. ForceReply bool `json:"force_reply"` // The placeholder to be shown in the input field when the reply is active; 1-64 characters. InputFieldPlaceholder OptString `json:"input_field_placeholder"` // Use this parameter if you want to force reply from specific users only. Targets: 1) users that are // @mentioned in the text of the Message object; 2) if the bot's message is a reply (has // reply_to_message_id), sender of the original message. Selective OptBool `json:"selective"` } // Input for forwardMessage. // Ref: #/components/schemas/forwardMessage type ForwardMessage struct { ChatID ID `json:"chat_id"` FromChatID ID `json:"from_chat_id"` // Sends the message silently. Users will receive a notification with no sound. DisableNotification OptBool `json:"disable_notification"` // Message identifier in the chat specified in from_chat_id. MessageID int `json:"message_id"` } // This object represents a game. Use BotFather to create and edit games, their short names will act // as unique identifiers. // Ref: #/components/schemas/Game type Game struct { // Title of the game. Title string `json:"title"` // Description of the game. Description string `json:"description"` // Photo that will be displayed in the game message in chats. Photo []PhotoSize `json:"photo"` // Brief description of the game or high scores included in the game message. Can be automatically // edited to include current high scores for the game when the bot calls setGameScore, or manually // edited using editMessageText. 0-4096 characters. Text OptString `json:"text"` // Special entities that appear in text, such as usernames, URLs, bot commands, etc. TextEntities []MessageEntity `json:"text_entities"` Animation OptAnimation `json:"animation"` } // Input for getChat. // Ref: #/components/schemas/getChat type GetChat struct { ChatID ID `json:"chat_id"` } // Input for getChatAdministrators. // Ref: #/components/schemas/getChatAdministrators type GetChatAdministrators struct { ChatID ID `json:"chat_id"` } // Input for getChatMember. // Ref: #/components/schemas/getChatMember type GetChatMember struct { ChatID ID `json:"chat_id"` // Unique identifier of the target user. UserID int `json:"user_id"` } // Input for getChatMemberCount. // Ref: #/components/schemas/getChatMemberCount type GetChatMemberCount struct { ChatID ID `json:"chat_id"` } // Input for getFile. // Ref: #/components/schemas/getFile type GetFile struct { // File identifier to get info about. FileID string `json:"file_id"` } // Input for getGameHighScores. // Ref: #/components/schemas/getGameHighScores type GetGameHighScores struct { // Target user id. UserID int `json:"user_id"` // Required if inline_message_id is not specified. Unique identifier for the target chat. ChatID OptInt `json:"chat_id"` // Required if inline_message_id is not specified. Identifier of the sent message. MessageID OptInt `json:"message_id"` // Required if chat_id and message_id are not specified. Identifier of the inline message. InlineMessageID OptString `json:"inline_message_id"` } // Input for getMyCommands. // Ref: #/components/schemas/getMyCommands type GetMyCommands struct { Scope OptBotCommandScope `json:"scope"` // A two-letter ISO 639-1 language code or an empty string. LanguageCode OptString `json:"language_code"` } // Input for getStickerSet. // Ref: #/components/schemas/getStickerSet type GetStickerSet struct { // Name of the sticker set. Name string `json:"name"` } // Input for getUpdates. // Ref: #/components/schemas/getUpdates type GetUpdates struct { // Identifier of the first update to be returned. Must be greater by one than the highest among the // identifiers of previously received updates. By default, updates starting with the earliest // unconfirmed update are returned. An update is considered confirmed as soon as getUpdates is called // with an offset higher than its update_id. The negative offset can be specified to retrieve updates // starting from -offset update from the end of the updates queue. All previous updates will forgotten. Offset OptInt `json:"offset"` // Limits the number of updates to be retrieved. Values between 1-100 are accepted. Defaults to 100. Limit OptInt `json:"limit"` // Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling. Should be positive, // short polling should be used for testing purposes only. Timeout OptInt `json:"timeout"` // A JSON-serialized list of the update types you want your bot to receive. For example, specify // [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these // types. See Update for a complete list of available update types. Specify an empty list to receive // all update types except chat_member (default). If not specified, the previous setting will be used. // Please note that this parameter doesn't affect updates created before the call to the getUpdates, // so unwanted updates may be received for a short period of time. AllowedUpdates []string `json:"allowed_updates"` } // Input for getUserProfilePhotos. // Ref: #/components/schemas/getUserProfilePhotos type GetUserProfilePhotos struct { // Unique identifier of the target user. UserID int `json:"user_id"` // Sequential number of the first photo to be returned. By default, all photos are returned. Offset OptInt `json:"offset"` // Limits the number of photos to be retrieved. Values between 1-100 are accepted. Defaults to 100. Limit OptInt `json:"limit"` } // Ref: #/components/schemas/ID // ID represents sum type. type ID struct { Type IDType // switch on this field String string Int int } // IDType is oneOf type of ID. type IDType string // Possible values for IDType. const ( StringID IDType = "string" IntID IDType = "int" ) // IsString reports whether ID is string. func (s ID) IsString() bool { return s.Type == StringID } // IsInt reports whether ID is int. func (s ID) IsInt() bool { return s.Type == IntID } // SetString sets ID to string. func (s *ID) SetString(v string) { s.Type = StringID s.String = v } // GetString returns string and true boolean if ID is string. func (s ID) GetString() (v string, ok bool) { if !s.IsString() { return v, false } return s.String, true } // NewStringID returns new ID from string. func NewStringID(v string) ID { var s ID s.SetString(v) return s } // SetInt sets ID to int. func (s *ID) SetInt(v int) { s.Type = IntID s.Int = v } // GetInt returns int and true boolean if ID is int. func (s ID) GetInt() (v int, ok bool) { if !s.IsInt() { return v, false } return s.Int, true } // NewIntID returns new ID from int. func NewIntID(v int) ID { var s ID s.SetInt(v) return s } // This object represents one button of an inline keyboard. You must use exactly one of the optional // fields. // Ref: #/components/schemas/InlineKeyboardButton type InlineKeyboardButton struct { // Label text on the button. Text string `json:"text"` // HTTP or tg:// url to be opened when button is pressed. URL OptURL `json:"url"` LoginURL OptLoginUrl `json:"login_url"` // Data to be sent in a callback query to the bot when button is pressed, 1-64 bytes. CallbackData OptString `json:"callback_data"` // If set, pressing the button will prompt the user to select one of their chats, open that chat and // insert the bot's username and the specified inline query in the input field. Can be empty, in // which case just the bot's username will be inserted.Note: This offers an easy way for users to // start using your bot in inline mode when they are currently in a private chat with it. Especially // useful when combined with switch_pm… actions – in this case the user will be automatically // returned to the chat they switched from, skipping the chat selection screen. SwitchInlineQuery OptString `json:"switch_inline_query"` // If set, pressing the button will insert the bot's username and the specified inline query in the // current chat's input field. Can be empty, in which case only the bot's username will be inserted. // This offers a quick way for the user to open your bot in inline mode in the same chat – good for // selecting something from multiple options. SwitchInlineQueryCurrentChat OptString `json:"switch_inline_query_current_chat"` CallbackGame *CallbackGame `json:"callback_game"` // Specify True, to send a Pay button.NOTE: This type of button must always be the first button in // the first row. Pay OptBool `json:"pay"` } // This object represents an inline keyboard that appears right next to the message it belongs to. // Ref: #/components/schemas/InlineKeyboardMarkup type InlineKeyboardMarkup struct { // Array of button rows, each represented by an Array of InlineKeyboardButton objects. InlineKeyboard [][]InlineKeyboardButton `json:"inline_keyboard"` } type InlineQueryResult string // This object represents the content of a media message to be sent. // Ref: #/components/schemas/InputMedia // InputMedia represents sum type. type InputMedia struct { Type InputMediaType // switch on this field InputMediaAnimation InputMediaAnimation InputMediaDocument InputMediaDocument InputMediaAudio InputMediaAudio InputMediaPhoto InputMediaPhoto InputMediaVideo InputMediaVideo } // InputMediaType is oneOf type of InputMedia. type InputMediaType string // Possible values for InputMediaType. const ( InputMediaAnimationInputMedia InputMediaType = "InputMediaAnimation" InputMediaDocumentInputMedia InputMediaType = "InputMediaDocument" InputMediaAudioInputMedia InputMediaType = "InputMediaAudio" InputMediaPhotoInputMedia InputMediaType = "InputMediaPhoto" InputMediaVideoInputMedia InputMediaType = "InputMediaVideo" ) // IsInputMediaAnimation reports whether InputMedia is InputMediaAnimation. func (s InputMedia) IsInputMediaAnimation() bool { return s.Type == InputMediaAnimationInputMedia } // IsInputMediaDocument reports whether InputMedia is InputMediaDocument. func (s InputMedia) IsInputMediaDocument() bool { return s.Type == InputMediaDocumentInputMedia } // IsInputMediaAudio reports whether InputMedia is InputMediaAudio. func (s InputMedia) IsInputMediaAudio() bool { return s.Type == InputMediaAudioInputMedia } // IsInputMediaPhoto reports whether InputMedia is InputMediaPhoto. func (s InputMedia) IsInputMediaPhoto() bool { return s.Type == InputMediaPhotoInputMedia } // IsInputMediaVideo reports whether InputMedia is InputMediaVideo. func (s InputMedia) IsInputMediaVideo() bool { return s.Type == InputMediaVideoInputMedia } // SetInputMediaAnimation sets InputMedia to InputMediaAnimation. func (s *InputMedia) SetInputMediaAnimation(v InputMediaAnimation) { s.Type = InputMediaAnimationInputMedia s.InputMediaAnimation = v } // GetInputMediaAnimation returns InputMediaAnimation and true boolean if InputMedia is InputMediaAnimation. func (s InputMedia) GetInputMediaAnimation() (v InputMediaAnimation, ok bool) { if !s.IsInputMediaAnimation() { return v, false } return s.InputMediaAnimation, true } // NewInputMediaAnimationInputMedia returns new InputMedia from InputMediaAnimation. func NewInputMediaAnimationInputMedia(v InputMediaAnimation) InputMedia { var s InputMedia s.SetInputMediaAnimation(v) return s } // SetInputMediaDocument sets InputMedia to InputMediaDocument. func (s *InputMedia) SetInputMediaDocument(v InputMediaDocument) { s.Type = InputMediaDocumentInputMedia s.InputMediaDocument = v } // GetInputMediaDocument returns InputMediaDocument and true boolean if InputMedia is InputMediaDocument. func (s InputMedia) GetInputMediaDocument() (v InputMediaDocument, ok bool) { if !s.IsInputMediaDocument() { return v, false } return s.InputMediaDocument, true } // NewInputMediaDocumentInputMedia returns new InputMedia from InputMediaDocument. func NewInputMediaDocumentInputMedia(v InputMediaDocument) InputMedia { var s InputMedia s.SetInputMediaDocument(v) return s } // SetInputMediaAudio sets InputMedia to InputMediaAudio. func (s *InputMedia) SetInputMediaAudio(v InputMediaAudio) { s.Type = InputMediaAudioInputMedia s.InputMediaAudio = v } // GetInputMediaAudio returns InputMediaAudio and true boolean if InputMedia is InputMediaAudio. func (s InputMedia) GetInputMediaAudio() (v InputMediaAudio, ok bool) { if !s.IsInputMediaAudio() { return v, false } return s.InputMediaAudio, true } // NewInputMediaAudioInputMedia returns new InputMedia from InputMediaAudio. func NewInputMediaAudioInputMedia(v InputMediaAudio) InputMedia { var s InputMedia s.SetInputMediaAudio(v) return s } // SetInputMediaPhoto sets InputMedia to InputMediaPhoto. func (s *InputMedia) SetInputMediaPhoto(v InputMediaPhoto) { s.Type = InputMediaPhotoInputMedia s.InputMediaPhoto = v } // GetInputMediaPhoto returns InputMediaPhoto and true boolean if InputMedia is InputMediaPhoto. func (s InputMedia) GetInputMediaPhoto() (v InputMediaPhoto, ok bool) { if !s.IsInputMediaPhoto() { return v, false } return s.InputMediaPhoto, true } // NewInputMediaPhotoInputMedia returns new InputMedia from InputMediaPhoto. func NewInputMediaPhotoInputMedia(v InputMediaPhoto) InputMedia { var s InputMedia s.SetInputMediaPhoto(v) return s } // SetInputMediaVideo sets InputMedia to InputMediaVideo. func (s *InputMedia) SetInputMediaVideo(v InputMediaVideo) { s.Type = InputMediaVideoInputMedia s.InputMediaVideo = v } // GetInputMediaVideo returns InputMediaVideo and true boolean if InputMedia is InputMediaVideo. func (s InputMedia) GetInputMediaVideo() (v InputMediaVideo, ok bool) { if !s.IsInputMediaVideo() { return v, false } return s.InputMediaVideo, true } // NewInputMediaVideoInputMedia returns new InputMedia from InputMediaVideo. func NewInputMediaVideoInputMedia(v InputMediaVideo) InputMedia { var s InputMedia s.SetInputMediaVideo(v) return s } // Represents an animation file (GIF or H.264/MPEG-4 AVC video without sound) to be sent. // Ref: #/components/schemas/InputMediaAnimation type InputMediaAnimation struct { // Type of the result, must be animation. Type string `json:"type"` // File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), // pass an HTTP URL for Telegram to get a file from the Internet, or pass // “attach://<file_attach_name>” to upload a new one using multipart/form-data under // <file_attach_name> name. More info on Sending Files ». Media string `json:"media"` // Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported // server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's // width and height should not exceed 320. Ignored if the file is not uploaded using // multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can // pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data // under <file_attach_name>. More info on Sending Files ». Thumb OptString `json:"thumb"` // Caption of the animation to be sent, 0-1024 characters after entities parsing. Caption OptString `json:"caption"` // Mode for parsing entities in the animation caption. See formatting options for more details. ParseMode OptString `json:"parse_mode"` // List of special entities that appear in the caption, which can be specified instead of parse_mode. CaptionEntities []MessageEntity `json:"caption_entities"` // Animation width. Width OptInt `json:"width"` // Animation height. Height OptInt `json:"height"` // Animation duration in seconds. Duration OptInt `json:"duration"` } // Represents an audio file to be treated as music to be sent. // Ref: #/components/schemas/InputMediaAudio type InputMediaAudio struct { // Type of the result, must be audio. Type string `json:"type"` // File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), // pass an HTTP URL for Telegram to get a file from the Internet, or pass // “attach://<file_attach_name>” to upload a new one using multipart/form-data under // <file_attach_name> name. More info on Sending Files ». Media string `json:"media"` // Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported // server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's // width and height should not exceed 320. Ignored if the file is not uploaded using // multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can // pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data // under <file_attach_name>. More info on Sending Files ». Thumb OptString `json:"thumb"` // Caption of the audio to be sent, 0-1024 characters after entities parsing. Caption OptString `json:"caption"` // Mode for parsing entities in the audio caption. See formatting options for more details. ParseMode OptString `json:"parse_mode"` // List of special entities that appear in the caption, which can be specified instead of parse_mode. CaptionEntities []MessageEntity `json:"caption_entities"` // Duration of the audio in seconds. Duration OptInt `json:"duration"` // Performer of the audio. Performer OptString `json:"performer"` // Title of the audio. Title OptString `json:"title"` } // Represents a general file to be sent. // Ref: #/components/schemas/InputMediaDocument type InputMediaDocument struct { // Type of the result, must be document. Type string `json:"type"` // File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), // pass an HTTP URL for Telegram to get a file from the Internet, or pass // “attach://<file_attach_name>” to upload a new one using multipart/form-data under // <file_attach_name> name. More info on Sending Files ». Media string `json:"media"` // Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported // server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's // width and height should not exceed 320. Ignored if the file is not uploaded using // multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can // pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data // under <file_attach_name>. More info on Sending Files ». Thumb OptString `json:"thumb"` // Caption of the document to be sent, 0-1024 characters after entities parsing. Caption OptString `json:"caption"` // Mode for parsing entities in the document caption. See formatting options for more details. ParseMode OptString `json:"parse_mode"` // List of special entities that appear in the caption, which can be specified instead of parse_mode. CaptionEntities []MessageEntity `json:"caption_entities"` // Disables automatic server-side content type detection for files uploaded using multipart/form-data. // Always True, if the document is sent as part of an album. DisableContentTypeDetection OptBool `json:"disable_content_type_detection"` } // Represents a photo to be sent. // Ref: #/components/schemas/InputMediaPhoto type InputMediaPhoto struct { // Type of the result, must be photo. Type string `json:"type"` // File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), // pass an HTTP URL for Telegram to get a file from the Internet, or pass // “attach://<file_attach_name>” to upload a new one using multipart/form-data under // <file_attach_name> name. More info on Sending Files ». Media string `json:"media"` // Caption of the photo to be sent, 0-1024 characters after entities parsing. Caption OptString `json:"caption"` // Mode for parsing entities in the photo caption. See formatting options for more details. ParseMode OptString `json:"parse_mode"` // List of special entities that appear in the caption, which can be specified instead of parse_mode. CaptionEntities []MessageEntity `json:"caption_entities"` } // Represents a video to be sent. // Ref: #/components/schemas/InputMediaVideo type InputMediaVideo struct { // Type of the result, must be video. Type string `json:"type"` // File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), // pass an HTTP URL for Telegram to get a file from the Internet, or pass // “attach://<file_attach_name>” to upload a new one using multipart/form-data under // <file_attach_name> name. More info on Sending Files ». Media string `json:"media"` // Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported // server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's // width and height should not exceed 320. Ignored if the file is not uploaded using // multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can // pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data // under <file_attach_name>. More info on Sending Files ». Thumb OptString `json:"thumb"` // Caption of the video to be sent, 0-1024 characters after entities parsing. Caption OptString `json:"caption"` // Mode for parsing entities in the video caption. See formatting options for more details. ParseMode OptString `json:"parse_mode"` // List of special entities that appear in the caption, which can be specified instead of parse_mode. CaptionEntities []MessageEntity `json:"caption_entities"` // Video width. Width OptInt `json:"width"` // Video height. Height OptInt `json:"height"` // Video duration in seconds. Duration OptInt `json:"duration"` // Pass True, if the uploaded video is suitable for streaming. SupportsStreaming OptBool `json:"supports_streaming"` } // This object contains basic information about an invoice. // Ref: #/components/schemas/Invoice type Invoice struct { // Product name. Title string `json:"title"` // Product description. Description string `json:"description"` // Unique bot deep-linking parameter that can be used to generate this invoice. StartParameter string `json:"start_parameter"` // Three-letter ISO 4217 currency code. Currency string `json:"currency"` // Total price in the smallest units of the currency (integer, not float/double). For example, for a // price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number // of digits past the decimal point for each currency (2 for the majority of currencies). TotalAmount int `json:"total_amount"` } // This object represents one button of the reply keyboard. For simple text buttons String can be // used instead of this object to specify text of the button. Optional fields request_contact, // request_location, and request_poll are mutually exclusive. // Ref: #/components/schemas/KeyboardButton type KeyboardButton struct { // Text of the button. If none of the optional fields are used, it will be sent as a message when the // button is pressed. Text string `json:"text"` // If True, the user's phone number will be sent as a contact when the button is pressed. Available // in private chats only. RequestContact OptBool `json:"request_contact"` // If True, the user's current location will be sent when the button is pressed. Available in private // chats only. RequestLocation OptBool `json:"request_location"` RequestPoll OptKeyboardButtonPollType `json:"request_poll"` } // This object represents type of a poll, which is allowed to be created and sent when the // corresponding button is pressed. // Ref: #/components/schemas/KeyboardButtonPollType type KeyboardButtonPollType struct { // If quiz is passed, the user will be allowed to create only polls in the quiz mode. If regular is // passed, only regular polls will be allowed. Otherwise, the user will be allowed to create a poll // of any type. Type OptString `json:"type"` } // This object represents a portion of the price for goods or services. // Ref: #/components/schemas/LabeledPrice type LabeledPrice struct { // Portion label. Label string `json:"label"` // Price of the product in the smallest units of the currency (integer, not float/double). For // example, for a price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it // shows the number of digits past the decimal point for each currency (2 for the majority of // currencies). Amount int `json:"amount"` } // Input for leaveChat. // Ref: #/components/schemas/leaveChat type LeaveChat struct { ChatID ID `json:"chat_id"` } // This object represents a point on the map. // Ref: #/components/schemas/Location type Location struct { // Longitude as defined by sender. Longitude float64 `json:"longitude"` // Latitude as defined by sender. Latitude float64 `json:"latitude"` // The radius of uncertainty for the location, measured in meters; 0-1500. HorizontalAccuracy OptFloat64 `json:"horizontal_accuracy"` // Time relative to the message sending date, during which the location can be updated; in seconds. // For active live locations only. LivePeriod OptInt `json:"live_period"` // The direction in which user is moving, in degrees; 1-360. For active live locations only. Heading OptInt `json:"heading"` // Maximum distance for proximity alerts about approaching another chat member, in meters. For sent // live locations only. ProximityAlertRadius OptInt `json:"proximity_alert_radius"` } // Telegram apps support these buttons as of version 5.7. // Ref: #/components/schemas/LoginUrl type LoginUrl struct { // An HTTP URL to be opened with user authorization data added to the query string when the button is // pressed. If the user refuses to provide authorization data, the original URL without information // about the user will be opened. The data added is the same as described in Receiving authorization // data.NOTE: You must always check the hash of the received data to verify the authentication and // the integrity of the data as described in Checking authorization. URL url.URL `json:"url"` // New text of the button in forwarded messages. ForwardText OptString `json:"forward_text"` // Username of a bot, which will be used for user authorization. See Setting up a bot for more // details. If not specified, the current bot's username will be assumed. The url's domain must be // the same as the domain linked with the bot. See Linking your domain to the bot for more details. BotUsername OptString `json:"bot_username"` // Pass True to request the permission for your bot to send messages to the user. RequestWriteAccess OptBool `json:"request_write_access"` } // This object describes the position on faces where a mask should be placed by default. // Ref: #/components/schemas/MaskPosition type MaskPosition struct { // The part of the face relative to which the mask should be placed. One of “forehead”, // “eyes”, “mouth”, or “chin”. Point string `json:"point"` // Shift by X-axis measured in widths of the mask scaled to the face size, from left to right. For // example, choosing -1.0 will place mask just to the left of the default mask position. XShift float64 `json:"x_shift"` // Shift by Y-axis measured in heights of the mask scaled to the face size, from top to bottom. For // example, 1.0 will place the mask just below the default mask position. YShift float64 `json:"y_shift"` // Mask scaling coefficient. For example, 2.0 means double size. Scale float64 `json:"scale"` } // This object represents a message. // Ref: #/components/schemas/Message type Message struct { // Unique message identifier inside this chat. MessageID int `json:"message_id"` From OptUser `json:"from"` SenderChat OptChat `json:"sender_chat"` // Date the message was sent in Unix time. Date int `json:"date"` Chat Chat `json:"chat"` ForwardFrom OptUser `json:"forward_from"` ForwardFromChat OptChat `json:"forward_from_chat"` // For messages forwarded from channels, identifier of the original message in the channel. ForwardFromMessageID OptInt `json:"forward_from_message_id"` // For messages forwarded from channels, signature of the post author if present. ForwardSignature OptString `json:"forward_signature"` // Sender's name for messages forwarded from users who disallow adding a link to their account in // forwarded messages. ForwardSenderName OptString `json:"forward_sender_name"` // For forwarded messages, date the original message was sent in Unix time. ForwardDate OptInt `json:"forward_date"` ReplyToMessage *Message `json:"reply_to_message"` ViaBot OptUser `json:"via_bot"` // Date the message was last edited in Unix time. EditDate OptInt `json:"edit_date"` // The unique identifier of a media message group this message belongs to. MediaGroupID OptString `json:"media_group_id"` // Signature of the post author for messages in channels, or the custom title of an anonymous group // administrator. AuthorSignature OptString `json:"author_signature"` // For text messages, the actual UTF-8 text of the message, 0-4096 characters. Text OptString `json:"text"` // For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the // text. Entities []MessageEntity `json:"entities"` Animation OptAnimation `json:"animation"` Audio OptAudio `json:"audio"` Document OptDocument `json:"document"` // Message is a photo, available sizes of the photo. Photo []PhotoSize `json:"photo"` Sticker OptSticker `json:"sticker"` Video OptVideo `json:"video"` VideoNote OptVideoNote `json:"video_note"` Voice OptVoice `json:"voice"` // Caption for the animation, audio, document, photo, video or voice, 0-1024 characters. Caption OptString `json:"caption"` // For messages with a caption, special entities like usernames, URLs, bot commands, etc. that appear // in the caption. CaptionEntities []MessageEntity `json:"caption_entities"` Contact OptContact `json:"contact"` Dice OptDice `json:"dice"` Game OptGame `json:"game"` Poll OptPoll `json:"poll"` Venue OptVenue `json:"venue"` Location OptLocation `json:"location"` // New members that were added to the group or supergroup and information about them (the bot itself // may be one of these members). NewChatMembers []User `json:"new_chat_members"` LeftChatMember OptUser `json:"left_chat_member"` // A chat title was changed to this value. NewChatTitle OptString `json:"new_chat_title"` // A chat photo was change to this value. NewChatPhoto []PhotoSize `json:"new_chat_photo"` // Service message: the chat photo was deleted. DeleteChatPhoto OptBool `json:"delete_chat_photo"` // Service message: the group has been created. GroupChatCreated OptBool `json:"group_chat_created"` // Service message: the supergroup has been created. This field can't be received in a message coming // through updates, because bot can't be a member of a supergroup when it is created. It can only be // found in reply_to_message if someone replies to a very first message in a directly created // supergroup. SupergroupChatCreated OptBool `json:"supergroup_chat_created"` // Service message: the channel has been created. This field can't be received in a message coming // through updates, because bot can't be a member of a channel when it is created. It can only be // found in reply_to_message if someone replies to a very first message in a channel. ChannelChatCreated OptBool `json:"channel_chat_created"` MessageAutoDeleteTimerChanged OptMessageAutoDeleteTimerChanged `json:"message_auto_delete_timer_changed"` // The group has been migrated to a supergroup with the specified identifier. This number may have // more than 32 significant bits and some programming languages may have difficulty/silent defects in // interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or // double-precision float type are safe for storing this identifier. MigrateToChatID OptInt `json:"migrate_to_chat_id"` // The supergroup has been migrated from a group with the specified identifier. This number may have // more than 32 significant bits and some programming languages may have difficulty/silent defects in // interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or // double-precision float type are safe for storing this identifier. MigrateFromChatID OptInt `json:"migrate_from_chat_id"` PinnedMessage *Message `json:"pinned_message"` Invoice OptInvoice `json:"invoice"` SuccessfulPayment OptSuccessfulPayment `json:"successful_payment"` // The domain name of the website on which the user has logged in. More about Telegram Login ». ConnectedWebsite OptString `json:"connected_website"` PassportData OptPassportData `json:"passport_data"` ProximityAlertTriggered OptProximityAlertTriggered `json:"proximity_alert_triggered"` VoiceChatScheduled OptVoiceChatScheduled `json:"voice_chat_scheduled"` VoiceChatStarted *VoiceChatStarted `json:"voice_chat_started"` VoiceChatEnded OptVoiceChatEnded `json:"voice_chat_ended"` VoiceChatParticipantsInvited OptVoiceChatParticipantsInvited `json:"voice_chat_participants_invited"` ReplyMarkup OptInlineKeyboardMarkup `json:"reply_markup"` } // This object represents a service message about a change in auto-delete timer settings. // Ref: #/components/schemas/MessageAutoDeleteTimerChanged type MessageAutoDeleteTimerChanged struct { // New auto-delete time for messages in the chat; in seconds. MessageAutoDeleteTime int `json:"message_auto_delete_time"` } // This object represents one special entity in a text message. For example, hashtags, usernames, // URLs, etc. // Ref: #/components/schemas/MessageEntity type MessageEntity struct { // Type of the entity. Can be “mention” (@username), “hashtag” (#hashtag), “cashtag” // ($USD), “bot_command” (/start@jobs_bot), “url” (https://telegram.org), “email” // (<EMAIL>), “phone_number” (+1-212-555-0123), “bold” (bold text), // “italic” (italic text), “underline” (underlined text), “strikethrough” (strikethrough // text), “code” (monowidth string), “pre” (monowidth block), “text_link” (for clickable // text URLs), “text_mention” (for users without usernames). Type string `json:"type"` // Offset in UTF-16 code units to the start of the entity. Offset int `json:"offset"` // Length of the entity in UTF-16 code units. Length int `json:"length"` // For “text_link” only, url that will be opened after user taps on the text. URL OptURL `json:"url"` User OptUser `json:"user"` // For “pre” only, the programming language of the entity text. Language OptString `json:"language"` } // NewOptAnimation returns new OptAnimation with value set to v. func NewOptAnimation(v Animation) OptAnimation { return OptAnimation{ Value: v, Set: true, } } // OptAnimation is optional Animation. type OptAnimation struct { Value Animation Set bool } // IsSet returns true if OptAnimation was set. func (o OptAnimation) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptAnimation) Reset() { var v Animation o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptAnimation) SetTo(v Animation) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptAnimation) Get() (v Animation, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptAnimation) Or(d Animation) Animation { if v, ok := o.Get(); ok { return v } return d } // NewOptAudio returns new OptAudio with value set to v. func NewOptAudio(v Audio) OptAudio { return OptAudio{ Value: v, Set: true, } } // OptAudio is optional Audio. type OptAudio struct { Value Audio Set bool } // IsSet returns true if OptAudio was set. func (o OptAudio) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptAudio) Reset() { var v Audio o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptAudio) SetTo(v Audio) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptAudio) Get() (v Audio, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptAudio) Or(d Audio) Audio { if v, ok := o.Get(); ok { return v } return d } // NewOptBool returns new OptBool with value set to v. func NewOptBool(v bool) OptBool { return OptBool{ Value: v, Set: true, } } // OptBool is optional bool. type OptBool struct { Value bool Set bool } // IsSet returns true if OptBool was set. func (o OptBool) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptBool) Reset() { var v bool o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptBool) SetTo(v bool) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptBool) Get() (v bool, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptBool) Or(d bool) bool { if v, ok := o.Get(); ok { return v } return d } // NewOptBotCommandScope returns new OptBotCommandScope with value set to v. func NewOptBotCommandScope(v BotCommandScope) OptBotCommandScope { return OptBotCommandScope{ Value: v, Set: true, } } // OptBotCommandScope is optional BotCommandScope. type OptBotCommandScope struct { Value BotCommandScope Set bool } // IsSet returns true if OptBotCommandScope was set. func (o OptBotCommandScope) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptBotCommandScope) Reset() { var v BotCommandScope o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptBotCommandScope) SetTo(v BotCommandScope) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptBotCommandScope) Get() (v BotCommandScope, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptBotCommandScope) Or(d BotCommandScope) BotCommandScope { if v, ok := o.Get(); ok { return v } return d } // NewOptChat returns new OptChat with value set to v. func NewOptChat(v Chat) OptChat { return OptChat{ Value: v, Set: true, } } // OptChat is optional Chat. type OptChat struct { Value Chat Set bool } // IsSet returns true if OptChat was set. func (o OptChat) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptChat) Reset() { var v Chat o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptChat) SetTo(v Chat) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptChat) Get() (v Chat, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptChat) Or(d Chat) Chat { if v, ok := o.Get(); ok { return v } return d } // NewOptChatLocation returns new OptChatLocation with value set to v. func NewOptChatLocation(v ChatLocation) OptChatLocation { return OptChatLocation{ Value: v, Set: true, } } // OptChatLocation is optional ChatLocation. type OptChatLocation struct { Value ChatLocation Set bool } // IsSet returns true if OptChatLocation was set. func (o OptChatLocation) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptChatLocation) Reset() { var v ChatLocation o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptChatLocation) SetTo(v ChatLocation) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptChatLocation) Get() (v ChatLocation, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptChatLocation) Or(d ChatLocation) ChatLocation { if v, ok := o.Get(); ok { return v } return d } // NewOptChatPermissions returns new OptChatPermissions with value set to v. func NewOptChatPermissions(v ChatPermissions) OptChatPermissions { return OptChatPermissions{ Value: v, Set: true, } } // OptChatPermissions is optional ChatPermissions. type OptChatPermissions struct { Value ChatPermissions Set bool } // IsSet returns true if OptChatPermissions was set. func (o OptChatPermissions) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptChatPermissions) Reset() { var v ChatPermissions o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptChatPermissions) SetTo(v ChatPermissions) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptChatPermissions) Get() (v ChatPermissions, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptChatPermissions) Or(d ChatPermissions) ChatPermissions { if v, ok := o.Get(); ok { return v } return d } // NewOptChatPhoto returns new OptChatPhoto with value set to v. func NewOptChatPhoto(v ChatPhoto) OptChatPhoto { return OptChatPhoto{ Value: v, Set: true, } } // OptChatPhoto is optional ChatPhoto. type OptChatPhoto struct { Value ChatPhoto Set bool } // IsSet returns true if OptChatPhoto was set. func (o OptChatPhoto) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptChatPhoto) Reset() { var v ChatPhoto o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptChatPhoto) SetTo(v ChatPhoto) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptChatPhoto) Get() (v ChatPhoto, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptChatPhoto) Or(d ChatPhoto) ChatPhoto { if v, ok := o.Get(); ok { return v } return d } // NewOptContact returns new OptContact with value set to v. func NewOptContact(v Contact) OptContact { return OptContact{ Value: v, Set: true, } } // OptContact is optional Contact. type OptContact struct { Value Contact Set bool } // IsSet returns true if OptContact was set. func (o OptContact) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptContact) Reset() { var v Contact o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptContact) SetTo(v Contact) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptContact) Get() (v Contact, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptContact) Or(d Contact) Contact { if v, ok := o.Get(); ok { return v } return d } // NewOptCopyMessageReplyMarkup returns new OptCopyMessageReplyMarkup with value set to v. func NewOptCopyMessageReplyMarkup(v CopyMessageReplyMarkup) OptCopyMessageReplyMarkup { return OptCopyMessageReplyMarkup{ Value: v, Set: true, } } // OptCopyMessageReplyMarkup is optional CopyMessageReplyMarkup. type OptCopyMessageReplyMarkup struct { Value CopyMessageReplyMarkup Set bool } // IsSet returns true if OptCopyMessageReplyMarkup was set. func (o OptCopyMessageReplyMarkup) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptCopyMessageReplyMarkup) Reset() { var v CopyMessageReplyMarkup o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptCopyMessageReplyMarkup) SetTo(v CopyMessageReplyMarkup) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptCopyMessageReplyMarkup) Get() (v CopyMessageReplyMarkup, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptCopyMessageReplyMarkup) Or(d CopyMessageReplyMarkup) CopyMessageReplyMarkup { if v, ok := o.Get(); ok { return v } return d } // NewOptDice returns new OptDice with value set to v. func NewOptDice(v Dice) OptDice { return OptDice{ Value: v, Set: true, } } // OptDice is optional Dice. type OptDice struct { Value Dice Set bool } // IsSet returns true if OptDice was set. func (o OptDice) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptDice) Reset() { var v Dice o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptDice) SetTo(v Dice) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptDice) Get() (v Dice, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptDice) Or(d Dice) Dice { if v, ok := o.Get(); ok { return v } return d } // NewOptDocument returns new OptDocument with value set to v. func NewOptDocument(v Document) OptDocument { return OptDocument{ Value: v, Set: true, } } // OptDocument is optional Document. type OptDocument struct { Value Document Set bool } // IsSet returns true if OptDocument was set. func (o OptDocument) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptDocument) Reset() { var v Document o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptDocument) SetTo(v Document) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptDocument) Get() (v Document, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptDocument) Or(d Document) Document { if v, ok := o.Get(); ok { return v } return d } // NewOptFloat64 returns new OptFloat64 with value set to v. func NewOptFloat64(v float64) OptFloat64 { return OptFloat64{ Value: v, Set: true, } } // OptFloat64 is optional float64. type OptFloat64 struct { Value float64 Set bool } // IsSet returns true if OptFloat64 was set. func (o OptFloat64) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptFloat64) Reset() { var v float64 o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptFloat64) SetTo(v float64) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptFloat64) Get() (v float64, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptFloat64) Or(d float64) float64 { if v, ok := o.Get(); ok { return v } return d } // NewOptGame returns new OptGame with value set to v. func NewOptGame(v Game) OptGame { return OptGame{ Value: v, Set: true, } } // OptGame is optional Game. type OptGame struct { Value Game Set bool } // IsSet returns true if OptGame was set. func (o OptGame) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptGame) Reset() { var v Game o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptGame) SetTo(v Game) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptGame) Get() (v Game, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptGame) Or(d Game) Game { if v, ok := o.Get(); ok { return v } return d } // NewOptID returns new OptID with value set to v. func NewOptID(v ID) OptID { return OptID{ Value: v, Set: true, } } // OptID is optional ID. type OptID struct { Value ID Set bool } // IsSet returns true if OptID was set. func (o OptID) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptID) Reset() { var v ID o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptID) SetTo(v ID) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptID) Get() (v ID, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptID) Or(d ID) ID { if v, ok := o.Get(); ok { return v } return d } // NewOptInlineKeyboardMarkup returns new OptInlineKeyboardMarkup with value set to v. func NewOptInlineKeyboardMarkup(v InlineKeyboardMarkup) OptInlineKeyboardMarkup { return OptInlineKeyboardMarkup{ Value: v, Set: true, } } // OptInlineKeyboardMarkup is optional InlineKeyboardMarkup. type OptInlineKeyboardMarkup struct { Value InlineKeyboardMarkup Set bool } // IsSet returns true if OptInlineKeyboardMarkup was set. func (o OptInlineKeyboardMarkup) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptInlineKeyboardMarkup) Reset() { var v InlineKeyboardMarkup o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptInlineKeyboardMarkup) SetTo(v InlineKeyboardMarkup) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptInlineKeyboardMarkup) Get() (v InlineKeyboardMarkup, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptInlineKeyboardMarkup) Or(d InlineKeyboardMarkup) InlineKeyboardMarkup { if v, ok := o.Get(); ok { return v } return d } // NewOptInt returns new OptInt with value set to v. func NewOptInt(v int) OptInt { return OptInt{ Value: v, Set: true, } } // OptInt is optional int. type OptInt struct { Value int Set bool } // IsSet returns true if OptInt was set. func (o OptInt) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptInt) Reset() { var v int o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptInt) SetTo(v int) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptInt) Get() (v int, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptInt) Or(d int) int { if v, ok := o.Get(); ok { return v } return d } // NewOptInt64 returns new OptInt64 with value set to v. func NewOptInt64(v int64) OptInt64 { return OptInt64{ Value: v, Set: true, } } // OptInt64 is optional int64. type OptInt64 struct { Value int64 Set bool } // IsSet returns true if OptInt64 was set. func (o OptInt64) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptInt64) Reset() { var v int64 o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptInt64) SetTo(v int64) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptInt64) Get() (v int64, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptInt64) Or(d int64) int64 { if v, ok := o.Get(); ok { return v } return d } // NewOptInvoice returns new OptInvoice with value set to v. func NewOptInvoice(v Invoice) OptInvoice { return OptInvoice{ Value: v, Set: true, } } // OptInvoice is optional Invoice. type OptInvoice struct { Value Invoice Set bool } // IsSet returns true if OptInvoice was set. func (o OptInvoice) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptInvoice) Reset() { var v Invoice o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptInvoice) SetTo(v Invoice) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptInvoice) Get() (v Invoice, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptInvoice) Or(d Invoice) Invoice { if v, ok := o.Get(); ok { return v } return d } // NewOptKeyboardButtonPollType returns new OptKeyboardButtonPollType with value set to v. func NewOptKeyboardButtonPollType(v KeyboardButtonPollType) OptKeyboardButtonPollType { return OptKeyboardButtonPollType{ Value: v, Set: true, } } // OptKeyboardButtonPollType is optional KeyboardButtonPollType. type OptKeyboardButtonPollType struct { Value KeyboardButtonPollType Set bool } // IsSet returns true if OptKeyboardButtonPollType was set. func (o OptKeyboardButtonPollType) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptKeyboardButtonPollType) Reset() { var v KeyboardButtonPollType o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptKeyboardButtonPollType) SetTo(v KeyboardButtonPollType) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptKeyboardButtonPollType) Get() (v KeyboardButtonPollType, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptKeyboardButtonPollType) Or(d KeyboardButtonPollType) KeyboardButtonPollType { if v, ok := o.Get(); ok { return v } return d } // NewOptLocation returns new OptLocation with value set to v. func NewOptLocation(v Location) OptLocation { return OptLocation{ Value: v, Set: true, } } // OptLocation is optional Location. type OptLocation struct { Value Location Set bool } // IsSet returns true if OptLocation was set. func (o OptLocation) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptLocation) Reset() { var v Location o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptLocation) SetTo(v Location) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptLocation) Get() (v Location, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptLocation) Or(d Location) Location { if v, ok := o.Get(); ok { return v } return d } // NewOptLoginUrl returns new OptLoginUrl with value set to v. func NewOptLoginUrl(v LoginUrl) OptLoginUrl { return OptLoginUrl{ Value: v, Set: true, } } // OptLoginUrl is optional LoginUrl. type OptLoginUrl struct { Value LoginUrl Set bool } // IsSet returns true if OptLoginUrl was set. func (o OptLoginUrl) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptLoginUrl) Reset() { var v LoginUrl o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptLoginUrl) SetTo(v LoginUrl) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptLoginUrl) Get() (v LoginUrl, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptLoginUrl) Or(d LoginUrl) LoginUrl { if v, ok := o.Get(); ok { return v } return d } // NewOptMaskPosition returns new OptMaskPosition with value set to v. func NewOptMaskPosition(v MaskPosition) OptMaskPosition { return OptMaskPosition{ Value: v, Set: true, } } // OptMaskPosition is optional MaskPosition. type OptMaskPosition struct { Value MaskPosition Set bool } // IsSet returns true if OptMaskPosition was set. func (o OptMaskPosition) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptMaskPosition) Reset() { var v MaskPosition o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptMaskPosition) SetTo(v MaskPosition) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptMaskPosition) Get() (v MaskPosition, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptMaskPosition) Or(d MaskPosition) MaskPosition { if v, ok := o.Get(); ok { return v } return d } // NewOptMessage returns new OptMessage with value set to v. func NewOptMessage(v Message) OptMessage { return OptMessage{ Value: v, Set: true, } } // OptMessage is optional Message. type OptMessage struct { Value Message Set bool } // IsSet returns true if OptMessage was set. func (o OptMessage) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptMessage) Reset() { var v Message o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptMessage) SetTo(v Message) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptMessage) Get() (v Message, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptMessage) Or(d Message) Message { if v, ok := o.Get(); ok { return v } return d } // NewOptMessageAutoDeleteTimerChanged returns new OptMessageAutoDeleteTimerChanged with value set to v. func NewOptMessageAutoDeleteTimerChanged(v MessageAutoDeleteTimerChanged) OptMessageAutoDeleteTimerChanged { return OptMessageAutoDeleteTimerChanged{ Value: v, Set: true, } } // OptMessageAutoDeleteTimerChanged is optional MessageAutoDeleteTimerChanged. type OptMessageAutoDeleteTimerChanged struct { Value MessageAutoDeleteTimerChanged Set bool } // IsSet returns true if OptMessageAutoDeleteTimerChanged was set. func (o OptMessageAutoDeleteTimerChanged) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptMessageAutoDeleteTimerChanged) Reset() { var v MessageAutoDeleteTimerChanged o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptMessageAutoDeleteTimerChanged) SetTo(v MessageAutoDeleteTimerChanged) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptMessageAutoDeleteTimerChanged) Get() (v MessageAutoDeleteTimerChanged, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptMessageAutoDeleteTimerChanged) Or(d MessageAutoDeleteTimerChanged) MessageAutoDeleteTimerChanged { if v, ok := o.Get(); ok { return v } return d } // NewOptOrderInfo returns new OptOrderInfo with value set to v. func NewOptOrderInfo(v OrderInfo) OptOrderInfo { return OptOrderInfo{ Value: v, Set: true, } } // OptOrderInfo is optional OrderInfo. type OptOrderInfo struct { Value OrderInfo Set bool } // IsSet returns true if OptOrderInfo was set. func (o OptOrderInfo) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptOrderInfo) Reset() { var v OrderInfo o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptOrderInfo) SetTo(v OrderInfo) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptOrderInfo) Get() (v OrderInfo, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptOrderInfo) Or(d OrderInfo) OrderInfo { if v, ok := o.Get(); ok { return v } return d } // NewOptPassportData returns new OptPassportData with value set to v. func NewOptPassportData(v PassportData) OptPassportData { return OptPassportData{ Value: v, Set: true, } } // OptPassportData is optional PassportData. type OptPassportData struct { Value PassportData Set bool } // IsSet returns true if OptPassportData was set. func (o OptPassportData) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptPassportData) Reset() { var v PassportData o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptPassportData) SetTo(v PassportData) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptPassportData) Get() (v PassportData, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptPassportData) Or(d PassportData) PassportData { if v, ok := o.Get(); ok { return v } return d } // NewOptPassportFile returns new OptPassportFile with value set to v. func NewOptPassportFile(v PassportFile) OptPassportFile { return OptPassportFile{ Value: v, Set: true, } } // OptPassportFile is optional PassportFile. type OptPassportFile struct { Value PassportFile Set bool } // IsSet returns true if OptPassportFile was set. func (o OptPassportFile) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptPassportFile) Reset() { var v PassportFile o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptPassportFile) SetTo(v PassportFile) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptPassportFile) Get() (v PassportFile, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptPassportFile) Or(d PassportFile) PassportFile { if v, ok := o.Get(); ok { return v } return d } // NewOptPhotoSize returns new OptPhotoSize with value set to v. func NewOptPhotoSize(v PhotoSize) OptPhotoSize { return OptPhotoSize{ Value: v, Set: true, } } // OptPhotoSize is optional PhotoSize. type OptPhotoSize struct { Value PhotoSize Set bool } // IsSet returns true if OptPhotoSize was set. func (o OptPhotoSize) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptPhotoSize) Reset() { var v PhotoSize o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptPhotoSize) SetTo(v PhotoSize) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptPhotoSize) Get() (v PhotoSize, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptPhotoSize) Or(d PhotoSize) PhotoSize { if v, ok := o.Get(); ok { return v } return d } // NewOptPoll returns new OptPoll with value set to v. func NewOptPoll(v Poll) OptPoll { return OptPoll{ Value: v, Set: true, } } // OptPoll is optional Poll. type OptPoll struct { Value Poll Set bool } // IsSet returns true if OptPoll was set. func (o OptPoll) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptPoll) Reset() { var v Poll o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptPoll) SetTo(v Poll) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptPoll) Get() (v Poll, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptPoll) Or(d Poll) Poll { if v, ok := o.Get(); ok { return v } return d } // NewOptProximityAlertTriggered returns new OptProximityAlertTriggered with value set to v. func NewOptProximityAlertTriggered(v ProximityAlertTriggered) OptProximityAlertTriggered { return OptProximityAlertTriggered{ Value: v, Set: true, } } // OptProximityAlertTriggered is optional ProximityAlertTriggered. type OptProximityAlertTriggered struct { Value ProximityAlertTriggered Set bool } // IsSet returns true if OptProximityAlertTriggered was set. func (o OptProximityAlertTriggered) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptProximityAlertTriggered) Reset() { var v ProximityAlertTriggered o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptProximityAlertTriggered) SetTo(v ProximityAlertTriggered) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptProximityAlertTriggered) Get() (v ProximityAlertTriggered, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptProximityAlertTriggered) Or(d ProximityAlertTriggered) ProximityAlertTriggered { if v, ok := o.Get(); ok { return v } return d } // NewOptResponse returns new OptResponse with value set to v. func NewOptResponse(v Response) OptResponse { return OptResponse{ Value: v, Set: true, } } // OptResponse is optional Response. type OptResponse struct { Value Response Set bool } // IsSet returns true if OptResponse was set. func (o OptResponse) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptResponse) Reset() { var v Response o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptResponse) SetTo(v Response) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptResponse) Get() (v Response, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptResponse) Or(d Response) Response { if v, ok := o.Get(); ok { return v } return d } // NewOptSendAnimationReplyMarkup returns new OptSendAnimationReplyMarkup with value set to v. func NewOptSendAnimationReplyMarkup(v SendAnimationReplyMarkup) OptSendAnimationReplyMarkup { return OptSendAnimationReplyMarkup{ Value: v, Set: true, } } // OptSendAnimationReplyMarkup is optional SendAnimationReplyMarkup. type OptSendAnimationReplyMarkup struct { Value SendAnimationReplyMarkup Set bool } // IsSet returns true if OptSendAnimationReplyMarkup was set. func (o OptSendAnimationReplyMarkup) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptSendAnimationReplyMarkup) Reset() { var v SendAnimationReplyMarkup o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptSendAnimationReplyMarkup) SetTo(v SendAnimationReplyMarkup) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptSendAnimationReplyMarkup) Get() (v SendAnimationReplyMarkup, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptSendAnimationReplyMarkup) Or(d SendAnimationReplyMarkup) SendAnimationReplyMarkup { if v, ok := o.Get(); ok { return v } return d } // NewOptSendAudioReplyMarkup returns new OptSendAudioReplyMarkup with value set to v. func NewOptSendAudioReplyMarkup(v SendAudioReplyMarkup) OptSendAudioReplyMarkup { return OptSendAudioReplyMarkup{ Value: v, Set: true, } } // OptSendAudioReplyMarkup is optional SendAudioReplyMarkup. type OptSendAudioReplyMarkup struct { Value SendAudioReplyMarkup Set bool } // IsSet returns true if OptSendAudioReplyMarkup was set. func (o OptSendAudioReplyMarkup) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptSendAudioReplyMarkup) Reset() { var v SendAudioReplyMarkup o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptSendAudioReplyMarkup) SetTo(v SendAudioReplyMarkup) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptSendAudioReplyMarkup) Get() (v SendAudioReplyMarkup, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptSendAudioReplyMarkup) Or(d SendAudioReplyMarkup) SendAudioReplyMarkup { if v, ok := o.Get(); ok { return v } return d } // NewOptSendContactReplyMarkup returns new OptSendContactReplyMarkup with value set to v. func NewOptSendContactReplyMarkup(v SendContactReplyMarkup) OptSendContactReplyMarkup { return OptSendContactReplyMarkup{ Value: v, Set: true, } } // OptSendContactReplyMarkup is optional SendContactReplyMarkup. type OptSendContactReplyMarkup struct { Value SendContactReplyMarkup Set bool } // IsSet returns true if OptSendContactReplyMarkup was set. func (o OptSendContactReplyMarkup) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptSendContactReplyMarkup) Reset() { var v SendContactReplyMarkup o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptSendContactReplyMarkup) SetTo(v SendContactReplyMarkup) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptSendContactReplyMarkup) Get() (v SendContactReplyMarkup, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptSendContactReplyMarkup) Or(d SendContactReplyMarkup) SendContactReplyMarkup { if v, ok := o.Get(); ok { return v } return d } // NewOptSendDiceReplyMarkup returns new OptSendDiceReplyMarkup with value set to v. func NewOptSendDiceReplyMarkup(v SendDiceReplyMarkup) OptSendDiceReplyMarkup { return OptSendDiceReplyMarkup{ Value: v, Set: true, } } // OptSendDiceReplyMarkup is optional SendDiceReplyMarkup. type OptSendDiceReplyMarkup struct { Value SendDiceReplyMarkup Set bool } // IsSet returns true if OptSendDiceReplyMarkup was set. func (o OptSendDiceReplyMarkup) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptSendDiceReplyMarkup) Reset() { var v SendDiceReplyMarkup o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptSendDiceReplyMarkup) SetTo(v SendDiceReplyMarkup) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptSendDiceReplyMarkup) Get() (v SendDiceReplyMarkup, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptSendDiceReplyMarkup) Or(d SendDiceReplyMarkup) SendDiceReplyMarkup { if v, ok := o.Get(); ok { return v } return d } // NewOptSendDocumentReplyMarkup returns new OptSendDocumentReplyMarkup with value set to v. func NewOptSendDocumentReplyMarkup(v SendDocumentReplyMarkup) OptSendDocumentReplyMarkup { return OptSendDocumentReplyMarkup{ Value: v, Set: true, } } // OptSendDocumentReplyMarkup is optional SendDocumentReplyMarkup. type OptSendDocumentReplyMarkup struct { Value SendDocumentReplyMarkup Set bool } // IsSet returns true if OptSendDocumentReplyMarkup was set. func (o OptSendDocumentReplyMarkup) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptSendDocumentReplyMarkup) Reset() { var v SendDocumentReplyMarkup o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptSendDocumentReplyMarkup) SetTo(v SendDocumentReplyMarkup) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptSendDocumentReplyMarkup) Get() (v SendDocumentReplyMarkup, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptSendDocumentReplyMarkup) Or(d SendDocumentReplyMarkup) SendDocumentReplyMarkup { if v, ok := o.Get(); ok { return v } return d } // NewOptSendLocationReplyMarkup returns new OptSendLocationReplyMarkup with value set to v. func NewOptSendLocationReplyMarkup(v SendLocationReplyMarkup) OptSendLocationReplyMarkup { return OptSendLocationReplyMarkup{ Value: v, Set: true, } } // OptSendLocationReplyMarkup is optional SendLocationReplyMarkup. type OptSendLocationReplyMarkup struct { Value SendLocationReplyMarkup Set bool } // IsSet returns true if OptSendLocationReplyMarkup was set. func (o OptSendLocationReplyMarkup) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptSendLocationReplyMarkup) Reset() { var v SendLocationReplyMarkup o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptSendLocationReplyMarkup) SetTo(v SendLocationReplyMarkup) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptSendLocationReplyMarkup) Get() (v SendLocationReplyMarkup, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptSendLocationReplyMarkup) Or(d SendLocationReplyMarkup) SendLocationReplyMarkup { if v, ok := o.Get(); ok { return v } return d } // NewOptSendMessageReplyMarkup returns new OptSendMessageReplyMarkup with value set to v. func NewOptSendMessageReplyMarkup(v SendMessageReplyMarkup) OptSendMessageReplyMarkup { return OptSendMessageReplyMarkup{ Value: v, Set: true, } } // OptSendMessageReplyMarkup is optional SendMessageReplyMarkup. type OptSendMessageReplyMarkup struct { Value SendMessageReplyMarkup Set bool } // IsSet returns true if OptSendMessageReplyMarkup was set. func (o OptSendMessageReplyMarkup) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptSendMessageReplyMarkup) Reset() { var v SendMessageReplyMarkup o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptSendMessageReplyMarkup) SetTo(v SendMessageReplyMarkup) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptSendMessageReplyMarkup) Get() (v SendMessageReplyMarkup, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptSendMessageReplyMarkup) Or(d SendMessageReplyMarkup) SendMessageReplyMarkup { if v, ok := o.Get(); ok { return v } return d } // NewOptSendPhotoReplyMarkup returns new OptSendPhotoReplyMarkup with value set to v. func NewOptSendPhotoReplyMarkup(v SendPhotoReplyMarkup) OptSendPhotoReplyMarkup { return OptSendPhotoReplyMarkup{ Value: v, Set: true, } } // OptSendPhotoReplyMarkup is optional SendPhotoReplyMarkup. type OptSendPhotoReplyMarkup struct { Value SendPhotoReplyMarkup Set bool } // IsSet returns true if OptSendPhotoReplyMarkup was set. func (o OptSendPhotoReplyMarkup) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptSendPhotoReplyMarkup) Reset() { var v SendPhotoReplyMarkup o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptSendPhotoReplyMarkup) SetTo(v SendPhotoReplyMarkup) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptSendPhotoReplyMarkup) Get() (v SendPhotoReplyMarkup, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptSendPhotoReplyMarkup) Or(d SendPhotoReplyMarkup) SendPhotoReplyMarkup { if v, ok := o.Get(); ok { return v } return d } // NewOptSendPollReplyMarkup returns new OptSendPollReplyMarkup with value set to v. func NewOptSendPollReplyMarkup(v SendPollReplyMarkup) OptSendPollReplyMarkup { return OptSendPollReplyMarkup{ Value: v, Set: true, } } // OptSendPollReplyMarkup is optional SendPollReplyMarkup. type OptSendPollReplyMarkup struct { Value SendPollReplyMarkup Set bool } // IsSet returns true if OptSendPollReplyMarkup was set. func (o OptSendPollReplyMarkup) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptSendPollReplyMarkup) Reset() { var v SendPollReplyMarkup o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptSendPollReplyMarkup) SetTo(v SendPollReplyMarkup) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptSendPollReplyMarkup) Get() (v SendPollReplyMarkup, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptSendPollReplyMarkup) Or(d SendPollReplyMarkup) SendPollReplyMarkup { if v, ok := o.Get(); ok { return v } return d } // NewOptSendStickerReplyMarkup returns new OptSendStickerReplyMarkup with value set to v. func NewOptSendStickerReplyMarkup(v SendStickerReplyMarkup) OptSendStickerReplyMarkup { return OptSendStickerReplyMarkup{ Value: v, Set: true, } } // OptSendStickerReplyMarkup is optional SendStickerReplyMarkup. type OptSendStickerReplyMarkup struct { Value SendStickerReplyMarkup Set bool } // IsSet returns true if OptSendStickerReplyMarkup was set. func (o OptSendStickerReplyMarkup) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptSendStickerReplyMarkup) Reset() { var v SendStickerReplyMarkup o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptSendStickerReplyMarkup) SetTo(v SendStickerReplyMarkup) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptSendStickerReplyMarkup) Get() (v SendStickerReplyMarkup, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptSendStickerReplyMarkup) Or(d SendStickerReplyMarkup) SendStickerReplyMarkup { if v, ok := o.Get(); ok { return v } return d } // NewOptSendVenueReplyMarkup returns new OptSendVenueReplyMarkup with value set to v. func NewOptSendVenueReplyMarkup(v SendVenueReplyMarkup) OptSendVenueReplyMarkup { return OptSendVenueReplyMarkup{ Value: v, Set: true, } } // OptSendVenueReplyMarkup is optional SendVenueReplyMarkup. type OptSendVenueReplyMarkup struct { Value SendVenueReplyMarkup Set bool } // IsSet returns true if OptSendVenueReplyMarkup was set. func (o OptSendVenueReplyMarkup) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptSendVenueReplyMarkup) Reset() { var v SendVenueReplyMarkup o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptSendVenueReplyMarkup) SetTo(v SendVenueReplyMarkup) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptSendVenueReplyMarkup) Get() (v SendVenueReplyMarkup, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptSendVenueReplyMarkup) Or(d SendVenueReplyMarkup) SendVenueReplyMarkup { if v, ok := o.Get(); ok { return v } return d } // NewOptSendVideoNoteReplyMarkup returns new OptSendVideoNoteReplyMarkup with value set to v. func NewOptSendVideoNoteReplyMarkup(v SendVideoNoteReplyMarkup) OptSendVideoNoteReplyMarkup { return OptSendVideoNoteReplyMarkup{ Value: v, Set: true, } } // OptSendVideoNoteReplyMarkup is optional SendVideoNoteReplyMarkup. type OptSendVideoNoteReplyMarkup struct { Value SendVideoNoteReplyMarkup Set bool } // IsSet returns true if OptSendVideoNoteReplyMarkup was set. func (o OptSendVideoNoteReplyMarkup) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptSendVideoNoteReplyMarkup) Reset() { var v SendVideoNoteReplyMarkup o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptSendVideoNoteReplyMarkup) SetTo(v SendVideoNoteReplyMarkup) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptSendVideoNoteReplyMarkup) Get() (v SendVideoNoteReplyMarkup, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptSendVideoNoteReplyMarkup) Or(d SendVideoNoteReplyMarkup) SendVideoNoteReplyMarkup { if v, ok := o.Get(); ok { return v } return d } // NewOptSendVideoReplyMarkup returns new OptSendVideoReplyMarkup with value set to v. func NewOptSendVideoReplyMarkup(v SendVideoReplyMarkup) OptSendVideoReplyMarkup { return OptSendVideoReplyMarkup{ Value: v, Set: true, } } // OptSendVideoReplyMarkup is optional SendVideoReplyMarkup. type OptSendVideoReplyMarkup struct { Value SendVideoReplyMarkup Set bool } // IsSet returns true if OptSendVideoReplyMarkup was set. func (o OptSendVideoReplyMarkup) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptSendVideoReplyMarkup) Reset() { var v SendVideoReplyMarkup o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptSendVideoReplyMarkup) SetTo(v SendVideoReplyMarkup) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptSendVideoReplyMarkup) Get() (v SendVideoReplyMarkup, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptSendVideoReplyMarkup) Or(d SendVideoReplyMarkup) SendVideoReplyMarkup { if v, ok := o.Get(); ok { return v } return d } // NewOptSendVoiceReplyMarkup returns new OptSendVoiceReplyMarkup with value set to v. func NewOptSendVoiceReplyMarkup(v SendVoiceReplyMarkup) OptSendVoiceReplyMarkup { return OptSendVoiceReplyMarkup{ Value: v, Set: true, } } // OptSendVoiceReplyMarkup is optional SendVoiceReplyMarkup. type OptSendVoiceReplyMarkup struct { Value SendVoiceReplyMarkup Set bool } // IsSet returns true if OptSendVoiceReplyMarkup was set. func (o OptSendVoiceReplyMarkup) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptSendVoiceReplyMarkup) Reset() { var v SendVoiceReplyMarkup o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptSendVoiceReplyMarkup) SetTo(v SendVoiceReplyMarkup) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptSendVoiceReplyMarkup) Get() (v SendVoiceReplyMarkup, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptSendVoiceReplyMarkup) Or(d SendVoiceReplyMarkup) SendVoiceReplyMarkup { if v, ok := o.Get(); ok { return v } return d } // NewOptShippingAddress returns new OptShippingAddress with value set to v. func NewOptShippingAddress(v ShippingAddress) OptShippingAddress { return OptShippingAddress{ Value: v, Set: true, } } // OptShippingAddress is optional ShippingAddress. type OptShippingAddress struct { Value ShippingAddress Set bool } // IsSet returns true if OptShippingAddress was set. func (o OptShippingAddress) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptShippingAddress) Reset() { var v ShippingAddress o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptShippingAddress) SetTo(v ShippingAddress) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptShippingAddress) Get() (v ShippingAddress, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptShippingAddress) Or(d ShippingAddress) ShippingAddress { if v, ok := o.Get(); ok { return v } return d } // NewOptSticker returns new OptSticker with value set to v. func NewOptSticker(v Sticker) OptSticker { return OptSticker{ Value: v, Set: true, } } // OptSticker is optional Sticker. type OptSticker struct { Value Sticker Set bool } // IsSet returns true if OptSticker was set. func (o OptSticker) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptSticker) Reset() { var v Sticker o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptSticker) SetTo(v Sticker) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptSticker) Get() (v Sticker, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptSticker) Or(d Sticker) Sticker { if v, ok := o.Get(); ok { return v } return d } // NewOptString returns new OptString with value set to v. func NewOptString(v string) OptString { return OptString{ Value: v, Set: true, } } // OptString is optional string. type OptString struct { Value string Set bool } // IsSet returns true if OptString was set. func (o OptString) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptString) Reset() { var v string o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptString) SetTo(v string) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptString) Get() (v string, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptString) Or(d string) string { if v, ok := o.Get(); ok { return v } return d } // NewOptSuccessfulPayment returns new OptSuccessfulPayment with value set to v. func NewOptSuccessfulPayment(v SuccessfulPayment) OptSuccessfulPayment { return OptSuccessfulPayment{ Value: v, Set: true, } } // OptSuccessfulPayment is optional SuccessfulPayment. type OptSuccessfulPayment struct { Value SuccessfulPayment Set bool } // IsSet returns true if OptSuccessfulPayment was set. func (o OptSuccessfulPayment) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptSuccessfulPayment) Reset() { var v SuccessfulPayment o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptSuccessfulPayment) SetTo(v SuccessfulPayment) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptSuccessfulPayment) Get() (v SuccessfulPayment, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptSuccessfulPayment) Or(d SuccessfulPayment) SuccessfulPayment { if v, ok := o.Get(); ok { return v } return d } // NewOptURL returns new OptURL with value set to v. func NewOptURL(v url.URL) OptURL { return OptURL{ Value: v, Set: true, } } // OptURL is optional url.URL. type OptURL struct { Value url.URL Set bool } // IsSet returns true if OptURL was set. func (o OptURL) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptURL) Reset() { var v url.URL o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptURL) SetTo(v url.URL) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptURL) Get() (v url.URL, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptURL) Or(d url.URL) url.URL { if v, ok := o.Get(); ok { return v } return d } // NewOptUser returns new OptUser with value set to v. func NewOptUser(v User) OptUser { return OptUser{ Value: v, Set: true, } } // OptUser is optional User. type OptUser struct { Value User Set bool } // IsSet returns true if OptUser was set. func (o OptUser) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptUser) Reset() { var v User o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptUser) SetTo(v User) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptUser) Get() (v User, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptUser) Or(d User) User { if v, ok := o.Get(); ok { return v } return d } // NewOptVenue returns new OptVenue with value set to v. func NewOptVenue(v Venue) OptVenue { return OptVenue{ Value: v, Set: true, } } // OptVenue is optional Venue. type OptVenue struct { Value Venue Set bool } // IsSet returns true if OptVenue was set. func (o OptVenue) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptVenue) Reset() { var v Venue o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptVenue) SetTo(v Venue) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptVenue) Get() (v Venue, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptVenue) Or(d Venue) Venue { if v, ok := o.Get(); ok { return v } return d } // NewOptVideo returns new OptVideo with value set to v. func NewOptVideo(v Video) OptVideo { return OptVideo{ Value: v, Set: true, } } // OptVideo is optional Video. type OptVideo struct { Value Video Set bool } // IsSet returns true if OptVideo was set. func (o OptVideo) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptVideo) Reset() { var v Video o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptVideo) SetTo(v Video) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptVideo) Get() (v Video, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptVideo) Or(d Video) Video { if v, ok := o.Get(); ok { return v } return d } // NewOptVideoNote returns new OptVideoNote with value set to v. func NewOptVideoNote(v VideoNote) OptVideoNote { return OptVideoNote{ Value: v, Set: true, } } // OptVideoNote is optional VideoNote. type OptVideoNote struct { Value VideoNote Set bool } // IsSet returns true if OptVideoNote was set. func (o OptVideoNote) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptVideoNote) Reset() { var v VideoNote o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptVideoNote) SetTo(v VideoNote) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptVideoNote) Get() (v VideoNote, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptVideoNote) Or(d VideoNote) VideoNote { if v, ok := o.Get(); ok { return v } return d } // NewOptVoice returns new OptVoice with value set to v. func NewOptVoice(v Voice) OptVoice { return OptVoice{ Value: v, Set: true, } } // OptVoice is optional Voice. type OptVoice struct { Value Voice Set bool } // IsSet returns true if OptVoice was set. func (o OptVoice) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptVoice) Reset() { var v Voice o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptVoice) SetTo(v Voice) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptVoice) Get() (v Voice, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptVoice) Or(d Voice) Voice { if v, ok := o.Get(); ok { return v } return d } // NewOptVoiceChatEnded returns new OptVoiceChatEnded with value set to v. func NewOptVoiceChatEnded(v VoiceChatEnded) OptVoiceChatEnded { return OptVoiceChatEnded{ Value: v, Set: true, } } // OptVoiceChatEnded is optional VoiceChatEnded. type OptVoiceChatEnded struct { Value VoiceChatEnded Set bool } // IsSet returns true if OptVoiceChatEnded was set. func (o OptVoiceChatEnded) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptVoiceChatEnded) Reset() { var v VoiceChatEnded o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptVoiceChatEnded) SetTo(v VoiceChatEnded) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptVoiceChatEnded) Get() (v VoiceChatEnded, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptVoiceChatEnded) Or(d VoiceChatEnded) VoiceChatEnded { if v, ok := o.Get(); ok { return v } return d } // NewOptVoiceChatParticipantsInvited returns new OptVoiceChatParticipantsInvited with value set to v. func NewOptVoiceChatParticipantsInvited(v VoiceChatParticipantsInvited) OptVoiceChatParticipantsInvited { return OptVoiceChatParticipantsInvited{ Value: v, Set: true, } } // OptVoiceChatParticipantsInvited is optional VoiceChatParticipantsInvited. type OptVoiceChatParticipantsInvited struct { Value VoiceChatParticipantsInvited Set bool } // IsSet returns true if OptVoiceChatParticipantsInvited was set. func (o OptVoiceChatParticipantsInvited) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptVoiceChatParticipantsInvited) Reset() { var v VoiceChatParticipantsInvited o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptVoiceChatParticipantsInvited) SetTo(v VoiceChatParticipantsInvited) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptVoiceChatParticipantsInvited) Get() (v VoiceChatParticipantsInvited, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptVoiceChatParticipantsInvited) Or(d VoiceChatParticipantsInvited) VoiceChatParticipantsInvited { if v, ok := o.Get(); ok { return v } return d } // NewOptVoiceChatScheduled returns new OptVoiceChatScheduled with value set to v. func NewOptVoiceChatScheduled(v VoiceChatScheduled) OptVoiceChatScheduled { return OptVoiceChatScheduled{ Value: v, Set: true, } } // OptVoiceChatScheduled is optional VoiceChatScheduled. type OptVoiceChatScheduled struct { Value VoiceChatScheduled Set bool } // IsSet returns true if OptVoiceChatScheduled was set. func (o OptVoiceChatScheduled) IsSet() bool { return o.Set } // Reset unsets value. func (o *OptVoiceChatScheduled) Reset() { var v VoiceChatScheduled o.Value = v o.Set = false } // SetTo sets value to v. func (o *OptVoiceChatScheduled) SetTo(v VoiceChatScheduled) { o.Set = true o.Value = v } // Get returns value and boolean that denotes whether value was set. func (o OptVoiceChatScheduled) Get() (v VoiceChatScheduled, ok bool) { if !o.Set { return v, false } return o.Value, true } // Or returns value if set, or given parameter if does not. func (o OptVoiceChatScheduled) Or(d VoiceChatScheduled) VoiceChatScheduled { if v, ok := o.Get(); ok { return v } return d } // This object represents information about an order. // Ref: #/components/schemas/OrderInfo type OrderInfo struct { // User name. Name OptString `json:"name"` // User's phone number. PhoneNumber OptString `json:"phone_number"` // User email. Email OptString `json:"email"` ShippingAddress OptShippingAddress `json:"shipping_address"` } // Contains information about Telegram Passport data shared with the bot by the user. // Ref: #/components/schemas/PassportData type PassportData struct { // Array with information about documents and other Telegram Passport elements that was shared with // the bot. Data []EncryptedPassportElement `json:"data"` Credentials EncryptedCredentials `json:"credentials"` } // This object represents an error in the Telegram Passport element which was submitted that should // be resolved by the user. :. // Ref: #/components/schemas/PassportElementError // PassportElementError represents sum type. type PassportElementError struct { Type PassportElementErrorType // switch on this field PassportElementErrorDataField PassportElementErrorDataField PassportElementErrorFrontSide PassportElementErrorFrontSide PassportElementErrorReverseSide PassportElementErrorReverseSide PassportElementErrorSelfie PassportElementErrorSelfie PassportElementErrorFile PassportElementErrorFile PassportElementErrorFiles PassportElementErrorFiles PassportElementErrorTranslationFile PassportElementErrorTranslationFile PassportElementErrorTranslationFiles PassportElementErrorTranslationFiles PassportElementErrorUnspecified PassportElementErrorUnspecified } // PassportElementErrorType is oneOf type of PassportElementError. type PassportElementErrorType string // Possible values for PassportElementErrorType. const ( PassportElementErrorDataFieldPassportElementError PassportElementErrorType = "PassportElementErrorDataField" PassportElementErrorFrontSidePassportElementError PassportElementErrorType = "PassportElementErrorFrontSide" PassportElementErrorReverseSidePassportElementError PassportElementErrorType = "PassportElementErrorReverseSide" PassportElementErrorSelfiePassportElementError PassportElementErrorType = "PassportElementErrorSelfie" PassportElementErrorFilePassportElementError PassportElementErrorType = "PassportElementErrorFile" PassportElementErrorFilesPassportElementError PassportElementErrorType = "PassportElementErrorFiles" PassportElementErrorTranslationFilePassportElementError PassportElementErrorType = "PassportElementErrorTranslationFile" PassportElementErrorTranslationFilesPassportElementError PassportElementErrorType = "PassportElementErrorTranslationFiles" PassportElementErrorUnspecifiedPassportElementError PassportElementErrorType = "PassportElementErrorUnspecified" ) // IsPassportElementErrorDataField reports whether PassportElementError is PassportElementErrorDataField. func (s PassportElementError) IsPassportElementErrorDataField() bool { return s.Type == PassportElementErrorDataFieldPassportElementError } // IsPassportElementErrorFrontSide reports whether PassportElementError is PassportElementErrorFrontSide. func (s PassportElementError) IsPassportElementErrorFrontSide() bool { return s.Type == PassportElementErrorFrontSidePassportElementError } // IsPassportElementErrorReverseSide reports whether PassportElementError is PassportElementErrorReverseSide. func (s PassportElementError) IsPassportElementErrorReverseSide() bool { return s.Type == PassportElementErrorReverseSidePassportElementError } // IsPassportElementErrorSelfie reports whether PassportElementError is PassportElementErrorSelfie. func (s PassportElementError) IsPassportElementErrorSelfie() bool { return s.Type == PassportElementErrorSelfiePassportElementError } // IsPassportElementErrorFile reports whether PassportElementError is PassportElementErrorFile. func (s PassportElementError) IsPassportElementErrorFile() bool { return s.Type == PassportElementErrorFilePassportElementError } // IsPassportElementErrorFiles reports whether PassportElementError is PassportElementErrorFiles. func (s PassportElementError) IsPassportElementErrorFiles() bool { return s.Type == PassportElementErrorFilesPassportElementError } // IsPassportElementErrorTranslationFile reports whether PassportElementError is PassportElementErrorTranslationFile. func (s PassportElementError) IsPassportElementErrorTranslationFile() bool { return s.Type == PassportElementErrorTranslationFilePassportElementError } // IsPassportElementErrorTranslationFiles reports whether PassportElementError is PassportElementErrorTranslationFiles. func (s PassportElementError) IsPassportElementErrorTranslationFiles() bool { return s.Type == PassportElementErrorTranslationFilesPassportElementError } // IsPassportElementErrorUnspecified reports whether PassportElementError is PassportElementErrorUnspecified. func (s PassportElementError) IsPassportElementErrorUnspecified() bool { return s.Type == PassportElementErrorUnspecifiedPassportElementError } // SetPassportElementErrorDataField sets PassportElementError to PassportElementErrorDataField. func (s *PassportElementError) SetPassportElementErrorDataField(v PassportElementErrorDataField) { s.Type = PassportElementErrorDataFieldPassportElementError s.PassportElementErrorDataField = v } // GetPassportElementErrorDataField returns PassportElementErrorDataField and true boolean if PassportElementError is PassportElementErrorDataField. func (s PassportElementError) GetPassportElementErrorDataField() (v PassportElementErrorDataField, ok bool) { if !s.IsPassportElementErrorDataField() { return v, false } return s.PassportElementErrorDataField, true } // NewPassportElementErrorDataFieldPassportElementError returns new PassportElementError from PassportElementErrorDataField. func NewPassportElementErrorDataFieldPassportElementError(v PassportElementErrorDataField) PassportElementError { var s PassportElementError s.SetPassportElementErrorDataField(v) return s } // SetPassportElementErrorFrontSide sets PassportElementError to PassportElementErrorFrontSide. func (s *PassportElementError) SetPassportElementErrorFrontSide(v PassportElementErrorFrontSide) { s.Type = PassportElementErrorFrontSidePassportElementError s.PassportElementErrorFrontSide = v } // GetPassportElementErrorFrontSide returns PassportElementErrorFrontSide and true boolean if PassportElementError is PassportElementErrorFrontSide. func (s PassportElementError) GetPassportElementErrorFrontSide() (v PassportElementErrorFrontSide, ok bool) { if !s.IsPassportElementErrorFrontSide() { return v, false } return s.PassportElementErrorFrontSide, true } // NewPassportElementErrorFrontSidePassportElementError returns new PassportElementError from PassportElementErrorFrontSide. func NewPassportElementErrorFrontSidePassportElementError(v PassportElementErrorFrontSide) PassportElementError { var s PassportElementError s.SetPassportElementErrorFrontSide(v) return s } // SetPassportElementErrorReverseSide sets PassportElementError to PassportElementErrorReverseSide. func (s *PassportElementError) SetPassportElementErrorReverseSide(v PassportElementErrorReverseSide) { s.Type = PassportElementErrorReverseSidePassportElementError s.PassportElementErrorReverseSide = v } // GetPassportElementErrorReverseSide returns PassportElementErrorReverseSide and true boolean if PassportElementError is PassportElementErrorReverseSide. func (s PassportElementError) GetPassportElementErrorReverseSide() (v PassportElementErrorReverseSide, ok bool) { if !s.IsPassportElementErrorReverseSide() { return v, false } return s.PassportElementErrorReverseSide, true } // NewPassportElementErrorReverseSidePassportElementError returns new PassportElementError from PassportElementErrorReverseSide. func NewPassportElementErrorReverseSidePassportElementError(v PassportElementErrorReverseSide) PassportElementError { var s PassportElementError s.SetPassportElementErrorReverseSide(v) return s } // SetPassportElementErrorSelfie sets PassportElementError to PassportElementErrorSelfie. func (s *PassportElementError) SetPassportElementErrorSelfie(v PassportElementErrorSelfie) { s.Type = PassportElementErrorSelfiePassportElementError s.PassportElementErrorSelfie = v } // GetPassportElementErrorSelfie returns PassportElementErrorSelfie and true boolean if PassportElementError is PassportElementErrorSelfie. func (s PassportElementError) GetPassportElementErrorSelfie() (v PassportElementErrorSelfie, ok bool) { if !s.IsPassportElementErrorSelfie() { return v, false } return s.PassportElementErrorSelfie, true } // NewPassportElementErrorSelfiePassportElementError returns new PassportElementError from PassportElementErrorSelfie. func NewPassportElementErrorSelfiePassportElementError(v PassportElementErrorSelfie) PassportElementError { var s PassportElementError s.SetPassportElementErrorSelfie(v) return s } // SetPassportElementErrorFile sets PassportElementError to PassportElementErrorFile. func (s *PassportElementError) SetPassportElementErrorFile(v PassportElementErrorFile) { s.Type = PassportElementErrorFilePassportElementError s.PassportElementErrorFile = v } // GetPassportElementErrorFile returns PassportElementErrorFile and true boolean if PassportElementError is PassportElementErrorFile. func (s PassportElementError) GetPassportElementErrorFile() (v PassportElementErrorFile, ok bool) { if !s.IsPassportElementErrorFile() { return v, false } return s.PassportElementErrorFile, true } // NewPassportElementErrorFilePassportElementError returns new PassportElementError from PassportElementErrorFile. func NewPassportElementErrorFilePassportElementError(v PassportElementErrorFile) PassportElementError { var s PassportElementError s.SetPassportElementErrorFile(v) return s } // SetPassportElementErrorFiles sets PassportElementError to PassportElementErrorFiles. func (s *PassportElementError) SetPassportElementErrorFiles(v PassportElementErrorFiles) { s.Type = PassportElementErrorFilesPassportElementError s.PassportElementErrorFiles = v } // GetPassportElementErrorFiles returns PassportElementErrorFiles and true boolean if PassportElementError is PassportElementErrorFiles. func (s PassportElementError) GetPassportElementErrorFiles() (v PassportElementErrorFiles, ok bool) { if !s.IsPassportElementErrorFiles() { return v, false } return s.PassportElementErrorFiles, true } // NewPassportElementErrorFilesPassportElementError returns new PassportElementError from PassportElementErrorFiles. func NewPassportElementErrorFilesPassportElementError(v PassportElementErrorFiles) PassportElementError { var s PassportElementError s.SetPassportElementErrorFiles(v) return s } // SetPassportElementErrorTranslationFile sets PassportElementError to PassportElementErrorTranslationFile. func (s *PassportElementError) SetPassportElementErrorTranslationFile(v PassportElementErrorTranslationFile) { s.Type = PassportElementErrorTranslationFilePassportElementError s.PassportElementErrorTranslationFile = v } // GetPassportElementErrorTranslationFile returns PassportElementErrorTranslationFile and true boolean if PassportElementError is PassportElementErrorTranslationFile. func (s PassportElementError) GetPassportElementErrorTranslationFile() (v PassportElementErrorTranslationFile, ok bool) { if !s.IsPassportElementErrorTranslationFile() { return v, false } return s.PassportElementErrorTranslationFile, true } // NewPassportElementErrorTranslationFilePassportElementError returns new PassportElementError from PassportElementErrorTranslationFile. func NewPassportElementErrorTranslationFilePassportElementError(v PassportElementErrorTranslationFile) PassportElementError { var s PassportElementError s.SetPassportElementErrorTranslationFile(v) return s } // SetPassportElementErrorTranslationFiles sets PassportElementError to PassportElementErrorTranslationFiles. func (s *PassportElementError) SetPassportElementErrorTranslationFiles(v PassportElementErrorTranslationFiles) { s.Type = PassportElementErrorTranslationFilesPassportElementError s.PassportElementErrorTranslationFiles = v } // GetPassportElementErrorTranslationFiles returns PassportElementErrorTranslationFiles and true boolean if PassportElementError is PassportElementErrorTranslationFiles. func (s PassportElementError) GetPassportElementErrorTranslationFiles() (v PassportElementErrorTranslationFiles, ok bool) { if !s.IsPassportElementErrorTranslationFiles() { return v, false } return s.PassportElementErrorTranslationFiles, true } // NewPassportElementErrorTranslationFilesPassportElementError returns new PassportElementError from PassportElementErrorTranslationFiles. func NewPassportElementErrorTranslationFilesPassportElementError(v PassportElementErrorTranslationFiles) PassportElementError { var s PassportElementError s.SetPassportElementErrorTranslationFiles(v) return s } // SetPassportElementErrorUnspecified sets PassportElementError to PassportElementErrorUnspecified. func (s *PassportElementError) SetPassportElementErrorUnspecified(v PassportElementErrorUnspecified) { s.Type = PassportElementErrorUnspecifiedPassportElementError s.PassportElementErrorUnspecified = v } // GetPassportElementErrorUnspecified returns PassportElementErrorUnspecified and true boolean if PassportElementError is PassportElementErrorUnspecified. func (s PassportElementError) GetPassportElementErrorUnspecified() (v PassportElementErrorUnspecified, ok bool) { if !s.IsPassportElementErrorUnspecified() { return v, false } return s.PassportElementErrorUnspecified, true } // NewPassportElementErrorUnspecifiedPassportElementError returns new PassportElementError from PassportElementErrorUnspecified. func NewPassportElementErrorUnspecifiedPassportElementError(v PassportElementErrorUnspecified) PassportElementError { var s PassportElementError s.SetPassportElementErrorUnspecified(v) return s } // Represents an issue in one of the data fields that was provided by the user. The error is // considered resolved when the field's value changes. // Ref: #/components/schemas/PassportElementErrorDataField type PassportElementErrorDataField struct { // Error source, must be data. Source string `json:"source"` // The section of the user's Telegram Passport which has the error, one of “personal_details”, // “passport”, “driver_license”, “identity_card”, “internal_passport”, “address”. Type string `json:"type"` // Name of the data field which has the error. FieldName string `json:"field_name"` // Base64-encoded data hash. DataHash string `json:"data_hash"` // Error message. Message string `json:"message"` } // Represents an issue with a document scan. The error is considered resolved when the file with the // document scan changes. // Ref: #/components/schemas/PassportElementErrorFile type PassportElementErrorFile struct { // Error source, must be file. Source string `json:"source"` // The section of the user's Telegram Passport which has the issue, one of “utility_bill”, // “bank_statement”, “rental_agreement”, “passport_registration”, // “temporary_registration”. Type string `json:"type"` // Base64-encoded file hash. FileHash string `json:"file_hash"` // Error message. Message string `json:"message"` } // Represents an issue with a list of scans. The error is considered resolved when the list of files // containing the scans changes. // Ref: #/components/schemas/PassportElementErrorFiles type PassportElementErrorFiles struct { // Error source, must be files. Source string `json:"source"` // The section of the user's Telegram Passport which has the issue, one of “utility_bill”, // “bank_statement”, “rental_agreement”, “passport_registration”, // “temporary_registration”. Type string `json:"type"` // List of base64-encoded file hashes. FileHashes []string `json:"file_hashes"` // Error message. Message string `json:"message"` } // Represents an issue with the front side of a document. The error is considered resolved when the // file with the front side of the document changes. // Ref: #/components/schemas/PassportElementErrorFrontSide type PassportElementErrorFrontSide struct { // Error source, must be front_side. Source string `json:"source"` // The section of the user's Telegram Passport which has the issue, one of “passport”, // “driver_license”, “identity_card”, “internal_passport”. Type string `json:"type"` // Base64-encoded hash of the file with the front side of the document. FileHash string `json:"file_hash"` // Error message. Message string `json:"message"` } // Represents an issue with the reverse side of a document. The error is considered resolved when the // file with reverse side of the document changes. // Ref: #/components/schemas/PassportElementErrorReverseSide type PassportElementErrorReverseSide struct { // Error source, must be reverse_side. Source string `json:"source"` // The section of the user's Telegram Passport which has the issue, one of “driver_license”, // “identity_card”. Type string `json:"type"` // Base64-encoded hash of the file with the reverse side of the document. FileHash string `json:"file_hash"` // Error message. Message string `json:"message"` } // Represents an issue with the selfie with a document. The error is considered resolved when the // file with the selfie changes. // Ref: #/components/schemas/PassportElementErrorSelfie type PassportElementErrorSelfie struct { // Error source, must be selfie. Source string `json:"source"` // The section of the user's Telegram Passport which has the issue, one of “passport”, // “driver_license”, “identity_card”, “internal_passport”. Type string `json:"type"` // Base64-encoded hash of the file with the selfie. FileHash string `json:"file_hash"` // Error message. Message string `json:"message"` } // Represents an issue with one of the files that constitute the translation of a document. The error // is considered resolved when the file changes. // Ref: #/components/schemas/PassportElementErrorTranslationFile type PassportElementErrorTranslationFile struct { // Error source, must be translation_file. Source string `json:"source"` // Type of element of the user's Telegram Passport which has the issue, one of “passport”, // “driver_license”, “identity_card”, “internal_passport”, “utility_bill”, // “bank_statement”, “rental_agreement”, “passport_registration”, // “temporary_registration”. Type string `json:"type"` // Base64-encoded file hash. FileHash string `json:"file_hash"` // Error message. Message string `json:"message"` } // Represents an issue with the translated version of a document. The error is considered resolved // when a file with the document translation change. // Ref: #/components/schemas/PassportElementErrorTranslationFiles type PassportElementErrorTranslationFiles struct { // Error source, must be translation_files. Source string `json:"source"` // Type of element of the user's Telegram Passport which has the issue, one of “passport”, // “driver_license”, “identity_card”, “internal_passport”, “utility_bill”, // “bank_statement”, “rental_agreement”, “passport_registration”, // “temporary_registration”. Type string `json:"type"` // List of base64-encoded file hashes. FileHashes []string `json:"file_hashes"` // Error message. Message string `json:"message"` } // Represents an issue in an unspecified place. The error is considered resolved when new data is // added. // Ref: #/components/schemas/PassportElementErrorUnspecified type PassportElementErrorUnspecified struct { // Error source, must be unspecified. Source string `json:"source"` // Type of element of the user's Telegram Passport which has the issue. Type string `json:"type"` // Base64-encoded element hash. ElementHash string `json:"element_hash"` // Error message. Message string `json:"message"` } // This object represents a file uploaded to Telegram Passport. Currently all Telegram Passport files // are in JPEG format when decrypted and don't exceed 10MB. // Ref: #/components/schemas/PassportFile type PassportFile struct { // Identifier for this file, which can be used to download or reuse the file. FileID string `json:"file_id"` // Unique identifier for this file, which is supposed to be the same over time and for different bots. // Can't be used to download or reuse the file. FileUniqueID string `json:"file_unique_id"` // File size in bytes. FileSize int `json:"file_size"` // Unix time when the file was uploaded. FileDate int `json:"file_date"` } // This object represents one size of a photo or a file / sticker thumbnail. // Ref: #/components/schemas/PhotoSize type PhotoSize struct { // Identifier for this file, which can be used to download or reuse the file. FileID string `json:"file_id"` // Unique identifier for this file, which is supposed to be the same over time and for different bots. // Can't be used to download or reuse the file. FileUniqueID string `json:"file_unique_id"` // Photo width. Width int `json:"width"` // Photo height. Height int `json:"height"` // File size in bytes. FileSize OptInt `json:"file_size"` } // Input for pinChatMessage. // Ref: #/components/schemas/pinChatMessage type PinChatMessage struct { ChatID ID `json:"chat_id"` // Identifier of a message to pin. MessageID int `json:"message_id"` // Pass True, if it is not necessary to send a notification to all chat members about the new pinned // message. Notifications are always disabled in channels and private chats. DisableNotification OptBool `json:"disable_notification"` } // This object contains information about a poll. // Ref: #/components/schemas/Poll type Poll struct { // Unique poll identifier. ID string `json:"id"` // Poll question, 1-300 characters. Question string `json:"question"` // List of poll options. Options []PollOption `json:"options"` // Total number of users that voted in the poll. TotalVoterCount int `json:"total_voter_count"` // True, if the poll is closed. IsClosed bool `json:"is_closed"` // True, if the poll is anonymous. IsAnonymous bool `json:"is_anonymous"` // Poll type, currently can be “regular” or “quiz”. Type string `json:"type"` // True, if the poll allows multiple answers. AllowsMultipleAnswers bool `json:"allows_multiple_answers"` // 0-based identifier of the correct answer option. Available only for polls in the quiz mode, which // are closed, or was sent (not forwarded) by the bot or to the private chat with the bot. CorrectOptionID OptInt `json:"correct_option_id"` // Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a // quiz-style poll, 0-200 characters. Explanation OptString `json:"explanation"` // Special entities like usernames, URLs, bot commands, etc. that appear in the explanation. ExplanationEntities []MessageEntity `json:"explanation_entities"` // Amount of time in seconds the poll will be active after creation. OpenPeriod OptInt `json:"open_period"` // Point in time (Unix timestamp) when the poll will be automatically closed. CloseDate OptInt `json:"close_date"` } // This object contains information about one answer option in a poll. // Ref: #/components/schemas/PollOption type PollOption struct { // Option text, 1-100 characters. Text string `json:"text"` // Number of users that voted for this option. VoterCount int `json:"voter_count"` } // Input for promoteChatMember. // Ref: #/components/schemas/promoteChatMember type PromoteChatMember struct { ChatID ID `json:"chat_id"` // Unique identifier of the target user. UserID int `json:"user_id"` // Pass True, if the administrator's presence in the chat is hidden. IsAnonymous OptBool `json:"is_anonymous"` // Pass True, if the administrator can access the chat event log, chat statistics, message statistics // in channels, see channel members, see anonymous administrators in supergroups and ignore slow mode. // Implied by any other administrator privilege. CanManageChat OptBool `json:"can_manage_chat"` // Pass True, if the administrator can create channel posts, channels only. CanPostMessages OptBool `json:"can_post_messages"` // Pass True, if the administrator can edit messages of other users and can pin messages, channels // only. CanEditMessages OptBool `json:"can_edit_messages"` // Pass True, if the administrator can delete messages of other users. CanDeleteMessages OptBool `json:"can_delete_messages"` // Pass True, if the administrator can manage voice chats. CanManageVoiceChats OptBool `json:"can_manage_voice_chats"` // Pass True, if the administrator can restrict, ban or unban chat members. CanRestrictMembers OptBool `json:"can_restrict_members"` // Pass True, if the administrator can add new administrators with a subset of their own privileges // or demote administrators that he has promoted, directly or indirectly (promoted by administrators // that were appointed by him). CanPromoteMembers OptBool `json:"can_promote_members"` // Pass True, if the administrator can change chat title, photo and other settings. CanChangeInfo OptBool `json:"can_change_info"` // Pass True, if the administrator can invite new users to the chat. CanInviteUsers OptBool `json:"can_invite_users"` // Pass True, if the administrator can pin messages, supergroups only. CanPinMessages OptBool `json:"can_pin_messages"` } // This object represents the content of a service message, sent whenever a user in the chat triggers // a proximity alert set by another user. // Ref: #/components/schemas/ProximityAlertTriggered type ProximityAlertTriggered struct { Traveler User `json:"traveler"` Watcher User `json:"watcher"` // The distance between the users. Distance int `json:"distance"` } // This object represents a custom keyboard with reply options (see Introduction to bots for details // and examples). // Ref: #/components/schemas/ReplyKeyboardMarkup type ReplyKeyboardMarkup struct { // Array of button rows, each represented by an Array of KeyboardButton objects. Keyboard [][]KeyboardButton `json:"keyboard"` // Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard // smaller if there are just two rows of buttons). Defaults to false, in which case the custom // keyboard is always of the same height as the app's standard keyboard. ResizeKeyboard OptBool `json:"resize_keyboard"` // Requests clients to hide the keyboard as soon as it's been used. The keyboard will still be // available, but clients will automatically display the usual letter-keyboard in the chat – the // user can press a special button in the input field to see the custom keyboard again. Defaults to // false. OneTimeKeyboard OptBool `json:"one_time_keyboard"` // The placeholder to be shown in the input field when the keyboard is active; 1-64 characters. InputFieldPlaceholder OptString `json:"input_field_placeholder"` // Use this parameter if you want to show the keyboard to specific users only. Targets: 1) users that // are @mentioned in the text of the Message object; 2) if the bot's message is a reply (has // reply_to_message_id), sender of the original message.Example: A user requests to change the bot's // language, bot replies to the request with a keyboard to select the new language. Other users in // the group don't see the keyboard. Selective OptBool `json:"selective"` } // Upon receiving a message with this object, Telegram clients will remove the current custom // keyboard and display the default letter-keyboard. By default, custom keyboards are displayed until // a new keyboard is sent by a bot. An exception is made for one-time keyboards that are hidden // immediately after the user presses a button (see ReplyKeyboardMarkup). // Ref: #/components/schemas/ReplyKeyboardRemove type ReplyKeyboardRemove struct { // Requests clients to remove the custom keyboard (user will not be able to summon this keyboard; if // you want to hide the keyboard from sight but keep it accessible, use one_time_keyboard in // ReplyKeyboardMarkup). RemoveKeyboard bool `json:"remove_keyboard"` // Use this parameter if you want to remove the keyboard for specific users only. Targets: 1) users // that are @mentioned in the text of the Message object; 2) if the bot's message is a reply (has // reply_to_message_id), sender of the original message.Example: A user votes in a poll, bot returns // confirmation message in reply to the vote and removes the keyboard for that user, while still // showing the keyboard with poll options to users who haven't voted yet. Selective OptBool `json:"selective"` } // Contains information about why a request was unsuccessful. // Ref: #/components/schemas/Response type Response struct { // The group has been migrated to a supergroup with the specified identifier. This number may be // greater than 32 bits and some programming languages may have difficulty/silent defects in // interpreting it. But it is smaller than 52 bits, so a signed 64 bit integer or double-precision // float type are safe for storing this identifier. MigrateToChatID OptInt64 `json:"migrate_to_chat_id"` // In case of exceeding flood control, the number of seconds left to wait before the request can be // repeated. RetryAfter OptInt `json:"retry_after"` } // Input for restrictChatMember. // Ref: #/components/schemas/restrictChatMember type RestrictChatMember struct { ChatID ID `json:"chat_id"` // Unique identifier of the target user. UserID int `json:"user_id"` Permissions ChatPermissions `json:"permissions"` // Date when restrictions will be lifted for the user, unix time. If user is restricted for more than // 366 days or less than 30 seconds from the current time, they are considered to be restricted // forever. UntilDate OptInt `json:"until_date"` } // Ref: #/components/schemas/Result type Result struct { Result OptBool `json:"result"` Ok bool `json:"ok"` } // Ref: #/components/schemas/ResultMsg type ResultMsg struct { Result OptMessage `json:"result"` Ok bool `json:"ok"` } // Ref: #/components/schemas/ResultUsr type ResultUsr struct { Result OptUser `json:"result"` Ok bool `json:"ok"` } // Input for revokeChatInviteLink. // Ref: #/components/schemas/revokeChatInviteLink type RevokeChatInviteLink struct { ChatID ID `json:"chat_id"` // The invite link to revoke. InviteLink string `json:"invite_link"` } // Input for sendAnimation. // Ref: #/components/schemas/sendAnimation type SendAnimation struct { ChatID ID `json:"chat_id"` // Animation to send. Pass a file_id as String to send an animation that exists on the Telegram // servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the // Internet, or upload a new animation using multipart/form-data. More info on Sending Files ». Animation string `json:"animation"` // Duration of sent animation in seconds. Duration OptInt `json:"duration"` // Animation width. Width OptInt `json:"width"` // Animation height. Height OptInt `json:"height"` // Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported // server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's // width and height should not exceed 320. Ignored if the file is not uploaded using // multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can // pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data // under <file_attach_name>. More info on Sending Files ». Thumb OptString `json:"thumb"` // Animation caption (may also be used when resending animation by file_id), 0-1024 characters after // entities parsing. Caption OptString `json:"caption"` // Mode for parsing entities in the animation caption. See formatting options for more details. ParseMode OptString `json:"parse_mode"` // A JSON-serialized list of special entities that appear in the caption, which can be specified // instead of parse_mode. CaptionEntities []MessageEntity `json:"caption_entities"` // Sends the message silently. Users will receive a notification with no sound. DisableNotification OptBool `json:"disable_notification"` // If the message is a reply, ID of the original message. ReplyToMessageID OptInt `json:"reply_to_message_id"` // Pass True, if the message should be sent even if the specified replied-to message is not found. AllowSendingWithoutReply OptBool `json:"allow_sending_without_reply"` // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply // keyboard, instructions to remove reply keyboard or to force a reply from the user. ReplyMarkup OptSendAnimationReplyMarkup `json:"reply_markup"` } // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply // keyboard, instructions to remove reply keyboard or to force a reply from the user. // SendAnimationReplyMarkup represents sum type. type SendAnimationReplyMarkup struct { Type SendAnimationReplyMarkupType // switch on this field InlineKeyboardMarkup InlineKeyboardMarkup ReplyKeyboardMarkup ReplyKeyboardMarkup ReplyKeyboardRemove ReplyKeyboardRemove ForceReply ForceReply } // SendAnimationReplyMarkupType is oneOf type of SendAnimationReplyMarkup. type SendAnimationReplyMarkupType string // Possible values for SendAnimationReplyMarkupType. const ( InlineKeyboardMarkupSendAnimationReplyMarkup SendAnimationReplyMarkupType = "InlineKeyboardMarkup" ReplyKeyboardMarkupSendAnimationReplyMarkup SendAnimationReplyMarkupType = "ReplyKeyboardMarkup" ReplyKeyboardRemoveSendAnimationReplyMarkup SendAnimationReplyMarkupType = "ReplyKeyboardRemove" ForceReplySendAnimationReplyMarkup SendAnimationReplyMarkupType = "ForceReply" ) // IsInlineKeyboardMarkup reports whether SendAnimationReplyMarkup is InlineKeyboardMarkup. func (s SendAnimationReplyMarkup) IsInlineKeyboardMarkup() bool { return s.Type == InlineKeyboardMarkupSendAnimationReplyMarkup } // IsReplyKeyboardMarkup reports whether SendAnimationReplyMarkup is ReplyKeyboardMarkup. func (s SendAnimationReplyMarkup) IsReplyKeyboardMarkup() bool { return s.Type == ReplyKeyboardMarkupSendAnimationReplyMarkup } // IsReplyKeyboardRemove reports whether SendAnimationReplyMarkup is ReplyKeyboardRemove. func (s SendAnimationReplyMarkup) IsReplyKeyboardRemove() bool { return s.Type == ReplyKeyboardRemoveSendAnimationReplyMarkup } // IsForceReply reports whether SendAnimationReplyMarkup is ForceReply. func (s SendAnimationReplyMarkup) IsForceReply() bool { return s.Type == ForceReplySendAnimationReplyMarkup } // SetInlineKeyboardMarkup sets SendAnimationReplyMarkup to InlineKeyboardMarkup. func (s *SendAnimationReplyMarkup) SetInlineKeyboardMarkup(v InlineKeyboardMarkup) { s.Type = InlineKeyboardMarkupSendAnimationReplyMarkup s.InlineKeyboardMarkup = v } // GetInlineKeyboardMarkup returns InlineKeyboardMarkup and true boolean if SendAnimationReplyMarkup is InlineKeyboardMarkup. func (s SendAnimationReplyMarkup) GetInlineKeyboardMarkup() (v InlineKeyboardMarkup, ok bool) { if !s.IsInlineKeyboardMarkup() { return v, false } return s.InlineKeyboardMarkup, true } // NewInlineKeyboardMarkupSendAnimationReplyMarkup returns new SendAnimationReplyMarkup from InlineKeyboardMarkup. func NewInlineKeyboardMarkupSendAnimationReplyMarkup(v InlineKeyboardMarkup) SendAnimationReplyMarkup { var s SendAnimationReplyMarkup s.SetInlineKeyboardMarkup(v) return s } // SetReplyKeyboardMarkup sets SendAnimationReplyMarkup to ReplyKeyboardMarkup. func (s *SendAnimationReplyMarkup) SetReplyKeyboardMarkup(v ReplyKeyboardMarkup) { s.Type = ReplyKeyboardMarkupSendAnimationReplyMarkup s.ReplyKeyboardMarkup = v } // GetReplyKeyboardMarkup returns ReplyKeyboardMarkup and true boolean if SendAnimationReplyMarkup is ReplyKeyboardMarkup. func (s SendAnimationReplyMarkup) GetReplyKeyboardMarkup() (v ReplyKeyboardMarkup, ok bool) { if !s.IsReplyKeyboardMarkup() { return v, false } return s.ReplyKeyboardMarkup, true } // NewReplyKeyboardMarkupSendAnimationReplyMarkup returns new SendAnimationReplyMarkup from ReplyKeyboardMarkup. func NewReplyKeyboardMarkupSendAnimationReplyMarkup(v ReplyKeyboardMarkup) SendAnimationReplyMarkup { var s SendAnimationReplyMarkup s.SetReplyKeyboardMarkup(v) return s } // SetReplyKeyboardRemove sets SendAnimationReplyMarkup to ReplyKeyboardRemove. func (s *SendAnimationReplyMarkup) SetReplyKeyboardRemove(v ReplyKeyboardRemove) { s.Type = ReplyKeyboardRemoveSendAnimationReplyMarkup s.ReplyKeyboardRemove = v } // GetReplyKeyboardRemove returns ReplyKeyboardRemove and true boolean if SendAnimationReplyMarkup is ReplyKeyboardRemove. func (s SendAnimationReplyMarkup) GetReplyKeyboardRemove() (v ReplyKeyboardRemove, ok bool) { if !s.IsReplyKeyboardRemove() { return v, false } return s.ReplyKeyboardRemove, true } // NewReplyKeyboardRemoveSendAnimationReplyMarkup returns new SendAnimationReplyMarkup from ReplyKeyboardRemove. func NewReplyKeyboardRemoveSendAnimationReplyMarkup(v ReplyKeyboardRemove) SendAnimationReplyMarkup { var s SendAnimationReplyMarkup s.SetReplyKeyboardRemove(v) return s } // SetForceReply sets SendAnimationReplyMarkup to ForceReply. func (s *SendAnimationReplyMarkup) SetForceReply(v ForceReply) { s.Type = ForceReplySendAnimationReplyMarkup s.ForceReply = v } // GetForceReply returns ForceReply and true boolean if SendAnimationReplyMarkup is ForceReply. func (s SendAnimationReplyMarkup) GetForceReply() (v ForceReply, ok bool) { if !s.IsForceReply() { return v, false } return s.ForceReply, true } // NewForceReplySendAnimationReplyMarkup returns new SendAnimationReplyMarkup from ForceReply. func NewForceReplySendAnimationReplyMarkup(v ForceReply) SendAnimationReplyMarkup { var s SendAnimationReplyMarkup s.SetForceReply(v) return s } // Input for sendAudio. // Ref: #/components/schemas/sendAudio type SendAudio struct { ChatID ID `json:"chat_id"` // Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram // servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the // Internet, or upload a new one using multipart/form-data. More info on Sending Files ». Audio string `json:"audio"` // Audio caption, 0-1024 characters after entities parsing. Caption OptString `json:"caption"` // Mode for parsing entities in the audio caption. See formatting options for more details. ParseMode OptString `json:"parse_mode"` // A JSON-serialized list of special entities that appear in the caption, which can be specified // instead of parse_mode. CaptionEntities []MessageEntity `json:"caption_entities"` // Duration of the audio in seconds. Duration OptInt `json:"duration"` // Performer. Performer OptString `json:"performer"` // Track name. Title OptString `json:"title"` // Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported // server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's // width and height should not exceed 320. Ignored if the file is not uploaded using // multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can // pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data // under <file_attach_name>. More info on Sending Files ». Thumb OptString `json:"thumb"` // Sends the message silently. Users will receive a notification with no sound. DisableNotification OptBool `json:"disable_notification"` // If the message is a reply, ID of the original message. ReplyToMessageID OptInt `json:"reply_to_message_id"` // Pass True, if the message should be sent even if the specified replied-to message is not found. AllowSendingWithoutReply OptBool `json:"allow_sending_without_reply"` // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply // keyboard, instructions to remove reply keyboard or to force a reply from the user. ReplyMarkup OptSendAudioReplyMarkup `json:"reply_markup"` } // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply // keyboard, instructions to remove reply keyboard or to force a reply from the user. // SendAudioReplyMarkup represents sum type. type SendAudioReplyMarkup struct { Type SendAudioReplyMarkupType // switch on this field InlineKeyboardMarkup InlineKeyboardMarkup ReplyKeyboardMarkup ReplyKeyboardMarkup ReplyKeyboardRemove ReplyKeyboardRemove ForceReply ForceReply } // SendAudioReplyMarkupType is oneOf type of SendAudioReplyMarkup. type SendAudioReplyMarkupType string // Possible values for SendAudioReplyMarkupType. const ( InlineKeyboardMarkupSendAudioReplyMarkup SendAudioReplyMarkupType = "InlineKeyboardMarkup" ReplyKeyboardMarkupSendAudioReplyMarkup SendAudioReplyMarkupType = "ReplyKeyboardMarkup" ReplyKeyboardRemoveSendAudioReplyMarkup SendAudioReplyMarkupType = "ReplyKeyboardRemove" ForceReplySendAudioReplyMarkup SendAudioReplyMarkupType = "ForceReply" ) // IsInlineKeyboardMarkup reports whether SendAudioReplyMarkup is InlineKeyboardMarkup. func (s SendAudioReplyMarkup) IsInlineKeyboardMarkup() bool { return s.Type == InlineKeyboardMarkupSendAudioReplyMarkup } // IsReplyKeyboardMarkup reports whether SendAudioReplyMarkup is ReplyKeyboardMarkup. func (s SendAudioReplyMarkup) IsReplyKeyboardMarkup() bool { return s.Type == ReplyKeyboardMarkupSendAudioReplyMarkup } // IsReplyKeyboardRemove reports whether SendAudioReplyMarkup is ReplyKeyboardRemove. func (s SendAudioReplyMarkup) IsReplyKeyboardRemove() bool { return s.Type == ReplyKeyboardRemoveSendAudioReplyMarkup } // IsForceReply reports whether SendAudioReplyMarkup is ForceReply. func (s SendAudioReplyMarkup) IsForceReply() bool { return s.Type == ForceReplySendAudioReplyMarkup } // SetInlineKeyboardMarkup sets SendAudioReplyMarkup to InlineKeyboardMarkup. func (s *SendAudioReplyMarkup) SetInlineKeyboardMarkup(v InlineKeyboardMarkup) { s.Type = InlineKeyboardMarkupSendAudioReplyMarkup s.InlineKeyboardMarkup = v } // GetInlineKeyboardMarkup returns InlineKeyboardMarkup and true boolean if SendAudioReplyMarkup is InlineKeyboardMarkup. func (s SendAudioReplyMarkup) GetInlineKeyboardMarkup() (v InlineKeyboardMarkup, ok bool) { if !s.IsInlineKeyboardMarkup() { return v, false } return s.InlineKeyboardMarkup, true } // NewInlineKeyboardMarkupSendAudioReplyMarkup returns new SendAudioReplyMarkup from InlineKeyboardMarkup. func NewInlineKeyboardMarkupSendAudioReplyMarkup(v InlineKeyboardMarkup) SendAudioReplyMarkup { var s SendAudioReplyMarkup s.SetInlineKeyboardMarkup(v) return s } // SetReplyKeyboardMarkup sets SendAudioReplyMarkup to ReplyKeyboardMarkup. func (s *SendAudioReplyMarkup) SetReplyKeyboardMarkup(v ReplyKeyboardMarkup) { s.Type = ReplyKeyboardMarkupSendAudioReplyMarkup s.ReplyKeyboardMarkup = v } // GetReplyKeyboardMarkup returns ReplyKeyboardMarkup and true boolean if SendAudioReplyMarkup is ReplyKeyboardMarkup. func (s SendAudioReplyMarkup) GetReplyKeyboardMarkup() (v ReplyKeyboardMarkup, ok bool) { if !s.IsReplyKeyboardMarkup() { return v, false } return s.ReplyKeyboardMarkup, true } // NewReplyKeyboardMarkupSendAudioReplyMarkup returns new SendAudioReplyMarkup from ReplyKeyboardMarkup. func NewReplyKeyboardMarkupSendAudioReplyMarkup(v ReplyKeyboardMarkup) SendAudioReplyMarkup { var s SendAudioReplyMarkup s.SetReplyKeyboardMarkup(v) return s } // SetReplyKeyboardRemove sets SendAudioReplyMarkup to ReplyKeyboardRemove. func (s *SendAudioReplyMarkup) SetReplyKeyboardRemove(v ReplyKeyboardRemove) { s.Type = ReplyKeyboardRemoveSendAudioReplyMarkup s.ReplyKeyboardRemove = v } // GetReplyKeyboardRemove returns ReplyKeyboardRemove and true boolean if SendAudioReplyMarkup is ReplyKeyboardRemove. func (s SendAudioReplyMarkup) GetReplyKeyboardRemove() (v ReplyKeyboardRemove, ok bool) { if !s.IsReplyKeyboardRemove() { return v, false } return s.ReplyKeyboardRemove, true } // NewReplyKeyboardRemoveSendAudioReplyMarkup returns new SendAudioReplyMarkup from ReplyKeyboardRemove. func NewReplyKeyboardRemoveSendAudioReplyMarkup(v ReplyKeyboardRemove) SendAudioReplyMarkup { var s SendAudioReplyMarkup s.SetReplyKeyboardRemove(v) return s } // SetForceReply sets SendAudioReplyMarkup to ForceReply. func (s *SendAudioReplyMarkup) SetForceReply(v ForceReply) { s.Type = ForceReplySendAudioReplyMarkup s.ForceReply = v } // GetForceReply returns ForceReply and true boolean if SendAudioReplyMarkup is ForceReply. func (s SendAudioReplyMarkup) GetForceReply() (v ForceReply, ok bool) { if !s.IsForceReply() { return v, false } return s.ForceReply, true } // NewForceReplySendAudioReplyMarkup returns new SendAudioReplyMarkup from ForceReply. func NewForceReplySendAudioReplyMarkup(v ForceReply) SendAudioReplyMarkup { var s SendAudioReplyMarkup s.SetForceReply(v) return s } // Input for sendChatAction. // Ref: #/components/schemas/sendChatAction type SendChatAction struct { ChatID ID `json:"chat_id"` // Type of action to broadcast. Choose one, depending on what the user is about to receive: typing // for text messages, upload_photo for photos, record_video or upload_video for videos, record_voice // or upload_voice for voice notes, upload_document for general files, choose_sticker for stickers, // find_location for location data, record_video_note or upload_video_note for video notes. Action string `json:"action"` } // Input for sendContact. // Ref: #/components/schemas/sendContact type SendContact struct { ChatID ID `json:"chat_id"` // Contact's phone number. PhoneNumber string `json:"phone_number"` // Contact's first name. FirstName string `json:"first_name"` // Contact's last name. LastName OptString `json:"last_name"` // Additional data about the contact in the form of a vCard, 0-2048 bytes. Vcard OptString `json:"vcard"` // Sends the message silently. Users will receive a notification with no sound. DisableNotification OptBool `json:"disable_notification"` // If the message is a reply, ID of the original message. ReplyToMessageID OptInt `json:"reply_to_message_id"` // Pass True, if the message should be sent even if the specified replied-to message is not found. AllowSendingWithoutReply OptBool `json:"allow_sending_without_reply"` // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply // keyboard, instructions to remove keyboard or to force a reply from the user. ReplyMarkup OptSendContactReplyMarkup `json:"reply_markup"` } // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply // keyboard, instructions to remove keyboard or to force a reply from the user. // SendContactReplyMarkup represents sum type. type SendContactReplyMarkup struct { Type SendContactReplyMarkupType // switch on this field InlineKeyboardMarkup InlineKeyboardMarkup ReplyKeyboardMarkup ReplyKeyboardMarkup ReplyKeyboardRemove ReplyKeyboardRemove ForceReply ForceReply } // SendContactReplyMarkupType is oneOf type of SendContactReplyMarkup. type SendContactReplyMarkupType string // Possible values for SendContactReplyMarkupType. const ( InlineKeyboardMarkupSendContactReplyMarkup SendContactReplyMarkupType = "InlineKeyboardMarkup" ReplyKeyboardMarkupSendContactReplyMarkup SendContactReplyMarkupType = "ReplyKeyboardMarkup" ReplyKeyboardRemoveSendContactReplyMarkup SendContactReplyMarkupType = "ReplyKeyboardRemove" ForceReplySendContactReplyMarkup SendContactReplyMarkupType = "ForceReply" ) // IsInlineKeyboardMarkup reports whether SendContactReplyMarkup is InlineKeyboardMarkup. func (s SendContactReplyMarkup) IsInlineKeyboardMarkup() bool { return s.Type == InlineKeyboardMarkupSendContactReplyMarkup } // IsReplyKeyboardMarkup reports whether SendContactReplyMarkup is ReplyKeyboardMarkup. func (s SendContactReplyMarkup) IsReplyKeyboardMarkup() bool { return s.Type == ReplyKeyboardMarkupSendContactReplyMarkup } // IsReplyKeyboardRemove reports whether SendContactReplyMarkup is ReplyKeyboardRemove. func (s SendContactReplyMarkup) IsReplyKeyboardRemove() bool { return s.Type == ReplyKeyboardRemoveSendContactReplyMarkup } // IsForceReply reports whether SendContactReplyMarkup is ForceReply. func (s SendContactReplyMarkup) IsForceReply() bool { return s.Type == ForceReplySendContactReplyMarkup } // SetInlineKeyboardMarkup sets SendContactReplyMarkup to InlineKeyboardMarkup. func (s *SendContactReplyMarkup) SetInlineKeyboardMarkup(v InlineKeyboardMarkup) { s.Type = InlineKeyboardMarkupSendContactReplyMarkup s.InlineKeyboardMarkup = v } // GetInlineKeyboardMarkup returns InlineKeyboardMarkup and true boolean if SendContactReplyMarkup is InlineKeyboardMarkup. func (s SendContactReplyMarkup) GetInlineKeyboardMarkup() (v InlineKeyboardMarkup, ok bool) { if !s.IsInlineKeyboardMarkup() { return v, false } return s.InlineKeyboardMarkup, true } // NewInlineKeyboardMarkupSendContactReplyMarkup returns new SendContactReplyMarkup from InlineKeyboardMarkup. func NewInlineKeyboardMarkupSendContactReplyMarkup(v InlineKeyboardMarkup) SendContactReplyMarkup { var s SendContactReplyMarkup s.SetInlineKeyboardMarkup(v) return s } // SetReplyKeyboardMarkup sets SendContactReplyMarkup to ReplyKeyboardMarkup. func (s *SendContactReplyMarkup) SetReplyKeyboardMarkup(v ReplyKeyboardMarkup) { s.Type = ReplyKeyboardMarkupSendContactReplyMarkup s.ReplyKeyboardMarkup = v } // GetReplyKeyboardMarkup returns ReplyKeyboardMarkup and true boolean if SendContactReplyMarkup is ReplyKeyboardMarkup. func (s SendContactReplyMarkup) GetReplyKeyboardMarkup() (v ReplyKeyboardMarkup, ok bool) { if !s.IsReplyKeyboardMarkup() { return v, false } return s.ReplyKeyboardMarkup, true } // NewReplyKeyboardMarkupSendContactReplyMarkup returns new SendContactReplyMarkup from ReplyKeyboardMarkup. func NewReplyKeyboardMarkupSendContactReplyMarkup(v ReplyKeyboardMarkup) SendContactReplyMarkup { var s SendContactReplyMarkup s.SetReplyKeyboardMarkup(v) return s } // SetReplyKeyboardRemove sets SendContactReplyMarkup to ReplyKeyboardRemove. func (s *SendContactReplyMarkup) SetReplyKeyboardRemove(v ReplyKeyboardRemove) { s.Type = ReplyKeyboardRemoveSendContactReplyMarkup s.ReplyKeyboardRemove = v } // GetReplyKeyboardRemove returns ReplyKeyboardRemove and true boolean if SendContactReplyMarkup is ReplyKeyboardRemove. func (s SendContactReplyMarkup) GetReplyKeyboardRemove() (v ReplyKeyboardRemove, ok bool) { if !s.IsReplyKeyboardRemove() { return v, false } return s.ReplyKeyboardRemove, true } // NewReplyKeyboardRemoveSendContactReplyMarkup returns new SendContactReplyMarkup from ReplyKeyboardRemove. func NewReplyKeyboardRemoveSendContactReplyMarkup(v ReplyKeyboardRemove) SendContactReplyMarkup { var s SendContactReplyMarkup s.SetReplyKeyboardRemove(v) return s } // SetForceReply sets SendContactReplyMarkup to ForceReply. func (s *SendContactReplyMarkup) SetForceReply(v ForceReply) { s.Type = ForceReplySendContactReplyMarkup s.ForceReply = v } // GetForceReply returns ForceReply and true boolean if SendContactReplyMarkup is ForceReply. func (s SendContactReplyMarkup) GetForceReply() (v ForceReply, ok bool) { if !s.IsForceReply() { return v, false } return s.ForceReply, true } // NewForceReplySendContactReplyMarkup returns new SendContactReplyMarkup from ForceReply. func NewForceReplySendContactReplyMarkup(v ForceReply) SendContactReplyMarkup { var s SendContactReplyMarkup s.SetForceReply(v) return s } // Input for sendDice. // Ref: #/components/schemas/sendDice type SendDice struct { ChatID ID `json:"chat_id"` // Emoji on which the dice throw animation is based. Currently, must be one of “”, “”, “”, // “”, “”, or “”. Dice can have values 1-6 for “”, “” and “”, values 1-5 for // “” and “”, and values 1-64 for “”. Defaults to “”. Emoji OptString `json:"emoji"` // Sends the message silently. Users will receive a notification with no sound. DisableNotification OptBool `json:"disable_notification"` // If the message is a reply, ID of the original message. ReplyToMessageID OptInt `json:"reply_to_message_id"` // Pass True, if the message should be sent even if the specified replied-to message is not found. AllowSendingWithoutReply OptBool `json:"allow_sending_without_reply"` // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply // keyboard, instructions to remove reply keyboard or to force a reply from the user. ReplyMarkup OptSendDiceReplyMarkup `json:"reply_markup"` } // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply // keyboard, instructions to remove reply keyboard or to force a reply from the user. // SendDiceReplyMarkup represents sum type. type SendDiceReplyMarkup struct { Type SendDiceReplyMarkupType // switch on this field InlineKeyboardMarkup InlineKeyboardMarkup ReplyKeyboardMarkup ReplyKeyboardMarkup ReplyKeyboardRemove ReplyKeyboardRemove ForceReply ForceReply } // SendDiceReplyMarkupType is oneOf type of SendDiceReplyMarkup. type SendDiceReplyMarkupType string // Possible values for SendDiceReplyMarkupType. const ( InlineKeyboardMarkupSendDiceReplyMarkup SendDiceReplyMarkupType = "InlineKeyboardMarkup" ReplyKeyboardMarkupSendDiceReplyMarkup SendDiceReplyMarkupType = "ReplyKeyboardMarkup" ReplyKeyboardRemoveSendDiceReplyMarkup SendDiceReplyMarkupType = "ReplyKeyboardRemove" ForceReplySendDiceReplyMarkup SendDiceReplyMarkupType = "ForceReply" ) // IsInlineKeyboardMarkup reports whether SendDiceReplyMarkup is InlineKeyboardMarkup. func (s SendDiceReplyMarkup) IsInlineKeyboardMarkup() bool { return s.Type == InlineKeyboardMarkupSendDiceReplyMarkup } // IsReplyKeyboardMarkup reports whether SendDiceReplyMarkup is ReplyKeyboardMarkup. func (s SendDiceReplyMarkup) IsReplyKeyboardMarkup() bool { return s.Type == ReplyKeyboardMarkupSendDiceReplyMarkup } // IsReplyKeyboardRemove reports whether SendDiceReplyMarkup is ReplyKeyboardRemove. func (s SendDiceReplyMarkup) IsReplyKeyboardRemove() bool { return s.Type == ReplyKeyboardRemoveSendDiceReplyMarkup } // IsForceReply reports whether SendDiceReplyMarkup is ForceReply. func (s SendDiceReplyMarkup) IsForceReply() bool { return s.Type == ForceReplySendDiceReplyMarkup } // SetInlineKeyboardMarkup sets SendDiceReplyMarkup to InlineKeyboardMarkup. func (s *SendDiceReplyMarkup) SetInlineKeyboardMarkup(v InlineKeyboardMarkup) { s.Type = InlineKeyboardMarkupSendDiceReplyMarkup s.InlineKeyboardMarkup = v } // GetInlineKeyboardMarkup returns InlineKeyboardMarkup and true boolean if SendDiceReplyMarkup is InlineKeyboardMarkup. func (s SendDiceReplyMarkup) GetInlineKeyboardMarkup() (v InlineKeyboardMarkup, ok bool) { if !s.IsInlineKeyboardMarkup() { return v, false } return s.InlineKeyboardMarkup, true } // NewInlineKeyboardMarkupSendDiceReplyMarkup returns new SendDiceReplyMarkup from InlineKeyboardMarkup. func NewInlineKeyboardMarkupSendDiceReplyMarkup(v InlineKeyboardMarkup) SendDiceReplyMarkup { var s SendDiceReplyMarkup s.SetInlineKeyboardMarkup(v) return s } // SetReplyKeyboardMarkup sets SendDiceReplyMarkup to ReplyKeyboardMarkup. func (s *SendDiceReplyMarkup) SetReplyKeyboardMarkup(v ReplyKeyboardMarkup) { s.Type = ReplyKeyboardMarkupSendDiceReplyMarkup s.ReplyKeyboardMarkup = v } // GetReplyKeyboardMarkup returns ReplyKeyboardMarkup and true boolean if SendDiceReplyMarkup is ReplyKeyboardMarkup. func (s SendDiceReplyMarkup) GetReplyKeyboardMarkup() (v ReplyKeyboardMarkup, ok bool) { if !s.IsReplyKeyboardMarkup() { return v, false } return s.ReplyKeyboardMarkup, true } // NewReplyKeyboardMarkupSendDiceReplyMarkup returns new SendDiceReplyMarkup from ReplyKeyboardMarkup. func NewReplyKeyboardMarkupSendDiceReplyMarkup(v ReplyKeyboardMarkup) SendDiceReplyMarkup { var s SendDiceReplyMarkup s.SetReplyKeyboardMarkup(v) return s } // SetReplyKeyboardRemove sets SendDiceReplyMarkup to ReplyKeyboardRemove. func (s *SendDiceReplyMarkup) SetReplyKeyboardRemove(v ReplyKeyboardRemove) { s.Type = ReplyKeyboardRemoveSendDiceReplyMarkup s.ReplyKeyboardRemove = v } // GetReplyKeyboardRemove returns ReplyKeyboardRemove and true boolean if SendDiceReplyMarkup is ReplyKeyboardRemove. func (s SendDiceReplyMarkup) GetReplyKeyboardRemove() (v ReplyKeyboardRemove, ok bool) { if !s.IsReplyKeyboardRemove() { return v, false } return s.ReplyKeyboardRemove, true } // NewReplyKeyboardRemoveSendDiceReplyMarkup returns new SendDiceReplyMarkup from ReplyKeyboardRemove. func NewReplyKeyboardRemoveSendDiceReplyMarkup(v ReplyKeyboardRemove) SendDiceReplyMarkup { var s SendDiceReplyMarkup s.SetReplyKeyboardRemove(v) return s } // SetForceReply sets SendDiceReplyMarkup to ForceReply. func (s *SendDiceReplyMarkup) SetForceReply(v ForceReply) { s.Type = ForceReplySendDiceReplyMarkup s.ForceReply = v } // GetForceReply returns ForceReply and true boolean if SendDiceReplyMarkup is ForceReply. func (s SendDiceReplyMarkup) GetForceReply() (v ForceReply, ok bool) { if !s.IsForceReply() { return v, false } return s.ForceReply, true } // NewForceReplySendDiceReplyMarkup returns new SendDiceReplyMarkup from ForceReply. func NewForceReplySendDiceReplyMarkup(v ForceReply) SendDiceReplyMarkup { var s SendDiceReplyMarkup s.SetForceReply(v) return s } // Input for sendDocument. // Ref: #/components/schemas/sendDocument type SendDocument struct { ChatID ID `json:"chat_id"` // File to send. Pass a file_id as String to send a file that exists on the Telegram servers // (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or // upload a new one using multipart/form-data. More info on Sending Files ». Document string `json:"document"` // Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported // server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's // width and height should not exceed 320. Ignored if the file is not uploaded using // multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can // pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data // under <file_attach_name>. More info on Sending Files ». Thumb OptString `json:"thumb"` // Document caption (may also be used when resending documents by file_id), 0-1024 characters after // entities parsing. Caption OptString `json:"caption"` // Mode for parsing entities in the document caption. See formatting options for more details. ParseMode OptString `json:"parse_mode"` // A JSON-serialized list of special entities that appear in the caption, which can be specified // instead of parse_mode. CaptionEntities []MessageEntity `json:"caption_entities"` // Disables automatic server-side content type detection for files uploaded using multipart/form-data. DisableContentTypeDetection OptBool `json:"disable_content_type_detection"` // Sends the message silently. Users will receive a notification with no sound. DisableNotification OptBool `json:"disable_notification"` // If the message is a reply, ID of the original message. ReplyToMessageID OptInt `json:"reply_to_message_id"` // Pass True, if the message should be sent even if the specified replied-to message is not found. AllowSendingWithoutReply OptBool `json:"allow_sending_without_reply"` // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply // keyboard, instructions to remove reply keyboard or to force a reply from the user. ReplyMarkup OptSendDocumentReplyMarkup `json:"reply_markup"` } // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply // keyboard, instructions to remove reply keyboard or to force a reply from the user. // SendDocumentReplyMarkup represents sum type. type SendDocumentReplyMarkup struct { Type SendDocumentReplyMarkupType // switch on this field InlineKeyboardMarkup InlineKeyboardMarkup ReplyKeyboardMarkup ReplyKeyboardMarkup ReplyKeyboardRemove ReplyKeyboardRemove ForceReply ForceReply } // SendDocumentReplyMarkupType is oneOf type of SendDocumentReplyMarkup. type SendDocumentReplyMarkupType string // Possible values for SendDocumentReplyMarkupType. const ( InlineKeyboardMarkupSendDocumentReplyMarkup SendDocumentReplyMarkupType = "InlineKeyboardMarkup" ReplyKeyboardMarkupSendDocumentReplyMarkup SendDocumentReplyMarkupType = "ReplyKeyboardMarkup" ReplyKeyboardRemoveSendDocumentReplyMarkup SendDocumentReplyMarkupType = "ReplyKeyboardRemove" ForceReplySendDocumentReplyMarkup SendDocumentReplyMarkupType = "ForceReply" ) // IsInlineKeyboardMarkup reports whether SendDocumentReplyMarkup is InlineKeyboardMarkup. func (s SendDocumentReplyMarkup) IsInlineKeyboardMarkup() bool { return s.Type == InlineKeyboardMarkupSendDocumentReplyMarkup } // IsReplyKeyboardMarkup reports whether SendDocumentReplyMarkup is ReplyKeyboardMarkup. func (s SendDocumentReplyMarkup) IsReplyKeyboardMarkup() bool { return s.Type == ReplyKeyboardMarkupSendDocumentReplyMarkup } // IsReplyKeyboardRemove reports whether SendDocumentReplyMarkup is ReplyKeyboardRemove. func (s SendDocumentReplyMarkup) IsReplyKeyboardRemove() bool { return s.Type == ReplyKeyboardRemoveSendDocumentReplyMarkup } // IsForceReply reports whether SendDocumentReplyMarkup is ForceReply. func (s SendDocumentReplyMarkup) IsForceReply() bool { return s.Type == ForceReplySendDocumentReplyMarkup } // SetInlineKeyboardMarkup sets SendDocumentReplyMarkup to InlineKeyboardMarkup. func (s *SendDocumentReplyMarkup) SetInlineKeyboardMarkup(v InlineKeyboardMarkup) { s.Type = InlineKeyboardMarkupSendDocumentReplyMarkup s.InlineKeyboardMarkup = v } // GetInlineKeyboardMarkup returns InlineKeyboardMarkup and true boolean if SendDocumentReplyMarkup is InlineKeyboardMarkup. func (s SendDocumentReplyMarkup) GetInlineKeyboardMarkup() (v InlineKeyboardMarkup, ok bool) { if !s.IsInlineKeyboardMarkup() { return v, false } return s.InlineKeyboardMarkup, true } // NewInlineKeyboardMarkupSendDocumentReplyMarkup returns new SendDocumentReplyMarkup from InlineKeyboardMarkup. func NewInlineKeyboardMarkupSendDocumentReplyMarkup(v InlineKeyboardMarkup) SendDocumentReplyMarkup { var s SendDocumentReplyMarkup s.SetInlineKeyboardMarkup(v) return s } // SetReplyKeyboardMarkup sets SendDocumentReplyMarkup to ReplyKeyboardMarkup. func (s *SendDocumentReplyMarkup) SetReplyKeyboardMarkup(v ReplyKeyboardMarkup) { s.Type = ReplyKeyboardMarkupSendDocumentReplyMarkup s.ReplyKeyboardMarkup = v } // GetReplyKeyboardMarkup returns ReplyKeyboardMarkup and true boolean if SendDocumentReplyMarkup is ReplyKeyboardMarkup. func (s SendDocumentReplyMarkup) GetReplyKeyboardMarkup() (v ReplyKeyboardMarkup, ok bool) { if !s.IsReplyKeyboardMarkup() { return v, false } return s.ReplyKeyboardMarkup, true } // NewReplyKeyboardMarkupSendDocumentReplyMarkup returns new SendDocumentReplyMarkup from ReplyKeyboardMarkup. func NewReplyKeyboardMarkupSendDocumentReplyMarkup(v ReplyKeyboardMarkup) SendDocumentReplyMarkup { var s SendDocumentReplyMarkup s.SetReplyKeyboardMarkup(v) return s } // SetReplyKeyboardRemove sets SendDocumentReplyMarkup to ReplyKeyboardRemove. func (s *SendDocumentReplyMarkup) SetReplyKeyboardRemove(v ReplyKeyboardRemove) { s.Type = ReplyKeyboardRemoveSendDocumentReplyMarkup s.ReplyKeyboardRemove = v } // GetReplyKeyboardRemove returns ReplyKeyboardRemove and true boolean if SendDocumentReplyMarkup is ReplyKeyboardRemove. func (s SendDocumentReplyMarkup) GetReplyKeyboardRemove() (v ReplyKeyboardRemove, ok bool) { if !s.IsReplyKeyboardRemove() { return v, false } return s.ReplyKeyboardRemove, true } // NewReplyKeyboardRemoveSendDocumentReplyMarkup returns new SendDocumentReplyMarkup from ReplyKeyboardRemove. func NewReplyKeyboardRemoveSendDocumentReplyMarkup(v ReplyKeyboardRemove) SendDocumentReplyMarkup { var s SendDocumentReplyMarkup s.SetReplyKeyboardRemove(v) return s } // SetForceReply sets SendDocumentReplyMarkup to ForceReply. func (s *SendDocumentReplyMarkup) SetForceReply(v ForceReply) { s.Type = ForceReplySendDocumentReplyMarkup s.ForceReply = v } // GetForceReply returns ForceReply and true boolean if SendDocumentReplyMarkup is ForceReply. func (s SendDocumentReplyMarkup) GetForceReply() (v ForceReply, ok bool) { if !s.IsForceReply() { return v, false } return s.ForceReply, true } // NewForceReplySendDocumentReplyMarkup returns new SendDocumentReplyMarkup from ForceReply. func NewForceReplySendDocumentReplyMarkup(v ForceReply) SendDocumentReplyMarkup { var s SendDocumentReplyMarkup s.SetForceReply(v) return s } // Input for sendGame. // Ref: #/components/schemas/sendGame type SendGame struct { // Unique identifier for the target chat. ChatID int `json:"chat_id"` // Short name of the game, serves as the unique identifier for the game. Set up your games via // Botfather. GameShortName string `json:"game_short_name"` // Sends the message silently. Users will receive a notification with no sound. DisableNotification OptBool `json:"disable_notification"` // If the message is a reply, ID of the original message. ReplyToMessageID OptInt `json:"reply_to_message_id"` // Pass True, if the message should be sent even if the specified replied-to message is not found. AllowSendingWithoutReply OptBool `json:"allow_sending_without_reply"` ReplyMarkup OptInlineKeyboardMarkup `json:"reply_markup"` } // Input for sendInvoice. // Ref: #/components/schemas/sendInvoice type SendInvoice struct { ChatID ID `json:"chat_id"` // Product name, 1-32 characters. Title string `json:"title"` // Product description, 1-255 characters. Description string `json:"description"` // Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your // internal processes. Payload string `json:"payload"` // Payments provider token, obtained via Botfather. ProviderToken string `json:"provider_token"` // Three-letter ISO 4217 currency code, see more on currencies. Currency string `json:"currency"` // Price breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery // cost, delivery tax, bonus, etc.). Prices []LabeledPrice `json:"prices"` // The maximum accepted amount for tips in the smallest units of the currency (integer, not // float/double). For example, for a maximum tip of US$ 1.45 pass max_tip_amount = 145. See the exp // parameter in currencies.json, it shows the number of digits past the decimal point for each // currency (2 for the majority of currencies). Defaults to 0. MaxTipAmount OptInt `json:"max_tip_amount"` // A JSON-serialized array of suggested amounts of tips in the smallest units of the currency // (integer, not float/double). At most 4 suggested tip amounts can be specified. The suggested tip // amounts must be positive, passed in a strictly increased order and must not exceed max_tip_amount. SuggestedTipAmounts []int `json:"suggested_tip_amounts"` // Unique deep-linking parameter. If left empty, forwarded copies of the sent message will have a Pay // button, allowing multiple users to pay directly from the forwarded message, using the same invoice. // If non-empty, forwarded copies of the sent message will have a URL button with a deep link to the // bot (instead of a Pay button), with the value used as the start parameter. StartParameter OptString `json:"start_parameter"` // A JSON-serialized data about the invoice, which will be shared with the payment provider. A // detailed description of required fields should be provided by the payment provider. ProviderData OptString `json:"provider_data"` // URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a // service. People like it better when they see what they are paying for. PhotoURL OptURL `json:"photo_url"` // Photo size. PhotoSize OptInt `json:"photo_size"` // Photo width. PhotoWidth OptInt `json:"photo_width"` // Photo height. PhotoHeight OptInt `json:"photo_height"` // Pass True, if you require the user's full name to complete the order. NeedName OptBool `json:"need_name"` // Pass True, if you require the user's phone number to complete the order. NeedPhoneNumber OptBool `json:"need_phone_number"` // Pass True, if you require the user's email address to complete the order. NeedEmail OptBool `json:"need_email"` // Pass True, if you require the user's shipping address to complete the order. NeedShippingAddress OptBool `json:"need_shipping_address"` // Pass True, if user's phone number should be sent to provider. SendPhoneNumberToProvider OptBool `json:"send_phone_number_to_provider"` // Pass True, if user's email address should be sent to provider. SendEmailToProvider OptBool `json:"send_email_to_provider"` // Pass True, if the final price depends on the shipping method. IsFlexible OptBool `json:"is_flexible"` // Sends the message silently. Users will receive a notification with no sound. DisableNotification OptBool `json:"disable_notification"` // If the message is a reply, ID of the original message. ReplyToMessageID OptInt `json:"reply_to_message_id"` // Pass True, if the message should be sent even if the specified replied-to message is not found. AllowSendingWithoutReply OptBool `json:"allow_sending_without_reply"` ReplyMarkup OptInlineKeyboardMarkup `json:"reply_markup"` } // Input for sendLocation. // Ref: #/components/schemas/sendLocation type SendLocation struct { ChatID ID `json:"chat_id"` // Latitude of the location. Latitude float64 `json:"latitude"` // Longitude of the location. Longitude float64 `json:"longitude"` // The radius of uncertainty for the location, measured in meters; 0-1500. HorizontalAccuracy OptFloat64 `json:"horizontal_accuracy"` // Period in seconds for which the location will be updated (see Live Locations, should be between 60 // and 86400. LivePeriod OptInt `json:"live_period"` // For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 // if specified. Heading OptInt `json:"heading"` // For live locations, a maximum distance for proximity alerts about approaching another chat member, // in meters. Must be between 1 and 100000 if specified. ProximityAlertRadius OptInt `json:"proximity_alert_radius"` // Sends the message silently. Users will receive a notification with no sound. DisableNotification OptBool `json:"disable_notification"` // If the message is a reply, ID of the original message. ReplyToMessageID OptInt `json:"reply_to_message_id"` // Pass True, if the message should be sent even if the specified replied-to message is not found. AllowSendingWithoutReply OptBool `json:"allow_sending_without_reply"` // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply // keyboard, instructions to remove reply keyboard or to force a reply from the user. ReplyMarkup OptSendLocationReplyMarkup `json:"reply_markup"` } // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply // keyboard, instructions to remove reply keyboard or to force a reply from the user. // SendLocationReplyMarkup represents sum type. type SendLocationReplyMarkup struct { Type SendLocationReplyMarkupType // switch on this field InlineKeyboardMarkup InlineKeyboardMarkup ReplyKeyboardMarkup ReplyKeyboardMarkup ReplyKeyboardRemove ReplyKeyboardRemove ForceReply ForceReply } // SendLocationReplyMarkupType is oneOf type of SendLocationReplyMarkup. type SendLocationReplyMarkupType string // Possible values for SendLocationReplyMarkupType. const ( InlineKeyboardMarkupSendLocationReplyMarkup SendLocationReplyMarkupType = "InlineKeyboardMarkup" ReplyKeyboardMarkupSendLocationReplyMarkup SendLocationReplyMarkupType = "ReplyKeyboardMarkup" ReplyKeyboardRemoveSendLocationReplyMarkup SendLocationReplyMarkupType = "ReplyKeyboardRemove" ForceReplySendLocationReplyMarkup SendLocationReplyMarkupType = "ForceReply" ) // IsInlineKeyboardMarkup reports whether SendLocationReplyMarkup is InlineKeyboardMarkup. func (s SendLocationReplyMarkup) IsInlineKeyboardMarkup() bool { return s.Type == InlineKeyboardMarkupSendLocationReplyMarkup } // IsReplyKeyboardMarkup reports whether SendLocationReplyMarkup is ReplyKeyboardMarkup. func (s SendLocationReplyMarkup) IsReplyKeyboardMarkup() bool { return s.Type == ReplyKeyboardMarkupSendLocationReplyMarkup } // IsReplyKeyboardRemove reports whether SendLocationReplyMarkup is ReplyKeyboardRemove. func (s SendLocationReplyMarkup) IsReplyKeyboardRemove() bool { return s.Type == ReplyKeyboardRemoveSendLocationReplyMarkup } // IsForceReply reports whether SendLocationReplyMarkup is ForceReply. func (s SendLocationReplyMarkup) IsForceReply() bool { return s.Type == ForceReplySendLocationReplyMarkup } // SetInlineKeyboardMarkup sets SendLocationReplyMarkup to InlineKeyboardMarkup. func (s *SendLocationReplyMarkup) SetInlineKeyboardMarkup(v InlineKeyboardMarkup) { s.Type = InlineKeyboardMarkupSendLocationReplyMarkup s.InlineKeyboardMarkup = v } // GetInlineKeyboardMarkup returns InlineKeyboardMarkup and true boolean if SendLocationReplyMarkup is InlineKeyboardMarkup. func (s SendLocationReplyMarkup) GetInlineKeyboardMarkup() (v InlineKeyboardMarkup, ok bool) { if !s.IsInlineKeyboardMarkup() { return v, false } return s.InlineKeyboardMarkup, true } // NewInlineKeyboardMarkupSendLocationReplyMarkup returns new SendLocationReplyMarkup from InlineKeyboardMarkup. func NewInlineKeyboardMarkupSendLocationReplyMarkup(v InlineKeyboardMarkup) SendLocationReplyMarkup { var s SendLocationReplyMarkup s.SetInlineKeyboardMarkup(v) return s } // SetReplyKeyboardMarkup sets SendLocationReplyMarkup to ReplyKeyboardMarkup. func (s *SendLocationReplyMarkup) SetReplyKeyboardMarkup(v ReplyKeyboardMarkup) { s.Type = ReplyKeyboardMarkupSendLocationReplyMarkup s.ReplyKeyboardMarkup = v } // GetReplyKeyboardMarkup returns ReplyKeyboardMarkup and true boolean if SendLocationReplyMarkup is ReplyKeyboardMarkup. func (s SendLocationReplyMarkup) GetReplyKeyboardMarkup() (v ReplyKeyboardMarkup, ok bool) { if !s.IsReplyKeyboardMarkup() { return v, false } return s.ReplyKeyboardMarkup, true } // NewReplyKeyboardMarkupSendLocationReplyMarkup returns new SendLocationReplyMarkup from ReplyKeyboardMarkup. func NewReplyKeyboardMarkupSendLocationReplyMarkup(v ReplyKeyboardMarkup) SendLocationReplyMarkup { var s SendLocationReplyMarkup s.SetReplyKeyboardMarkup(v) return s } // SetReplyKeyboardRemove sets SendLocationReplyMarkup to ReplyKeyboardRemove. func (s *SendLocationReplyMarkup) SetReplyKeyboardRemove(v ReplyKeyboardRemove) { s.Type = ReplyKeyboardRemoveSendLocationReplyMarkup s.ReplyKeyboardRemove = v } // GetReplyKeyboardRemove returns ReplyKeyboardRemove and true boolean if SendLocationReplyMarkup is ReplyKeyboardRemove. func (s SendLocationReplyMarkup) GetReplyKeyboardRemove() (v ReplyKeyboardRemove, ok bool) { if !s.IsReplyKeyboardRemove() { return v, false } return s.ReplyKeyboardRemove, true } // NewReplyKeyboardRemoveSendLocationReplyMarkup returns new SendLocationReplyMarkup from ReplyKeyboardRemove. func NewReplyKeyboardRemoveSendLocationReplyMarkup(v ReplyKeyboardRemove) SendLocationReplyMarkup { var s SendLocationReplyMarkup s.SetReplyKeyboardRemove(v) return s } // SetForceReply sets SendLocationReplyMarkup to ForceReply. func (s *SendLocationReplyMarkup) SetForceReply(v ForceReply) { s.Type = ForceReplySendLocationReplyMarkup s.ForceReply = v } // GetForceReply returns ForceReply and true boolean if SendLocationReplyMarkup is ForceReply. func (s SendLocationReplyMarkup) GetForceReply() (v ForceReply, ok bool) { if !s.IsForceReply() { return v, false } return s.ForceReply, true } // NewForceReplySendLocationReplyMarkup returns new SendLocationReplyMarkup from ForceReply. func NewForceReplySendLocationReplyMarkup(v ForceReply) SendLocationReplyMarkup { var s SendLocationReplyMarkup s.SetForceReply(v) return s } // Input for sendMediaGroup. // Ref: #/components/schemas/sendMediaGroup type SendMediaGroup struct { ChatID ID `json:"chat_id"` // A JSON-serialized array describing messages to be sent, must include 2-10 items. Media []SendMediaGroupMediaItem `json:"media"` // Sends messages silently. Users will receive a notification with no sound. DisableNotification OptBool `json:"disable_notification"` // If the messages are a reply, ID of the original message. ReplyToMessageID OptInt `json:"reply_to_message_id"` // Pass True, if the message should be sent even if the specified replied-to message is not found. AllowSendingWithoutReply OptBool `json:"allow_sending_without_reply"` } // SendMediaGroupMediaItem represents sum type. type SendMediaGroupMediaItem struct { Type SendMediaGroupMediaItemType // switch on this field InputMediaAudio InputMediaAudio InputMediaDocument InputMediaDocument InputMediaPhoto InputMediaPhoto InputMediaVideo InputMediaVideo } // SendMediaGroupMediaItemType is oneOf type of SendMediaGroupMediaItem. type SendMediaGroupMediaItemType string // Possible values for SendMediaGroupMediaItemType. const ( InputMediaAudioSendMediaGroupMediaItem SendMediaGroupMediaItemType = "InputMediaAudio" InputMediaDocumentSendMediaGroupMediaItem SendMediaGroupMediaItemType = "InputMediaDocument" InputMediaPhotoSendMediaGroupMediaItem SendMediaGroupMediaItemType = "InputMediaPhoto" InputMediaVideoSendMediaGroupMediaItem SendMediaGroupMediaItemType = "InputMediaVideo" ) // IsInputMediaAudio reports whether SendMediaGroupMediaItem is InputMediaAudio. func (s SendMediaGroupMediaItem) IsInputMediaAudio() bool { return s.Type == InputMediaAudioSendMediaGroupMediaItem } // IsInputMediaDocument reports whether SendMediaGroupMediaItem is InputMediaDocument. func (s SendMediaGroupMediaItem) IsInputMediaDocument() bool { return s.Type == InputMediaDocumentSendMediaGroupMediaItem } // IsInputMediaPhoto reports whether SendMediaGroupMediaItem is InputMediaPhoto. func (s SendMediaGroupMediaItem) IsInputMediaPhoto() bool { return s.Type == InputMediaPhotoSendMediaGroupMediaItem } // IsInputMediaVideo reports whether SendMediaGroupMediaItem is InputMediaVideo. func (s SendMediaGroupMediaItem) IsInputMediaVideo() bool { return s.Type == InputMediaVideoSendMediaGroupMediaItem } // SetInputMediaAudio sets SendMediaGroupMediaItem to InputMediaAudio. func (s *SendMediaGroupMediaItem) SetInputMediaAudio(v InputMediaAudio) { s.Type = InputMediaAudioSendMediaGroupMediaItem s.InputMediaAudio = v } // GetInputMediaAudio returns InputMediaAudio and true boolean if SendMediaGroupMediaItem is InputMediaAudio. func (s SendMediaGroupMediaItem) GetInputMediaAudio() (v InputMediaAudio, ok bool) { if !s.IsInputMediaAudio() { return v, false } return s.InputMediaAudio, true } // NewInputMediaAudioSendMediaGroupMediaItem returns new SendMediaGroupMediaItem from InputMediaAudio. func NewInputMediaAudioSendMediaGroupMediaItem(v InputMediaAudio) SendMediaGroupMediaItem { var s SendMediaGroupMediaItem s.SetInputMediaAudio(v) return s } // SetInputMediaDocument sets SendMediaGroupMediaItem to InputMediaDocument. func (s *SendMediaGroupMediaItem) SetInputMediaDocument(v InputMediaDocument) { s.Type = InputMediaDocumentSendMediaGroupMediaItem s.InputMediaDocument = v } // GetInputMediaDocument returns InputMediaDocument and true boolean if SendMediaGroupMediaItem is InputMediaDocument. func (s SendMediaGroupMediaItem) GetInputMediaDocument() (v InputMediaDocument, ok bool) { if !s.IsInputMediaDocument() { return v, false } return s.InputMediaDocument, true } // NewInputMediaDocumentSendMediaGroupMediaItem returns new SendMediaGroupMediaItem from InputMediaDocument. func NewInputMediaDocumentSendMediaGroupMediaItem(v InputMediaDocument) SendMediaGroupMediaItem { var s SendMediaGroupMediaItem s.SetInputMediaDocument(v) return s } // SetInputMediaPhoto sets SendMediaGroupMediaItem to InputMediaPhoto. func (s *SendMediaGroupMediaItem) SetInputMediaPhoto(v InputMediaPhoto) { s.Type = InputMediaPhotoSendMediaGroupMediaItem s.InputMediaPhoto = v } // GetInputMediaPhoto returns InputMediaPhoto and true boolean if SendMediaGroupMediaItem is InputMediaPhoto. func (s SendMediaGroupMediaItem) GetInputMediaPhoto() (v InputMediaPhoto, ok bool) { if !s.IsInputMediaPhoto() { return v, false } return s.InputMediaPhoto, true } // NewInputMediaPhotoSendMediaGroupMediaItem returns new SendMediaGroupMediaItem from InputMediaPhoto. func NewInputMediaPhotoSendMediaGroupMediaItem(v InputMediaPhoto) SendMediaGroupMediaItem { var s SendMediaGroupMediaItem s.SetInputMediaPhoto(v) return s } // SetInputMediaVideo sets SendMediaGroupMediaItem to InputMediaVideo. func (s *SendMediaGroupMediaItem) SetInputMediaVideo(v InputMediaVideo) { s.Type = InputMediaVideoSendMediaGroupMediaItem s.InputMediaVideo = v } // GetInputMediaVideo returns InputMediaVideo and true boolean if SendMediaGroupMediaItem is InputMediaVideo. func (s SendMediaGroupMediaItem) GetInputMediaVideo() (v InputMediaVideo, ok bool) { if !s.IsInputMediaVideo() { return v, false } return s.InputMediaVideo, true } // NewInputMediaVideoSendMediaGroupMediaItem returns new SendMediaGroupMediaItem from InputMediaVideo. func NewInputMediaVideoSendMediaGroupMediaItem(v InputMediaVideo) SendMediaGroupMediaItem { var s SendMediaGroupMediaItem s.SetInputMediaVideo(v) return s } // Input for sendMessage. // Ref: #/components/schemas/sendMessage type SendMessage struct { ChatID ID `json:"chat_id"` // Text of the message to be sent, 1-4096 characters after entities parsing. Text string `json:"text"` // Mode for parsing entities in the message text. See formatting options for more details. ParseMode OptString `json:"parse_mode"` // A JSON-serialized list of special entities that appear in message text, which can be specified // instead of parse_mode. Entities []MessageEntity `json:"entities"` // Disables link previews for links in this message. DisableWebPagePreview OptBool `json:"disable_web_page_preview"` // Sends the message silently. Users will receive a notification with no sound. DisableNotification OptBool `json:"disable_notification"` // If the message is a reply, ID of the original message. ReplyToMessageID OptInt `json:"reply_to_message_id"` // Pass True, if the message should be sent even if the specified replied-to message is not found. AllowSendingWithoutReply OptBool `json:"allow_sending_without_reply"` // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply // keyboard, instructions to remove reply keyboard or to force a reply from the user. ReplyMarkup OptSendMessageReplyMarkup `json:"reply_markup"` } // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply // keyboard, instructions to remove reply keyboard or to force a reply from the user. // SendMessageReplyMarkup represents sum type. type SendMessageReplyMarkup struct { Type SendMessageReplyMarkupType // switch on this field InlineKeyboardMarkup InlineKeyboardMarkup ReplyKeyboardMarkup ReplyKeyboardMarkup ReplyKeyboardRemove ReplyKeyboardRemove ForceReply ForceReply } // SendMessageReplyMarkupType is oneOf type of SendMessageReplyMarkup. type SendMessageReplyMarkupType string // Possible values for SendMessageReplyMarkupType. const ( InlineKeyboardMarkupSendMessageReplyMarkup SendMessageReplyMarkupType = "InlineKeyboardMarkup" ReplyKeyboardMarkupSendMessageReplyMarkup SendMessageReplyMarkupType = "ReplyKeyboardMarkup" ReplyKeyboardRemoveSendMessageReplyMarkup SendMessageReplyMarkupType = "ReplyKeyboardRemove" ForceReplySendMessageReplyMarkup SendMessageReplyMarkupType = "ForceReply" ) // IsInlineKeyboardMarkup reports whether SendMessageReplyMarkup is InlineKeyboardMarkup. func (s SendMessageReplyMarkup) IsInlineKeyboardMarkup() bool { return s.Type == InlineKeyboardMarkupSendMessageReplyMarkup } // IsReplyKeyboardMarkup reports whether SendMessageReplyMarkup is ReplyKeyboardMarkup. func (s SendMessageReplyMarkup) IsReplyKeyboardMarkup() bool { return s.Type == ReplyKeyboardMarkupSendMessageReplyMarkup } // IsReplyKeyboardRemove reports whether SendMessageReplyMarkup is ReplyKeyboardRemove. func (s SendMessageReplyMarkup) IsReplyKeyboardRemove() bool { return s.Type == ReplyKeyboardRemoveSendMessageReplyMarkup } // IsForceReply reports whether SendMessageReplyMarkup is ForceReply. func (s SendMessageReplyMarkup) IsForceReply() bool { return s.Type == ForceReplySendMessageReplyMarkup } // SetInlineKeyboardMarkup sets SendMessageReplyMarkup to InlineKeyboardMarkup. func (s *SendMessageReplyMarkup) SetInlineKeyboardMarkup(v InlineKeyboardMarkup) { s.Type = InlineKeyboardMarkupSendMessageReplyMarkup s.InlineKeyboardMarkup = v } // GetInlineKeyboardMarkup returns InlineKeyboardMarkup and true boolean if SendMessageReplyMarkup is InlineKeyboardMarkup. func (s SendMessageReplyMarkup) GetInlineKeyboardMarkup() (v InlineKeyboardMarkup, ok bool) { if !s.IsInlineKeyboardMarkup() { return v, false } return s.InlineKeyboardMarkup, true } // NewInlineKeyboardMarkupSendMessageReplyMarkup returns new SendMessageReplyMarkup from InlineKeyboardMarkup. func NewInlineKeyboardMarkupSendMessageReplyMarkup(v InlineKeyboardMarkup) SendMessageReplyMarkup { var s SendMessageReplyMarkup s.SetInlineKeyboardMarkup(v) return s } // SetReplyKeyboardMarkup sets SendMessageReplyMarkup to ReplyKeyboardMarkup. func (s *SendMessageReplyMarkup) SetReplyKeyboardMarkup(v ReplyKeyboardMarkup) { s.Type = ReplyKeyboardMarkupSendMessageReplyMarkup s.ReplyKeyboardMarkup = v } // GetReplyKeyboardMarkup returns ReplyKeyboardMarkup and true boolean if SendMessageReplyMarkup is ReplyKeyboardMarkup. func (s SendMessageReplyMarkup) GetReplyKeyboardMarkup() (v ReplyKeyboardMarkup, ok bool) { if !s.IsReplyKeyboardMarkup() { return v, false } return s.ReplyKeyboardMarkup, true } // NewReplyKeyboardMarkupSendMessageReplyMarkup returns new SendMessageReplyMarkup from ReplyKeyboardMarkup. func NewReplyKeyboardMarkupSendMessageReplyMarkup(v ReplyKeyboardMarkup) SendMessageReplyMarkup { var s SendMessageReplyMarkup s.SetReplyKeyboardMarkup(v) return s } // SetReplyKeyboardRemove sets SendMessageReplyMarkup to ReplyKeyboardRemove. func (s *SendMessageReplyMarkup) SetReplyKeyboardRemove(v ReplyKeyboardRemove) { s.Type = ReplyKeyboardRemoveSendMessageReplyMarkup s.ReplyKeyboardRemove = v } // GetReplyKeyboardRemove returns ReplyKeyboardRemove and true boolean if SendMessageReplyMarkup is ReplyKeyboardRemove. func (s SendMessageReplyMarkup) GetReplyKeyboardRemove() (v ReplyKeyboardRemove, ok bool) { if !s.IsReplyKeyboardRemove() { return v, false } return s.ReplyKeyboardRemove, true } // NewReplyKeyboardRemoveSendMessageReplyMarkup returns new SendMessageReplyMarkup from ReplyKeyboardRemove. func NewReplyKeyboardRemoveSendMessageReplyMarkup(v ReplyKeyboardRemove) SendMessageReplyMarkup { var s SendMessageReplyMarkup s.SetReplyKeyboardRemove(v) return s } // SetForceReply sets SendMessageReplyMarkup to ForceReply. func (s *SendMessageReplyMarkup) SetForceReply(v ForceReply) { s.Type = ForceReplySendMessageReplyMarkup s.ForceReply = v } // GetForceReply returns ForceReply and true boolean if SendMessageReplyMarkup is ForceReply. func (s SendMessageReplyMarkup) GetForceReply() (v ForceReply, ok bool) { if !s.IsForceReply() { return v, false } return s.ForceReply, true } // NewForceReplySendMessageReplyMarkup returns new SendMessageReplyMarkup from ForceReply. func NewForceReplySendMessageReplyMarkup(v ForceReply) SendMessageReplyMarkup { var s SendMessageReplyMarkup s.SetForceReply(v) return s } // Input for sendPhoto. // Ref: #/components/schemas/sendPhoto type SendPhoto struct { ChatID ID `json:"chat_id"` // Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers // (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or // upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's // width and height must not exceed 10000 in total. Width and height ratio must be at most 20. More // info on Sending Files ». Photo string `json:"photo"` // Photo caption (may also be used when resending photos by file_id), 0-1024 characters after // entities parsing. Caption OptString `json:"caption"` // Mode for parsing entities in the photo caption. See formatting options for more details. ParseMode OptString `json:"parse_mode"` // A JSON-serialized list of special entities that appear in the caption, which can be specified // instead of parse_mode. CaptionEntities []MessageEntity `json:"caption_entities"` // Sends the message silently. Users will receive a notification with no sound. DisableNotification OptBool `json:"disable_notification"` // If the message is a reply, ID of the original message. ReplyToMessageID OptInt `json:"reply_to_message_id"` // Pass True, if the message should be sent even if the specified replied-to message is not found. AllowSendingWithoutReply OptBool `json:"allow_sending_without_reply"` // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply // keyboard, instructions to remove reply keyboard or to force a reply from the user. ReplyMarkup OptSendPhotoReplyMarkup `json:"reply_markup"` } // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply // keyboard, instructions to remove reply keyboard or to force a reply from the user. // SendPhotoReplyMarkup represents sum type. type SendPhotoReplyMarkup struct { Type SendPhotoReplyMarkupType // switch on this field InlineKeyboardMarkup InlineKeyboardMarkup ReplyKeyboardMarkup ReplyKeyboardMarkup ReplyKeyboardRemove ReplyKeyboardRemove ForceReply ForceReply } // SendPhotoReplyMarkupType is oneOf type of SendPhotoReplyMarkup. type SendPhotoReplyMarkupType string // Possible values for SendPhotoReplyMarkupType. const ( InlineKeyboardMarkupSendPhotoReplyMarkup SendPhotoReplyMarkupType = "InlineKeyboardMarkup" ReplyKeyboardMarkupSendPhotoReplyMarkup SendPhotoReplyMarkupType = "ReplyKeyboardMarkup" ReplyKeyboardRemoveSendPhotoReplyMarkup SendPhotoReplyMarkupType = "ReplyKeyboardRemove" ForceReplySendPhotoReplyMarkup SendPhotoReplyMarkupType = "ForceReply" ) // IsInlineKeyboardMarkup reports whether SendPhotoReplyMarkup is InlineKeyboardMarkup. func (s SendPhotoReplyMarkup) IsInlineKeyboardMarkup() bool { return s.Type == InlineKeyboardMarkupSendPhotoReplyMarkup } // IsReplyKeyboardMarkup reports whether SendPhotoReplyMarkup is ReplyKeyboardMarkup. func (s SendPhotoReplyMarkup) IsReplyKeyboardMarkup() bool { return s.Type == ReplyKeyboardMarkupSendPhotoReplyMarkup } // IsReplyKeyboardRemove reports whether SendPhotoReplyMarkup is ReplyKeyboardRemove. func (s SendPhotoReplyMarkup) IsReplyKeyboardRemove() bool { return s.Type == ReplyKeyboardRemoveSendPhotoReplyMarkup } // IsForceReply reports whether SendPhotoReplyMarkup is ForceReply. func (s SendPhotoReplyMarkup) IsForceReply() bool { return s.Type == ForceReplySendPhotoReplyMarkup } // SetInlineKeyboardMarkup sets SendPhotoReplyMarkup to InlineKeyboardMarkup. func (s *SendPhotoReplyMarkup) SetInlineKeyboardMarkup(v InlineKeyboardMarkup) { s.Type = InlineKeyboardMarkupSendPhotoReplyMarkup s.InlineKeyboardMarkup = v } // GetInlineKeyboardMarkup returns InlineKeyboardMarkup and true boolean if SendPhotoReplyMarkup is InlineKeyboardMarkup. func (s SendPhotoReplyMarkup) GetInlineKeyboardMarkup() (v InlineKeyboardMarkup, ok bool) { if !s.IsInlineKeyboardMarkup() { return v, false } return s.InlineKeyboardMarkup, true } // NewInlineKeyboardMarkupSendPhotoReplyMarkup returns new SendPhotoReplyMarkup from InlineKeyboardMarkup. func NewInlineKeyboardMarkupSendPhotoReplyMarkup(v InlineKeyboardMarkup) SendPhotoReplyMarkup { var s SendPhotoReplyMarkup s.SetInlineKeyboardMarkup(v) return s } // SetReplyKeyboardMarkup sets SendPhotoReplyMarkup to ReplyKeyboardMarkup. func (s *SendPhotoReplyMarkup) SetReplyKeyboardMarkup(v ReplyKeyboardMarkup) { s.Type = ReplyKeyboardMarkupSendPhotoReplyMarkup s.ReplyKeyboardMarkup = v } // GetReplyKeyboardMarkup returns ReplyKeyboardMarkup and true boolean if SendPhotoReplyMarkup is ReplyKeyboardMarkup. func (s SendPhotoReplyMarkup) GetReplyKeyboardMarkup() (v ReplyKeyboardMarkup, ok bool) { if !s.IsReplyKeyboardMarkup() { return v, false } return s.ReplyKeyboardMarkup, true } // NewReplyKeyboardMarkupSendPhotoReplyMarkup returns new SendPhotoReplyMarkup from ReplyKeyboardMarkup. func NewReplyKeyboardMarkupSendPhotoReplyMarkup(v ReplyKeyboardMarkup) SendPhotoReplyMarkup { var s SendPhotoReplyMarkup s.SetReplyKeyboardMarkup(v) return s } // SetReplyKeyboardRemove sets SendPhotoReplyMarkup to ReplyKeyboardRemove. func (s *SendPhotoReplyMarkup) SetReplyKeyboardRemove(v ReplyKeyboardRemove) { s.Type = ReplyKeyboardRemoveSendPhotoReplyMarkup s.ReplyKeyboardRemove = v } // GetReplyKeyboardRemove returns ReplyKeyboardRemove and true boolean if SendPhotoReplyMarkup is ReplyKeyboardRemove. func (s SendPhotoReplyMarkup) GetReplyKeyboardRemove() (v ReplyKeyboardRemove, ok bool) { if !s.IsReplyKeyboardRemove() { return v, false } return s.ReplyKeyboardRemove, true } // NewReplyKeyboardRemoveSendPhotoReplyMarkup returns new SendPhotoReplyMarkup from ReplyKeyboardRemove. func NewReplyKeyboardRemoveSendPhotoReplyMarkup(v ReplyKeyboardRemove) SendPhotoReplyMarkup { var s SendPhotoReplyMarkup s.SetReplyKeyboardRemove(v) return s } // SetForceReply sets SendPhotoReplyMarkup to ForceReply. func (s *SendPhotoReplyMarkup) SetForceReply(v ForceReply) { s.Type = ForceReplySendPhotoReplyMarkup s.ForceReply = v } // GetForceReply returns ForceReply and true boolean if SendPhotoReplyMarkup is ForceReply. func (s SendPhotoReplyMarkup) GetForceReply() (v ForceReply, ok bool) { if !s.IsForceReply() { return v, false } return s.ForceReply, true } // NewForceReplySendPhotoReplyMarkup returns new SendPhotoReplyMarkup from ForceReply. func NewForceReplySendPhotoReplyMarkup(v ForceReply) SendPhotoReplyMarkup { var s SendPhotoReplyMarkup s.SetForceReply(v) return s } // Input for sendPoll. // Ref: #/components/schemas/sendPoll type SendPoll struct { ChatID ID `json:"chat_id"` // Poll question, 1-300 characters. Question string `json:"question"` // A JSON-serialized list of answer options, 2-10 strings 1-100 characters each. Options []string `json:"options"` // True, if the poll needs to be anonymous, defaults to True. IsAnonymous OptBool `json:"is_anonymous"` // Poll type, “quiz” or “regular”, defaults to “regular”. Type OptString `json:"type"` // True, if the poll allows multiple answers, ignored for polls in quiz mode, defaults to False. AllowsMultipleAnswers OptBool `json:"allows_multiple_answers"` // 0-based identifier of the correct answer option, required for polls in quiz mode. CorrectOptionID OptInt `json:"correct_option_id"` // Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a // quiz-style poll, 0-200 characters with at most 2 line feeds after entities parsing. Explanation OptString `json:"explanation"` // Mode for parsing entities in the explanation. See formatting options for more details. ExplanationParseMode OptString `json:"explanation_parse_mode"` // A JSON-serialized list of special entities that appear in the poll explanation, which can be // specified instead of parse_mode. ExplanationEntities []MessageEntity `json:"explanation_entities"` // Amount of time in seconds the poll will be active after creation, 5-600. Can't be used together // with close_date. OpenPeriod OptInt `json:"open_period"` // Point in time (Unix timestamp) when the poll will be automatically closed. Must be at least 5 and // no more than 600 seconds in the future. Can't be used together with open_period. CloseDate OptInt `json:"close_date"` // Pass True, if the poll needs to be immediately closed. This can be useful for poll preview. IsClosed OptBool `json:"is_closed"` // Sends the message silently. Users will receive a notification with no sound. DisableNotification OptBool `json:"disable_notification"` // If the message is a reply, ID of the original message. ReplyToMessageID OptInt `json:"reply_to_message_id"` // Pass True, if the message should be sent even if the specified replied-to message is not found. AllowSendingWithoutReply OptBool `json:"allow_sending_without_reply"` // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply // keyboard, instructions to remove reply keyboard or to force a reply from the user. ReplyMarkup OptSendPollReplyMarkup `json:"reply_markup"` } // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply // keyboard, instructions to remove reply keyboard or to force a reply from the user. // SendPollReplyMarkup represents sum type. type SendPollReplyMarkup struct { Type SendPollReplyMarkupType // switch on this field InlineKeyboardMarkup InlineKeyboardMarkup ReplyKeyboardMarkup ReplyKeyboardMarkup ReplyKeyboardRemove ReplyKeyboardRemove ForceReply ForceReply } // SendPollReplyMarkupType is oneOf type of SendPollReplyMarkup. type SendPollReplyMarkupType string // Possible values for SendPollReplyMarkupType. const ( InlineKeyboardMarkupSendPollReplyMarkup SendPollReplyMarkupType = "InlineKeyboardMarkup" ReplyKeyboardMarkupSendPollReplyMarkup SendPollReplyMarkupType = "ReplyKeyboardMarkup" ReplyKeyboardRemoveSendPollReplyMarkup SendPollReplyMarkupType = "ReplyKeyboardRemove" ForceReplySendPollReplyMarkup SendPollReplyMarkupType = "ForceReply" ) // IsInlineKeyboardMarkup reports whether SendPollReplyMarkup is InlineKeyboardMarkup. func (s SendPollReplyMarkup) IsInlineKeyboardMarkup() bool { return s.Type == InlineKeyboardMarkupSendPollReplyMarkup } // IsReplyKeyboardMarkup reports whether SendPollReplyMarkup is ReplyKeyboardMarkup. func (s SendPollReplyMarkup) IsReplyKeyboardMarkup() bool { return s.Type == ReplyKeyboardMarkupSendPollReplyMarkup } // IsReplyKeyboardRemove reports whether SendPollReplyMarkup is ReplyKeyboardRemove. func (s SendPollReplyMarkup) IsReplyKeyboardRemove() bool { return s.Type == ReplyKeyboardRemoveSendPollReplyMarkup } // IsForceReply reports whether SendPollReplyMarkup is ForceReply. func (s SendPollReplyMarkup) IsForceReply() bool { return s.Type == ForceReplySendPollReplyMarkup } // SetInlineKeyboardMarkup sets SendPollReplyMarkup to InlineKeyboardMarkup. func (s *SendPollReplyMarkup) SetInlineKeyboardMarkup(v InlineKeyboardMarkup) { s.Type = InlineKeyboardMarkupSendPollReplyMarkup s.InlineKeyboardMarkup = v } // GetInlineKeyboardMarkup returns InlineKeyboardMarkup and true boolean if SendPollReplyMarkup is InlineKeyboardMarkup. func (s SendPollReplyMarkup) GetInlineKeyboardMarkup() (v InlineKeyboardMarkup, ok bool) { if !s.IsInlineKeyboardMarkup() { return v, false } return s.InlineKeyboardMarkup, true } // NewInlineKeyboardMarkupSendPollReplyMarkup returns new SendPollReplyMarkup from InlineKeyboardMarkup. func NewInlineKeyboardMarkupSendPollReplyMarkup(v InlineKeyboardMarkup) SendPollReplyMarkup { var s SendPollReplyMarkup s.SetInlineKeyboardMarkup(v) return s } // SetReplyKeyboardMarkup sets SendPollReplyMarkup to ReplyKeyboardMarkup. func (s *SendPollReplyMarkup) SetReplyKeyboardMarkup(v ReplyKeyboardMarkup) { s.Type = ReplyKeyboardMarkupSendPollReplyMarkup s.ReplyKeyboardMarkup = v } // GetReplyKeyboardMarkup returns ReplyKeyboardMarkup and true boolean if SendPollReplyMarkup is ReplyKeyboardMarkup. func (s SendPollReplyMarkup) GetReplyKeyboardMarkup() (v ReplyKeyboardMarkup, ok bool) { if !s.IsReplyKeyboardMarkup() { return v, false } return s.ReplyKeyboardMarkup, true } // NewReplyKeyboardMarkupSendPollReplyMarkup returns new SendPollReplyMarkup from ReplyKeyboardMarkup. func NewReplyKeyboardMarkupSendPollReplyMarkup(v ReplyKeyboardMarkup) SendPollReplyMarkup { var s SendPollReplyMarkup s.SetReplyKeyboardMarkup(v) return s } // SetReplyKeyboardRemove sets SendPollReplyMarkup to ReplyKeyboardRemove. func (s *SendPollReplyMarkup) SetReplyKeyboardRemove(v ReplyKeyboardRemove) { s.Type = ReplyKeyboardRemoveSendPollReplyMarkup s.ReplyKeyboardRemove = v } // GetReplyKeyboardRemove returns ReplyKeyboardRemove and true boolean if SendPollReplyMarkup is ReplyKeyboardRemove. func (s SendPollReplyMarkup) GetReplyKeyboardRemove() (v ReplyKeyboardRemove, ok bool) { if !s.IsReplyKeyboardRemove() { return v, false } return s.ReplyKeyboardRemove, true } // NewReplyKeyboardRemoveSendPollReplyMarkup returns new SendPollReplyMarkup from ReplyKeyboardRemove. func NewReplyKeyboardRemoveSendPollReplyMarkup(v ReplyKeyboardRemove) SendPollReplyMarkup { var s SendPollReplyMarkup s.SetReplyKeyboardRemove(v) return s } // SetForceReply sets SendPollReplyMarkup to ForceReply. func (s *SendPollReplyMarkup) SetForceReply(v ForceReply) { s.Type = ForceReplySendPollReplyMarkup s.ForceReply = v } // GetForceReply returns ForceReply and true boolean if SendPollReplyMarkup is ForceReply. func (s SendPollReplyMarkup) GetForceReply() (v ForceReply, ok bool) { if !s.IsForceReply() { return v, false } return s.ForceReply, true } // NewForceReplySendPollReplyMarkup returns new SendPollReplyMarkup from ForceReply. func NewForceReplySendPollReplyMarkup(v ForceReply) SendPollReplyMarkup { var s SendPollReplyMarkup s.SetForceReply(v) return s } // Input for sendSticker. // Ref: #/components/schemas/sendSticker type SendSticker struct { ChatID ID `json:"chat_id"` // Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers // (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP file from the Internet, or // upload a new one using multipart/form-data. More info on Sending Files ». Sticker string `json:"sticker"` // Sends the message silently. Users will receive a notification with no sound. DisableNotification OptBool `json:"disable_notification"` // If the message is a reply, ID of the original message. ReplyToMessageID OptInt `json:"reply_to_message_id"` // Pass True, if the message should be sent even if the specified replied-to message is not found. AllowSendingWithoutReply OptBool `json:"allow_sending_without_reply"` // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply // keyboard, instructions to remove reply keyboard or to force a reply from the user. ReplyMarkup OptSendStickerReplyMarkup `json:"reply_markup"` } // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply // keyboard, instructions to remove reply keyboard or to force a reply from the user. // SendStickerReplyMarkup represents sum type. type SendStickerReplyMarkup struct { Type SendStickerReplyMarkupType // switch on this field InlineKeyboardMarkup InlineKeyboardMarkup ReplyKeyboardMarkup ReplyKeyboardMarkup ReplyKeyboardRemove ReplyKeyboardRemove ForceReply ForceReply } // SendStickerReplyMarkupType is oneOf type of SendStickerReplyMarkup. type SendStickerReplyMarkupType string // Possible values for SendStickerReplyMarkupType. const ( InlineKeyboardMarkupSendStickerReplyMarkup SendStickerReplyMarkupType = "InlineKeyboardMarkup" ReplyKeyboardMarkupSendStickerReplyMarkup SendStickerReplyMarkupType = "ReplyKeyboardMarkup" ReplyKeyboardRemoveSendStickerReplyMarkup SendStickerReplyMarkupType = "ReplyKeyboardRemove" ForceReplySendStickerReplyMarkup SendStickerReplyMarkupType = "ForceReply" ) // IsInlineKeyboardMarkup reports whether SendStickerReplyMarkup is InlineKeyboardMarkup. func (s SendStickerReplyMarkup) IsInlineKeyboardMarkup() bool { return s.Type == InlineKeyboardMarkupSendStickerReplyMarkup } // IsReplyKeyboardMarkup reports whether SendStickerReplyMarkup is ReplyKeyboardMarkup. func (s SendStickerReplyMarkup) IsReplyKeyboardMarkup() bool { return s.Type == ReplyKeyboardMarkupSendStickerReplyMarkup } // IsReplyKeyboardRemove reports whether SendStickerReplyMarkup is ReplyKeyboardRemove. func (s SendStickerReplyMarkup) IsReplyKeyboardRemove() bool { return s.Type == ReplyKeyboardRemoveSendStickerReplyMarkup } // IsForceReply reports whether SendStickerReplyMarkup is ForceReply. func (s SendStickerReplyMarkup) IsForceReply() bool { return s.Type == ForceReplySendStickerReplyMarkup } // SetInlineKeyboardMarkup sets SendStickerReplyMarkup to InlineKeyboardMarkup. func (s *SendStickerReplyMarkup) SetInlineKeyboardMarkup(v InlineKeyboardMarkup) { s.Type = InlineKeyboardMarkupSendStickerReplyMarkup s.InlineKeyboardMarkup = v } // GetInlineKeyboardMarkup returns InlineKeyboardMarkup and true boolean if SendStickerReplyMarkup is InlineKeyboardMarkup. func (s SendStickerReplyMarkup) GetInlineKeyboardMarkup() (v InlineKeyboardMarkup, ok bool) { if !s.IsInlineKeyboardMarkup() { return v, false } return s.InlineKeyboardMarkup, true } // NewInlineKeyboardMarkupSendStickerReplyMarkup returns new SendStickerReplyMarkup from InlineKeyboardMarkup. func NewInlineKeyboardMarkupSendStickerReplyMarkup(v InlineKeyboardMarkup) SendStickerReplyMarkup { var s SendStickerReplyMarkup s.SetInlineKeyboardMarkup(v) return s } // SetReplyKeyboardMarkup sets SendStickerReplyMarkup to ReplyKeyboardMarkup. func (s *SendStickerReplyMarkup) SetReplyKeyboardMarkup(v ReplyKeyboardMarkup) { s.Type = ReplyKeyboardMarkupSendStickerReplyMarkup s.ReplyKeyboardMarkup = v } // GetReplyKeyboardMarkup returns ReplyKeyboardMarkup and true boolean if SendStickerReplyMarkup is ReplyKeyboardMarkup. func (s SendStickerReplyMarkup) GetReplyKeyboardMarkup() (v ReplyKeyboardMarkup, ok bool) { if !s.IsReplyKeyboardMarkup() { return v, false } return s.ReplyKeyboardMarkup, true } // NewReplyKeyboardMarkupSendStickerReplyMarkup returns new SendStickerReplyMarkup from ReplyKeyboardMarkup. func NewReplyKeyboardMarkupSendStickerReplyMarkup(v ReplyKeyboardMarkup) SendStickerReplyMarkup { var s SendStickerReplyMarkup s.SetReplyKeyboardMarkup(v) return s } // SetReplyKeyboardRemove sets SendStickerReplyMarkup to ReplyKeyboardRemove. func (s *SendStickerReplyMarkup) SetReplyKeyboardRemove(v ReplyKeyboardRemove) { s.Type = ReplyKeyboardRemoveSendStickerReplyMarkup s.ReplyKeyboardRemove = v } // GetReplyKeyboardRemove returns ReplyKeyboardRemove and true boolean if SendStickerReplyMarkup is ReplyKeyboardRemove. func (s SendStickerReplyMarkup) GetReplyKeyboardRemove() (v ReplyKeyboardRemove, ok bool) { if !s.IsReplyKeyboardRemove() { return v, false } return s.ReplyKeyboardRemove, true } // NewReplyKeyboardRemoveSendStickerReplyMarkup returns new SendStickerReplyMarkup from ReplyKeyboardRemove. func NewReplyKeyboardRemoveSendStickerReplyMarkup(v ReplyKeyboardRemove) SendStickerReplyMarkup { var s SendStickerReplyMarkup s.SetReplyKeyboardRemove(v) return s } // SetForceReply sets SendStickerReplyMarkup to ForceReply. func (s *SendStickerReplyMarkup) SetForceReply(v ForceReply) { s.Type = ForceReplySendStickerReplyMarkup s.ForceReply = v } // GetForceReply returns ForceReply and true boolean if SendStickerReplyMarkup is ForceReply. func (s SendStickerReplyMarkup) GetForceReply() (v ForceReply, ok bool) { if !s.IsForceReply() { return v, false } return s.ForceReply, true } // NewForceReplySendStickerReplyMarkup returns new SendStickerReplyMarkup from ForceReply. func NewForceReplySendStickerReplyMarkup(v ForceReply) SendStickerReplyMarkup { var s SendStickerReplyMarkup s.SetForceReply(v) return s } // Input for sendVenue. // Ref: #/components/schemas/sendVenue type SendVenue struct { ChatID ID `json:"chat_id"` // Latitude of the venue. Latitude float64 `json:"latitude"` // Longitude of the venue. Longitude float64 `json:"longitude"` // Name of the venue. Title string `json:"title"` // Address of the venue. Address string `json:"address"` // Foursquare identifier of the venue. FoursquareID OptString `json:"foursquare_id"` // Foursquare type of the venue, if known. (For example, “arts_entertainment/default”, // “arts_entertainment/aquarium” or “food/icecream”.). FoursquareType OptString `json:"foursquare_type"` // Google Places identifier of the venue. GooglePlaceID OptString `json:"google_place_id"` // Google Places type of the venue. (See supported types.). GooglePlaceType OptString `json:"google_place_type"` // Sends the message silently. Users will receive a notification with no sound. DisableNotification OptBool `json:"disable_notification"` // If the message is a reply, ID of the original message. ReplyToMessageID OptInt `json:"reply_to_message_id"` // Pass True, if the message should be sent even if the specified replied-to message is not found. AllowSendingWithoutReply OptBool `json:"allow_sending_without_reply"` // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply // keyboard, instructions to remove reply keyboard or to force a reply from the user. ReplyMarkup OptSendVenueReplyMarkup `json:"reply_markup"` } // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply // keyboard, instructions to remove reply keyboard or to force a reply from the user. // SendVenueReplyMarkup represents sum type. type SendVenueReplyMarkup struct { Type SendVenueReplyMarkupType // switch on this field InlineKeyboardMarkup InlineKeyboardMarkup ReplyKeyboardMarkup ReplyKeyboardMarkup ReplyKeyboardRemove ReplyKeyboardRemove ForceReply ForceReply } // SendVenueReplyMarkupType is oneOf type of SendVenueReplyMarkup. type SendVenueReplyMarkupType string // Possible values for SendVenueReplyMarkupType. const ( InlineKeyboardMarkupSendVenueReplyMarkup SendVenueReplyMarkupType = "InlineKeyboardMarkup" ReplyKeyboardMarkupSendVenueReplyMarkup SendVenueReplyMarkupType = "ReplyKeyboardMarkup" ReplyKeyboardRemoveSendVenueReplyMarkup SendVenueReplyMarkupType = "ReplyKeyboardRemove" ForceReplySendVenueReplyMarkup SendVenueReplyMarkupType = "ForceReply" ) // IsInlineKeyboardMarkup reports whether SendVenueReplyMarkup is InlineKeyboardMarkup. func (s SendVenueReplyMarkup) IsInlineKeyboardMarkup() bool { return s.Type == InlineKeyboardMarkupSendVenueReplyMarkup } // IsReplyKeyboardMarkup reports whether SendVenueReplyMarkup is ReplyKeyboardMarkup. func (s SendVenueReplyMarkup) IsReplyKeyboardMarkup() bool { return s.Type == ReplyKeyboardMarkupSendVenueReplyMarkup } // IsReplyKeyboardRemove reports whether SendVenueReplyMarkup is ReplyKeyboardRemove. func (s SendVenueReplyMarkup) IsReplyKeyboardRemove() bool { return s.Type == ReplyKeyboardRemoveSendVenueReplyMarkup } // IsForceReply reports whether SendVenueReplyMarkup is ForceReply. func (s SendVenueReplyMarkup) IsForceReply() bool { return s.Type == ForceReplySendVenueReplyMarkup } // SetInlineKeyboardMarkup sets SendVenueReplyMarkup to InlineKeyboardMarkup. func (s *SendVenueReplyMarkup) SetInlineKeyboardMarkup(v InlineKeyboardMarkup) { s.Type = InlineKeyboardMarkupSendVenueReplyMarkup s.InlineKeyboardMarkup = v } // GetInlineKeyboardMarkup returns InlineKeyboardMarkup and true boolean if SendVenueReplyMarkup is InlineKeyboardMarkup. func (s SendVenueReplyMarkup) GetInlineKeyboardMarkup() (v InlineKeyboardMarkup, ok bool) { if !s.IsInlineKeyboardMarkup() { return v, false } return s.InlineKeyboardMarkup, true } // NewInlineKeyboardMarkupSendVenueReplyMarkup returns new SendVenueReplyMarkup from InlineKeyboardMarkup. func NewInlineKeyboardMarkupSendVenueReplyMarkup(v InlineKeyboardMarkup) SendVenueReplyMarkup { var s SendVenueReplyMarkup s.SetInlineKeyboardMarkup(v) return s } // SetReplyKeyboardMarkup sets SendVenueReplyMarkup to ReplyKeyboardMarkup. func (s *SendVenueReplyMarkup) SetReplyKeyboardMarkup(v ReplyKeyboardMarkup) { s.Type = ReplyKeyboardMarkupSendVenueReplyMarkup s.ReplyKeyboardMarkup = v } // GetReplyKeyboardMarkup returns ReplyKeyboardMarkup and true boolean if SendVenueReplyMarkup is ReplyKeyboardMarkup. func (s SendVenueReplyMarkup) GetReplyKeyboardMarkup() (v ReplyKeyboardMarkup, ok bool) { if !s.IsReplyKeyboardMarkup() { return v, false } return s.ReplyKeyboardMarkup, true } // NewReplyKeyboardMarkupSendVenueReplyMarkup returns new SendVenueReplyMarkup from ReplyKeyboardMarkup. func NewReplyKeyboardMarkupSendVenueReplyMarkup(v ReplyKeyboardMarkup) SendVenueReplyMarkup { var s SendVenueReplyMarkup s.SetReplyKeyboardMarkup(v) return s } // SetReplyKeyboardRemove sets SendVenueReplyMarkup to ReplyKeyboardRemove. func (s *SendVenueReplyMarkup) SetReplyKeyboardRemove(v ReplyKeyboardRemove) { s.Type = ReplyKeyboardRemoveSendVenueReplyMarkup s.ReplyKeyboardRemove = v } // GetReplyKeyboardRemove returns ReplyKeyboardRemove and true boolean if SendVenueReplyMarkup is ReplyKeyboardRemove. func (s SendVenueReplyMarkup) GetReplyKeyboardRemove() (v ReplyKeyboardRemove, ok bool) { if !s.IsReplyKeyboardRemove() { return v, false } return s.ReplyKeyboardRemove, true } // NewReplyKeyboardRemoveSendVenueReplyMarkup returns new SendVenueReplyMarkup from ReplyKeyboardRemove. func NewReplyKeyboardRemoveSendVenueReplyMarkup(v ReplyKeyboardRemove) SendVenueReplyMarkup { var s SendVenueReplyMarkup s.SetReplyKeyboardRemove(v) return s } // SetForceReply sets SendVenueReplyMarkup to ForceReply. func (s *SendVenueReplyMarkup) SetForceReply(v ForceReply) { s.Type = ForceReplySendVenueReplyMarkup s.ForceReply = v } // GetForceReply returns ForceReply and true boolean if SendVenueReplyMarkup is ForceReply. func (s SendVenueReplyMarkup) GetForceReply() (v ForceReply, ok bool) { if !s.IsForceReply() { return v, false } return s.ForceReply, true } // NewForceReplySendVenueReplyMarkup returns new SendVenueReplyMarkup from ForceReply. func NewForceReplySendVenueReplyMarkup(v ForceReply) SendVenueReplyMarkup { var s SendVenueReplyMarkup s.SetForceReply(v) return s } // Input for sendVideo. // Ref: #/components/schemas/sendVideo type SendVideo struct { ChatID ID `json:"chat_id"` // Video to send. Pass a file_id as String to send a video that exists on the Telegram servers // (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or // upload a new video using multipart/form-data. More info on Sending Files ». Video string `json:"video"` // Duration of sent video in seconds. Duration OptInt `json:"duration"` // Video width. Width OptInt `json:"width"` // Video height. Height OptInt `json:"height"` // Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported // server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's // width and height should not exceed 320. Ignored if the file is not uploaded using // multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can // pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data // under <file_attach_name>. More info on Sending Files ». Thumb OptString `json:"thumb"` // Video caption (may also be used when resending videos by file_id), 0-1024 characters after // entities parsing. Caption OptString `json:"caption"` // Mode for parsing entities in the video caption. See formatting options for more details. ParseMode OptString `json:"parse_mode"` // A JSON-serialized list of special entities that appear in the caption, which can be specified // instead of parse_mode. CaptionEntities []MessageEntity `json:"caption_entities"` // Pass True, if the uploaded video is suitable for streaming. SupportsStreaming OptBool `json:"supports_streaming"` // Sends the message silently. Users will receive a notification with no sound. DisableNotification OptBool `json:"disable_notification"` // If the message is a reply, ID of the original message. ReplyToMessageID OptInt `json:"reply_to_message_id"` // Pass True, if the message should be sent even if the specified replied-to message is not found. AllowSendingWithoutReply OptBool `json:"allow_sending_without_reply"` // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply // keyboard, instructions to remove reply keyboard or to force a reply from the user. ReplyMarkup OptSendVideoReplyMarkup `json:"reply_markup"` } // Input for sendVideoNote. // Ref: #/components/schemas/sendVideoNote type SendVideoNote struct { ChatID ID `json:"chat_id"` // Video note to send. Pass a file_id as String to send a video note that exists on the Telegram // servers (recommended) or upload a new video using multipart/form-data. More info on Sending Files // ». Sending video notes by a URL is currently unsupported. VideoNote string `json:"video_note"` // Duration of sent video in seconds. Duration OptInt `json:"duration"` // Video width and height, i.e. diameter of the video message. Length OptInt `json:"length"` // Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported // server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's // width and height should not exceed 320. Ignored if the file is not uploaded using // multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can // pass “attach://<file_attach_name>” if the thumbnail was uploaded using multipart/form-data // under <file_attach_name>. More info on Sending Files ». Thumb OptString `json:"thumb"` // Sends the message silently. Users will receive a notification with no sound. DisableNotification OptBool `json:"disable_notification"` // If the message is a reply, ID of the original message. ReplyToMessageID OptInt `json:"reply_to_message_id"` // Pass True, if the message should be sent even if the specified replied-to message is not found. AllowSendingWithoutReply OptBool `json:"allow_sending_without_reply"` // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply // keyboard, instructions to remove reply keyboard or to force a reply from the user. ReplyMarkup OptSendVideoNoteReplyMarkup `json:"reply_markup"` } // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply // keyboard, instructions to remove reply keyboard or to force a reply from the user. // SendVideoNoteReplyMarkup represents sum type. type SendVideoNoteReplyMarkup struct { Type SendVideoNoteReplyMarkupType // switch on this field InlineKeyboardMarkup InlineKeyboardMarkup ReplyKeyboardMarkup ReplyKeyboardMarkup ReplyKeyboardRemove ReplyKeyboardRemove ForceReply ForceReply } // SendVideoNoteReplyMarkupType is oneOf type of SendVideoNoteReplyMarkup. type SendVideoNoteReplyMarkupType string // Possible values for SendVideoNoteReplyMarkupType. const ( InlineKeyboardMarkupSendVideoNoteReplyMarkup SendVideoNoteReplyMarkupType = "InlineKeyboardMarkup" ReplyKeyboardMarkupSendVideoNoteReplyMarkup SendVideoNoteReplyMarkupType = "ReplyKeyboardMarkup" ReplyKeyboardRemoveSendVideoNoteReplyMarkup SendVideoNoteReplyMarkupType = "ReplyKeyboardRemove" ForceReplySendVideoNoteReplyMarkup SendVideoNoteReplyMarkupType = "ForceReply" ) // IsInlineKeyboardMarkup reports whether SendVideoNoteReplyMarkup is InlineKeyboardMarkup. func (s SendVideoNoteReplyMarkup) IsInlineKeyboardMarkup() bool { return s.Type == InlineKeyboardMarkupSendVideoNoteReplyMarkup } // IsReplyKeyboardMarkup reports whether SendVideoNoteReplyMarkup is ReplyKeyboardMarkup. func (s SendVideoNoteReplyMarkup) IsReplyKeyboardMarkup() bool { return s.Type == ReplyKeyboardMarkupSendVideoNoteReplyMarkup } // IsReplyKeyboardRemove reports whether SendVideoNoteReplyMarkup is ReplyKeyboardRemove. func (s SendVideoNoteReplyMarkup) IsReplyKeyboardRemove() bool { return s.Type == ReplyKeyboardRemoveSendVideoNoteReplyMarkup } // IsForceReply reports whether SendVideoNoteReplyMarkup is ForceReply. func (s SendVideoNoteReplyMarkup) IsForceReply() bool { return s.Type == ForceReplySendVideoNoteReplyMarkup } // SetInlineKeyboardMarkup sets SendVideoNoteReplyMarkup to InlineKeyboardMarkup. func (s *SendVideoNoteReplyMarkup) SetInlineKeyboardMarkup(v InlineKeyboardMarkup) { s.Type = InlineKeyboardMarkupSendVideoNoteReplyMarkup s.InlineKeyboardMarkup = v } // GetInlineKeyboardMarkup returns InlineKeyboardMarkup and true boolean if SendVideoNoteReplyMarkup is InlineKeyboardMarkup. func (s SendVideoNoteReplyMarkup) GetInlineKeyboardMarkup() (v InlineKeyboardMarkup, ok bool) { if !s.IsInlineKeyboardMarkup() { return v, false } return s.InlineKeyboardMarkup, true } // NewInlineKeyboardMarkupSendVideoNoteReplyMarkup returns new SendVideoNoteReplyMarkup from InlineKeyboardMarkup. func NewInlineKeyboardMarkupSendVideoNoteReplyMarkup(v InlineKeyboardMarkup) SendVideoNoteReplyMarkup { var s SendVideoNoteReplyMarkup s.SetInlineKeyboardMarkup(v) return s } // SetReplyKeyboardMarkup sets SendVideoNoteReplyMarkup to ReplyKeyboardMarkup. func (s *SendVideoNoteReplyMarkup) SetReplyKeyboardMarkup(v ReplyKeyboardMarkup) { s.Type = ReplyKeyboardMarkupSendVideoNoteReplyMarkup s.ReplyKeyboardMarkup = v } // GetReplyKeyboardMarkup returns ReplyKeyboardMarkup and true boolean if SendVideoNoteReplyMarkup is ReplyKeyboardMarkup. func (s SendVideoNoteReplyMarkup) GetReplyKeyboardMarkup() (v ReplyKeyboardMarkup, ok bool) { if !s.IsReplyKeyboardMarkup() { return v, false } return s.ReplyKeyboardMarkup, true } // NewReplyKeyboardMarkupSendVideoNoteReplyMarkup returns new SendVideoNoteReplyMarkup from ReplyKeyboardMarkup. func NewReplyKeyboardMarkupSendVideoNoteReplyMarkup(v ReplyKeyboardMarkup) SendVideoNoteReplyMarkup { var s SendVideoNoteReplyMarkup s.SetReplyKeyboardMarkup(v) return s } // SetReplyKeyboardRemove sets SendVideoNoteReplyMarkup to ReplyKeyboardRemove. func (s *SendVideoNoteReplyMarkup) SetReplyKeyboardRemove(v ReplyKeyboardRemove) { s.Type = ReplyKeyboardRemoveSendVideoNoteReplyMarkup s.ReplyKeyboardRemove = v } // GetReplyKeyboardRemove returns ReplyKeyboardRemove and true boolean if SendVideoNoteReplyMarkup is ReplyKeyboardRemove. func (s SendVideoNoteReplyMarkup) GetReplyKeyboardRemove() (v ReplyKeyboardRemove, ok bool) { if !s.IsReplyKeyboardRemove() { return v, false } return s.ReplyKeyboardRemove, true } // NewReplyKeyboardRemoveSendVideoNoteReplyMarkup returns new SendVideoNoteReplyMarkup from ReplyKeyboardRemove. func NewReplyKeyboardRemoveSendVideoNoteReplyMarkup(v ReplyKeyboardRemove) SendVideoNoteReplyMarkup { var s SendVideoNoteReplyMarkup s.SetReplyKeyboardRemove(v) return s } // SetForceReply sets SendVideoNoteReplyMarkup to ForceReply. func (s *SendVideoNoteReplyMarkup) SetForceReply(v ForceReply) { s.Type = ForceReplySendVideoNoteReplyMarkup s.ForceReply = v } // GetForceReply returns ForceReply and true boolean if SendVideoNoteReplyMarkup is ForceReply. func (s SendVideoNoteReplyMarkup) GetForceReply() (v ForceReply, ok bool) { if !s.IsForceReply() { return v, false } return s.ForceReply, true } // NewForceReplySendVideoNoteReplyMarkup returns new SendVideoNoteReplyMarkup from ForceReply. func NewForceReplySendVideoNoteReplyMarkup(v ForceReply) SendVideoNoteReplyMarkup { var s SendVideoNoteReplyMarkup s.SetForceReply(v) return s } // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply // keyboard, instructions to remove reply keyboard or to force a reply from the user. // SendVideoReplyMarkup represents sum type. type SendVideoReplyMarkup struct { Type SendVideoReplyMarkupType // switch on this field InlineKeyboardMarkup InlineKeyboardMarkup ReplyKeyboardMarkup ReplyKeyboardMarkup ReplyKeyboardRemove ReplyKeyboardRemove ForceReply ForceReply } // SendVideoReplyMarkupType is oneOf type of SendVideoReplyMarkup. type SendVideoReplyMarkupType string // Possible values for SendVideoReplyMarkupType. const ( InlineKeyboardMarkupSendVideoReplyMarkup SendVideoReplyMarkupType = "InlineKeyboardMarkup" ReplyKeyboardMarkupSendVideoReplyMarkup SendVideoReplyMarkupType = "ReplyKeyboardMarkup" ReplyKeyboardRemoveSendVideoReplyMarkup SendVideoReplyMarkupType = "ReplyKeyboardRemove" ForceReplySendVideoReplyMarkup SendVideoReplyMarkupType = "ForceReply" ) // IsInlineKeyboardMarkup reports whether SendVideoReplyMarkup is InlineKeyboardMarkup. func (s SendVideoReplyMarkup) IsInlineKeyboardMarkup() bool { return s.Type == InlineKeyboardMarkupSendVideoReplyMarkup } // IsReplyKeyboardMarkup reports whether SendVideoReplyMarkup is ReplyKeyboardMarkup. func (s SendVideoReplyMarkup) IsReplyKeyboardMarkup() bool { return s.Type == ReplyKeyboardMarkupSendVideoReplyMarkup } // IsReplyKeyboardRemove reports whether SendVideoReplyMarkup is ReplyKeyboardRemove. func (s SendVideoReplyMarkup) IsReplyKeyboardRemove() bool { return s.Type == ReplyKeyboardRemoveSendVideoReplyMarkup } // IsForceReply reports whether SendVideoReplyMarkup is ForceReply. func (s SendVideoReplyMarkup) IsForceReply() bool { return s.Type == ForceReplySendVideoReplyMarkup } // SetInlineKeyboardMarkup sets SendVideoReplyMarkup to InlineKeyboardMarkup. func (s *SendVideoReplyMarkup) SetInlineKeyboardMarkup(v InlineKeyboardMarkup) { s.Type = InlineKeyboardMarkupSendVideoReplyMarkup s.InlineKeyboardMarkup = v } // GetInlineKeyboardMarkup returns InlineKeyboardMarkup and true boolean if SendVideoReplyMarkup is InlineKeyboardMarkup. func (s SendVideoReplyMarkup) GetInlineKeyboardMarkup() (v InlineKeyboardMarkup, ok bool) { if !s.IsInlineKeyboardMarkup() { return v, false } return s.InlineKeyboardMarkup, true } // NewInlineKeyboardMarkupSendVideoReplyMarkup returns new SendVideoReplyMarkup from InlineKeyboardMarkup. func NewInlineKeyboardMarkupSendVideoReplyMarkup(v InlineKeyboardMarkup) SendVideoReplyMarkup { var s SendVideoReplyMarkup s.SetInlineKeyboardMarkup(v) return s } // SetReplyKeyboardMarkup sets SendVideoReplyMarkup to ReplyKeyboardMarkup. func (s *SendVideoReplyMarkup) SetReplyKeyboardMarkup(v ReplyKeyboardMarkup) { s.Type = ReplyKeyboardMarkupSendVideoReplyMarkup s.ReplyKeyboardMarkup = v } // GetReplyKeyboardMarkup returns ReplyKeyboardMarkup and true boolean if SendVideoReplyMarkup is ReplyKeyboardMarkup. func (s SendVideoReplyMarkup) GetReplyKeyboardMarkup() (v ReplyKeyboardMarkup, ok bool) { if !s.IsReplyKeyboardMarkup() { return v, false } return s.ReplyKeyboardMarkup, true } // NewReplyKeyboardMarkupSendVideoReplyMarkup returns new SendVideoReplyMarkup from ReplyKeyboardMarkup. func NewReplyKeyboardMarkupSendVideoReplyMarkup(v ReplyKeyboardMarkup) SendVideoReplyMarkup { var s SendVideoReplyMarkup s.SetReplyKeyboardMarkup(v) return s } // SetReplyKeyboardRemove sets SendVideoReplyMarkup to ReplyKeyboardRemove. func (s *SendVideoReplyMarkup) SetReplyKeyboardRemove(v ReplyKeyboardRemove) { s.Type = ReplyKeyboardRemoveSendVideoReplyMarkup s.ReplyKeyboardRemove = v } // GetReplyKeyboardRemove returns ReplyKeyboardRemove and true boolean if SendVideoReplyMarkup is ReplyKeyboardRemove. func (s SendVideoReplyMarkup) GetReplyKeyboardRemove() (v ReplyKeyboardRemove, ok bool) { if !s.IsReplyKeyboardRemove() { return v, false } return s.ReplyKeyboardRemove, true } // NewReplyKeyboardRemoveSendVideoReplyMarkup returns new SendVideoReplyMarkup from ReplyKeyboardRemove. func NewReplyKeyboardRemoveSendVideoReplyMarkup(v ReplyKeyboardRemove) SendVideoReplyMarkup { var s SendVideoReplyMarkup s.SetReplyKeyboardRemove(v) return s } // SetForceReply sets SendVideoReplyMarkup to ForceReply. func (s *SendVideoReplyMarkup) SetForceReply(v ForceReply) { s.Type = ForceReplySendVideoReplyMarkup s.ForceReply = v } // GetForceReply returns ForceReply and true boolean if SendVideoReplyMarkup is ForceReply. func (s SendVideoReplyMarkup) GetForceReply() (v ForceReply, ok bool) { if !s.IsForceReply() { return v, false } return s.ForceReply, true } // NewForceReplySendVideoReplyMarkup returns new SendVideoReplyMarkup from ForceReply. func NewForceReplySendVideoReplyMarkup(v ForceReply) SendVideoReplyMarkup { var s SendVideoReplyMarkup s.SetForceReply(v) return s } // Input for sendVoice. // Ref: #/components/schemas/sendVoice type SendVoice struct { ChatID ID `json:"chat_id"` // Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers // (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or // upload a new one using multipart/form-data. More info on Sending Files ». Voice string `json:"voice"` // Voice message caption, 0-1024 characters after entities parsing. Caption OptString `json:"caption"` // Mode for parsing entities in the voice message caption. See formatting options for more details. ParseMode OptString `json:"parse_mode"` // A JSON-serialized list of special entities that appear in the caption, which can be specified // instead of parse_mode. CaptionEntities []MessageEntity `json:"caption_entities"` // Duration of the voice message in seconds. Duration OptInt `json:"duration"` // Sends the message silently. Users will receive a notification with no sound. DisableNotification OptBool `json:"disable_notification"` // If the message is a reply, ID of the original message. ReplyToMessageID OptInt `json:"reply_to_message_id"` // Pass True, if the message should be sent even if the specified replied-to message is not found. AllowSendingWithoutReply OptBool `json:"allow_sending_without_reply"` // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply // keyboard, instructions to remove reply keyboard or to force a reply from the user. ReplyMarkup OptSendVoiceReplyMarkup `json:"reply_markup"` } // Additional interface options. A JSON-serialized object for an inline keyboard, custom reply // keyboard, instructions to remove reply keyboard or to force a reply from the user. // SendVoiceReplyMarkup represents sum type. type SendVoiceReplyMarkup struct { Type SendVoiceReplyMarkupType // switch on this field InlineKeyboardMarkup InlineKeyboardMarkup ReplyKeyboardMarkup ReplyKeyboardMarkup ReplyKeyboardRemove ReplyKeyboardRemove ForceReply ForceReply } // SendVoiceReplyMarkupType is oneOf type of SendVoiceReplyMarkup. type SendVoiceReplyMarkupType string // Possible values for SendVoiceReplyMarkupType. const ( InlineKeyboardMarkupSendVoiceReplyMarkup SendVoiceReplyMarkupType = "InlineKeyboardMarkup" ReplyKeyboardMarkupSendVoiceReplyMarkup SendVoiceReplyMarkupType = "ReplyKeyboardMarkup" ReplyKeyboardRemoveSendVoiceReplyMarkup SendVoiceReplyMarkupType = "ReplyKeyboardRemove" ForceReplySendVoiceReplyMarkup SendVoiceReplyMarkupType = "ForceReply" ) // IsInlineKeyboardMarkup reports whether SendVoiceReplyMarkup is InlineKeyboardMarkup. func (s SendVoiceReplyMarkup) IsInlineKeyboardMarkup() bool { return s.Type == InlineKeyboardMarkupSendVoiceReplyMarkup } // IsReplyKeyboardMarkup reports whether SendVoiceReplyMarkup is ReplyKeyboardMarkup. func (s SendVoiceReplyMarkup) IsReplyKeyboardMarkup() bool { return s.Type == ReplyKeyboardMarkupSendVoiceReplyMarkup } // IsReplyKeyboardRemove reports whether SendVoiceReplyMarkup is ReplyKeyboardRemove. func (s SendVoiceReplyMarkup) IsReplyKeyboardRemove() bool { return s.Type == ReplyKeyboardRemoveSendVoiceReplyMarkup } // IsForceReply reports whether SendVoiceReplyMarkup is ForceReply. func (s SendVoiceReplyMarkup) IsForceReply() bool { return s.Type == ForceReplySendVoiceReplyMarkup } // SetInlineKeyboardMarkup sets SendVoiceReplyMarkup to InlineKeyboardMarkup. func (s *SendVoiceReplyMarkup) SetInlineKeyboardMarkup(v InlineKeyboardMarkup) { s.Type = InlineKeyboardMarkupSendVoiceReplyMarkup s.InlineKeyboardMarkup = v } // GetInlineKeyboardMarkup returns InlineKeyboardMarkup and true boolean if SendVoiceReplyMarkup is InlineKeyboardMarkup. func (s SendVoiceReplyMarkup) GetInlineKeyboardMarkup() (v InlineKeyboardMarkup, ok bool) { if !s.IsInlineKeyboardMarkup() { return v, false } return s.InlineKeyboardMarkup, true } // NewInlineKeyboardMarkupSendVoiceReplyMarkup returns new SendVoiceReplyMarkup from InlineKeyboardMarkup. func NewInlineKeyboardMarkupSendVoiceReplyMarkup(v InlineKeyboardMarkup) SendVoiceReplyMarkup { var s SendVoiceReplyMarkup s.SetInlineKeyboardMarkup(v) return s } // SetReplyKeyboardMarkup sets SendVoiceReplyMarkup to ReplyKeyboardMarkup. func (s *SendVoiceReplyMarkup) SetReplyKeyboardMarkup(v ReplyKeyboardMarkup) { s.Type = ReplyKeyboardMarkupSendVoiceReplyMarkup s.ReplyKeyboardMarkup = v } // GetReplyKeyboardMarkup returns ReplyKeyboardMarkup and true boolean if SendVoiceReplyMarkup is ReplyKeyboardMarkup. func (s SendVoiceReplyMarkup) GetReplyKeyboardMarkup() (v ReplyKeyboardMarkup, ok bool) { if !s.IsReplyKeyboardMarkup() { return v, false } return s.ReplyKeyboardMarkup, true } // NewReplyKeyboardMarkupSendVoiceReplyMarkup returns new SendVoiceReplyMarkup from ReplyKeyboardMarkup. func NewReplyKeyboardMarkupSendVoiceReplyMarkup(v ReplyKeyboardMarkup) SendVoiceReplyMarkup { var s SendVoiceReplyMarkup s.SetReplyKeyboardMarkup(v) return s } // SetReplyKeyboardRemove sets SendVoiceReplyMarkup to ReplyKeyboardRemove. func (s *SendVoiceReplyMarkup) SetReplyKeyboardRemove(v ReplyKeyboardRemove) { s.Type = ReplyKeyboardRemoveSendVoiceReplyMarkup s.ReplyKeyboardRemove = v } // GetReplyKeyboardRemove returns ReplyKeyboardRemove and true boolean if SendVoiceReplyMarkup is ReplyKeyboardRemove. func (s SendVoiceReplyMarkup) GetReplyKeyboardRemove() (v ReplyKeyboardRemove, ok bool) { if !s.IsReplyKeyboardRemove() { return v, false } return s.ReplyKeyboardRemove, true } // NewReplyKeyboardRemoveSendVoiceReplyMarkup returns new SendVoiceReplyMarkup from ReplyKeyboardRemove. func NewReplyKeyboardRemoveSendVoiceReplyMarkup(v ReplyKeyboardRemove) SendVoiceReplyMarkup { var s SendVoiceReplyMarkup s.SetReplyKeyboardRemove(v) return s } // SetForceReply sets SendVoiceReplyMarkup to ForceReply. func (s *SendVoiceReplyMarkup) SetForceReply(v ForceReply) { s.Type = ForceReplySendVoiceReplyMarkup s.ForceReply = v } // GetForceReply returns ForceReply and true boolean if SendVoiceReplyMarkup is ForceReply. func (s SendVoiceReplyMarkup) GetForceReply() (v ForceReply, ok bool) { if !s.IsForceReply() { return v, false } return s.ForceReply, true } // NewForceReplySendVoiceReplyMarkup returns new SendVoiceReplyMarkup from ForceReply. func NewForceReplySendVoiceReplyMarkup(v ForceReply) SendVoiceReplyMarkup { var s SendVoiceReplyMarkup s.SetForceReply(v) return s } // Input for setChatAdministratorCustomTitle. // Ref: #/components/schemas/setChatAdministratorCustomTitle type SetChatAdministratorCustomTitle struct { ChatID ID `json:"chat_id"` // Unique identifier of the target user. UserID int `json:"user_id"` // New custom title for the administrator; 0-16 characters, emoji are not allowed. CustomTitle string `json:"custom_title"` } // Input for setChatDescription. // Ref: #/components/schemas/setChatDescription type SetChatDescription struct { ChatID ID `json:"chat_id"` // New chat description, 0-255 characters. Description OptString `json:"description"` } // Input for setChatPermissions. // Ref: #/components/schemas/setChatPermissions type SetChatPermissions struct { ChatID ID `json:"chat_id"` Permissions ChatPermissions `json:"permissions"` } // Input for setChatPhoto. // Ref: #/components/schemas/setChatPhoto type SetChatPhoto struct { ChatID ID `json:"chat_id"` // New chat photo, uploaded using multipart/form-data. Photo string `json:"photo"` } // Input for setChatStickerSet. // Ref: #/components/schemas/setChatStickerSet type SetChatStickerSet struct { ChatID ID `json:"chat_id"` // Name of the sticker set to be set as the group sticker set. StickerSetName string `json:"sticker_set_name"` } // Input for setChatTitle. // Ref: #/components/schemas/setChatTitle type SetChatTitle struct { ChatID ID `json:"chat_id"` // New chat title, 1-255 characters. Title string `json:"title"` } // Input for setGameScore. // Ref: #/components/schemas/setGameScore type SetGameScore struct { // User identifier. UserID int `json:"user_id"` // New score, must be non-negative. Score int `json:"score"` // Pass True, if the high score is allowed to decrease. This can be useful when fixing mistakes or // banning cheaters. Force OptBool `json:"force"` // Pass True, if the game message should not be automatically edited to include the current scoreboard. DisableEditMessage OptBool `json:"disable_edit_message"` // Required if inline_message_id is not specified. Unique identifier for the target chat. ChatID OptInt `json:"chat_id"` // Required if inline_message_id is not specified. Identifier of the sent message. MessageID OptInt `json:"message_id"` // Required if chat_id and message_id are not specified. Identifier of the inline message. InlineMessageID OptString `json:"inline_message_id"` } // Input for setMyCommands. // Ref: #/components/schemas/setMyCommands type SetMyCommands struct { // A JSON-serialized list of bot commands to be set as the list of the bot's commands. At most 100 // commands can be specified. Commands []BotCommand `json:"commands"` Scope OptBotCommandScope `json:"scope"` // A two-letter ISO 639-1 language code. If empty, commands will be applied to all users from the // given scope, for whose language there are no dedicated commands. LanguageCode OptString `json:"language_code"` } // Input for setPassportDataErrors. // Ref: #/components/schemas/setPassportDataErrors type SetPassportDataErrors struct { // User identifier. UserID int `json:"user_id"` // A JSON-serialized array describing the errors. Errors []PassportElementError `json:"errors"` } // Input for setStickerPositionInSet. // Ref: #/components/schemas/setStickerPositionInSet type SetStickerPositionInSet struct { // File identifier of the sticker. Sticker string `json:"sticker"` // New sticker position in the set, zero-based. Position int `json:"position"` } // Input for setStickerSetThumb. // Ref: #/components/schemas/setStickerSetThumb type SetStickerSetThumb struct { // Sticker set name. Name string `json:"name"` // User identifier of the sticker set owner. UserID int `json:"user_id"` // A PNG image with the thumbnail, must be up to 128 kilobytes in size and have width and height // exactly 100px, or a TGS animation with the thumbnail up to 32 kilobytes in size; see https://core. // telegram.org/animated_stickers#technical-requirements for animated sticker technical requirements. // Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an // HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using // multipart/form-data. More info on Sending Files ». Animated sticker set thumbnail can't be // uploaded via HTTP URL. Thumb OptString `json:"thumb"` } // Input for setWebhook. // Ref: #/components/schemas/setWebhook type SetWebhook struct { // HTTPS url to send updates to. Use an empty string to remove webhook integration. URL url.URL `json:"url"` // Upload your public key certificate so that the root certificate in use can be checked. See our // self-signed guide for details. Certificate OptString `json:"certificate"` // The fixed IP address which will be used to send webhook requests instead of the IP address // resolved through DNS. IPAddress OptString `json:"ip_address"` // Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. // Defaults to 40. Use lower values to limit the load on your bot's server, and higher values to // increase your bot's throughput. MaxConnections OptInt `json:"max_connections"` // A JSON-serialized list of the update types you want your bot to receive. For example, specify // [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these // types. See Update for a complete list of available update types. Specify an empty list to receive // all update types except chat_member (default). If not specified, the previous setting will be used. // Please note that this parameter doesn't affect updates created before the call to the setWebhook, // so unwanted updates may be received for a short period of time. AllowedUpdates []string `json:"allowed_updates"` // Pass True to drop all pending updates. DropPendingUpdates OptBool `json:"drop_pending_updates"` } // This object represents a shipping address. // Ref: #/components/schemas/ShippingAddress type ShippingAddress struct { // ISO 3166-1 alpha-2 country code. CountryCode string `json:"country_code"` // State, if applicable. State string `json:"state"` // City. City string `json:"city"` // First line for the address. StreetLine1 string `json:"street_line1"` // Second line for the address. StreetLine2 string `json:"street_line2"` // Address post code. PostCode string `json:"post_code"` } // This object represents one shipping option. // Ref: #/components/schemas/ShippingOption type ShippingOption struct { // Shipping option identifier. ID string `json:"id"` // Option title. Title string `json:"title"` // List of price portions. Prices []LabeledPrice `json:"prices"` } // This object represents a sticker. // Ref: #/components/schemas/Sticker type Sticker struct { // Identifier for this file, which can be used to download or reuse the file. FileID string `json:"file_id"` // Unique identifier for this file, which is supposed to be the same over time and for different bots. // Can't be used to download or reuse the file. FileUniqueID string `json:"file_unique_id"` // Sticker width. Width int `json:"width"` // Sticker height. Height int `json:"height"` // True, if the sticker is animated. IsAnimated bool `json:"is_animated"` Thumb OptPhotoSize `json:"thumb"` // Emoji associated with the sticker. Emoji OptString `json:"emoji"` // Name of the sticker set to which the sticker belongs. SetName OptString `json:"set_name"` MaskPosition OptMaskPosition `json:"mask_position"` // File size in bytes. FileSize OptInt `json:"file_size"` } // Input for stopMessageLiveLocation. // Ref: #/components/schemas/stopMessageLiveLocation type StopMessageLiveLocation struct { ChatID OptID `json:"chat_id"` // Required if inline_message_id is not specified. Identifier of the message with live location to // stop. MessageID OptInt `json:"message_id"` // Required if chat_id and message_id are not specified. Identifier of the inline message. InlineMessageID OptString `json:"inline_message_id"` ReplyMarkup OptInlineKeyboardMarkup `json:"reply_markup"` } // Input for stopPoll. // Ref: #/components/schemas/stopPoll type StopPoll struct { ChatID ID `json:"chat_id"` // Identifier of the original message with the poll. MessageID int `json:"message_id"` ReplyMarkup OptInlineKeyboardMarkup `json:"reply_markup"` } // This object contains basic information about a successful payment. // Ref: #/components/schemas/SuccessfulPayment type SuccessfulPayment struct { // Three-letter ISO 4217 currency code. Currency string `json:"currency"` // Total price in the smallest units of the currency (integer, not float/double). For example, for a // price of US$ 1.45 pass amount = 145. See the exp parameter in currencies.json, it shows the number // of digits past the decimal point for each currency (2 for the majority of currencies). TotalAmount int `json:"total_amount"` // Bot specified invoice payload. InvoicePayload string `json:"invoice_payload"` // Identifier of the shipping option chosen by the user. ShippingOptionID OptString `json:"shipping_option_id"` OrderInfo OptOrderInfo `json:"order_info"` // Telegram payment identifier. TelegramPaymentChargeID string `json:"telegram_payment_charge_id"` // Provider payment identifier. ProviderPaymentChargeID string `json:"provider_payment_charge_id"` } // Input for unbanChatMember. // Ref: #/components/schemas/unbanChatMember type UnbanChatMember struct { ChatID ID `json:"chat_id"` // Unique identifier of the target user. UserID int `json:"user_id"` // Do nothing if the user is not banned. OnlyIfBanned OptBool `json:"only_if_banned"` } // Input for unpinAllChatMessages. // Ref: #/components/schemas/unpinAllChatMessages type UnpinAllChatMessages struct { ChatID ID `json:"chat_id"` } // Input for unpinChatMessage. // Ref: #/components/schemas/unpinChatMessage type UnpinChatMessage struct { ChatID ID `json:"chat_id"` // Identifier of a message to unpin. If not specified, the most recent pinned message (by sending // date) will be unpinned. MessageID OptInt `json:"message_id"` } // Input for uploadStickerFile. // Ref: #/components/schemas/uploadStickerFile type UploadStickerFile struct { // User identifier of sticker file owner. UserID int `json:"user_id"` // PNG image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, // and either width or height must be exactly 512px. More info on Sending Files ». PNGSticker string `json:"png_sticker"` } // This object represents a Telegram user or bot. // Ref: #/components/schemas/User type User struct { // Unique identifier for this user or bot. This number may have more than 32 significant bits and // some programming languages may have difficulty/silent defects in interpreting it. But it has at // most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing // this identifier. ID int `json:"id"` // True, if this user is a bot. IsBot bool `json:"is_bot"` // User's or bot's first name. FirstName string `json:"first_name"` // User's or bot's last name. LastName OptString `json:"last_name"` // User's or bot's username. Username OptString `json:"username"` // IETF language tag of the user's language. LanguageCode OptString `json:"language_code"` // True, if the bot can be invited to groups. Returned only in getMe. CanJoinGroups OptBool `json:"can_join_groups"` // True, if privacy mode is disabled for the bot. Returned only in getMe. CanReadAllGroupMessages OptBool `json:"can_read_all_group_messages"` // True, if the bot supports inline queries. Returned only in getMe. SupportsInlineQueries OptBool `json:"supports_inline_queries"` } // This object represents a venue. // Ref: #/components/schemas/Venue type Venue struct { Location Location `json:"location"` // Name of the venue. Title string `json:"title"` // Address of the venue. Address string `json:"address"` // Foursquare identifier of the venue. FoursquareID OptString `json:"foursquare_id"` // Foursquare type of the venue. (For example, “arts_entertainment/default”, // “arts_entertainment/aquarium” or “food/icecream”.). FoursquareType OptString `json:"foursquare_type"` // Google Places identifier of the venue. GooglePlaceID OptString `json:"google_place_id"` // Google Places type of the venue. (See supported types.). GooglePlaceType OptString `json:"google_place_type"` } // This object represents a video file. // Ref: #/components/schemas/Video type Video struct { // Identifier for this file, which can be used to download or reuse the file. FileID string `json:"file_id"` // Unique identifier for this file, which is supposed to be the same over time and for different bots. // Can't be used to download or reuse the file. FileUniqueID string `json:"file_unique_id"` // Video width as defined by sender. Width int `json:"width"` // Video height as defined by sender. Height int `json:"height"` // Duration of the video in seconds as defined by sender. Duration int `json:"duration"` Thumb OptPhotoSize `json:"thumb"` // Original filename as defined by sender. FileName OptString `json:"file_name"` // Mime type of a file as defined by sender. MimeType OptString `json:"mime_type"` // File size in bytes. FileSize OptInt `json:"file_size"` } // This object represents a video message (available in Telegram apps as of v.4.0). // Ref: #/components/schemas/VideoNote type VideoNote struct { // Identifier for this file, which can be used to download or reuse the file. FileID string `json:"file_id"` // Unique identifier for this file, which is supposed to be the same over time and for different bots. // Can't be used to download or reuse the file. FileUniqueID string `json:"file_unique_id"` // Video width and height (diameter of the video message) as defined by sender. Length int `json:"length"` // Duration of the video in seconds as defined by sender. Duration int `json:"duration"` Thumb OptPhotoSize `json:"thumb"` // File size in bytes. FileSize OptInt `json:"file_size"` } // This object represents a voice note. // Ref: #/components/schemas/Voice type Voice struct { // Identifier for this file, which can be used to download or reuse the file. FileID string `json:"file_id"` // Unique identifier for this file, which is supposed to be the same over time and for different bots. // Can't be used to download or reuse the file. FileUniqueID string `json:"file_unique_id"` // Duration of the audio in seconds as defined by sender. Duration int `json:"duration"` // MIME type of the file as defined by sender. MimeType OptString `json:"mime_type"` // File size in bytes. FileSize OptInt `json:"file_size"` } // This object represents a service message about a voice chat ended in the chat. // Ref: #/components/schemas/VoiceChatEnded type VoiceChatEnded struct { // Voice chat duration in seconds. Duration int `json:"duration"` } // This object represents a service message about new members invited to a voice chat. // Ref: #/components/schemas/VoiceChatParticipantsInvited type VoiceChatParticipantsInvited struct { // New members that were invited to the voice chat. Users []User `json:"users"` } // This object represents a service message about a voice chat scheduled in the chat. // Ref: #/components/schemas/VoiceChatScheduled type VoiceChatScheduled struct { // Point in time (Unix timestamp) when the voice chat is supposed to be started by a chat // administrator. StartDate int `json:"start_date"` } // This object represents a service message about a voice chat started in the chat. Currently holds // no information. // Ref: #/components/schemas/VoiceChatStarted type VoiceChatStarted struct{}
# grc overides for ls # Made possible through contributions from generous benefactors like # `brew install coreutils` if $(gls &>/dev/null) then alias ls="gls -F --color" alias l="gls -lAh --color" alias ll="gls -l --color" alias la='gls -A --color' fi if [[ $OS == 'LINUX' ]] then alias pbcopy='xsel --clipboard --input' alias pbpaste='xsel --clipboard --output' alias bigs='du -hs * | sort -hr' elif [[ `os` == 'osx' ]] then alias bigs='du -hs * | gsort -hr' fi alias json='python3 -m json.tool' alias js=json alias x=xargs alias bash='PS1="in $(pwd) › " bash' close_all_panes() { YELLOW='\033[0;33m' RESET='\033[0m' echo -n "${YELLOW}Press <return> to close all panes ${RESET}" read tmux kill-pane -a tmux kill-pane } # typos alias clera=clear alias cler=clear alias eixt=exit alias eit=exit alias exi=exit alias :q=exit alias :qa=close_all_panes alias :wq=exit # metro transit alias metro="open ~/.metro-transit/routes/535.pdf" alias bus="open ~/.metro-transit/routes/535.pdf" alias watch='watch --color '
#!/bin/bash RED='\033[0;31m' GREEN='\033[0;32m' NC='\033[0m' function check_err() { if [ $1 -ne 0 ]; then echo -e "${RED}=========\nFailed\n=========${NC}" exit 1; fi echo -e "${GREEN}===========\nSuccess!!!\n===========${NC}" } echo "Installing MongoDB" echo "Step 1. Add repo" sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927 && \ sudo bash -c 'echo "deb http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.2 multiverse" > /etc/apt/sources.list.d/mongodb-org-3.2.list' check_err $? #if [ $? -ne 0 ]; then # echo "Repo install error: $repo" # exit 1; #fi echo "Step 2. Install mongo" sudo apt update && sudo apt install -y mongodb-org check_err $? echo "Step 3. Start mongodb" sudo systemctl start mongod && sudo systemctl enable mongod check_err $?
""" Parse the following html string and print the text between the h3 tags. """ import bs4 html_string = "<h3>This is an example</h3><p>This is some text</p>" soup = bs4.BeautifulSoup(html_string, 'html.parser') h3_tag = soup.find('h3') if h3_tag: print(h3_tag.text)
package uk.gov.companieshouse.ocrapiconsumer.request; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import uk.gov.companieshouse.logging.Logger; import uk.gov.companieshouse.logging.LoggerFactory; import uk.gov.companieshouse.ocr.OcrRequestMessage; import uk.gov.companieshouse.ocrapiconsumer.OcrApiConsumerApplication; import java.util.LinkedHashMap; import java.util.Map; @Service public class OcrApiConsumerService { private static final Logger LOG = LoggerFactory.getLogger(OcrApiConsumerApplication.APPLICATION_NAME_SPACE); private final OcrApiRequestRestClient ocrApiRequestRestClient; private final ImageRestClient imageRestClient; private final CallbackExtractedTextRestClient callbackExtractedTextRestClient; @Autowired public OcrApiConsumerService(OcrApiRequestRestClient ocrApiRequestRestClient, ImageRestClient imageRestClient, CallbackExtractedTextRestClient callbackExtractedTextRestClient) { this.ocrApiRequestRestClient = ocrApiRequestRestClient; this.imageRestClient = imageRestClient; this.callbackExtractedTextRestClient = callbackExtractedTextRestClient; } public void ocrRequest(OcrRequestMessage message) { orchestrateOcrRequest(new OcrRequestDTO(message)); } @Async public void processOcrRequest(OcrRequestDTO ocrRequestDTO) { orchestrateOcrRequest(ocrRequestDTO); } private void orchestrateOcrRequest(OcrRequestDTO ocrRequestDTO) { LOG.infoContext(ocrRequestDTO.getContextId(), String.format("Request received with Image Endpoint: %s, Extracted Text Endpoint: %s", ocrRequestDTO.getImageEndpoint(), ocrRequestDTO.getConvertedTextEndpoint()), null); LOG.debugContext(ocrRequestDTO.getContextId(), "Getting the TIFF image", null); byte[] image = getImageContents(ocrRequestDTO); LOG.debugContext(ocrRequestDTO.getContextId(), "Sending image to ocr microservice for conversion", imageLogMap(image)); ResponseEntity<ExtractTextResultDTO> response = sendRequestToOcrMicroservice(ocrRequestDTO.getContextId(), image, ocrRequestDTO.getResponseId()); ExtractTextResultDTO extractedText = null; Map<String, Object> metadata = null; if (response != null) { extractedText = response.getBody(); metadata = extractedText != null ? extractedText.metadataMap() : null; } LOG.debugContext(ocrRequestDTO.getContextId(), "Sending the extracted text response for the articles of association", metadata); sendTextResult(ocrRequestDTO, extractedText); } private Map<String, Object> imageLogMap(byte[] image) { Map<String,Object> map = new LinkedHashMap<>(); map.put("image_length", image.length); return map; } private byte[] getImageContents(OcrRequestDTO ocrRequestDTO) { return imageRestClient.getImageContentsFromEndpoint(ocrRequestDTO.getContextId(), ocrRequestDTO.getImageEndpoint()); } private ResponseEntity<ExtractTextResultDTO> sendRequestToOcrMicroservice(String contextId, byte[] image, String responseId) { return ocrApiRequestRestClient.obtainExtractTextResult(contextId, image, responseId); } private void sendTextResult(OcrRequestDTO ocrRequestDTO, ExtractTextResultDTO extractedText) { callbackExtractedTextRestClient.sendTextResult(ocrRequestDTO.getConvertedTextEndpoint(), extractedText); } }
function countOccurrences(arr) { let count = {}; arr.forEach(num => { if (count[num]) { count[num]++; } else { count[num] = 1; } }); return count; }
package Controller; import Model.Computer; import Model.FileDownload; import Model.FileSeed; import Model.FileShare; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import org.apache.commons.codec.digest.DigestUtils; import util.Constant; import java.io.File; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.Queue; import java.util.zip.Adler32; import java.util.zip.Checksum; public class DownloadController extends Thread { private FileDownload fileDownload; private RandomAccessFile randomAccessFile; private ArrayList<Computer> listCom; private HashMap<Integer, Integer> listIndex = new HashMap<>(); private Queue<JsonObject> listPart = new LinkedList<>(); private boolean isEndTask = false; // private ArrayList public DownloadController(FileSeed fileSeed){ this.fileDownload = new FileDownload(fileSeed); this.listCom = fileSeed.getListComputer(); File file = new File(fileDownload.getPath()); try { if(!file.exists()){ file.createNewFile(); this.randomAccessFile = new RandomAccessFile(fileDownload.getPath(), "rw"); this.randomAccessFile.setLength(fileDownload.getSize()); // randomAccessFile.close(); } }catch (Exception e){ System.out.println("Create empty error: " + e.getMessage()); } if(listCom.size() == 1){ PackageController.getInstance().sendDownloadRangeRequest(listCom.get(0).getIp(), listCom.get(0).getPort(), fileDownload.getMd5(), 0, fileDownload.getTotalPart()-1); } for (int i = 0; i < this.fileDownload.getTotalPart(); i++){ this.listIndex.put(i, 0); } // int leftNumPart = fileDownload.getTotalPart() % this.listCom.size(); // if() // int numCom = this.listCom.size(); // for(int i = 0; i < numCom; i++){ // int startIndex = numCom*i; // int endIndex = numCom*(i+1); // } } @Override public void run() { super.run(); while (!this.isEndTask){ if(this.listPart.size() == 0) continue; JsonObject jsonObject = this.listPart.poll(); JsonArray dataJson = jsonObject.get("data").getAsJsonArray(); byte[] data = new byte[dataJson.size()]; for(int i = 0; i < dataJson.size(); i++){ data[i] = (byte)dataJson.get(i).getAsInt(); } Checksum checker = new Adler32(); System.out.println("wr"); ((Adler32) checker).update(data); long checksum = jsonObject.get("checksum").getAsLong(); int indexPart = jsonObject.get("indexPart").getAsInt(); if(checker.getValue() == checksum){ System.out.println("+++++++"); addPartToFile(indexPart, data); } } if(isEndTask){ FileShare fileShare = new FileShare(); fileShare.setName(fileDownload.getName()); fileShare.setMd5(fileDownload.getMd5()); fileShare.setPath(fileDownload.getPath()); fileShare.setSize(fileDownload.getSize()); MyComputer.getInstance().getSharingList().addElement(fileShare); } } public void addDataPartToQueue(JsonObject jsonObject){ this.listPart.add(jsonObject); } public void addPartToFile(int index, byte[] data){ try { if(this.listIndex.containsKey(index)){ System.out.println("write " + index); randomAccessFile.seek(index * Constant.PART_SIZE); randomAccessFile.write(data); this.listIndex.remove(index); this.fileDownload.addDownloadedSize(data.length); if(this.listIndex.isEmpty()){ this.isEndTask = true; this.fileDownload.setStatus(Constant.DOWNLOADED); System.out.println("write done"); randomAccessFile.close(); } } }catch (Exception e){ System.out.println("Write part error: " + e.getMessage()); } } public FileDownload getFileDownload() { return fileDownload; } }
import sqlite3 from sqlite3 import Error from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker def create_new_db(db_file): """ create a database connection to an SQLite database """ conn=None try: conn=sqlite3.connect(db_file) print(sqlite3.version) except Exception as e: print(e) finally: if conn: conn.close() #Create a Network table in the database and add frame data to it def create_connection(db_file): """ create a connection to the specified SQLite database file (db_file) :param db_file: database file :return: connection object (or None if not successful)""" conn=None try: conn = sqlite3.connect(db_file) return conn except Exception as e: print(e) return conn def create_table(conn, table_creation_sql_statement): """ create a table using the table_creation_sql_statement :param conn: Connection object :param table_creation_sql_statement: an sqlite CREATE TABLE statement :return: """ try: c = conn.cursor() c.execute(table_creation_sql_statement) except Exception as e: print(e) ################################################## # For step2 ### This code adapted from ### ### https://writeonly.wordpress.com/2009/07/16/simple-read-only-sqlalchemy-sessions/ ### used to ensure input SQL query string will effectively not have write access def abort_ro(*args,**kwargs): ''' the terrible consequences for trying to flush to the db ''' print("No writing allowed, tsk! We're telling mom!") return def db_setup(connstring,readOnly,echo): engine = create_engine(connstring, echo=echo) Session = sessionmaker( bind=engine, autoflush=not readOnly, autocommit=not readOnly ) session = Session() if readOnly: session.flush = abort_ro # now it won't flush! return session, engine ### ### ###
<filename>MyNotesApp/app/src/main/java/com/ramusthastudio/mynotesapp/MainActivity.java package com.ramusthastudio.mynotesapp; import android.annotation.SuppressLint; import android.content.Intent; import android.database.Cursor; import android.os.AsyncTask; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ProgressBar; import static com.ramusthastudio.mynotesapp.DatabaseContract.CONTENT_URI; import static com.ramusthastudio.mynotesapp.FormAddUpdateActivity.REQUEST_UPDATE; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private RecyclerView fNotesListView; private ProgressBar fProgressBarView; private FloatingActionButton fFabAddView; private Cursor list; private NoteAdapter adapter; private final NoteHelper noteHelper = new NoteHelper(this); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (getSupportActionBar() != null) { getSupportActionBar().setTitle("Notes"); } fNotesListView = findViewById(R.id.rv_notes); fProgressBarView = findViewById(R.id.progressbar); fFabAddView = findViewById(R.id.fab_add); fNotesListView.setLayoutManager(new LinearLayoutManager(this)); fNotesListView.setHasFixedSize(true); fFabAddView.setOnClickListener(this); noteHelper.open(); adapter = new NoteAdapter(this); adapter.setListNotes(list); fNotesListView.setAdapter(adapter); new LoadNoteAsync().execute(); } @Override protected void onResume() { super.onResume(); } @Override public void onClick(View view) { if (view.getId() == R.id.fab_add) { Intent intent = new Intent(MainActivity.this, FormAddUpdateActivity.class); startActivityForResult(intent, FormAddUpdateActivity.REQUEST_ADD); } } @SuppressLint("StaticFieldLeak") private class LoadNoteAsync extends AsyncTask<Void, Void, Cursor> { @Override protected void onPreExecute() { super.onPreExecute(); fNotesListView.setVisibility(View.GONE); fProgressBarView.setVisibility(View.VISIBLE); } @Override protected Cursor doInBackground(Void... voids) { return getContentResolver().query(CONTENT_URI, null, null, null, null); } @Override protected void onPostExecute(Cursor notes) { super.onPostExecute(notes); fNotesListView.setVisibility(View.VISIBLE); fProgressBarView.setVisibility(View.GONE); list = notes; adapter.setListNotes(list); adapter.notifyDataSetChanged(); if (list.getCount() == 0) { showSnackbarMessage("Tidak ada data saat ini"); } } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == FormAddUpdateActivity.REQUEST_ADD) { if (resultCode == FormAddUpdateActivity.RESULT_ADD) { new LoadNoteAsync().execute(); showSnackbarMessage("Satu item berhasil ditambahkan"); } } else if (requestCode == REQUEST_UPDATE) { if (resultCode == FormAddUpdateActivity.RESULT_UPDATE) { new LoadNoteAsync().execute(); showSnackbarMessage("Satu item berhasil diubah"); } else if (resultCode == FormAddUpdateActivity.RESULT_DELETE) { new LoadNoteAsync().execute(); showSnackbarMessage("Satu item berhasil dihapus"); } } } @Override protected void onDestroy() { super.onDestroy(); noteHelper.close(); } private void showSnackbarMessage(String message) { Snackbar.make(fNotesListView, message, Snackbar.LENGTH_SHORT).show(); } }
#!/bin/bash -e managed_distribs="jessie wheezy centos6 archlinux" usage() { echo "$* usage: $(basename $0) [-d] [-v] [-h] [test1 test2 ...] or: $(basename $0) -q -d : activates debug mode -v : gets verbose (mainly outputs docker outputs) -q : query the list of managed distributions -p : run tests matching a given pattern -h : this help If tests names are passed as arguments, only those will run. Default is to run all tests. " exit } start_container() { local container="$1" # sad, but if I don't do this and run two times it tries to build while removal in progress. while (docker ps -a | grep ${container} >/dev/null 2>&1); do sleep 1 ; done docker ps -a --format="{{.Names}}" | grep '^'${container}'$' >/dev/null 2>&1 && docker rm --force ${container} >/dev/null eval echo "Running docker with flags [${docker_flags}]" ${output} docker run -d ${docker_flags} ${docker_volumes} --name=${container} --hostname=${container} ${docker_image} if grep jessie <(echo $distrib_name) >/dev/null then #wait for systemd to be ready while ! docker exec $container systemctl status >/dev/null ; do sleep 1 ; done #wait for tmpfiles cleaner to be started so that it does not clean /tmp while tests are running while ! docker exec $container systemctl status systemd-tmpfiles-clean.timer >/dev/null ; do sleep 1 ; done fi if grep wheezy <(echo $distrib_name) >/dev/null then tst_file=$(docker exec $container mktemp) max_wait=10 while [ ${max_wait} -gt 0 ] ; do max_wait=$((max_wait-1)) [ $(docker exec $container ls ${tst_file} >/dev/null 2>&1 | wc -l ) -eq 0 ] && max_wait=0 sleep 1 done fi } format() { local color=$1 shift if [ -t 1 ] ; then echo -en "$color" ; fi if [ $# -gt 0 ] then [[ $verbose_flag -eq 0 ]] && echo $* else [[ $verbose_flag -eq 0 ]] && cat fi if [ -t 1 ] ; then echo -en "$NOCOLOR" ; fi } docker_image="multimediabs/plumb_unit:centos6" init=system5 cluster_mode=0 cd $(dirname $0) test_name=$(basename $(cd ..; pwd)) distrib_name=$(basename $0 | sed -r 's/run_tests_*([^_]*)(_cluster)?.sh/\1/') grep _cluster <(basename $0) >/dev/null && cluster_mode=1 [ ${cluster_mode} -eq 1 ] && cluster=_cluster if [ $distrib_name ] then distrib=_${distrib_name} [ "${distrib_name}" == "jessie" ] && docker_image="multimediabs/plumb_unit:debian_jessie" && init=systemd [ "${distrib_name}" == "wheezy" ] && docker_image="multimediabs/plumb_unit:debian_wheezy" [ "${distrib_name}" == "centos6" ] && docker_image="multimediabs/plumb_unit:centos6" [ "${distrib_name}" == "archlinux" ] && docker_image="multimediabs/plumb_unit:archlinux" else #echo "No distribution specified. Running tests for $(echo ${docker_image} | sed 's/^.*://')" distrib=_centos6 # we do not want $distrib_name to be set here fi ESCAPE=$(printf "\033") NOCOLOR="${ESCAPE}[0m" RED="${ESCAPE}[91m" GREEN="${ESCAPE}[92m" YELLOW="${ESCAPE}[93m" BLUE="${ESCAPE}[94m" docker_flags_file=".docker_flags" roles_path="$(readlink -f ../..)" inside_roles_path="/etc/ansible/roles" [ ${cluster_mode} -eq 1 ] && inside_roles_path=${roles_path} inside_tests_path="${inside_roles_path}/${test_name}/tests" verbose_flag=0 debug_flag=0 while getopts "vhdqp:" name do case $name in v) verbose_flag=1 ;; d) debug_flag=1 ;; q) echo ${managed_distribs} exit ;; p) list_of_patterns+=("-p $OPTARG") ;; h) usage ;; esac done shift $((OPTIND-1)) [ $verbose_flag -eq 0 ] && output=">/dev/null 2>&1" || output="2>&1" bash_unit="${inside_tests_path}/bash_unit" files_with_tests=$(find . | sed '/.*test_.*'${distrib}${cluster}'$/!d;/~$/d' | sed "s:./:${inside_tests_path}/:g" | xargs) run_test="${bash_unit} ${list_of_patterns[@]} ${files_with_tests}" container_base_name=$(echo ${test_name} | tr -d "_") containers=${container_base_name} [ ${cluster_mode} -eq 1 ] && containers="${container_base_name}01 ${container_base_name}02" if [ -f /.dockerenv -a $(id -u) -eq 0 ] then ${run_test} else if [ -f Dockerfile ] then format ${BLUE} -n "Building ${test_name} ${docker_build_flags} container..." eval docker build -t ${test_name} ${docker_build_flags} . ${output} || exit 42 format ${GREEN} "DONE" docker_image=${test_name} fi [ $init == "systemd" ] && docker_flags="--privileged" docker_exec_flags="-i" docker_volumes="-v $(cd ${roles_path};pwd):${inside_roles_path}" [ ${cluster_mode} -eq 1 ] && docker_volumes= docker_network_flags="" if [ ${cluster_mode} -eq 1 ] then docker_network_flags="--network ${test_name}" docker network ls --format={{.Name}} |grep '^'${test_name}'$' || docker network create ${test_name} fi [ -t 1 ] && docker_exec_flags="$docker_exec_flags -t" docker_flags="$docker_flags $docker_network_flags $([ -f ${docker_flags_file} ] && cat ${docker_flags_file} || true)" for container in ${containers} do start_container ${container} done trap "docker rm --force ${containers} >/dev/null" EXIT if [ ${cluster_mode} -eq 0 ] then [ $debug_flag -eq 1 ] && run_test=/bin/bash docker exec -e ftp_proxy="${ftp_proxy}" ${docker_exec_flags} $container /bin/bash -c "exec >/dev/tty 2>/dev/tty </dev/tty ; cd ${inside_tests_path} ; ${run_test}" result=$? else mkdir -p roles [ -L roles/${test_name} ] || ln -s ../.. roles/${test_name} if [ $debug_flag -eq 1 ] then echo "you're in debug mode" echo "once debug done, remove the containers by running the following command :" echo "docker rm -f ${containers}" trap - EXIT run_test="echo -n" fi ${run_test} result=$? fi fi exit $result
sleep 2 sudo supervisorctl restart smart-scripts sleep 3 sudo chmod 777 /home/config/smart-scripts.sock sudo service nginx restart
using System.Collections.Generic; using System.Threading.Tasks; public static class CollectionExtensions { public static void RemoveWithLock<T>(this ICollection<T> collection, T item, AsyncReaderWriterLock rwLock) { using (rwLock.WriterLock()) { collection.Remove(item); } } public static async Task RemoveWithLockAsync<T>(this ICollection<T> collection, T item, AsyncReaderWriterLock rwLock) { using (await rwLock.WriterLockAsync()) { collection.Remove(item); } } }
// Define the OrePricesState enum const OrePricesState = { SET: 'set', NOT_SET: 'not_set' }; class OrePriceManager { constructor() { this.orePricesState = OrePricesState.NOT_SET; } setOrePrices(prices) { if (this.validatePrices(prices)) { this.orePricesState = OrePricesState.SET; console.log("Ore prices are set"); } else { console.log("Ore prices are not set"); } } validatePrices(prices) { // Add validation logic for ore prices // For example, check if all prices are positive numbers return prices.every(price => price > 0); } } // Example usage const manager = new OrePriceManager(); manager.setOrePrices([10, 20, 30]); // Output: Ore prices are set manager.setOrePrices([-5, 15, 25]); // Output: Ore prices are not set
import React from 'react' import PropTypes from 'prop-types' import styled from 'styled-components' const Button = styled.div` align-self: center; justify-self: flex-end; amp-social-share { align-items: center; background: none; border: 1px solid var(--c_7); border-radius: 8px; box-sizing: border-box; color: var(--c_7); display: flex; font-size: 0.8rem; font-weight: bold; justify-content: center; padding: 0 16px; } ` export default function Share({ meta }) { return ( <Button> <amp-social-share width="79px" height="32px" type="system" data-param-text={meta.title} data-param-url={meta.url}> SHARE </amp-social-share> </Button> ) } Share.propTypes = { meta: PropTypes.object, }
# # Copyright (c) Contributors to the Open 3D Engine Project. # For complete copyright and license terms please see the LICENSE at the root of this distribution. # # SPDX-License-Identifier: Apache-2.0 OR MIT # # rm -rf temp/build_test mkdir temp/build_test cmake -S test -B temp/build_test -G Xcode \ -DCMAKE_TOOLCHAIN_FILE=../../../../Scripts/cmake/Platform/iOS/Toolchain_ios.cmake \ -DCMAKE_MODULE_PATH="$DOWNLOADED_PACKAGE_FOLDERS;$PACKAGE_ROOT" || exit 1 cmake --build temp/build_test --parallel --config Release || exit 1 # we can't actually run it on ios, that'd require an emulator or device as well as # cert / signing - but we can at least make sure it compiles. exit 0
<reponame>d-ashe/go-scrt-events package types import ( b64 "encoding/base64" "strconv" "encoding/json" "github.com/sirupsen/logrus" ) //WsResponse is used to unmarshall JSONRPC responses type WsResponse struct { JSONRPC string `json:"jsonrpc"` ID int `json:"id"` RespResult json.RawMessage `json:"result"` } //StatusResult is used to unmarshall JSONRPC responses for status? endpoint type StatusResult struct { NInfo NodeInfo `json:"node_info"` SyInfo SyncInfo `json:"sync_info"` ValInfo ValidatorInfo `json:"validator_info"` } type ValidatorInfo struct { Address string `json:"address"` PubKey PubKeyStatus `json:"pub_key"` VotingPower string `json:"voting_power"` } type PubKeyStatus struct { PType string `json:"type"` PValue string `json:"value"` } type NodeInfo struct { PVersion ProtocolVersion `json:"protocol_version"` ID string `json:"id"` ListenAddr string `json:"listen_addr"` Network string `json:"network"` Version string `json:"version"` Channels string `json:"channels"` Moniker string `json:"moniker"` OtherInfo OtherStatus `json:"other"` } type OtherStatus struct { TxIndex string `json:"tx_index"` RpcAddr string `json:"rpc_address"` } type ProtocolVersion struct { P2P string `json:"p2p"` Block string `json:"block"` App string `json:"app"` } type SyncInfo struct { LatestBlockHash string `json:"latest_block_hash"` LatestAppHash string `json:"latest_app_hash"` LatestBlockHeight string `json:"latest_block_height"` LatestBlockTime string `json:"latest_block_time"` EarliestBlockHash string `json:"earliest_block_hash"` EarliestAppHash string `json:"earliest_app_hash"` EarliestBlockHeight string `json:"earliest_block_height"` EarliestBlockTime string `json:"earliest_block_time"` CatchingUp bool `json:"catching_up"` } //BlockResult is used to unmarshall JSONRPC responses for block_results?height={n} endpoint type BlockResult struct { Height string `json:"height"` Txs []Tx `json:"txs_results"` BeginBlockEvents []Event `json:"begin_block_events"` EndBlockEvents []Event `json:"end_block_events"` ValidatorUpdates json.RawMessage `json:"validator_updates"` ConsensusParamUpdates json.RawMessage `json:"consensus_param_updates"` } //BlockResult is used to unmarshall JSONRPC responses type BlockResultDB struct { tableName struct{} `pg:"block"` ID int `pg:block_id",pk"` ChainId string Height int Txs []Tx `pg:"rel:has-many,join_fk:block_id"` BeginBlockEvents []Event `pg:"rel:has-many,join_fk:block_id"` EndBlockEvents []Event `pg:"rel:has-many,join_fk:block_id"` ValidatorUpdates json.RawMessage ConsensusParamUpdates json.RawMessage } //Tx is used to unmarshall JSONRPC responses type Tx struct { tableName struct{} `pg:"tx"` ID int `pg:tx_id",pk"` BlockId int `pg:block_id` Code int `json:"code"` CodeSpace string `json:"codespace"` Info string `json:"info"` Data string `json:"data"` GasWanted string `json:"gasWanted"` GasUsed string `json:"gasUsed"` Log string `json:"log"` Events []Event `json:"events" pg:"rel:has-many,join_fk:tx_id"` } //Event is used to unmarshall JSONRPC responses type Event struct { tableName struct{} `pg:"events"` ID int `pg:e_id",pk"` BlockId int `pg:block_id` TxId int `pg:tx_id` Type string `json:"type"` Attributes []Attribute `json:"attributes"` } //Attribute is used to unmarshall JSONRPC responses type Attribute struct { Key string `json:"key"` Value string `json:"value"` } func (attr *Attribute) decodeAttribute() (attrOut Attribute){ decKey, err1 := b64.StdEncoding.DecodeString(attr.Key) if err1 != nil { logrus.Fatal("read:", err1) } else { attrOut.Key = string(decKey[:]) } decValue, err2 := b64.StdEncoding.DecodeString(attr.Value) if err2 != nil { logrus.Fatal("read:", err2) } else { attrOut.Value = string(decValue[:]) } return attrOut } func (ev *Event) decodeEventAttributes() (evOut Event){ var attrsOut []Attribute for _, x := range ev.Attributes { attrsOut = append(attrsOut, x.decodeAttribute()) } evOut.Attributes = attrsOut evOut.Type = ev.Type return evOut } func decodeEventList(encEvents []Event) (decEvents []Event) { for _, x := range encEvents { decEvents = append(decEvents, x.decodeEventAttributes()) } return decEvents } func (tx *Tx) decodeTx() { if len(tx.Events) != 0 { decEvents := decodeEventList(tx.Events) tx.Events = decEvents } } //DecodeBlock() converts WsResponse BlockResult to BlockResultDB //----- //Base64 decodes event attributes, converts, adds fields for DB insert //Decodes Txs //Decodes BeginBlockEvents //Decodes EndBlockEvents //Converts height from string to int //Adds chainId param to returned BlockResultDB struct func (bl *BlockResult) DecodeBlock(chainId string) (dbBlock BlockResultDB){ if len(bl.Txs) != 0 { logrus.Debug("Decoding Txs") for _, x := range bl.Txs { x.decodeTx() } } dbBlock.Txs = bl.Txs if len(bl.BeginBlockEvents) != 0 { logrus.Debug("Decoding Begin Block Events") bl.BeginBlockEvents = decodeEventList(bl.BeginBlockEvents) } dbBlock.BeginBlockEvents = bl.BeginBlockEvents if len(bl.EndBlockEvents) != 0 { logrus.Debug("Decoding End Block Events") bl.EndBlockEvents = decodeEventList(bl.EndBlockEvents) } dbBlock.EndBlockEvents = bl.EndBlockEvents dbBlock.ChainId = chainId height, errHeight := strconv.Atoi(bl.Height) if errHeight != nil { logrus.Fatal("Failed to decode height: string -> int", errHeight) } else { dbBlock.Height = height } dbBlock.ValidatorUpdates = bl.ValidatorUpdates dbBlock.ConsensusParamUpdates = bl.ConsensusParamUpdates return dbBlock }
#!/bin/bash DIR=$1 if [ -z "$1" ] then echo "please supply directory where backup resides" exit 1 fi echo "***********************************" echo "* ELYSIAN RESTORE *" echo "***********************************" echo "" echo "Restore database from backup/$DIR" echo "" docker-compose exec db mongorestore /backup/$DIR --host db:27017 echo "" echo "***********************************" echo "* ELYSIAN RESTORE COMPLETE *" echo "***********************************"
<gh_stars>0 package acceptance.shellMarket; import org.openqa.selenium.By; import org.openqa.selenium.support.ui.ExpectedConditions; import org.testng.annotations.Listeners; import org.testng.annotations.Test; @Listeners(ListenersClass.class) public class DeleteNews extends WebDriverSetting{ @Test public void testDeleteNews() { for (int i = 0; i < 6; i++) { driver.navigate().to("https://shell-market.test.aurocraft.com/admin/articles/news/list"); wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("a[href=\"/admin/articles/news/create\"]"))); driver.findElement(By.xpath("//tr[1]//td[7]//div[1]//button[1]")).click(); wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("button[class=\"close\"]"))); driver.findElement(By.id("btn-delete-confirm")).click(); wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("[class=\"alert alert-success alert-dismissable\"]"))); } } }
<gh_stars>1-10 const path = require('path') const webpack = require('webpack') const StaticSiteGeneratorPlugin = require('static-site-generator-webpack-plugin') const NodePolyfillPlugin = require('node-polyfill-webpack-plugin') module.exports = { target: 'webworker', entry: './src/index.ts', output: { filename: 'worker.js', path: path.join(__dirname, 'dist'), globalObject: 'this', }, devtool: 'cheap-module-source-map', mode: 'development', resolve: { extensions: ['.ts', '.tsx', '.js'], fallback: { url: false, os: false, https: false, http: false, crypto: false, assert: false, stream: false, }, }, plugins: [ // new webpack.IgnorePlugin({ resourceRegExp: /^/u, contextRegExp: /swarm-js/u }), new webpack.ProvidePlugin({ process: 'process/browser', Buffer: ['buffer', 'Buffer'], }), // new NodePolyfillPlugin(), // new StaticSiteGeneratorPlugin({ // globals: { // window: {}, // }, // }), ], module: { rules: [ { test: /\.tsx?$/, loader: 'ts-loader', options: { // transpileOnly is useful to skip typescript checks occasionally: // transpileOnly: true, }, }, ], }, }
def minibatches(data, minibatchSize): x_batch, y_batch = [], [] for i in range(0, len(data), minibatchSize): batch = data[i:i + minibatchSize] x_batch.append([item[0] for item in batch]) # Extract input sequences y_batch.append([item[1] for item in batch]) # Extract labels return x_batch, y_batch
import React from 'react' const Page404 = () => { return( <main> 404 </main> ) } export default Page404
<reponame>housnberg/taskana import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { SimpleChange } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { SharedModule } from 'app/shared/shared.module'; import { PaginationComponent } from './pagination.component'; import { WorkbasketSummaryResource } from 'app/models/workbasket-summary-resource'; import { Page } from 'app/models/page'; describe('PaginationComponent', () => { let component: PaginationComponent; let fixture: ComponentFixture<PaginationComponent>; let debugElement; beforeEach(async(() => { return TestBed.configureTestingModule({ declarations: [ PaginationComponent ], imports: [FormsModule, SharedModule] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(PaginationComponent); component = fixture.componentInstance; debugElement = fixture.debugElement.nativeElement; fixture.detectChanges(); }); afterEach(() => { fixture.detectChanges() document.body.removeChild(debugElement); }) it('should create', () => { expect(component).toBeTruthy(); expect(debugElement.querySelectorAll('#wb-pagination > li').length).toBe(2); }); it('should create 3 pages if total pages are 3', () => { component.workbasketsResource = new WorkbasketSummaryResource(undefined, undefined, new Page(6, 3, 3, 1)); fixture.detectChanges(); expect(debugElement.querySelectorAll('#wb-pagination > li').length).toBe(5); }); it('should emit change if previous page was different than current one', () => { component.workbasketsResource = new WorkbasketSummaryResource(undefined, undefined, new Page(6, 3, 3, 1)); component.previousPageSelected = 2; fixture.detectChanges(); component.changePage.subscribe(value => { expect(value).toBe(1) }) component.changeToPage(1); }); it('should not emit change if previous page was the same than current one', () => { component.workbasketsResource = new WorkbasketSummaryResource(undefined, undefined, new Page(6, 3, 3, 1)); component.previousPageSelected = 2; fixture.detectChanges(); component.changePage.subscribe(value => { expect(false).toBe(true) }) component.changeToPage(2); }); it('should emit totalPages if page is more than page.totalPages', () => { component.workbasketsResource = new WorkbasketSummaryResource(undefined, undefined, new Page(6, 3, 3, 1)); component.previousPageSelected = 2; fixture.detectChanges(); component.changePage.subscribe(value => { expect(value).toBe(3) }) component.changeToPage(100); }); it('should emit 1 if page is less than 1', () => { component.workbasketsResource = new WorkbasketSummaryResource(undefined, undefined, new Page(6, 3, 3, 1)); component.previousPageSelected = 2; fixture.detectChanges(); component.changePage.subscribe(value => { expect(value).toBe(1) }) component.changeToPage(0); }); it('should change pageSelected onChanges', () => { expect(component.pageSelected).toBe(1); component.ngOnChanges({ workbasketsResource: new SimpleChange(null, new WorkbasketSummaryResource(undefined, undefined, new Page(6, 3, 3, 2)), true) }); fixture.detectChanges(); expect(component.pageSelected).toBe(2); }); it('should getPagesTextToShow return 7 of 13 with size < totalElements', () => { component.workbasketsResource = new WorkbasketSummaryResource(undefined, undefined, new Page(7, 13, 3, 2)); expect(component.getPagesTextToShow()).toBe('7 of 13 workbaskets'); }); it('should getPagesTextToShow return 6 of 6 with size > totalElements', () => { component.workbasketsResource = new WorkbasketSummaryResource(undefined, undefined, new Page(7, 6, 3, 2)); expect(component.getPagesTextToShow()).toBe('6 of 6 workbaskets'); }); it('should getPagesTextToShow return of with totalElements = 0', () => { component.workbasketsResource = new WorkbasketSummaryResource(undefined, undefined, new Page(7, 0, 0, 0)); expect(component.getPagesTextToShow()).toBe('0 of 0 workbaskets'); }); });
#! /bin/bash echo "branch=$CI_COMMIT_REF_NAME" dotnet nuget add source "$SDK_NUGETS_URL" -n "M5x SDK Nugets" -u "$LOGATRON_CID_USR" -p "$LOGATRON_CID_PWD" --store-password-in-clear-text dotnet nuget add source "$LOGATRON_NUGETS_URL" -n "Logatron Nugets" -u "$LOGATRON_CID_USR" -p "$LOGATRON_CID_PWD" --store-password-in-clear-text cd "$CI_PROJECT_DIR"/src/clients/"$CLI_EXE" || exit # dotnet restore --disable-parallel if [ "$CI_COMMIT_REF_NAME" = "master" ]; then dotnet publish -o "$CI_PROJECT_DIR"/CLI --runtime alpine-x64 --self-contained else dotnet publish -o "$CI_PROJECT_DIR"/CLI --runtime alpine-x64 --self-contained --version-suffix "debug" fi cp Dockerfile "$CI_PROJECT_DIR"/CLI/
<reponame>johnlarusic/lebus<gh_stars>1-10 import lebus import logging import threading import time import argparse import os import sys import json DEFAULT_IMG_FILE = "sched.png" # Import configuration file with open('lebus_config.json') as f: data = json.load(f) p_api_key = data['api_key'] p_refresh_rate = data['refresh_rate'] p_send_to_led = data['send_to_led'] p_send_to_file = data['send_to_file'] p_default_image_file = data['default_image_file'] p_stops = data['stops'] p_led = data['led'] p_led_width = p_led['width'] p_led_height = p_led['height'] p_brightness = p_led['brightness'] p_timer = data['data_pull_timer'] p_min_time = p_timer['min'] p_max_time = p_timer['max'] p_colours = data['colours'] p_c_bg = p_colours['background'] p_c_text = p_colours['text'] p_c_t_default = p_colours['time_default'] p_c_t_warn = p_colours['time_warning'] p_c_t_crit = p_colours['time_critical'] # Setup logging logger = logging.getLogger("lebus") logging.getLogger("PIL").setLevel(logging.CRITICAL) logger.info('Starting lebus!!!') # Setup the schedules stops = [] for s in p_stops: k = lebus.Schedule(s['bus'], s['stop'], s['display_bus'], s['display_direction'], s['tminus_warning'], s['tminus_critical'], p_api_key) stops.append(k) # Parse colours c_bg = lebus.parse_colour_string(p_c_bg) c_text = lebus.parse_colour_string(p_c_text) c_t_default = lebus.parse_colour_string(p_c_t_default) c_t_warn = lebus.parse_colour_string(p_c_t_warn) c_t_crit = lebus.parse_colour_string(p_c_t_crit) # Setup matrix matrix = None if p_send_to_led: from rgbmatrix import RGBMatrix, RGBMatrixOptions options = RGBMatrixOptions() options.rows = 32 options.chain_length = 1 options.parallel = 1 options.brightness = p_brightness matrix = RGBMatrix(options=options) # Start the scheduled timer pulls for stop in stops: t = threading.Thread(target=lebus.timer, args=(stop, p_min_time, p_max_time, )) t.setDaemon(True) t.start() # Print out the latest schedules every thirty seconds img = None orig_stops = stops[:] # Make duplicate copy of list while True: lebus.print_schedule(orig_stops) if p_send_to_file or p_send_to_led: img = lebus.graphic_schedule(stops, p_led_width, p_led_height, c_bg, c_text, c_t_default, c_t_warn, c_t_crit) if p_send_to_file: img.save(p_default_image_file) if p_send_to_led: matrix.SetImage(img.convert('RGB')) if(len(stops) > 2): stops.append(stops.pop(0)) time.sleep(p_refresh_rate)
import platform from . import client from . import orm from . import proxy VERSION = platform.python_version_tuple() if VERSION[0] != "3" or VERSION[1] < "6": raise RuntimeError(f"version {platform.python_version()} < 3.6") __all__ = [client, orm, proxy]
#!/usr/bin/env bash set -e set -x while IFS=, read -r EKSTANSYON_FULL VESYON do IFS=. read -r PUBLISHER EKSTANSYON <<< ${EKSTANSYON_FULL} n=0 wait_time=1 until [ "$n" -ge 10 ] do curl "https://marketplace.visualstudio.com/_apis/public/gallery/publishers/${PUBLISHER}/vsextensions/${EKSTANSYON}/${VESYON}/vspackage" -o "${EKSTANSYON_FULL}.vsix.gz" gunzip "${EKSTANSYON_FULL}.vsix.gz" && break n=$((n+1)) sleep ${wait_time} wait_time=$((wait_time*2)) done code-server --extensions-dir /config/extensions --install-extension "${EKSTANSYON_FULL}.vsix" sleep 1 done < ekstansyon-ms.csv
<filename>core/src/main/java/cucumber/runtime/xstream/ComplexTypeWriter.java package cucumber.runtime.xstream; import cucumber.runtime.table.CamelCaseStringConverter; import java.util.ArrayList; import java.util.List; import static java.util.Arrays.asList; public class ComplexTypeWriter extends CellWriter { private final List<String> columnNames; private final List<String> fieldNames = new ArrayList<String>(); private final List<String> fieldValues = new ArrayList<String>(); private int nodeDepth = 0; public ComplexTypeWriter(List<String> columnNames) { this.columnNames = columnNames; } @Override public List<String> getHeader() { return columnNames.isEmpty() ? fieldNames : columnNames; } @Override public List<String> getValues() { CamelCaseStringConverter converter = new CamelCaseStringConverter(); if (!columnNames.isEmpty()) { String[] explicitFieldValues = new String[columnNames.size()]; int n = 0; for (String columnName : columnNames) { int index = fieldNames.indexOf(converter.map(columnName)); if (index == -1) { explicitFieldValues[n] = ""; } else { explicitFieldValues[n] = fieldValues.get(index); } n++; } return asList(explicitFieldValues); } else { return fieldValues; } } @Override public void startNode(String name) { if (nodeDepth == 1) { this.fieldNames.add(name); } nodeDepth++; } @Override public void addAttribute(String name, String value) { } @Override public void setValue(String value) { fieldValues.add(value == null ? "" : value); } @Override public void endNode() { nodeDepth--; } @Override public void flush() { throw new UnsupportedOperationException(); } @Override public void close() { throw new UnsupportedOperationException(); } }
#!/bin/bash ./configure --prefix=/usr \ --build=$SHED_NATIVE_TARGET \ --disable-static && \ make -j $SHED_NUMJOBS && \ make DESTDIR="$SHED_FAKEROOT" install
<reponame>jvega190/yoast-plugin /* External dependencies */ import React, { Component } from "react"; import styled from "styled-components"; import PropTypes from "prop-types"; /* Yoast dependencies */ import { colors } from "../../style-guide"; /* Internal dependencies */ import { handleImage, FACEBOOK_IMAGE_SIZES, } from "../helpers/determineImageProperties"; const FacebookImageContainer = styled.div` position: relative; height: ${ props => props.dimensions.height }; ${ props => props.mode === "landscape" ? `max-width: ${ props.dimensions.width }` : `min-width: ${ props.dimensions.width }` }; overflow: hidden; background-color: ${ colors.$color_white }; `; // Adding && for specificity, competing styles coming from blockeditor const StyledImage = styled.img` && { max-width: ${ props => props.imageProperties.width }px; height: ${ props => props.imageProperties.height }px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); max-width: none; } `; /** * Renders the FacebookImage component. * * @param {string} src The image source. * * @returns {ReactComponent} The FacebookImage component. */ class FacebookImage extends Component { /** * The constructor. * * @param {Object} props The component's props. */ constructor( props ) { super( props ); this.state = { imageProperties: null, status: "loading", }; this.socialMedium = "Facebook"; this.handleFacebookImage = this.handleFacebookImage.bind( this ); this.setState = this.setState.bind( this ); } /** * Handles setting the handled image properties on the state. * * @returns {void} */ async handleFacebookImage() { try { const newState = await handleImage( this.props.src, this.socialMedium ); this.setState( newState ); this.props.onImageLoaded( newState.imageProperties.mode || "landscape" ); } catch ( error ) { this.setState( error ); this.props.onImageLoaded( "landscape" ); } } /** * React Lifecycle method that is called after the component updates. * * @param {Object} prevProps The props. * * @returns {Object} The new props. */ componentDidUpdate( prevProps ) { // Only perform calculations on the image if the src has actually changed. if ( prevProps.src !== this.props.src ) { this.handleFacebookImage(); } } /** * Determine the image properties and set them in state. * * @param {string} src The image source URL. * * @returns {void} */ componentDidMount() { this.handleFacebookImage(); } /** * Retrieves the dimensions for the Facebook image container. * * @param {string} imageMode The Facebook image mode: landscape, portrait or square. * * @returns {Object} The width and height for the container. */ retrieveContainerDimensions( imageMode ) { switch ( imageMode ) { case "square": return { height: FACEBOOK_IMAGE_SIZES.squareHeight + "px", width: FACEBOOK_IMAGE_SIZES.squareWidth + "px", }; case "portrait": return { height: FACEBOOK_IMAGE_SIZES.portraitHeight + "px", width: FACEBOOK_IMAGE_SIZES.portraitWidth + "px", }; case "landscape": return { height: FACEBOOK_IMAGE_SIZES.landscapeHeight + "px", width: FACEBOOK_IMAGE_SIZES.landscapeWidth + "px", }; default: break; } } /** * Renders the FacebookImage. * * @returns {ReactComponent} Either the ErrorImage component or the FacebookImageContainer. */ render() { const { imageProperties, status } = this.state; if ( status === "loading" || this.props.src === "" || status === "errored" ) { return ( <></> ); } const containerDimensions = this.retrieveContainerDimensions( imageProperties.mode ); return <FacebookImageContainer mode={ imageProperties.mode } dimensions={ containerDimensions } onMouseEnter={ this.props.onMouseEnter } onMouseLeave={ this.props.onMouseLeave } onClick={ this.props.onImageClick } > <StyledImage src={ this.props.src } alt={ this.props.alt } imageProperties={ imageProperties } /> </FacebookImageContainer>; } } FacebookImage.propTypes = { src: PropTypes.string, alt: PropTypes.string, onImageLoaded: PropTypes.func, onImageClick: PropTypes.func, onMouseEnter: PropTypes.func, onMouseLeave: PropTypes.func, }; FacebookImage.defaultProps = { src: "", alt: "", onImageLoaded: () => {}, onImageClick: () => {}, onMouseEnter: () => {}, onMouseLeave: () => {}, }; export default FacebookImage;
fish_path = '/usr/local/bin/fish' directory "#{node[:xdg_config_home]}/fish" do user node[:user] end execute "echo #{fish_path} | sudo tee -a /etc/shells" do not_if "grep #{fish_path} /etc/shells" end execute "chsh -s #{fish_path}" do not_if { `dscl localhost -read Local/Default/Users/#{node[:user]} UserShell`.include?(fish_path) } end link File.expand_path("#{node[:xdg_config_home]}/fish/config.fish") do to File.expand_path('../files/.config/fish/config.fish', __FILE__) user node[:user] force true end execute 'curl https://git.io/fisher --create-dirs -sLo ~/.config/fish/functions/fisher.fish' do not_if "test -f #{node[:xdg_config_home]}/fish/functions/fisher.fish" end link File.expand_path("#{node[:xdg_config_home]}/fish/fishfile") do to File.expand_path('../files/.config/fish/fishfile', __FILE__) user node[:user] force true end
/* * Copyright (c) 2004-2009, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.patientattributevalue.hibernate; import java.util.Collection; import java.util.List; import org.hibernate.Query; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import org.hisp.dhis.hibernate.HibernateGenericStore; import org.hisp.dhis.patient.Patient; import org.hisp.dhis.patient.PatientAttribute; import org.hisp.dhis.patient.PatientAttributeOption; import org.hisp.dhis.patientattributevalue.PatientAttributeValue; import org.hisp.dhis.patientattributevalue.PatientAttributeValueStore; import org.springframework.jdbc.core.JdbcTemplate; /** * @author <NAME> * @version $Id$ */ public class HibernatePatientAttributeValueStore extends HibernateGenericStore<PatientAttributeValue> implements PatientAttributeValueStore { // ------------------------------------------------------------------------- // Dependency // ------------------------------------------------------------------------- private JdbcTemplate jdbcTemplate; public void setJdbcTemplate( JdbcTemplate jdbcTemplate ) { this.jdbcTemplate = jdbcTemplate; } // ------------------------------------------------------------------------- // Implementation methods // ------------------------------------------------------------------------- public void saveVoid( PatientAttributeValue patientAttributeValue ) { sessionFactory.getCurrentSession().save( patientAttributeValue ); } public int deleteByAttribute( PatientAttribute patientAttribute ) { Query query = getQuery( "delete from PatientAttributeValue where patientAttribute = :patientAttribute" ); query.setEntity( "patientAttribute", patientAttribute ); return query.executeUpdate(); } public int deleteByPatient( Patient patient ) { Query query = getQuery( "delete from PatientAttributeValue where patient = :patient" ); query.setEntity( "patient", patient ); return query.executeUpdate(); } public PatientAttributeValue get( Patient patient, PatientAttribute patientAttribute ) { return (PatientAttributeValue) getCriteria( Restrictions.eq( "patient", patient ), Restrictions.eq( "patientAttribute", patientAttribute ) ).uniqueResult(); } @SuppressWarnings( "unchecked" ) public Collection<PatientAttributeValue> get( Patient patient ) { return getCriteria( Restrictions.eq( "patient", patient ) ).list(); } @SuppressWarnings( "unchecked" ) public Collection<PatientAttributeValue> get( PatientAttribute patientAttribute ) { return getCriteria( Restrictions.eq( "patientAttribute", patientAttribute ) ).list(); } @SuppressWarnings( "unchecked" ) public Collection<PatientAttributeValue> get( Collection<Patient> patients ) { return getCriteria( Restrictions.in( "patient", patients ) ).list(); } @SuppressWarnings( "unchecked" ) public Collection<PatientAttributeValue> searchByValue( PatientAttribute patientAttribute, String searchText ) { return getCriteria( Restrictions.eq( "patientAttribute", patientAttribute ), Restrictions.ilike( "value", "%" + searchText + "%" ) ).list(); } public int countByPatientAttributeoption( PatientAttributeOption attributeOption ) { Number rs = (Number) getCriteria( Restrictions.eq( "patientAttributeOption", attributeOption ) ).setProjection( Projections.rowCount() ).uniqueResult(); return rs != null ? rs.intValue() : 0; } @SuppressWarnings( "unchecked" ) public Collection<Patient> getPatient( PatientAttribute attribute, String value ) { return getCriteria( Restrictions.and( Restrictions.eq( "patientAttribute", attribute ), Restrictions.eq( "value", value ) ) ) .setProjection( Projections.property( "patient" ) ).list(); } public int countSearchPatientAttributeValue( PatientAttribute patientAttribute, String searchText ) { Number rs = (Number) getCriteria( Restrictions.eq( "patientAttribute", patientAttribute ), Restrictions.ilike( "value", "%" + searchText + "%" ) ).setProjection( Projections.rowCount() ) .uniqueResult(); return rs != null ? rs.intValue() : 0; } @SuppressWarnings( "unchecked" ) public Collection<Patient> searchPatients( PatientAttribute patientAttribute, String searchText, int min, int max ) { return getCriteria( Restrictions.eq( "patientAttribute", patientAttribute ), Restrictions.ilike( "value", "%" + searchText + "%" ) ).setProjection( Projections.distinct( Projections.property( "patient" ) ) ).setFirstResult( min ).setMaxResults( max ) .list(); } @SuppressWarnings( "unchecked" ) public Collection<Patient> searchPatients( PatientAttribute patientAttribute, String searchText ) { String hql = "select pav.patient from PatientAttributeValue pav where pav.patientAttribute = :patientAttribute and pav.value like '%" + searchText + "%'"; Query query = getQuery( hql ); query.setEntity( "patientAttribute", patientAttribute ); return query.list(); } @SuppressWarnings( "unchecked" ) public Collection<Patient> searchPatients( List<Integer> patientAttributeIds, List<String> searchTexts, int min, int max ) { String hql = "SELECT DISTINCT p FROM Patient as p WHERE p in "; String end = ""; int index = 0; for ( Integer patientAttributeId : patientAttributeIds ) { end += ")"; hql += createHQL( patientAttributeId, searchTexts.get( index ), index, patientAttributeIds.size() ); index++; } hql += " ORDER BY p.id ASC"; Query query = getQuery( hql + end ).setFirstResult( min ).setMaxResults( max ); return query.list(); } public int countSearchPatients( List<Integer> patientAttributeIds, List<String> searchTexts ) { String hql = "SELECT COUNT( DISTINCT p ) FROM Patient as p WHERE p in "; String end = ""; int index = 0; for ( Integer patientAttributeId : patientAttributeIds ) { end += ")"; hql += createHQL( patientAttributeId, searchTexts.get( index ), index, patientAttributeIds.size() ); index++; } Query query = getQuery( hql + end ); Number rs = (Number) query.uniqueResult(); return (rs != null) ? rs.intValue() : 0; } // ------------------------------------------------------------------------- // Supportive methods // ------------------------------------------------------------------------- private String createHQL( Integer patientAttributeId, String searchText, int index, int noCondition ) { String hql = ""; searchText = searchText.trim(); boolean isSearchByAttribute = true; // --------------------------------------------------------------------- // search patients by name or identifier // --------------------------------------------------------------------- if ( patientAttributeId == null ) { int startIndex = searchText.indexOf( ' ' ); int endIndex = searchText.lastIndexOf( ' ' ); String firstName = searchText.toString(); String middleName = ""; String lastName = ""; if ( searchText.indexOf( ' ' ) != -1 ) { firstName = searchText.substring( 0, startIndex ); if ( startIndex == endIndex ) { middleName = ""; lastName = searchText.substring( startIndex + 1, searchText.length() ); } else { middleName = searchText.substring( startIndex + 1, endIndex ); lastName = searchText.substring( endIndex + 1, searchText.length() ); } } hql += " ( SELECT p" + index + " FROM Patient as p" + index + " JOIN p" + index + ".identifiers as identifier" + index + " " + "WHERE lower(identifier" + index + ".identifier)=lower('" + searchText + "') " + "OR (lower(p" + index + ".firstName) LIKE lower('%" + firstName + "%') " + "AND lower(p" + index + ".middleName) = lower('" + middleName + "') " + "AND lower(p" + index + ".lastName) LIKE lower('%" + lastName + "%')) "; isSearchByAttribute = false; } // ----------------------------------------------------------------- // search patients by program // ----------------------------------------------------------------- else if ( patientAttributeId == 0 ) { hql += " ( SELECT p" + index + " FROM Patient AS p" + index + " " + " JOIN p" + index + ".programs AS program" + index + " WHERE program" + index + ".id=" + searchText; isSearchByAttribute = false; } // ----------------------------------------------------------------- // search patients by attribute // ----------------------------------------------------------------- else { hql += " ( SELECT pav" + index + ".patient FROM PatientAttributeValue as pav" + index + " " + "WHERE pav" + index + ".patientAttribute.id=" + patientAttributeId + " AND lower(pav" + index + ".value) LIKE lower('%" + searchText + "%') "; } if ( index < noCondition - 1 ) { if ( isSearchByAttribute ) { hql += " AND pav" + index + ".patient in "; } else { hql += " AND p" + index + " in "; } } return hql; } public void updatePatientAttributeValues( PatientAttributeOption patientAttributeOption ) { String sql = "UPDATE patientattributevalue SET value='" + patientAttributeOption.getName() + "' WHERE patientattributeoptionid='" + patientAttributeOption.getId() + "'"; jdbcTemplate.execute( sql ); } }
<reponame>xerocross/xerocross.factor<gh_stars>0 import Vue from "vue"; import PrimeFactorsWidget from "./components/prime-factors-widget.vue"; const myWorker = new Worker("/js/get-factor-worker.js"); new Vue({ el : "#factor-primes", components : { PrimeFactorsWidget }, render : function (createElement) { return createElement(PrimeFactorsWidget, { props : { worker : myWorker } }); } });
public void addLootModifier(Entity internal, String name, String weapon, boolean matchDamage) { internal.addLootModifier(name, (entity, source, damageSource) -> { if (source instanceof PlayerEntity) { ItemStack weaponStack = ((PlayerEntity) source).getMainHandStack(); if (weaponStack.getItem().getTranslationKey().equals(weapon)) { if (matchDamage) { if (damageSource instanceof ProjectileDamageSource) { float weaponDamage = ((ProjectileDamageSource) damageSource).getProjectile().getDamage(); if (weaponDamage == entity.getHealth()) { // Add loot modifier // ... } } else if (damageSource instanceof EntityDamageSource) { float weaponDamage = ((EntityDamageSource) damageSource).getAttacker().getDamage(); if (weaponDamage == entity.getHealth()) { // Add loot modifier // ... } } } else { // Add loot modifier // ... } } } }); }
#! /bin/bash #SBATCH -o /home/hpc/pr63so/di69fol/workspace/SWEET_2015_12_26/benchmarks_performance/rexi_tests_lrz_freq_waves/2016_01_03_scalability_rexi_fd_high_res_run2/run_rexi_fd_par_m0512_t001_n0128_r1820_a1.txt ###SBATCH -e /home/hpc/pr63so/di69fol/workspace/SWEET_2015_12_26/benchmarks_performance/rexi_tests_lrz_freq_waves/2016_01_03_scalability_rexi_fd_high_res_run2/run_rexi_fd_par_m0512_t001_n0128_r1820_a1.err #SBATCH -J rexi_fd_par_m0512_t001_n0128_r1820_a1 #SBATCH --get-user-env #SBATCH --clusters=mpp2 #SBATCH --ntasks=1820 #SBATCH --cpus-per-task=1 #SBATCH --exclusive #SBATCH --export=NONE #SBATCH --time=03:00:00 #declare -x NUMA_BLOCK_ALLOC_VERBOSITY=1 declare -x KMP_AFFINITY="granularity=thread,compact,1,0" declare -x OMP_NUM_THREADS=1 echo "OMP_NUM_THREADS=$OMP_NUM_THREADS" echo . /etc/profile.d/modules.sh module unload gcc module unload fftw module unload python module load python/2.7_anaconda_nompi module unload intel module load intel/16.0 module unload mpi.intel module load mpi.intel/5.1 module load gcc/5 cd /home/hpc/pr63so/di69fol/workspace/SWEET_2015_12_26/benchmarks_performance/rexi_tests_lrz_freq_waves/2016_01_03_scalability_rexi_fd_high_res_run2 cd ../../../ . local_software/env_vars.sh # force to use FFTW WISDOM data declare -x SWEET_FFTW_LOAD_WISDOM_FROM_FILE="FFTW_WISDOM_nofreq_T0" time -p mpiexec.hydra -genv OMP_NUM_THREADS 1 -envall -ppn 28 -n 1820 ./build/rexi_fd_par_m_tno_a1 --initial-freq-x-mul=2.0 --initial-freq-y-mul=1.0 -f 1 -g 1 -H 1 -X 1 -Y 1 --compute-error 1 -t 50 -R 4 -C 0.3 -N 128 -U 0 -S 0 --use-specdiff-for-complex-array 0 --rexi-h 0.8 --timestepping-mode 1 --staggering 0 --rexi-m=512 -C -5.0
#!/bin/bash mkdir build cd build cmake -Wno-dev -GXcode -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS="-DPNG_ARM_NEON_OPT=0 -std=c++11" -DCMAKE_C_FLAGS="-DPNG_ARM_NEON_OPT=0" -DCMAKE_CXX_COMPILER_WORKS=1 -DCMAKE_C_COMPILER_WORKS=1 -DCMAKE_THREAD_LIBS_INIT="-lpthread" -DCMAKE_USE_PTHREADS_INIT=1 -DCMAKE_OSX_ARCHITECTURES="arm64" -DCMAKE_OSX_SYSROOT=$(xcode-select -p)/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk -DCMAKE_MACOSX_BUNDLE=ON -DCMAKE_XCODE_ATTRIBUTE_CODE_SIGNING_REQUIRED=NO -DLIBPNG_IS_GOOD=0 -DLIBJPEG_IS_GOOD=0 -DAPPLE=1 -DDLIB_NO_GUI_SUPPORT=1 -DDLIB_USE_CUDA=0 -DDLIB_USE_BLAS=1 -DDLIB_USE_LAPACK=1 -DUNIX=1 ../ CMAKE_VERSION=`cmake --version | tr -dc '0-9'` if [ $CMAKE_VERSION -lt 300 ]; then sed -i '' 's~/build/dlib/Release~/build/dlib/Release-iphoneos~g' dlib/CMakeScripts/dlib_shared_postBuildPhase.makeRelease; fi xcodebuild -arch arm64 -sdk iphoneos -configuration Release ONLY_ACTIVE_ARCH=NO -target ALL_BUILD build xcodebuild -arch x86_64 -sdk iphonesimulator -configuration Release ONLY_ACTIVE_ARCH=NO -target ALL_BUILD build sed -i '' 's~/build/dlib/Release~/build/dlib/Release-iphoneos~g' dlib/cmake_install.cmake cmake -DCMAKE_INSTALL_PREFIX=install -P cmake_install.cmake lipo -create install/lib/libdlib.19.6.99.dylib dlib/Release-iphonesimulator/libdlib.19.6.99.dylib -output libdlib.dylib install_name_tool -id @rpath/libdlib.dylib libdlib.dylib
import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { DeleteResult, Repository, UpdateResult } from 'typeorm'; import { Category } from './category.entity'; @Injectable() export class CategoryService { constructor( @InjectRepository(Category) private readonly categoryRepository: Repository<Category>, ) {} private getCategoryBaseQuery() { return this.categoryRepository .createQueryBuilder('c') .orderBy('c.id', 'DESC'); } public getPlainCategories() { return this.getCategoryBaseQuery().execute(); } public async getCategoriesWithCountOfSkills() { return this.getCategoryBaseQuery() .loadRelationCountAndMap('c.skillCount', 'c.skills') .getMany(); } public async getCategory(id: number) { return await this.categoryRepository .createQueryBuilder('c') .leftJoinAndSelect('c.skills', 'skill') .where('c.id = :id', { id }) .getOne(); } public async updateCategory( id: number, input: { name: string }, ): Promise<UpdateResult> { return await this.categoryRepository .createQueryBuilder('category') .update(Category) .set({ name: input.name }) .where('category.id = :id', { id }) .execute(); } public async deleteCategory(id: number): Promise<DeleteResult> { return await this.categoryRepository .createQueryBuilder('c') .delete() .where('id = :id', { id }) .execute(); } }
#!/bin/bash set -eo pipefail dir="$(dirname "$(readlink -f "$BASH_SOURCE")")" serverImage="$1" # Use a client image with curl for testing clientImage='buildpack-deps:buster-curl' # ensure the clientImage is ready and available if ! docker image inspect "$clientImage" &> /dev/null; then docker pull "$clientImage" > /dev/null fi # Create an instance of the container-under-test cid="$(docker run -d "$serverImage")" trap "docker rm -vf $cid > /dev/null" EXIT _request() { local method="$1" shift local url="${1#/}" shift docker run --rm \ --link "$cid":apache \ "$clientImage" \ curl -fsL -X"$method" "$@" "http://apache/$url" } # Make sure that Apache is listening and ready . "$dir/../../retry.sh" --tries 30 '_request GET / --output /dev/null' # Check that we can request / and that it contains the pattern "Finish setup" somewhere # <input type="submit" class="primary" value="Finish setup" data-finishing="Finishing …"> _request GET '/' | grep -i "Finish setup" > /dev/null
#!/bin/bash # Description: It contains methods to change file modes or Access Control Lists of files. # Author: Luciano Sampaio # Date: 20-Dec-2020 getCurrentFileMode() { stat -f %A $1 } changeFileMode() { #$1 - Options #$2 - New Mode #$3 - Path currentMode=$(getCurrentFileMode $3) if [ $currentMode -ne $2 ]; then logDebug "chmod" $* sudo chmod $* fi }
from enum import Enum import math class Metric(Enum): EUCLIDEAN = 0 MANHATTAN = 1 HAMMING = 2 L2 = 3 class DistanceCalculator: def __init__(self, metric): self.metric = metric def calculate_distance(self, point1, point2): x1, y1 = point1 x2, y2 = point2 if self.metric == Metric.EUCLIDEAN: return math.sqrt((x2 - x1)**2 + (y2 - y1)**2) elif self.metric == Metric.MANHATTAN: return abs(x2 - x1) + abs(y2 - y1) elif self.metric == Metric.HAMMING: return sum(1 for i in range(len(point1)) if point1[i] != point2[i]) elif self.metric == Metric.L2: return math.sqrt((x2 - x1)**2 + (y2 - y1)**2) # Example usage calculator = DistanceCalculator(Metric.EUCLIDEAN) print(calculator.calculate_distance((1, 2), (4, 6))) # Output: 5.0 calculator = DistanceCalculator(Metric.MANHATTAN) print(calculator.calculate_distance((1, 2), (4, 6))) # Output: 7 calculator = DistanceCalculator(Metric.HAMMING) print(calculator.calculate_distance((101, 110), (100, 100))) # Output: 2 calculator = DistanceCalculator(Metric.L2) print(calculator.calculate_distance((1, 2), (4, 6))) # Output: 5.0
/******************************************************************************* * Copyright (C) 2016 Maxim Integrated Products, Inc., All Rights Reserved. * * 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 MAXIM INTEGRATED 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. * * Except as contained in this notice, the name of Maxim Integrated * Products, Inc. shall not be used except as stated in the Maxim Integrated * Products, Inc. Branding Policy. * * The mere transfer of this software does not imply any licenses * of trade secrets, proprietary technology, copyrights, patents, * trademarks, maskwork rights, or any other form of intellectual * property whatsoever. Maxim Integrated Products, Inc. retains all * ownership rights. * * $Date: 2016-05-26 11:38:10 -0500 (Thu, 26 May 2016) $ * $Revision: 23065 $ * ******************************************************************************/ /** * @file spix.h * @brief This is the high level API for the serial peripheral interface execute in place module. * @warning If using this SPIX with IAR Embedded Workbench for Arm, it is required to define * <tt>IAR_SPIX_PRAGMA=1</tt>. This should be done under Project->Options-> * C/C++ Compiler->Preprocessor in the Defined Symbols input box. See the IAR documentation * for additional information on how to set a preprocessor define in a project. */ #include "mxc_sys.h" #include "spix_regs.h" #ifndef _SPIX_H_ #define _SPIX_H_ #ifdef __cplusplus extern "C" { #endif /***** Definitions *****/ /// @brief Options for number of I/O pins to use during for each fetch stage typedef enum { SPIX_SINGLE_IO = MXC_V_SPIX_FETCH_CTRL_CMD_WIDTH_SINGLE, SPIX_DUAL_IO = MXC_V_SPIX_FETCH_CTRL_CMD_WIDTH_DUAL_IO, SPIX_QUAD_IO = MXC_V_SPIX_FETCH_CTRL_CMD_WIDTH_QUAD_IO } spix_width_t; /// @brief Options for number of address bytes to use during fetch typedef enum { SPIX_3BYTE_FETCH_ADDR = 0, SPIX_4BYTE_FETCH_ADDR = 1 } spix_addr_size_t; /// @brief SPIX fetch configuration. typedef struct { spix_width_t cmd_width; ///< Number of I/O lines used for command SPI transaction. spix_width_t addr_width; ///< Number of I/O lines used for address SPI transaction. spix_width_t data_width; ///< Number of I/O lines used for data SPI transaction. spix_addr_size_t addr_size; ///< Use 3 or 4 byte addresses for fetches. uint8_t cmd; ///< Command value to initiate fetch. uint8_t mode_clocks; ///< Number of SPI clocks required during mode phase of fetch. uint8_t no_cmd_mode; ///< Read command sent only once. uint16_t mode_data; ///< Data sent with mode clocks. } spix_fetch_t; /***** Globals *****/ /***** Function Prototypes *****/ /** * @brief Configure SPI execute in place clocking. * @param sys_cfg Pointer to system level configuration structure. * @param mode SPI mode to use for the clocking. * @param baud Frequency in hertz to set the clock to. May not be able to achieve with * the given clock divider. * @param sample Number of SPIX clocks to delay the sampling of the SDIO lines. Will use * feedback mode if set to 0. * @returns #E_NO_ERROR if everything is successful */ int SPIX_ConfigClock(const sys_cfg_spix_t *sys_cfg, uint32_t baud, uint8_t sample); /** * @brief Configure SPI execute in place slave select. * @param ssel Index of which slave select line to use. * @param pol Polarity of slave select (0 for active low, 1 for active high). * @param act_delay SPIX clocks between slave select assert and active SPI clock. * @param inact_delay SPIX clocks between active SPI clock and slave select deassert. */ void SPIX_ConfigSlave(uint8_t ssel, uint8_t pol, uint8_t act_delay, uint8_t inact_delay); /** * @brief Configure how the SPIX fetches data. * @param fetch Pointer to configuration struct that describes how to fetch data. */ void SPIX_ConfigFetch(const spix_fetch_t *fetch); /** * @brief Shutdown SPIX module. * @param spix Pointer to SPIX regs. * @returns #E_NO_ERROR if everything is successful */ int SPIX_Shutdown(mxc_spix_regs_t *spix); #ifdef __cplusplus } #endif #endif /* _SPIX_H */
export PATH=$PATH:/opt/intelFPGA_pro/20.2/modelsim_ase/linuxaloem/ cd ../bin rm -rf msim make XLEN=64 SIM=vivado
/** * Created by msi on 19/07/2017. */ import Router from 'express' let router = Router() const db = require('../pgp') const blog = require('../model/blog') router.get('/get-cate-sidebar', (req, res, next) => { blog .selectCate() .then(data => { res.status(200).json(data) }) .catch(error => { res.json({ success: false, error: error.message || error }) }) }) router.get('/blogfornd', (req, res, next) => { blog .selectBlogForND() .then(data => { res.status(200).json(data) }) .catch(error => { res.json({ success: false, error: error.message || error }) }) }) router.get('/blogforda', (req, res, next) => { blog.selectBlogForDA().then(data => { res.json(data) }) }) router.get('/blogformv', (req, res, next) => { blog.selectBlogForMV().then(data => { res.json(data) }) }) router.get('/blog/:id', (req, res, next) => { let id = req.params.id blog .detailBlog(id) .then(data => { res.json(data) }) .catch(error => { res.json({ success: false, error: error.message || error }) }) }) router.get('/blogs/:slug', (req, res, next) => { let slug = req.params.slug let q = parseInt(req.query.page) || 1 let n = 15 let pgfrom = 0 if (q !== undefined && q > 0) { pgfrom = (pgfrom + q - 1) * n } else { q = 1 } db .task(t => { return t.batch([ blog.selectBlogForCate(slug, n, pgfrom), blog.countByCate(slug), q ]) }) .then(data => { let page = 0 data[1].forEach(index => { page = Math.ceil(index.count / n, 0) }) if (q > page) { q = 1 } res.json({ blogs: data[0], countAll: data[1], allpage: page, pageCurrent: q }) }) .catch(error => { res.json({ success: false, error: error.message || error }) }) }) router.get('/blogs/', (req, res, next) => { let q = parseInt(req.query.trang) let n = 15 let pgfrom = 0 if (q !== undefined && q > 0) { pgfrom = (pgfrom + q - 1) * n } else { q = 1 } db .task(t => { return t.batch([blog.selectByPagination(n, pgfrom), blog.countAll(), q]) }) .then(data => { let page = 0 data[1].forEach(index => { page = Math.ceil(index.count / n, 0) }) if (q > page) { q = 1 } res.json({ blogs: data[0], countAll: data[1], allpage: page, pageCurrent: q }) }) .catch(error => { res.json({ success: false, error: error.message || error }) }) }) export default router
7z x Bosphorus_1920x1080_120fps_420_8bit_YUV_Y4M.7z tar -xf rav1e-v0.3.0.tar.gz cd rav1e-0.3.0 cargo build --bin rav1e --release -j $NUM_CPU_PHYSICAL_CORES echo $? > ~/install-exit-status cd ~ echo "#!/bin/sh cd rav1e-0.3.0 ./target/release/rav1e ../Bosphorus_1920x1080_120fps_420_8bit_YUV.y4m --threads \$NUM_CPU_CORES --tiles 4 --output /dev/null \$@ > log.out 2>&1 echo \$? > ~/test-exit-status tr -s '\r' '\n' < log.out > \$LOG_FILE" > rav1e chmod +x rav1e
#!/bin/bash # Helper library for other bash-based tests. set -e banner() { echo echo "# $1" } fail() { echo "$1" >&2 exit 1 } dfm() { echo "\$ dfm" "$@" command dfm "$@" }
ruby -rubygems -e 'require "jekyll-import"; JekyllImport::Importers::Blogger.run({ "source" => "blog-11-22-2015.xml", "no-blogger-info" => true, # not to leave blogger-URL info (id and old URL) in the front matter "replace-internal-link" => true, # replace internal links using the post_url liquid tag. })'
#!/bin/bash # Run https://github.com/huggingface/transformers/blob/master/examples/tensorflow/language-modeling/run_clm.py on CSC puhti #SBATCH --account=project_2004600 #SBATCH --partition=gputest #SBATCH --time=00:15:00 #SBATCH --mem=64G #SBATCH --nodes=2 #SBATCH --gres=gpu:v100:4 #SBATCH --output=logs/%j.out #SBATCH --error=logs/%j.err module purge module load gcc/9.1.0 cuda/11.1.0 pytorch/1.9 pdsh/2.31 # Bind directory with pdsh to /usr/local/sbin in singularity export SING_FLAGS="$SING_FLAGS -B /appl/spack/install-tree/gcc-4.8.5/pdsh-2.31-cdzt5w/bin:/usr/local/sbin" # Check that pdsh is found as expected also from singularity python which pdsh python -c 'import shutil; print(shutil.which("pdsh"))' OUTPUT_DIR=output_dir # Start from scratch rm -rf "$OUTPUT_DIR" rm -f logs/latest.out logs/latest.err ln -s $SLURM_JOBID.out logs/latest.out ln -s $SLURM_JOBID.err logs/latest.err # `scontrol show hostnames` turns condenced nodelist # (e.g. "g[1102,1201]") into list of host names (e.g. "g1102\ng1102") MASTER_NODE=$(scontrol show hostnames "$SLURM_JOB_NODELIST" | head -n 1) # Create deepspeed hostfile. mkdir -p hostfiles HOSTFILE=hostfiles/$SLURM_JOBID.txt rm -f hostfiles/latest.txt ln -s $SLURM_JOBID.txt hostfiles/latest.txt scontrol show hostnames "$SLURM_JOB_NODELIST" \ | perl -pe 's/$/ slots=4/' \ > "$HOSTFILE" ./deepspeed_singularity.sh \ --master_addr "$MASTER_NODE" \ --hostfile "$HOSTFILE" \ run_clm.py \ --tokenizer tokenizer \ --model_type gpt2 \ --train_file texts.txt \ --do_train \ --num_train_epochs 1 \ --per_device_train_batch_size 6 \ --output_dir "$OUTPUT_DIR" \ --deepspeed ds_config.json
const taskUpgrade = require('task.Upgrade') const taskHarvest = require('task.Harvest') const taskTransfer = require('task.Transfer') const taskPickup = require('task.Pickup') const taskBuild = require('task.Build') const taskRepair = require('task.Repair') const taskTravel = require('task.Travel') const taskDefend = require('task.Defend') const taskAttack = require('task.Attack') const taskSpawn = require('task.Spawn') const utils = require('utils') module.exports = { init:function(){ if (!global.task) global.task = {} for (var roomName of global.rooms.my) { if (!Game.rooms[roomName].memory.taskExpiration || Game.rooms[roomName].memory.taskExpiration <= Game.time){ Game.rooms[roomName].memory.taskExpiration = Game.time + utils.getCacheExpiration(1500) Game.rooms[roomName].refreshTask() } } taskUpgrade(); taskHarvest(); taskBuild(); taskRepair(); taskPickup(); taskTransfer(); taskAttack(); taskDefend(); taskTravel(); }, spawn:function(){ taskSpawn(); } }
package me_wedding.repository; import java.util.List; import javax.annotation.PostConstruct; import javax.inject.Inject; import javax.sql.DataSource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import me_wedding.model.Transaction; import me_wedding.repository.sqlBuilder.TransactionSQLBuilder; @Repository public class TransactionRepository implements IRepository<Transaction> { @Inject private DataSource dataSource; private JdbcTemplate jdbcTemplate; private static final TransactionSQLBuilder transactionBuilder = new TransactionSQLBuilder(); private static final String findByIdQuery = transactionBuilder.buildFindByIdQuery(); private static final String findAllQuery = transactionBuilder.buildFindAllQuery(); private static final String saveQuery = transactionBuilder.buildSaveQuery(); private static final String updateQuery = transactionBuilder.buildUpdateQuery(); private static final String deleteQuery = transactionBuilder.buildDeleteQuery(); private static final String findByNameQuery = "SELECT * FROM " + transactionBuilder.getTableName() + " WHERE name = ?;"; @PostConstruct private void postConstruct() { jdbcTemplate = new JdbcTemplate(dataSource); } @Override public Transaction findById(long id) { List<Transaction> mails = jdbcTemplate.query(findByIdQuery, new Object[] { id }, (resultSet, i) -> { return Transaction.toTransaction(resultSet); }); if (mails.size() == 1) { return mails.get(0); } return null; } @Override public List<Transaction> findAll() { List<Transaction> mails = jdbcTemplate.query(findAllQuery, (resultSet, i) -> { return Transaction.toTransaction(resultSet); }); return mails; } public Transaction findByName(String name) { List<Transaction> mails = jdbcTemplate.query(findByNameQuery, new Object[] { name }, (resultSet, i) -> { return Transaction.toTransaction(resultSet); }); if (mails.size() == 1) { return mails.get(0); } return null; } @Override public int save(Transaction t) { int nbRowAffected = jdbcTemplate.update(saveQuery, new Object[] { t.getName(), t.getTransactionDate(), t.getAmount() }); return nbRowAffected; } @Override public int delete(long id) { int nbRowAffected = jdbcTemplate.update(deleteQuery, new Object[] { id }); return nbRowAffected; } @Override public int update(Transaction t) { int nbRowAffected = jdbcTemplate.update(updateQuery, new Object[] { t.getName(), t.getTransactionDate(), t.getAmount(), t.getId() }); return nbRowAffected; } }
import { Observable, throwError, timer } from 'rxjs'; import { mergeMap } from 'rxjs/operators'; import { RetryStrategyConfig } from '../model'; import { Logger } from '../util'; export const retryStrategy$ = (cfg: RetryStrategyConfig) => (attempts: Observable<any>) => { return attempts.pipe( mergeMap((error, i) => { const LOGGER = Logger.getLogger(); const retryAttempt = i + 1; LOGGER.error('Error during keep configuration from cloud config server') LOGGER.error(`Path: ${error.config.baseURL}`) if (retryAttempt > cfg.maxRetryAttempts) { LOGGER.error(`Max retry attempt.`) return throwError(error); } const waitFor = retryAttempt * cfg.scalingDuration; LOGGER.info(`The system will retry other ${cfg.maxRetryAttempts - i} times before fail. `) LOGGER.info(`Waiting before retry: ${waitFor} ms`) return timer(waitFor); }) // finalize(() => console.log(`Max retry attempt ${cfg.maxRetryAttempts} expired. `)) ); };
import mock import time from shakenfist.constants import GiB from shakenfist import exceptions from shakenfist import scheduler from shakenfist.tests import base from shakenfist.tests.mock_etcd import MockEtcd from shakenfist.config import SFConfig fake_config = SFConfig( NODE_NAME='node01', SCHEDULER_CACHE_TIMEOUT=30, CPU_OVERCOMMIT_RATIO=16.0, RAM_OVERCOMMIT_RATIO=1.5, RAM_SYSTEM_RESERVATION=5.0, NETWORK_NODE_IP='10.0.0.1', LOG_METHOD_TRACE=1, ) class SchedulerTestCase(base.ShakenFistTestCase): def setUp(self): super(SchedulerTestCase, self).setUp() self.recorded_op = mock.patch( 'shakenfist.util.general.RecordedOperation') self.recorded_op.start() self.addCleanup(self.recorded_op.stop) self.mock_config = mock.patch( 'shakenfist.scheduler.config', fake_config) self.mock_config.start() self.addCleanup(self.mock_config.stop) self.mock_etcd = MockEtcd(self, node_count=4) self.mock_etcd.setup() class LowResourceTestCase(SchedulerTestCase): """Test low resource exceptions.""" def test_no_metrics(self): fake_inst = self.mock_etcd.createInstance('fake-inst', 'fakeuuid') exc = self.assertRaises(exceptions.LowResourceException, scheduler.Scheduler().place_instance, fake_inst, []) self.assertEqual('No nodes with metrics', str(exc)) def test_requested_too_many_cpu(self): self.mock_etcd.set_node_metrics_same({ 'cpu_max_per_instance': 5, 'cpu_total_instance_vcpus': 4, 'cpu_available': 12 }) fake_inst = self.mock_etcd.createInstance('fake-inst', 'fakeuuid', cpus=6) exc = self.assertRaises(exceptions.LowResourceException, scheduler.Scheduler().place_instance, fake_inst, []) self.assertEqual('Requested vCPUs exceeds vCPU limit', str(exc)) def test_not_enough_cpu(self): self.mock_etcd.set_node_metrics_same({ 'cpu_max_per_instance': 16, 'cpu_max': 4, 'cpu_total_instance_vcpus': 4*16, 'memory_available': 5*1024+1024-1, 'memory_max': 24000, 'disk_free_instances': 2000*GiB, 'cpu_available': 4 }) fake_inst = self.mock_etcd.createInstance('fake-inst', 'fakeuuid') exc = self.assertRaises(exceptions.LowResourceException, scheduler.Scheduler().place_instance, fake_inst, []) self.assertEqual('No nodes with enough idle CPU', str(exc)) def test_not_enough_ram_for_system(self): self.mock_etcd.set_node_metrics_same({ 'cpu_max_per_instance': 16, 'cpu_max': 4, 'memory_available': 5*1024+1024-1, 'memory_max': 24000, 'disk_free_instances': 2000*GiB, 'cpu_total_instance_vcpus': 4, 'cpu_available': 12 }) fake_inst = self.mock_etcd.createInstance('fake-inst', 'fakeuuid') exc = self.assertRaises(exceptions.LowResourceException, scheduler.Scheduler().place_instance, fake_inst, []) self.assertEqual('No nodes with enough idle RAM', str(exc)) def test_not_enough_ram_on_node(self): self.mock_etcd.set_node_metrics_same({ 'cpu_max_per_instance': 16, 'cpu_max': 4, 'memory_available': 10000, 'memory_max': 10000, 'memory_total_instance_actual': 15001, 'disk_free_instances': 2000*GiB, 'cpu_total_instance_vcpus': 4, 'cpu_available': 12 }) fake_inst = self.mock_etcd.createInstance('fake-inst', 'fakeuuid') exc = self.assertRaises(exceptions.LowResourceException, scheduler.Scheduler().place_instance, fake_inst, []) self.assertEqual('No nodes with enough idle RAM', str(exc)) def test_not_enough_disk(self): self.mock_etcd.set_node_metrics_same({ 'cpu_max_per_instance': 16, 'cpu_max': 4, 'memory_available': 22000, 'memory_max': 24000, 'disk_free_instances': 20*GiB, 'cpu_total_instance_vcpus': 4, 'cpu_available': 12 }) fake_inst = self.mock_etcd.createInstance( 'fake-inst', 'fakeuuid', disk_spec=[{ 'base': 'cirros', 'size': 21 }]) exc = self.assertRaises(exceptions.LowResourceException, scheduler.Scheduler().place_instance, fake_inst, []) self.assertEqual('No nodes with enough disk space', str(exc)) def test_ok(self): self.mock_etcd.set_node_metrics_same() fake_inst = self.mock_etcd.createInstance('fake-inst', 'fakeuuid') nodes = scheduler.Scheduler().place_instance(fake_inst, []) self.assertSetEqual(set(self.mock_etcd.node_names)-{'node1_net', }, set(nodes)) class CorrectAllocationTestCase(SchedulerTestCase): """Test correct node allocation.""" def test_any_node_but_not_network_node(self): self.mock_etcd.createInstance('instance-1', 'uuid-inst-1', place_on_node='node3') self.mock_etcd.set_node_metrics_same() fake_inst = self.mock_etcd.createInstance('fake-inst', 'fakeuuid') nets = [{'network_uuid': 'uuid-net2'}] nodes = scheduler.Scheduler().place_instance(fake_inst, nets) self.assertSetEqual(set(self.mock_etcd.node_names)-{'node1_net', }, set(nodes)) class ForcedCandidatesTestCase(SchedulerTestCase): """Test when we force candidates.""" def setUp(self): super(ForcedCandidatesTestCase, self).setUp() self.mock_etcd.set_node_metrics_same() def test_only_two(self): fake_inst = self.mock_etcd.createInstance('fake-inst', 'fakeuuid') nodes = scheduler.Scheduler().place_instance( fake_inst, [], candidates=['node1_net', 'node2']) self.assertSetEqual({'node2', }, set(nodes)) def test_no_such_node(self): fake_inst = self.mock_etcd.createInstance('fake-inst', 'fakeuuid') self.assertRaises( exceptions.CandidateNodeNotFoundException, scheduler.Scheduler().place_instance, fake_inst, [], candidates=['barry']) class MetricsRefreshTestCase(SchedulerTestCase): """Test that we refresh metrics.""" def test_refresh(self): self.mock_etcd.set_node_metrics_same({ 'cpu_max_per_instance': 16, 'cpu_max': 4, 'memory_available': 22000, 'memory_max': 24000, 'disk_free_instances': 2000*GiB, 'cpu_total_instance_vcpus': 4, 'cpu_available': 12 }) fake_inst = self.mock_etcd.createInstance('fake-inst', 'fakeuuid') s = scheduler.Scheduler() s.place_instance(fake_inst, None) self.assertEqual(22000, s.metrics['node1_net']['memory_available']) self.mock_etcd.set_node_metrics_same({ 'cpu_max_per_instance': 16, 'cpu_max': 4, 'memory_available': 11000, 'memory_max': 24000, 'disk_free_instances': 2000*GiB, 'cpu_total_instance_vcpus': 4, 'cpu_available': 12 }) s.metrics_updated = time.time() - 400 s.place_instance(fake_inst, None) self.assertEqual(11000, s.metrics['node1_net']['memory_available']) class CPUloadAffinityTestCase(SchedulerTestCase): """Test CPU load affinity.""" def setUp(self): super().setUp() self.mock_etcd.set_node_metrics_same() def test_affinity_to_same_node(self): self.mock_etcd.createInstance('instance-1', 'uuid-inst-1', place_on_node='node3', metadata={'tags': ['socialite']}) # Start test inst = self.mock_etcd.createInstance('instance-3', 'uuid-inst-3', metadata={ "affinity": { "cpu": { "socialite": 2, "nerd": -100, } }, }) nodes = scheduler.Scheduler().place_instance(inst, []) self.assertSetEqual({'node3'}, set(nodes)) def test_anti_affinity_single_inst(self): self.mock_etcd.createInstance('instance-1', 'uuid-inst-1', place_on_node='node3', metadata={'tags': ['nerd']}) # Start test inst = self.mock_etcd.createInstance('instance-3', 'uuid-inst-3', metadata={ "affinity": { "cpu": { "socialite": 2, "nerd": -100, } }, }) nodes = scheduler.Scheduler().place_instance(inst, []) self.assertSetEqual({'node2', 'node4'}, set(nodes)) def test_anti_affinity_multiple_inst(self): self.mock_etcd.createInstance('instance-1', 'uuid-inst-1', place_on_node='node3', metadata={'tags': ['nerd']}) self.mock_etcd.createInstance('instance-2', 'uuid-inst-2', place_on_node='node4', metadata={'tags': ['nerd']}) # Start test inst = self.mock_etcd.createInstance('instance-3', 'uuid-inst-3', metadata={ "affinity": { "cpu": { "socialite": 2, "nerd": -100, } }, }) nodes = scheduler.Scheduler().place_instance(inst, []) self.assertSetEqual({'node2'}, set(nodes)) def test_anti_affinity_multiple_inst_different_tags(self): self.mock_etcd.createInstance('instance-1', 'uuid-inst-1', place_on_node='node3', metadata={'tags': ['socialite']}) self.mock_etcd.createInstance('instance-2', 'uuid-inst-2', place_on_node='node4', metadata={'tags': ['nerd']}) # Start test inst = self.mock_etcd.createInstance('instance-3', 'uuid-inst-3', metadata={ "affinity": { "cpu": { "socialite": 2, "nerd": -100, } }, }) nodes = scheduler.Scheduler().place_instance(inst, []) self.assertSetEqual({'node3'}, set(nodes))
import * as React from 'react'; import { useRemoteData, WithRemoteData } from 'use-remote-data'; var i = 0; const freshData = (): Promise<number> => new Promise((resolve) => { i += 1; setTimeout(() => resolve(i), 1000); }); export const Component: React.FC = () => { const [autoRefresh, setAutoRefresh] = React.useState(true); const store = useRemoteData(freshData, { ttlMillis: autoRefresh ? 1000 : undefined }); return ( <div> <label> Autorefresh: <input type="checkbox" onChange={(e) => setAutoRefresh(!autoRefresh)} checked={autoRefresh} /> </label> <br /> <WithRemoteData store={store}> {(num, isInvalidated) => <span style={{ color: isInvalidated ? 'darkgray' : 'black' }}>{num}</span>} </WithRemoteData> </div> ); };