file_name
stringlengths 3
137
| prefix
stringlengths 0
918k
| suffix
stringlengths 0
962k
| middle
stringlengths 0
812k
|
---|---|---|---|
user_repository_impl.go | package repo_impl
import (
"article_api/src/domain/entity"
"article_api/src/domain/repository"
"github.com/jinzhu/gorm"
)
type userRepositoryImpl struct {
DB *gorm.DB
}
var _ repository.UserRepository = &userRepositoryImpl{}
func NewUserRepositoryImpl(db *gorm.DB) *userRepositoryImpl |
func (u userRepositoryImpl) FindOne(filter interface{}) (interface{}, error) {
var user entity.User
err := u.DB.Preload("Profile").Where(filter).Find(&user).Error
if err != nil {
return nil, err
}
return user, nil
}
func (u userRepositoryImpl) Find(filter ...interface{}) (interface{}, error) {
var users entity.Users
err := u.DB.Preload("Profile").Find(&users, filter).Error
if err != nil {
return nil, err
}
return users.UsersOutput(), nil
}
func (u userRepositoryImpl) Remove(data interface{}) error {
return u.DB.Delete(data).Error
}
func (u userRepositoryImpl) Save(data interface{}) error {
return u.DB.Create(data).Error
}
func (u userRepositoryImpl) Update(data interface{}) error {
return u.DB.Update(data).Error
}
| {
return &userRepositoryImpl{db}
} |
2.1.js | function | (min, max, initial)
{
this.min = min;
this.max = max;
this.value = initial;
}
ValueList.prototype.increment = function(amount) {
if(amount >= 0)
{
this.value = Math.min(this.value+amount, this.max);
}
else
{
this.value = Math.max(this.value+amount, this.min);
}
}
var x = new ValueList(0, 2, 1);
var y = new ValueList(0, 2, 1);
var keypad = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
var moveX = {
'L': -1,
'R': 1
};
var moveY = {
'U': -1,
'D': 1
}
var inputs = `ULUULLUULUUUUDURUUULLDLDDRDRDULULRULLRLULRUDRRLDDLRULLLDRDRRDDLLLLDURUURDUDUUURDRLRLLURUDRDULURRUDLRDRRLLRDULLDURURLLLULLRLUDDLRRURRLDULRDDULDLRLURDUDRLLRUDDRLRDLLDDUURLRUDDURRLRURLDDDURRDLLDUUDLLLDUDURLUDURLRDLURURRLRLDDRURRLRRDURLURURRRULRRDLDDDDLLRDLDDDRDDRLUUDDLDUURUULDLUULUURRDRLDDDULRRRRULULLRLLDDUDRLRRLLLLLDRULURLLDULULLUULDDRURUDULDRDRRURLDRDDLULRDDRDLRLUDLLLDUDULUUUUDRDRURDDULLRDRLRRURLRDLRRRRUDDLRDDUDLDLUUDLDDRRRDRLLRLUURUDRUUULUDDDLDUULULLRUDULULLLDRLDDLLUUDRDDDDRUDURDRRUUDDLRRRRURLURLD
LDLUDDLLDDRLLDLDRDDDDDUURUDDDUURLRLRLDULLLDLUDDDULLDUDLRUUDDLUULLDRLDDUDLUDDLURRRLDUURDDRULLURLLRLLUUDRLDDDLDLDRDUDLRDURULDLDRRDRLDLUURRRRLUDDULDULUUUDULDDRLLDDRRUULURRUURRLDUUUDDDDRUURUDRRRDDDDLRLURRRRUUDDDULRRURRDLULRURDDRDRLUDLURDDRDURRUURDUDUDRRDDURRRDURDLUUUURRUDULLDDRLLLURLDUDRRLDDLULUDUDDDDUDLUUULUURUDRURUUDUUURRLDUUDRDRURLLDLLLLLRLLUDURDRRLULRRDDDRLDRDDURLRDULULLDDURURLRRDRULDULUUUURLDURUDUDUDDLUDRRDURULRDULLLDRRDLDLUDURDULULLDDURDDUDRUUUDUDRLDUURDUUUDUURURUDRULRURLDLRDDURDLUU
DDLDRLLDRRDRRLLUUURDDULRDUDRDRUDULURLLDDLRRRUDRDLDLURRRULUDRDLULLULLDUUDRLRUDDLRRURRUULRLDLLLDLRLLLURLLLURLLRDDLULLDUURLURDLLDLDUDLDRUUUDDLLDRRRRRUDRURUURRRDRUURDRDDRLDUUULUDUDRUDLLLLDRDRURRRDUUURLDLRLRDDDRLUDULDRLLULRDLDURDLDURUUDDULLULRDDRLRUURLLLURDRUURUUDUUULRDUDDRDURRRDUUDRRRUDRDLRURDLLDDDURLLRRDDDDLDULULDRLDRULDDLRRRLUDLLLLUDURRRUURUUULRRLDUURDLURRLRLLRDLRDDRDDLRDLULRUUUDDDUDRRURDDURURDDUDLURUUURUUUUDURDDLDRDULDRLDRLLRLRRRLDRLLDDRDLDLUDDLUDLULDLLDRDLLRDULDUDDULRRRUUDULDULRRURLRDRUDLDUDLURRRDDULRDDRULDLUUDDLRDUURDRDR
URDURRRRUURULDLRUUDURDLLDUULULDURUDULLUDULRUDUUURLDRRULRRLLRDUURDDDLRDDRULUUURRRRDLLDLRLRULDLRRRRUDULDDURDLDUUULDURLLUDLURULLURRRDRLLDRRDULUDDURLDULLDURLUDUULRRLLURURLDLLLURDUDRLDDDRDULLUDDRLDDRRRLDULLLLDUURULUDDDURUULUUUDURUDURDURULLLDRULULDRRLDRLDLRLRUDUDURRLURLRUUDRRDULULDLLDRDRRRDUDUURLDULLLURRDLUDDLDDRDDUDLDDRRRUDRULLURDDULRLDUDDDRULURLLUDLLRLRRDRDRRURUUUURDLUURRDULLRDLDLRDDRDRLLLRRDDLDDDDLUDLRLULRRDDRDLDLUUUDLDURURLULLLDDDULURLRRURLDDRDDLD
UDUULLRLUDLLUULRURRUUDDLLLDUURRURURDDRDLRRURLLRURLDDDRRDDUDRLLDRRUDRDRDDRURLULDDLDLRRUDDULLRLDDLRURLUURUURURDLDUDRLUUURRRLUURUDUDUUDDLDULUULRLDLLURLDRUDRLLRULURDLDDLLULLDRRUUDDLRRRUDDLRDRRRULDRDDRRULLLUDRUULURDUDRDLRRLDLRLRLDDULRRLULUUDDULDUDDULRRURLRDRDURUDDDLLRLDRDRULDDLLRLLRDUDDDDDDRLRLLDURUULDUUUDRURRLLRLDDDDRDRDUURRURDRDLLLUDDRDRRRDLUDLUUDRULURDLLLLLRDUDLLRULUULRLULRURULRLRRULUURLUDLDLLUURDLLULLLDDLRUDDRULRDLULRUURLDRULRRLULRLRULRDLURLLRURULRDRDLRRLRRDRUUURURULLLDDUURLDUDLLRRLRLRULLDUUUULDDUUU`;
var code = '';
var lines = inputs.split('\n');
for(var i in lines)
{
var line = lines[i];
for(var j = 0; j < line.length; j++)
{
var char = line[j];
if(moveX[char])
{
x.increment(moveX[char]);
}
else if(moveY[char])
{
y.increment(moveY[char]);
}
}
code += keypad[y.value][x.value];
}
console.log(code);
| ValueList |
generic-tag-match.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[allow(dead_assignment)];
enum foo<T> { arm(T), }
fn altfoo<T>(f: foo<T>) {
let mut hit = false;
match f { arm::<T>(_x) => { info!("in arm"); hit = true; } }
assert!((hit));
}
pub fn | () { altfoo::<int>(arm::<int>(10)); }
| main |
daylightFramework.js | function createDayLightNamespace() {
// intialize configuration
var dayLightConfig = parseQuery(window.location.search.substr(1));
var platform = "HTML-Javascript|sdk v1.2.5|";
function setConfig(str) {
dayLightConfig = parseQuery(str);
dayLight.dayLightConfig = dayLightConfig;
platform = "Win8 Store-WinJS|sdk v1.2.5|";
}
// Request Functions
function getAuthHeader() {
var results, def;
def = $.Deferred();
var daylightUrl = dayLightConfig.daylightUrl;
var xhr = new XMLHttpRequest();
xhr.open('POST', daylightUrl + "/oauth2/token");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status === 200) {
results = JSON.parse(xhr.responseText);
def.resolve(results);
} else if (xhr.readyState == 4) {
def.reject();
}
}
xhr.onerror = function (e) {
def.reject();
};
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send('grant_type=client_credentials&client_id=' + dayLightConfig.clientId + '&client_secret=' + dayLightConfig.clientSecret);
return def.promise();
}
function createRun(authResponse, testRun) {
var results, def;
def = $.Deferred();
var daylightUrl = dayLightConfig.daylightUrl;
var jtoken = authResponse.access_token;
var jsonStr = JSON.stringify(testRun);
var xhr = new XMLHttpRequest();
var requestUrl = daylightUrl + "/api/zumo2/runs?access_token=" + jtoken;
xhr.open('POST', requestUrl);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status === 201) {
results = JSON.parse(xhr.responseText);
results.access_token = jtoken;
def.resolve(results);
} else if (xhr.readyState == 4) {
def.reject();
}
};
xhr.onerror = function (e) {
def.reject();
};
xhr.setRequestHeader('Accept', 'application/json');
xhr.send(jsonStr);
return def.promise();
}
function parseRunResult(runId, testGroup, testGroupMap) {
var result = [];
for (var i = 0; i < testGroup.tests.length; i++) {
var testObj = testGroup.tests[i];
var attach = {
"logs.txt": testObj.filename
};
var test = {
adapter: "zumotestsconverter",
name: testObj.name,
full_name: testObj.name,
source: testGroupMap[testObj.name] === undefined ? "Setup" : testGroupMap[testObj.name].replace(/\s/g, '_'),
run_id: runId,
outcome: statusToOutcome(testObj.status),
start_time: getFileTime(Date.parse(testObj.startTime)),
end_time: getFileTime(Date.parse(testObj.endTime)),
tags: [platform],
attachments: attach
}
result.push(test);
}
return result;
}
function createMasterRunResult(testGrp, runId, fileName) {
var result = [];
var attach = {
"logs.txt": fileName
};
var test = {
adapter: "zumotestsconverter",
name: platform + dayLightConfig.runtime,
full_name: platform + dayLightConfig.runtime,
source: "Javascript",
run_id: runId,
outcome: testGrp.failedTestCount == 0 ? statusToOutcome(0) : statusToOutcome(1),
start_time: getFileTime(Date.parse(testGrp.startTime)),
end_time: getFileTime(Date.parse(testGrp.endTime)),
tags: [platform],
attachments: attach,
}
result.push(test);
return result;
}
function requestBlobAccess(runResponse) {
var results, def;
def = $.Deferred();
var body = 'grant_type=urn%3Adaylight%3Aoauth2%3Ashared-access-signature&permissions=rwdl&scope=attachments';
var xhr = new XMLHttpRequest();
var requestUrl = dayLightConfig.daylightUrl + "/api/zumo2/storageaccounts/token?access_token=" + runResponse.access_token;
xhr.open('POST', requestUrl);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status === 201) {
results = JSON.parse(xhr.responseText);
results.token = runResponse.access_token;
results.runId = runResponse.run_id;
def.resolve(results);
} else if (xhr.readyState == 4) {
def.reject();
}
};
xhr.onerror = function (e) {
def.reject();
};
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(body);
return def.promise();
}
function uploadBlob(tests, blobAccessToken) {
var urlBlob = "https://daylight.blob.core.windows.net/attachments";
var jtoken = blobAccessToken.access_token;
var xhr = new XMLHttpRequest();
for (var i = 0; i < tests.length; i++) {
var blobName = getGuid();
var requestUrl = urlBlob + "/" + blobName + "?" + jtoken;
tests[i].filename = blobName;
xhr.open('PUT', requestUrl);
xhr.setRequestHeader('x-ms-blob-type', 'BlockBlob');
xhr.send(tests[i].logs);
}
return;
}
function createMasterTestLog(testGrp, runId) {
var testLogs = [];
testLogs.push("TestRun:" + dayLightConfig.daylightUrl + "/" + dayLightConfig.dayLightProject + "/runs/" + runId);
testLogs.push("Passed:" + (testGrp.tests.length - (testGrp.failedTestCount + testGrp.skippedCount)).toString());
testLogs.push("Failed:" + testGrp.failedTestCount.toString());
testLogs.push("Skipped:" + testGrp.skippedCount.toString());
testLogs.push("TestCount:" + (testGrp.tests.length).toString());
var test = {
logs: testLogs
};
return [test];
}
function po | token, testResultArray) {
var def;
def = $.Deferred();
var jsonStr = JSON.stringify(testResultArray);
var xhr = new XMLHttpRequest();
var requestUrl = dayLightConfig.daylightUrl + "/api/zumo2/results?access_token=" + jtoken;
xhr.open('POST', requestUrl);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status === 200) {
def.resolve();
} else if (xhr.readyState == 4) {
def.reject();
}
};
xhr.onerror = function (e) {
def.reject();
};
xhr.send(jsonStr);
return def.promise();
}
function closeBrowserWindow() {
window.open('', '_parent', '');
window.close();
}
function reportResults(testResultsGroup, index) {
var testGrp = testResultsGroup[index];
var testCount = testGrp.tests.length;
var startTime = Date.parse(testGrp.startTime);
var testRun = initializeRun(testCount, startTime);
var testGroupMap = groupTestMapping(testResultsGroup);
getAuthHeader().then(
function (authResponse) {
return createRun(authResponse, testRun);
}, closeBrowserWindow).then(
function (runResponse) {
return requestBlobAccess(runResponse);
}, closeBrowserWindow).then(
function (blobAccessToken) {
uploadBlob(testGrp.tests, blobAccessToken);
// Upload master test log
var mastertests = createMasterTestLog(testGrp, blobAccessToken.runId);
uploadBlob(mastertests, blobAccessToken);
//Post result for master test run
var masterRunResult = createMasterRunResult(testGrp, dayLightConfig.masterRunId, mastertests[0].filename);
postResult(blobAccessToken.token, masterRunResult);
////post test results
var result = parseRunResult(blobAccessToken.runId, testResultsGroup[index], testGroupMap);
return postResult(blobAccessToken.token, result);
}, closeBrowserWindow).then(
function () {
setTimeout(closeBrowserWindow, 5000);
});
}
//helper Functions
function dateToString(date) {
/// <param name="date" type="Date">The date to convert to string</param>
function padLeft0(number, size) {
number = number.toString();
while (number.length < size) number = '0' + number;
return number;
}
date = date || new Date(Date.UTC(1900, 0, 1, 0, 0, 0, 0));
var result =
padLeft0(date.getUTCFullYear(), 4) + '-' +
padLeft0(date.getUTCMonth() + 1, 2) + '-' +
padLeft0(date.getUTCDate(), 2) + ' ' +
padLeft0(date.getUTCHours(), 2) + ':' +
padLeft0(date.getUTCMinutes(), 2) + ':' +
padLeft0(date.getUTCSeconds(), 2) + '.' +
padLeft0(date.getUTCMilliseconds(), 3);
return result;
}
function getFileTime(timeInMilliseconds) {
// Time in interval of 100 nano seconds from 1-1-1601 A.D to 1-1-1970 A.D
var baseDate = 116444736000000000;
return baseDate + (timeInMilliseconds * 10000);
}
function initializeRun(testCount, startTime) {
var versionSpec = {
project_name: dayLightConfig.dayLightProject,
branch_name: dayLightConfig.runtime,
revision: "20140729-002505"
};
return {
name: platform + dayLightConfig.runtime,
start_time: getFileTime(startTime),
version_spec: versionSpec,
tags: platform,
test_count: testCount
};
}
function groupTestMapping(testGroups) {
var testGrpMap = {};
for (var i = 0; i < testGroups.length; i++) {
for (var j = 0; j < testGroups[i].tests.length; j++) {
if (testGroups[i].name.indexOf("All tests") < 0)
testGrpMap[testGroups[i].tests[j].name] = testGroups[i].name;
}
}
return testGrpMap;
}
function statusToOutcome(status) {
switch (status) {
case 0:
return "Passed";
case 1:
return 'Failed';
default:
return 'Skipped';
}
}
function parseQuery(qstr) {
if (qstr == "")
return;
qstr = decodeURIComponent(qstr);
var query = {};
var keyPair = qstr.split('&');
for (var i in keyPair) {
var qParam = keyPair[i].split('=');
query[decodeURIComponent(qParam[0])] = decodeURIComponent(qParam[1]);
}
return query;
}
function getGuid() {
var pad4 = function (str) { return "0000".substring(str.length) + str; };
var hex4 = function () { return pad4(Math.floor(Math.random() * 0x10000 /* 65536 */).toString(16)); };
return (hex4() + hex4() + "-" + hex4() + "-" + hex4() + "-" + hex4() + "-" + hex4() + hex4() + hex4());
}
return {
ReportResultsToDaylight: reportResults,
dayLightConfig: dayLightConfig,
setConfig: setConfig
};
}
dayLight = createDayLightNamespace(); | stResult(j |
appengine-gen.go | // Copyright 2021 Google LLC.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Code generated file. DO NOT EDIT.
// Package appengine provides access to the App Engine Admin API.
//
// For product documentation, see: https://cloud.google.com/appengine/docs/admin-api/
//
// Creating a client
//
// Usage example:
//
// import "google.golang.org/api/appengine/v1beta"
// ...
// ctx := context.Background()
// appengineService, err := appengine.NewService(ctx)
//
// In this example, Google Application Default Credentials are used for authentication.
//
// For information on how to create and obtain Application Default Credentials, see https://developers.google.com/identity/protocols/application-default-credentials.
//
// Other authentication options
//
// By default, all available scopes (see "Constants") are used to authenticate. To restrict scopes, use option.WithScopes:
//
// appengineService, err := appengine.NewService(ctx, option.WithScopes(appengine.CloudPlatformReadOnlyScope))
//
// To use an API key for authentication (note: some APIs do not support API keys), use option.WithAPIKey:
//
// appengineService, err := appengine.NewService(ctx, option.WithAPIKey("AIza..."))
//
// To use an OAuth token (e.g., a user token obtained via a three-legged OAuth flow), use option.WithTokenSource:
//
// config := &oauth2.Config{...}
// // ...
// token, err := config.Exchange(ctx, ...)
// appengineService, err := appengine.NewService(ctx, option.WithTokenSource(config.TokenSource(ctx, token)))
//
// See https://godoc.org/google.golang.org/api/option/ for details on options.
package appengine // import "google.golang.org/api/appengine/v1beta"
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
googleapi "google.golang.org/api/googleapi"
gensupport "google.golang.org/api/internal/gensupport"
option "google.golang.org/api/option"
internaloption "google.golang.org/api/option/internaloption"
htransport "google.golang.org/api/transport/http"
)
// Always reference these packages, just in case the auto-generated code
// below doesn't.
var _ = bytes.NewBuffer
var _ = strconv.Itoa
var _ = fmt.Sprintf
var _ = json.NewDecoder
var _ = io.Copy
var _ = url.Parse
var _ = gensupport.MarshalJSON
var _ = googleapi.Version
var _ = errors.New
var _ = strings.Replace
var _ = context.Canceled
var _ = internaloption.WithDefaultEndpoint
const apiId = "appengine:v1beta"
const apiName = "appengine"
const apiVersion = "v1beta"
const basePath = "https://appengine.googleapis.com/"
const mtlsBasePath = "https://appengine.mtls.googleapis.com/"
// OAuth2 scopes used by this API.
const (
// View and manage your applications deployed on Google App Engine
AppengineAdminScope = "https://www.googleapis.com/auth/appengine.admin"
// See, edit, configure, and delete your Google Cloud data and see the
// email address for your Google Account.
CloudPlatformScope = "https://www.googleapis.com/auth/cloud-platform"
// View your data across Google Cloud services and see the email address
// of your Google Account
CloudPlatformReadOnlyScope = "https://www.googleapis.com/auth/cloud-platform.read-only"
)
// NewService creates a new APIService.
func | (ctx context.Context, opts ...option.ClientOption) (*APIService, error) {
scopesOption := option.WithScopes(
"https://www.googleapis.com/auth/appengine.admin",
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only",
)
// NOTE: prepend, so we don't override user-specified scopes.
opts = append([]option.ClientOption{scopesOption}, opts...)
opts = append(opts, internaloption.WithDefaultEndpoint(basePath))
opts = append(opts, internaloption.WithDefaultMTLSEndpoint(mtlsBasePath))
client, endpoint, err := htransport.NewClient(ctx, opts...)
if err != nil {
return nil, err
}
s, err := New(client)
if err != nil {
return nil, err
}
if endpoint != "" {
s.BasePath = endpoint
}
return s, nil
}
// New creates a new APIService. It uses the provided http.Client for requests.
//
// Deprecated: please use NewService instead.
// To provide a custom HTTP client, use option.WithHTTPClient.
// If you are using google.golang.org/api/googleapis/transport.APIKey, use option.WithAPIKey with NewService instead.
func New(client *http.Client) (*APIService, error) {
if client == nil {
return nil, errors.New("client is nil")
}
s := &APIService{client: client, BasePath: basePath}
s.Apps = NewAppsService(s)
return s, nil
}
type APIService struct {
client *http.Client
BasePath string // API endpoint base URL
UserAgent string // optional additional User-Agent fragment
Apps *AppsService
}
func (s *APIService) userAgent() string {
if s.UserAgent == "" {
return googleapi.UserAgent
}
return googleapi.UserAgent + " " + s.UserAgent
}
func NewAppsService(s *APIService) *AppsService {
rs := &AppsService{s: s}
rs.AuthorizedCertificates = NewAppsAuthorizedCertificatesService(s)
rs.AuthorizedDomains = NewAppsAuthorizedDomainsService(s)
rs.DomainMappings = NewAppsDomainMappingsService(s)
rs.Firewall = NewAppsFirewallService(s)
rs.Locations = NewAppsLocationsService(s)
rs.Operations = NewAppsOperationsService(s)
rs.Services = NewAppsServicesService(s)
return rs
}
type AppsService struct {
s *APIService
AuthorizedCertificates *AppsAuthorizedCertificatesService
AuthorizedDomains *AppsAuthorizedDomainsService
DomainMappings *AppsDomainMappingsService
Firewall *AppsFirewallService
Locations *AppsLocationsService
Operations *AppsOperationsService
Services *AppsServicesService
}
func NewAppsAuthorizedCertificatesService(s *APIService) *AppsAuthorizedCertificatesService {
rs := &AppsAuthorizedCertificatesService{s: s}
return rs
}
type AppsAuthorizedCertificatesService struct {
s *APIService
}
func NewAppsAuthorizedDomainsService(s *APIService) *AppsAuthorizedDomainsService {
rs := &AppsAuthorizedDomainsService{s: s}
return rs
}
type AppsAuthorizedDomainsService struct {
s *APIService
}
func NewAppsDomainMappingsService(s *APIService) *AppsDomainMappingsService {
rs := &AppsDomainMappingsService{s: s}
return rs
}
type AppsDomainMappingsService struct {
s *APIService
}
func NewAppsFirewallService(s *APIService) *AppsFirewallService {
rs := &AppsFirewallService{s: s}
rs.IngressRules = NewAppsFirewallIngressRulesService(s)
return rs
}
type AppsFirewallService struct {
s *APIService
IngressRules *AppsFirewallIngressRulesService
}
func NewAppsFirewallIngressRulesService(s *APIService) *AppsFirewallIngressRulesService {
rs := &AppsFirewallIngressRulesService{s: s}
return rs
}
type AppsFirewallIngressRulesService struct {
s *APIService
}
func NewAppsLocationsService(s *APIService) *AppsLocationsService {
rs := &AppsLocationsService{s: s}
return rs
}
type AppsLocationsService struct {
s *APIService
}
func NewAppsOperationsService(s *APIService) *AppsOperationsService {
rs := &AppsOperationsService{s: s}
return rs
}
type AppsOperationsService struct {
s *APIService
}
func NewAppsServicesService(s *APIService) *AppsServicesService {
rs := &AppsServicesService{s: s}
rs.Versions = NewAppsServicesVersionsService(s)
return rs
}
type AppsServicesService struct {
s *APIService
Versions *AppsServicesVersionsService
}
func NewAppsServicesVersionsService(s *APIService) *AppsServicesVersionsService {
rs := &AppsServicesVersionsService{s: s}
rs.Instances = NewAppsServicesVersionsInstancesService(s)
return rs
}
type AppsServicesVersionsService struct {
s *APIService
Instances *AppsServicesVersionsInstancesService
}
func NewAppsServicesVersionsInstancesService(s *APIService) *AppsServicesVersionsInstancesService {
rs := &AppsServicesVersionsInstancesService{s: s}
return rs
}
type AppsServicesVersionsInstancesService struct {
s *APIService
}
// ApiConfigHandler: Google Cloud Endpoints
// (https://cloud.google.com/appengine/docs/python/endpoints/)
// configuration for API handlers.
type ApiConfigHandler struct {
// AuthFailAction: Action to take when users access resources that
// require authentication. Defaults to redirect.
//
// Possible values:
// "AUTH_FAIL_ACTION_UNSPECIFIED" - Not specified.
// AUTH_FAIL_ACTION_REDIRECT is assumed.
// "AUTH_FAIL_ACTION_REDIRECT" - Redirects user to
// "accounts.google.com". The user is redirected back to the application
// URL after signing in or creating an account.
// "AUTH_FAIL_ACTION_UNAUTHORIZED" - Rejects request with a 401 HTTP
// status code and an error message.
AuthFailAction string `json:"authFailAction,omitempty"`
// Login: Level of login required to access this resource. Defaults to
// optional.
//
// Possible values:
// "LOGIN_UNSPECIFIED" - Not specified. LOGIN_OPTIONAL is assumed.
// "LOGIN_OPTIONAL" - Does not require that the user is signed in.
// "LOGIN_ADMIN" - If the user is not signed in, the auth_fail_action
// is taken. In addition, if the user is not an administrator for the
// application, they are given an error message regardless of
// auth_fail_action. If the user is an administrator, the handler
// proceeds.
// "LOGIN_REQUIRED" - If the user has signed in, the handler proceeds
// normally. Otherwise, the auth_fail_action is taken.
Login string `json:"login,omitempty"`
// Script: Path to the script from the application root directory.
Script string `json:"script,omitempty"`
// SecurityLevel: Security (HTTPS) enforcement for this URL.
//
// Possible values:
// "SECURE_UNSPECIFIED" - Not specified.
// "SECURE_DEFAULT" - Both HTTP and HTTPS requests with URLs that
// match the handler succeed without redirects. The application can
// examine the request to determine which protocol was used, and respond
// accordingly.
// "SECURE_NEVER" - Requests for a URL that match this handler that
// use HTTPS are automatically redirected to the HTTP equivalent URL.
// "SECURE_OPTIONAL" - Both HTTP and HTTPS requests with URLs that
// match the handler succeed without redirects. The application can
// examine the request to determine which protocol was used and respond
// accordingly.
// "SECURE_ALWAYS" - Requests for a URL that match this handler that
// do not use HTTPS are automatically redirected to the HTTPS URL with
// the same path. Query parameters are reserved for the redirect.
SecurityLevel string `json:"securityLevel,omitempty"`
// Url: URL to serve the endpoint at.
Url string `json:"url,omitempty"`
// ForceSendFields is a list of field names (e.g. "AuthFailAction") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "AuthFailAction") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *ApiConfigHandler) MarshalJSON() ([]byte, error) {
type NoMethod ApiConfigHandler
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ApiEndpointHandler: Uses Google Cloud Endpoints to handle requests.
type ApiEndpointHandler struct {
// ScriptPath: Path to the script from the application root directory.
ScriptPath string `json:"scriptPath,omitempty"`
// ForceSendFields is a list of field names (e.g. "ScriptPath") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ScriptPath") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ApiEndpointHandler) MarshalJSON() ([]byte, error) {
type NoMethod ApiEndpointHandler
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Application: An Application resource contains the top-level
// configuration of an App Engine application.
type Application struct {
// AuthDomain: Google Apps authentication domain that controls which
// users can access this application.Defaults to open access for any
// Google Account.
AuthDomain string `json:"authDomain,omitempty"`
// CodeBucket: Google Cloud Storage bucket that can be used for storing
// files associated with this application. This bucket is associated
// with the application and can be used by the gcloud deployment
// commands.@OutputOnly
CodeBucket string `json:"codeBucket,omitempty"`
// DatabaseType: The type of the Cloud Firestore or Cloud Datastore
// database associated with this application.
//
// Possible values:
// "DATABASE_TYPE_UNSPECIFIED" - Database type is unspecified.
// "CLOUD_DATASTORE" - Cloud Datastore
// "CLOUD_FIRESTORE" - Cloud Firestore Native
// "CLOUD_DATASTORE_COMPATIBILITY" - Cloud Firestore in Datastore Mode
DatabaseType string `json:"databaseType,omitempty"`
// DefaultBucket: Google Cloud Storage bucket that can be used by this
// application to store content.@OutputOnly
DefaultBucket string `json:"defaultBucket,omitempty"`
// DefaultCookieExpiration: Cookie expiration policy for this
// application.
DefaultCookieExpiration string `json:"defaultCookieExpiration,omitempty"`
// DefaultHostname: Hostname used to reach this application, as resolved
// by App Engine.@OutputOnly
DefaultHostname string `json:"defaultHostname,omitempty"`
// DispatchRules: HTTP path dispatch rules for requests to the
// application that do not explicitly target a service or version. Rules
// are order-dependent. Up to 20 dispatch rules can be supported.
DispatchRules []*UrlDispatchRule `json:"dispatchRules,omitempty"`
// FeatureSettings: The feature specific settings to be used in the
// application.
FeatureSettings *FeatureSettings `json:"featureSettings,omitempty"`
// GcrDomain: The Google Container Registry domain used for storing
// managed build docker images for this application.
GcrDomain string `json:"gcrDomain,omitempty"`
Iap *IdentityAwareProxy `json:"iap,omitempty"`
// Id: Identifier of the Application resource. This identifier is
// equivalent to the project ID of the Google Cloud Platform project
// where you want to deploy your application. Example: myapp.
Id string `json:"id,omitempty"`
// LocationId: Location from which this application runs. Application
// instances run out of the data centers in the specified location,
// which is also where all of the application's end user content is
// stored.Defaults to us-central.View the list of supported locations
// (https://cloud.google.com/appengine/docs/locations).
LocationId string `json:"locationId,omitempty"`
// Name: Full path to the Application resource in the API. Example:
// apps/myapp.@OutputOnly
Name string `json:"name,omitempty"`
// ServiceAccount: The service account associated with the application.
// This is the app-level default identity. If no identity provided
// during create version, Admin API will fallback to this one.
ServiceAccount string `json:"serviceAccount,omitempty"`
// ServingStatus: Serving status of this application.
//
// Possible values:
// "UNSPECIFIED" - Serving status is unspecified.
// "SERVING" - Application is serving.
// "USER_DISABLED" - Application has been disabled by the user.
// "SYSTEM_DISABLED" - Application has been disabled by the system.
ServingStatus string `json:"servingStatus,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "AuthDomain") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "AuthDomain") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Application) MarshalJSON() ([]byte, error) {
type NoMethod Application
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// AuthorizedCertificate: An SSL certificate that a user has been
// authorized to administer. A user is authorized to administer any
// certificate that applies to one of their authorized domains.
type AuthorizedCertificate struct {
// CertificateRawData: The SSL certificate serving the
// AuthorizedCertificate resource. This must be obtained independently
// from a certificate authority.
CertificateRawData *CertificateRawData `json:"certificateRawData,omitempty"`
// DisplayName: The user-specified display name of the certificate. This
// is not guaranteed to be unique. Example: My Certificate.
DisplayName string `json:"displayName,omitempty"`
// DomainMappingsCount: Aggregate count of the domain mappings with this
// certificate mapped. This count includes domain mappings on
// applications for which the user does not have VIEWER permissions.Only
// returned by GET or LIST requests when specifically requested by the
// view=FULL_CERTIFICATE option.@OutputOnly
DomainMappingsCount int64 `json:"domainMappingsCount,omitempty"`
// DomainNames: Topmost applicable domains of this certificate. This
// certificate applies to these domains and their subdomains. Example:
// example.com.@OutputOnly
DomainNames []string `json:"domainNames,omitempty"`
// ExpireTime: The time when this certificate expires. To update the
// renewal time on this certificate, upload an SSL certificate with a
// different expiration time using
// AuthorizedCertificates.UpdateAuthorizedCertificate.@OutputOnly
ExpireTime string `json:"expireTime,omitempty"`
// Id: Relative name of the certificate. This is a unique value
// autogenerated on AuthorizedCertificate resource creation. Example:
// 12345.@OutputOnly
Id string `json:"id,omitempty"`
// ManagedCertificate: Only applicable if this certificate is managed by
// App Engine. Managed certificates are tied to the lifecycle of a
// DomainMapping and cannot be updated or deleted via the
// AuthorizedCertificates API. If this certificate is manually
// administered by the user, this field will be empty.@OutputOnly
ManagedCertificate *ManagedCertificate `json:"managedCertificate,omitempty"`
// Name: Full path to the AuthorizedCertificate resource in the API.
// Example: apps/myapp/authorizedCertificates/12345.@OutputOnly
Name string `json:"name,omitempty"`
// VisibleDomainMappings: The full paths to user visible Domain Mapping
// resources that have this certificate mapped. Example:
// apps/myapp/domainMappings/example.com.This may not represent the full
// list of mapped domain mappings if the user does not have VIEWER
// permissions on all of the applications that have this certificate
// mapped. See domain_mappings_count for a complete count.Only returned
// by GET or LIST requests when specifically requested by the
// view=FULL_CERTIFICATE option.@OutputOnly
VisibleDomainMappings []string `json:"visibleDomainMappings,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "CertificateRawData")
// to unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CertificateRawData") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *AuthorizedCertificate) MarshalJSON() ([]byte, error) {
type NoMethod AuthorizedCertificate
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// AuthorizedDomain: A domain that a user has been authorized to
// administer. To authorize use of a domain, verify ownership via
// Webmaster Central
// (https://www.google.com/webmasters/verification/home).
type AuthorizedDomain struct {
// Id: Fully qualified domain name of the domain authorized for use.
// Example: example.com.
Id string `json:"id,omitempty"`
// Name: Full path to the AuthorizedDomain resource in the API. Example:
// apps/myapp/authorizedDomains/example.com.@OutputOnly
Name string `json:"name,omitempty"`
// ForceSendFields is a list of field names (e.g. "Id") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Id") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *AuthorizedDomain) MarshalJSON() ([]byte, error) {
type NoMethod AuthorizedDomain
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// AutomaticScaling: Automatic scaling is based on request rate,
// response latencies, and other application metrics.
type AutomaticScaling struct {
// CoolDownPeriod: The time period that the Autoscaler
// (https://cloud.google.com/compute/docs/autoscaler/) should wait
// before it starts collecting information from a new instance. This
// prevents the autoscaler from collecting information when the instance
// is initializing, during which the collected usage would not be
// reliable. Only applicable in the App Engine flexible environment.
CoolDownPeriod string `json:"coolDownPeriod,omitempty"`
// CpuUtilization: Target scaling by CPU usage.
CpuUtilization *CpuUtilization `json:"cpuUtilization,omitempty"`
// CustomMetrics: Target scaling by user-provided metrics. Only
// applicable in the App Engine flexible environment.
CustomMetrics []*CustomMetric `json:"customMetrics,omitempty"`
// DiskUtilization: Target scaling by disk usage.
DiskUtilization *DiskUtilization `json:"diskUtilization,omitempty"`
// MaxConcurrentRequests: Number of concurrent requests an automatic
// scaling instance can accept before the scheduler spawns a new
// instance.Defaults to a runtime-specific value.
MaxConcurrentRequests int64 `json:"maxConcurrentRequests,omitempty"`
// MaxIdleInstances: Maximum number of idle instances that should be
// maintained for this version.
MaxIdleInstances int64 `json:"maxIdleInstances,omitempty"`
// MaxPendingLatency: Maximum amount of time that a request should wait
// in the pending queue before starting a new instance to handle it.
MaxPendingLatency string `json:"maxPendingLatency,omitempty"`
// MaxTotalInstances: Maximum number of instances that should be started
// to handle requests for this version.
MaxTotalInstances int64 `json:"maxTotalInstances,omitempty"`
// MinIdleInstances: Minimum number of idle instances that should be
// maintained for this version. Only applicable for the default version
// of a service.
MinIdleInstances int64 `json:"minIdleInstances,omitempty"`
// MinPendingLatency: Minimum amount of time a request should wait in
// the pending queue before starting a new instance to handle it.
MinPendingLatency string `json:"minPendingLatency,omitempty"`
// MinTotalInstances: Minimum number of running instances that should be
// maintained for this version.
MinTotalInstances int64 `json:"minTotalInstances,omitempty"`
// NetworkUtilization: Target scaling by network usage.
NetworkUtilization *NetworkUtilization `json:"networkUtilization,omitempty"`
// RequestUtilization: Target scaling by request utilization.
RequestUtilization *RequestUtilization `json:"requestUtilization,omitempty"`
// StandardSchedulerSettings: Scheduler settings for standard
// environment.
StandardSchedulerSettings *StandardSchedulerSettings `json:"standardSchedulerSettings,omitempty"`
// ForceSendFields is a list of field names (e.g. "CoolDownPeriod") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CoolDownPeriod") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *AutomaticScaling) MarshalJSON() ([]byte, error) {
type NoMethod AutomaticScaling
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// BasicScaling: A service with basic scaling will create an instance
// when the application receives a request. The instance will be turned
// down when the app becomes idle. Basic scaling is ideal for work that
// is intermittent or driven by user activity.
type BasicScaling struct {
// IdleTimeout: Duration of time after the last request that an instance
// must wait before the instance is shut down.
IdleTimeout string `json:"idleTimeout,omitempty"`
// MaxInstances: Maximum number of instances to create for this version.
MaxInstances int64 `json:"maxInstances,omitempty"`
// ForceSendFields is a list of field names (e.g. "IdleTimeout") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "IdleTimeout") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *BasicScaling) MarshalJSON() ([]byte, error) {
type NoMethod BasicScaling
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// BatchUpdateIngressRulesRequest: Request message for
// Firewall.BatchUpdateIngressRules.
type BatchUpdateIngressRulesRequest struct {
// IngressRules: A list of FirewallRules to replace the existing set.
IngressRules []*FirewallRule `json:"ingressRules,omitempty"`
// ForceSendFields is a list of field names (e.g. "IngressRules") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "IngressRules") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *BatchUpdateIngressRulesRequest) MarshalJSON() ([]byte, error) {
type NoMethod BatchUpdateIngressRulesRequest
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// BatchUpdateIngressRulesResponse: Response message for
// Firewall.UpdateAllIngressRules.
type BatchUpdateIngressRulesResponse struct {
// IngressRules: The full list of ingress FirewallRules for this
// application.
IngressRules []*FirewallRule `json:"ingressRules,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "IngressRules") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "IngressRules") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *BatchUpdateIngressRulesResponse) MarshalJSON() ([]byte, error) {
type NoMethod BatchUpdateIngressRulesResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// BuildInfo: Google Cloud Build information.
type BuildInfo struct {
// CloudBuildId: The Google Cloud Build id. Example:
// "f966068f-08b2-42c8-bdfe-74137dff2bf9"
CloudBuildId string `json:"cloudBuildId,omitempty"`
// ForceSendFields is a list of field names (e.g. "CloudBuildId") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CloudBuildId") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *BuildInfo) MarshalJSON() ([]byte, error) {
type NoMethod BuildInfo
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// CertificateRawData: An SSL certificate obtained from a certificate
// authority.
type CertificateRawData struct {
// PrivateKey: Unencrypted PEM encoded RSA private key. This field is
// set once on certificate creation and then encrypted. The key size
// must be 2048 bits or fewer. Must include the header and footer.
// Example: -----BEGIN RSA PRIVATE KEY----- -----END RSA PRIVATE
// KEY----- @InputOnly
PrivateKey string `json:"privateKey,omitempty"`
// PublicCertificate: PEM encoded x.509 public key certificate. This
// field is set once on certificate creation. Must include the header
// and footer. Example: -----BEGIN CERTIFICATE----- -----END
// CERTIFICATE-----
PublicCertificate string `json:"publicCertificate,omitempty"`
// ForceSendFields is a list of field names (e.g. "PrivateKey") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "PrivateKey") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *CertificateRawData) MarshalJSON() ([]byte, error) {
type NoMethod CertificateRawData
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// CloudBuildOptions: Options for the build operations performed as a
// part of the version deployment. Only applicable for App Engine
// flexible environment when creating a version using source code
// directly.
type CloudBuildOptions struct {
// AppYamlPath: Path to the yaml file used in deployment, used to
// determine runtime configuration details.Required for flexible
// environment builds.See
// https://cloud.google.com/appengine/docs/standard/python/config/appref
// for more details.
AppYamlPath string `json:"appYamlPath,omitempty"`
// CloudBuildTimeout: The Cloud Build timeout used as part of any
// dependent builds performed by version creation. Defaults to 10
// minutes.
CloudBuildTimeout string `json:"cloudBuildTimeout,omitempty"`
// ForceSendFields is a list of field names (e.g. "AppYamlPath") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "AppYamlPath") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *CloudBuildOptions) MarshalJSON() ([]byte, error) {
type NoMethod CloudBuildOptions
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ContainerInfo: Docker image that is used to create a container and
// start a VM instance for the version that you deploy. Only applicable
// for instances running in the App Engine flexible environment.
type ContainerInfo struct {
// Image: URI to the hosted container image in Google Container
// Registry. The URI must be fully qualified and include a tag or
// digest. Examples: "gcr.io/my-project/image:tag" or
// "gcr.io/my-project/image@digest"
Image string `json:"image,omitempty"`
// ForceSendFields is a list of field names (e.g. "Image") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Image") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ContainerInfo) MarshalJSON() ([]byte, error) {
type NoMethod ContainerInfo
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// CpuUtilization: Target scaling by CPU usage.
type CpuUtilization struct {
// AggregationWindowLength: Period of time over which CPU utilization is
// calculated.
AggregationWindowLength string `json:"aggregationWindowLength,omitempty"`
// TargetUtilization: Target CPU utilization ratio to maintain when
// scaling. Must be between 0 and 1.
TargetUtilization float64 `json:"targetUtilization,omitempty"`
// ForceSendFields is a list of field names (e.g.
// "AggregationWindowLength") to unconditionally include in API
// requests. By default, fields with empty or default values are omitted
// from API requests. However, any non-pointer, non-interface field
// appearing in ForceSendFields will be sent to the server regardless of
// whether the field is empty or not. This may be used to include empty
// fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "AggregationWindowLength")
// to include in API requests with the JSON null value. By default,
// fields with empty values are omitted from API requests. However, any
// field with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *CpuUtilization) MarshalJSON() ([]byte, error) {
type NoMethod CpuUtilization
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *CpuUtilization) UnmarshalJSON(data []byte) error {
type NoMethod CpuUtilization
var s1 struct {
TargetUtilization gensupport.JSONFloat64 `json:"targetUtilization"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.TargetUtilization = float64(s1.TargetUtilization)
return nil
}
// CreateVersionMetadataV1: Metadata for the given
// google.longrunning.Operation during a
// google.appengine.v1.CreateVersionRequest.
type CreateVersionMetadataV1 struct {
// CloudBuildId: The Cloud Build ID if one was created as part of the
// version create. @OutputOnly
CloudBuildId string `json:"cloudBuildId,omitempty"`
// ForceSendFields is a list of field names (e.g. "CloudBuildId") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CloudBuildId") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *CreateVersionMetadataV1) MarshalJSON() ([]byte, error) {
type NoMethod CreateVersionMetadataV1
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// CreateVersionMetadataV1Alpha: Metadata for the given
// google.longrunning.Operation during a
// google.appengine.v1alpha.CreateVersionRequest.
type CreateVersionMetadataV1Alpha struct {
// CloudBuildId: The Cloud Build ID if one was created as part of the
// version create. @OutputOnly
CloudBuildId string `json:"cloudBuildId,omitempty"`
// ForceSendFields is a list of field names (e.g. "CloudBuildId") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CloudBuildId") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *CreateVersionMetadataV1Alpha) MarshalJSON() ([]byte, error) {
type NoMethod CreateVersionMetadataV1Alpha
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// CreateVersionMetadataV1Beta: Metadata for the given
// google.longrunning.Operation during a
// google.appengine.v1beta.CreateVersionRequest.
type CreateVersionMetadataV1Beta struct {
// CloudBuildId: The Cloud Build ID if one was created as part of the
// version create. @OutputOnly
CloudBuildId string `json:"cloudBuildId,omitempty"`
// ForceSendFields is a list of field names (e.g. "CloudBuildId") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CloudBuildId") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *CreateVersionMetadataV1Beta) MarshalJSON() ([]byte, error) {
type NoMethod CreateVersionMetadataV1Beta
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// CustomMetric: Allows autoscaling based on Stackdriver metrics.
type CustomMetric struct {
// Filter: Allows filtering on the metric's fields.
Filter string `json:"filter,omitempty"`
// MetricName: The name of the metric.
MetricName string `json:"metricName,omitempty"`
// SingleInstanceAssignment: May be used instead of target_utilization
// when an instance can handle a specific amount of work/resources and
// the metric value is equal to the current amount of work remaining.
// The autoscaler will try to keep the number of instances equal to the
// metric value divided by single_instance_assignment.
SingleInstanceAssignment float64 `json:"singleInstanceAssignment,omitempty"`
// TargetType: The type of the metric. Must be a string representing a
// Stackdriver metric type e.g. GAGUE, DELTA_PER_SECOND, etc.
TargetType string `json:"targetType,omitempty"`
// TargetUtilization: The target value for the metric.
TargetUtilization float64 `json:"targetUtilization,omitempty"`
// ForceSendFields is a list of field names (e.g. "Filter") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Filter") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *CustomMetric) MarshalJSON() ([]byte, error) {
type NoMethod CustomMetric
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *CustomMetric) UnmarshalJSON(data []byte) error {
type NoMethod CustomMetric
var s1 struct {
SingleInstanceAssignment gensupport.JSONFloat64 `json:"singleInstanceAssignment"`
TargetUtilization gensupport.JSONFloat64 `json:"targetUtilization"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.SingleInstanceAssignment = float64(s1.SingleInstanceAssignment)
s.TargetUtilization = float64(s1.TargetUtilization)
return nil
}
// DebugInstanceRequest: Request message for Instances.DebugInstance.
type DebugInstanceRequest struct {
// SshKey: Public SSH key to add to the instance. Examples:
// [USERNAME]:ssh-rsa [KEY_VALUE] [USERNAME] [USERNAME]:ssh-rsa
// [KEY_VALUE] google-ssh
// {"userName":"[USERNAME]","expireOn":"[EXPIRE_TIME]"}For more
// information, see Adding and Removing SSH Keys
// (https://cloud.google.com/compute/docs/instances/adding-removing-ssh-keys).
SshKey string `json:"sshKey,omitempty"`
// ForceSendFields is a list of field names (e.g. "SshKey") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "SshKey") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *DebugInstanceRequest) MarshalJSON() ([]byte, error) {
type NoMethod DebugInstanceRequest
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Deployment: Code and application artifacts used to deploy a version
// to App Engine.
type Deployment struct {
// Build: Google Cloud Build build information. Only applicable for
// instances running in the App Engine flexible environment.
Build *BuildInfo `json:"build,omitempty"`
// CloudBuildOptions: Options for any Google Cloud Build builds created
// as a part of this deployment.These options will only be used if a new
// build is created, such as when deploying to the App Engine flexible
// environment using files or zip.
CloudBuildOptions *CloudBuildOptions `json:"cloudBuildOptions,omitempty"`
// Container: The Docker image for the container that runs the version.
// Only applicable for instances running in the App Engine flexible
// environment.
Container *ContainerInfo `json:"container,omitempty"`
// Files: Manifest of the files stored in Google Cloud Storage that are
// included as part of this version. All files must be readable using
// the credentials supplied with this call.
Files map[string]FileInfo `json:"files,omitempty"`
// Zip: The zip file for this deployment, if this is a zip deployment.
Zip *ZipInfo `json:"zip,omitempty"`
// ForceSendFields is a list of field names (e.g. "Build") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Build") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Deployment) MarshalJSON() ([]byte, error) {
type NoMethod Deployment
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// DiskUtilization: Target scaling by disk usage. Only applicable in the
// App Engine flexible environment.
type DiskUtilization struct {
// TargetReadBytesPerSecond: Target bytes read per second.
TargetReadBytesPerSecond int64 `json:"targetReadBytesPerSecond,omitempty"`
// TargetReadOpsPerSecond: Target ops read per seconds.
TargetReadOpsPerSecond int64 `json:"targetReadOpsPerSecond,omitempty"`
// TargetWriteBytesPerSecond: Target bytes written per second.
TargetWriteBytesPerSecond int64 `json:"targetWriteBytesPerSecond,omitempty"`
// TargetWriteOpsPerSecond: Target ops written per second.
TargetWriteOpsPerSecond int64 `json:"targetWriteOpsPerSecond,omitempty"`
// ForceSendFields is a list of field names (e.g.
// "TargetReadBytesPerSecond") to unconditionally include in API
// requests. By default, fields with empty or default values are omitted
// from API requests. However, any non-pointer, non-interface field
// appearing in ForceSendFields will be sent to the server regardless of
// whether the field is empty or not. This may be used to include empty
// fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "TargetReadBytesPerSecond")
// to include in API requests with the JSON null value. By default,
// fields with empty values are omitted from API requests. However, any
// field with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *DiskUtilization) MarshalJSON() ([]byte, error) {
type NoMethod DiskUtilization
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// DomainMapping: A domain serving an App Engine application.
type DomainMapping struct {
// Id: Relative name of the domain serving the application. Example:
// example.com.
Id string `json:"id,omitempty"`
// Name: Full path to the DomainMapping resource in the API. Example:
// apps/myapp/domainMapping/example.com.@OutputOnly
Name string `json:"name,omitempty"`
// ResourceRecords: The resource records required to configure this
// domain mapping. These records must be added to the domain's DNS
// configuration in order to serve the application via this domain
// mapping.@OutputOnly
ResourceRecords []*ResourceRecord `json:"resourceRecords,omitempty"`
// SslSettings: SSL configuration for this domain. If unconfigured, this
// domain will not serve with SSL.
SslSettings *SslSettings `json:"sslSettings,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Id") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Id") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *DomainMapping) MarshalJSON() ([]byte, error) {
type NoMethod DomainMapping
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Empty: A generic empty message that you can re-use to avoid defining
// duplicated empty messages in your APIs. A typical example is to use
// it as the request or the response type of an API method. For
// instance: service Foo { rpc Bar(google.protobuf.Empty) returns
// (google.protobuf.Empty); } The JSON representation for Empty is empty
// JSON object {}.
type Empty struct {
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
}
// EndpointsApiService: Cloud Endpoints
// (https://cloud.google.com/endpoints) configuration. The Endpoints API
// Service provides tooling for serving Open API and gRPC endpoints via
// an NGINX proxy. Only valid for App Engine Flexible environment
// deployments.The fields here refer to the name and configuration ID of
// a "service" resource in the Service Management API
// (https://cloud.google.com/service-management/overview).
type EndpointsApiService struct {
// ConfigId: Endpoints service configuration ID as specified by the
// Service Management API. For example "2016-09-19r1".By default, the
// rollout strategy for Endpoints is RolloutStrategy.FIXED. This means
// that Endpoints starts up with a particular configuration ID. When a
// new configuration is rolled out, Endpoints must be given the new
// configuration ID. The config_id field is used to give the
// configuration ID and is required in this case.Endpoints also has a
// rollout strategy called RolloutStrategy.MANAGED. When using this,
// Endpoints fetches the latest configuration and does not need the
// configuration ID. In this case, config_id must be omitted.
ConfigId string `json:"configId,omitempty"`
// DisableTraceSampling: Enable or disable trace sampling. By default,
// this is set to false for enabled.
DisableTraceSampling bool `json:"disableTraceSampling,omitempty"`
// Name: Endpoints service name which is the name of the "service"
// resource in the Service Management API. For example
// "myapi.endpoints.myproject.cloud.goog"
Name string `json:"name,omitempty"`
// RolloutStrategy: Endpoints rollout strategy. If FIXED, config_id must
// be specified. If MANAGED, config_id must be omitted.
//
// Possible values:
// "UNSPECIFIED_ROLLOUT_STRATEGY" - Not specified. Defaults to FIXED.
// "FIXED" - Endpoints service configuration ID will be fixed to the
// configuration ID specified by config_id.
// "MANAGED" - Endpoints service configuration ID will be updated with
// each rollout.
RolloutStrategy string `json:"rolloutStrategy,omitempty"`
// ForceSendFields is a list of field names (e.g. "ConfigId") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ConfigId") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *EndpointsApiService) MarshalJSON() ([]byte, error) {
type NoMethod EndpointsApiService
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Entrypoint: The entrypoint for the application.
type Entrypoint struct {
// Shell: The format should be a shell command that can be fed to bash
// -c.
Shell string `json:"shell,omitempty"`
// ForceSendFields is a list of field names (e.g. "Shell") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Shell") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Entrypoint) MarshalJSON() ([]byte, error) {
type NoMethod Entrypoint
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ErrorHandler: Custom static error page to be served when an error
// occurs.
type ErrorHandler struct {
// ErrorCode: Error condition this handler applies to.
//
// Possible values:
// "ERROR_CODE_UNSPECIFIED" - Not specified. ERROR_CODE_DEFAULT is
// assumed.
// "ERROR_CODE_DEFAULT" - All other error types.
// "ERROR_CODE_OVER_QUOTA" - Application has exceeded a resource
// quota.
// "ERROR_CODE_DOS_API_DENIAL" - Client blocked by the application's
// Denial of Service protection configuration.
// "ERROR_CODE_TIMEOUT" - Deadline reached before the application
// responds.
ErrorCode string `json:"errorCode,omitempty"`
// MimeType: MIME type of file. Defaults to text/html.
MimeType string `json:"mimeType,omitempty"`
// StaticFile: Static file content to be served for this error.
StaticFile string `json:"staticFile,omitempty"`
// ForceSendFields is a list of field names (e.g. "ErrorCode") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ErrorCode") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ErrorHandler) MarshalJSON() ([]byte, error) {
type NoMethod ErrorHandler
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// FeatureSettings: The feature specific settings to be used in the
// application. These define behaviors that are user configurable.
type FeatureSettings struct {
// SplitHealthChecks: Boolean value indicating if split health checks
// should be used instead of the legacy health checks. At an app.yaml
// level, this means defaulting to 'readiness_check' and
// 'liveness_check' values instead of 'health_check' ones. Once the
// legacy 'health_check' behavior is deprecated, and this value is
// always true, this setting can be removed.
SplitHealthChecks bool `json:"splitHealthChecks,omitempty"`
// UseContainerOptimizedOs: If true, use Container-Optimized OS
// (https://cloud.google.com/container-optimized-os/) base image for
// VMs, rather than a base Debian image.
UseContainerOptimizedOs bool `json:"useContainerOptimizedOs,omitempty"`
// ForceSendFields is a list of field names (e.g. "SplitHealthChecks")
// to unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "SplitHealthChecks") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *FeatureSettings) MarshalJSON() ([]byte, error) {
type NoMethod FeatureSettings
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// FileInfo: Single source file that is part of the version to be
// deployed. Each source file that is deployed must be specified
// separately.
type FileInfo struct {
// MimeType: The MIME type of the file.Defaults to the value from Google
// Cloud Storage.
MimeType string `json:"mimeType,omitempty"`
// Sha1Sum: The SHA1 hash of the file, in hex.
Sha1Sum string `json:"sha1Sum,omitempty"`
// SourceUrl: URL source to use to fetch this file. Must be a URL to a
// resource in Google Cloud Storage in the form
// 'http(s)://storage.googleapis.com//'.
SourceUrl string `json:"sourceUrl,omitempty"`
// ForceSendFields is a list of field names (e.g. "MimeType") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "MimeType") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *FileInfo) MarshalJSON() ([]byte, error) {
type NoMethod FileInfo
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// FirewallRule: A single firewall rule that is evaluated against
// incoming traffic and provides an action to take on matched requests.
type FirewallRule struct {
// Action: The action to take on matched requests.
//
// Possible values:
// "UNSPECIFIED_ACTION"
// "ALLOW" - Matching requests are allowed.
// "DENY" - Matching requests are denied.
Action string `json:"action,omitempty"`
// Description: An optional string description of this rule. This field
// has a maximum length of 400 characters.
Description string `json:"description,omitempty"`
// Priority: A positive integer between 1, Int32.MaxValue-1 that defines
// the order of rule evaluation. Rules with the lowest priority are
// evaluated first.A default rule at priority Int32.MaxValue matches all
// IPv4 and IPv6 traffic when no previous rule matches. Only the action
// of this rule can be modified by the user.
Priority int64 `json:"priority,omitempty"`
// SourceRange: IP address or range, defined using CIDR notation, of
// requests that this rule applies to. You can use the wildcard
// character "*" to match all IPs equivalent to "0/0" and "::/0"
// together. Examples: 192.168.1.1 or 192.168.0.0/16 or 2001:db8::/32 or
// 2001:0db8:0000:0042:0000:8a2e:0370:7334. Truncation will be silently
// performed on addresses which are not properly truncated. For example,
// 1.2.3.4/24 is accepted as the same address as 1.2.3.0/24. Similarly,
// for IPv6, 2001:db8::1/32 is accepted as the same address as
// 2001:db8::/32.
SourceRange string `json:"sourceRange,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Action") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Action") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *FirewallRule) MarshalJSON() ([]byte, error) {
type NoMethod FirewallRule
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// GoogleAppengineV1betaLocationMetadata: Metadata for the given
// google.cloud.location.Location.
type GoogleAppengineV1betaLocationMetadata struct {
// FlexibleEnvironmentAvailable: App Engine flexible environment is
// available in the given location.@OutputOnly
FlexibleEnvironmentAvailable bool `json:"flexibleEnvironmentAvailable,omitempty"`
// SearchApiAvailable: Output only. Search API
// (https://cloud.google.com/appengine/docs/standard/python/search) is
// available in the given location.
SearchApiAvailable bool `json:"searchApiAvailable,omitempty"`
// StandardEnvironmentAvailable: App Engine standard environment is
// available in the given location.@OutputOnly
StandardEnvironmentAvailable bool `json:"standardEnvironmentAvailable,omitempty"`
// ForceSendFields is a list of field names (e.g.
// "FlexibleEnvironmentAvailable") to unconditionally include in API
// requests. By default, fields with empty or default values are omitted
// from API requests. However, any non-pointer, non-interface field
// appearing in ForceSendFields will be sent to the server regardless of
// whether the field is empty or not. This may be used to include empty
// fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g.
// "FlexibleEnvironmentAvailable") to include in API requests with the
// JSON null value. By default, fields with empty values are omitted
// from API requests. However, any field with an empty value appearing
// in NullFields will be sent to the server as null. It is an error if a
// field in this list has a non-empty value. This may be used to include
// null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *GoogleAppengineV1betaLocationMetadata) MarshalJSON() ([]byte, error) {
type NoMethod GoogleAppengineV1betaLocationMetadata
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// HealthCheck: Health checking configuration for VM instances.
// Unhealthy instances are killed and replaced with new instances. Only
// applicable for instances in App Engine flexible environment.
type HealthCheck struct {
// CheckInterval: Interval between health checks.
CheckInterval string `json:"checkInterval,omitempty"`
// DisableHealthCheck: Whether to explicitly disable health checks for
// this instance.
DisableHealthCheck bool `json:"disableHealthCheck,omitempty"`
// HealthyThreshold: Number of consecutive successful health checks
// required before receiving traffic.
HealthyThreshold int64 `json:"healthyThreshold,omitempty"`
// Host: Host header to send when performing an HTTP health check.
// Example: "myapp.appspot.com"
Host string `json:"host,omitempty"`
// RestartThreshold: Number of consecutive failed health checks required
// before an instance is restarted.
RestartThreshold int64 `json:"restartThreshold,omitempty"`
// Timeout: Time before the health check is considered failed.
Timeout string `json:"timeout,omitempty"`
// UnhealthyThreshold: Number of consecutive failed health checks
// required before removing traffic.
UnhealthyThreshold int64 `json:"unhealthyThreshold,omitempty"`
// ForceSendFields is a list of field names (e.g. "CheckInterval") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CheckInterval") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *HealthCheck) MarshalJSON() ([]byte, error) {
type NoMethod HealthCheck
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// IdentityAwareProxy: Identity-Aware Proxy
type IdentityAwareProxy struct {
// Enabled: Whether the serving infrastructure will authenticate and
// authorize all incoming requests.If true, the oauth2_client_id and
// oauth2_client_secret fields must be non-empty.
Enabled bool `json:"enabled,omitempty"`
// Oauth2ClientId: OAuth2 client ID to use for the authentication flow.
Oauth2ClientId string `json:"oauth2ClientId,omitempty"`
// Oauth2ClientSecret: OAuth2 client secret to use for the
// authentication flow.For security reasons, this value cannot be
// retrieved via the API. Instead, the SHA-256 hash of the value is
// returned in the oauth2_client_secret_sha256 field.@InputOnly
Oauth2ClientSecret string `json:"oauth2ClientSecret,omitempty"`
// Oauth2ClientSecretSha256: Hex-encoded SHA-256 hash of the client
// secret.@OutputOnly
Oauth2ClientSecretSha256 string `json:"oauth2ClientSecretSha256,omitempty"`
// ForceSendFields is a list of field names (e.g. "Enabled") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Enabled") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *IdentityAwareProxy) MarshalJSON() ([]byte, error) {
type NoMethod IdentityAwareProxy
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Instance: An Instance resource is the computing unit that App Engine
// uses to automatically scale an application.
type Instance struct {
// AppEngineRelease: Output only. App Engine release this instance is
// running on.
AppEngineRelease string `json:"appEngineRelease,omitempty"`
// Availability: Output only. Availability of the instance.
//
// Possible values:
// "UNSPECIFIED"
// "RESIDENT"
// "DYNAMIC"
Availability string `json:"availability,omitempty"`
// AverageLatency: Output only. Average latency (ms) over the last
// minute.
AverageLatency int64 `json:"averageLatency,omitempty"`
// Errors: Output only. Number of errors since this instance was
// started.
Errors int64 `json:"errors,omitempty"`
// Id: Output only. Relative name of the instance within the version.
// Example: instance-1.
Id string `json:"id,omitempty"`
// MemoryUsage: Output only. Total memory in use (bytes).
MemoryUsage int64 `json:"memoryUsage,omitempty,string"`
// Name: Output only. Full path to the Instance resource in the API.
// Example:
// apps/myapp/services/default/versions/v1/instances/instance-1.
Name string `json:"name,omitempty"`
// Qps: Output only. Average queries per second (QPS) over the last
// minute.
Qps float64 `json:"qps,omitempty"`
// Requests: Output only. Number of requests since this instance was
// started.
Requests int64 `json:"requests,omitempty"`
// StartTime: Output only. Time that this instance was
// started.@OutputOnly
StartTime string `json:"startTime,omitempty"`
// VmDebugEnabled: Output only. Whether this instance is in debug mode.
// Only applicable for instances in App Engine flexible environment.
VmDebugEnabled bool `json:"vmDebugEnabled,omitempty"`
// VmId: Output only. Virtual machine ID of this instance. Only
// applicable for instances in App Engine flexible environment.
VmId string `json:"vmId,omitempty"`
// VmIp: Output only. The IP address of this instance. Only applicable
// for instances in App Engine flexible environment.
VmIp string `json:"vmIp,omitempty"`
// VmLiveness: Output only. The liveness health check of this instance.
// Only applicable for instances in App Engine flexible environment.
//
// Possible values:
// "LIVENESS_STATE_UNSPECIFIED" - There is no liveness health check
// for the instance. Only applicable for instances in App Engine
// standard environment.
// "UNKNOWN" - The health checking system is aware of the instance but
// its health is not known at the moment.
// "HEALTHY" - The instance is reachable i.e. a connection to the
// application health checking endpoint can be established, and conforms
// to the requirements defined by the health check.
// "UNHEALTHY" - The instance is reachable, but does not conform to
// the requirements defined by the health check.
// "DRAINING" - The instance is being drained. The existing
// connections to the instance have time to complete, but the new ones
// are being refused.
// "TIMEOUT" - The instance is unreachable i.e. a connection to the
// application health checking endpoint cannot be established, or the
// server does not respond within the specified timeout.
VmLiveness string `json:"vmLiveness,omitempty"`
// VmName: Output only. Name of the virtual machine where this instance
// lives. Only applicable for instances in App Engine flexible
// environment.
VmName string `json:"vmName,omitempty"`
// VmStatus: Output only. Status of the virtual machine where this
// instance lives. Only applicable for instances in App Engine flexible
// environment.
VmStatus string `json:"vmStatus,omitempty"`
// VmZoneName: Output only. Zone where the virtual machine is located.
// Only applicable for instances in App Engine flexible environment.
VmZoneName string `json:"vmZoneName,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "AppEngineRelease") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "AppEngineRelease") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *Instance) MarshalJSON() ([]byte, error) {
type NoMethod Instance
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *Instance) UnmarshalJSON(data []byte) error {
type NoMethod Instance
var s1 struct {
Qps gensupport.JSONFloat64 `json:"qps"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Qps = float64(s1.Qps)
return nil
}
// Library: Third-party Python runtime library that is required by the
// application.
type Library struct {
// Name: Name of the library. Example: "django".
Name string `json:"name,omitempty"`
// Version: Version of the library to select, or "latest".
Version string `json:"version,omitempty"`
// ForceSendFields is a list of field names (e.g. "Name") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Name") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Library) MarshalJSON() ([]byte, error) {
type NoMethod Library
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ListAuthorizedCertificatesResponse: Response message for
// AuthorizedCertificates.ListAuthorizedCertificates.
type ListAuthorizedCertificatesResponse struct {
// Certificates: The SSL certificates the user is authorized to
// administer.
Certificates []*AuthorizedCertificate `json:"certificates,omitempty"`
// NextPageToken: Continuation token for fetching the next page of
// results.
NextPageToken string `json:"nextPageToken,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Certificates") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Certificates") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ListAuthorizedCertificatesResponse) MarshalJSON() ([]byte, error) {
type NoMethod ListAuthorizedCertificatesResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ListAuthorizedDomainsResponse: Response message for
// AuthorizedDomains.ListAuthorizedDomains.
type ListAuthorizedDomainsResponse struct {
// Domains: The authorized domains belonging to the user.
Domains []*AuthorizedDomain `json:"domains,omitempty"`
// NextPageToken: Continuation token for fetching the next page of
// results.
NextPageToken string `json:"nextPageToken,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Domains") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Domains") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ListAuthorizedDomainsResponse) MarshalJSON() ([]byte, error) {
type NoMethod ListAuthorizedDomainsResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ListDomainMappingsResponse: Response message for
// DomainMappings.ListDomainMappings.
type ListDomainMappingsResponse struct {
// DomainMappings: The domain mappings for the application.
DomainMappings []*DomainMapping `json:"domainMappings,omitempty"`
// NextPageToken: Continuation token for fetching the next page of
// results.
NextPageToken string `json:"nextPageToken,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "DomainMappings") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "DomainMappings") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *ListDomainMappingsResponse) MarshalJSON() ([]byte, error) {
type NoMethod ListDomainMappingsResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ListIngressRulesResponse: Response message for
// Firewall.ListIngressRules.
type ListIngressRulesResponse struct {
// IngressRules: The ingress FirewallRules for this application.
IngressRules []*FirewallRule `json:"ingressRules,omitempty"`
// NextPageToken: Continuation token for fetching the next page of
// results.
NextPageToken string `json:"nextPageToken,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "IngressRules") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "IngressRules") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ListIngressRulesResponse) MarshalJSON() ([]byte, error) {
type NoMethod ListIngressRulesResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ListInstancesResponse: Response message for Instances.ListInstances.
type ListInstancesResponse struct {
// Instances: The instances belonging to the requested version.
Instances []*Instance `json:"instances,omitempty"`
// NextPageToken: Continuation token for fetching the next page of
// results.
NextPageToken string `json:"nextPageToken,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Instances") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Instances") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ListInstancesResponse) MarshalJSON() ([]byte, error) {
type NoMethod ListInstancesResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ListLocationsResponse: The response message for
// Locations.ListLocations.
type ListLocationsResponse struct {
// Locations: A list of locations that matches the specified filter in
// the request.
Locations []*Location `json:"locations,omitempty"`
// NextPageToken: The standard List next-page token.
NextPageToken string `json:"nextPageToken,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Locations") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Locations") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ListLocationsResponse) MarshalJSON() ([]byte, error) {
type NoMethod ListLocationsResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ListOperationsResponse: The response message for
// Operations.ListOperations.
type ListOperationsResponse struct {
// NextPageToken: The standard List next-page token.
NextPageToken string `json:"nextPageToken,omitempty"`
// Operations: A list of operations that matches the specified filter in
// the request.
Operations []*Operation `json:"operations,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "NextPageToken") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "NextPageToken") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ListOperationsResponse) MarshalJSON() ([]byte, error) {
type NoMethod ListOperationsResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ListServicesResponse: Response message for Services.ListServices.
type ListServicesResponse struct {
// NextPageToken: Continuation token for fetching the next page of
// results.
NextPageToken string `json:"nextPageToken,omitempty"`
// Services: The services belonging to the requested application.
Services []*Service `json:"services,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "NextPageToken") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "NextPageToken") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ListServicesResponse) MarshalJSON() ([]byte, error) {
type NoMethod ListServicesResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ListVersionsResponse: Response message for Versions.ListVersions.
type ListVersionsResponse struct {
// NextPageToken: Continuation token for fetching the next page of
// results.
NextPageToken string `json:"nextPageToken,omitempty"`
// Versions: The versions belonging to the requested service.
Versions []*Version `json:"versions,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "NextPageToken") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "NextPageToken") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ListVersionsResponse) MarshalJSON() ([]byte, error) {
type NoMethod ListVersionsResponse
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// LivenessCheck: Health checking configuration for VM instances.
// Unhealthy instances are killed and replaced with new instances.
type LivenessCheck struct {
// CheckInterval: Interval between health checks.
CheckInterval string `json:"checkInterval,omitempty"`
// FailureThreshold: Number of consecutive failed checks required before
// considering the VM unhealthy.
FailureThreshold int64 `json:"failureThreshold,omitempty"`
// Host: Host header to send when performing a HTTP Liveness check.
// Example: "myapp.appspot.com"
Host string `json:"host,omitempty"`
// InitialDelay: The initial delay before starting to execute the
// checks.
InitialDelay string `json:"initialDelay,omitempty"`
// Path: The request path.
Path string `json:"path,omitempty"`
// SuccessThreshold: Number of consecutive successful checks required
// before considering the VM healthy.
SuccessThreshold int64 `json:"successThreshold,omitempty"`
// Timeout: Time before the check is considered failed.
Timeout string `json:"timeout,omitempty"`
// ForceSendFields is a list of field names (e.g. "CheckInterval") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CheckInterval") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *LivenessCheck) MarshalJSON() ([]byte, error) {
type NoMethod LivenessCheck
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Location: A resource that represents Google Cloud Platform location.
type Location struct {
// DisplayName: The friendly name for this location, typically a nearby
// city name. For example, "Tokyo".
DisplayName string `json:"displayName,omitempty"`
// Labels: Cross-service attributes for the location. For example
// {"cloud.googleapis.com/region": "us-east1"}
Labels map[string]string `json:"labels,omitempty"`
// LocationId: The canonical id for this location. For example:
// "us-east1".
LocationId string `json:"locationId,omitempty"`
// Metadata: Service-specific metadata. For example the available
// capacity at the given location.
Metadata googleapi.RawMessage `json:"metadata,omitempty"`
// Name: Resource name for the location, which may vary between
// implementations. For example:
// "projects/example-project/locations/us-east1"
Name string `json:"name,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "DisplayName") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "DisplayName") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Location) MarshalJSON() ([]byte, error) {
type NoMethod Location
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// LocationMetadata: Metadata for the given
// google.cloud.location.Location.
type LocationMetadata struct {
// FlexibleEnvironmentAvailable: App Engine flexible environment is
// available in the given location.@OutputOnly
FlexibleEnvironmentAvailable bool `json:"flexibleEnvironmentAvailable,omitempty"`
// SearchApiAvailable: Output only. Search API
// (https://cloud.google.com/appengine/docs/standard/python/search) is
// available in the given location.
SearchApiAvailable bool `json:"searchApiAvailable,omitempty"`
// StandardEnvironmentAvailable: App Engine standard environment is
// available in the given location.@OutputOnly
StandardEnvironmentAvailable bool `json:"standardEnvironmentAvailable,omitempty"`
// ForceSendFields is a list of field names (e.g.
// "FlexibleEnvironmentAvailable") to unconditionally include in API
// requests. By default, fields with empty or default values are omitted
// from API requests. However, any non-pointer, non-interface field
// appearing in ForceSendFields will be sent to the server regardless of
// whether the field is empty or not. This may be used to include empty
// fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g.
// "FlexibleEnvironmentAvailable") to include in API requests with the
// JSON null value. By default, fields with empty values are omitted
// from API requests. However, any field with an empty value appearing
// in NullFields will be sent to the server as null. It is an error if a
// field in this list has a non-empty value. This may be used to include
// null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *LocationMetadata) MarshalJSON() ([]byte, error) {
type NoMethod LocationMetadata
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ManagedCertificate: A certificate managed by App Engine.
type ManagedCertificate struct {
// LastRenewalTime: Time at which the certificate was last renewed. The
// renewal process is fully managed. Certificate renewal will
// automatically occur before the certificate expires. Renewal errors
// can be tracked via ManagementStatus.@OutputOnly
LastRenewalTime string `json:"lastRenewalTime,omitempty"`
// Status: Status of certificate management. Refers to the most recent
// certificate acquisition or renewal attempt.@OutputOnly
//
// Possible values:
// "MANAGEMENT_STATUS_UNSPECIFIED"
// "OK" - Certificate was successfully obtained and inserted into the
// serving system.
// "PENDING" - Certificate is under active attempts to acquire or
// renew.
// "FAILED_RETRYING_NOT_VISIBLE" - Most recent renewal failed due to
// an invalid DNS setup and will be retried. Renewal attempts will
// continue to fail until the certificate domain's DNS configuration is
// fixed. The last successfully provisioned certificate may still be
// serving.
// "FAILED_PERMANENT" - All renewal attempts have been exhausted,
// likely due to an invalid DNS setup.
// "FAILED_RETRYING_CAA_FORBIDDEN" - Most recent renewal failed due to
// an explicit CAA record that does not include one of the in-use CAs
// (Google CA and Let's Encrypt). Renewals will continue to fail until
// the CAA is reconfigured. The last successfully provisioned
// certificate may still be serving.
// "FAILED_RETRYING_CAA_CHECKING" - Most recent renewal failed due to
// a CAA retrieval failure. This means that the domain's DNS provider
// does not properly handle CAA records, failing requests for CAA
// records when no CAA records are defined. Renewals will continue to
// fail until the DNS provider is changed or a CAA record is added for
// the given domain. The last successfully provisioned certificate may
// still be serving.
Status string `json:"status,omitempty"`
// ForceSendFields is a list of field names (e.g. "LastRenewalTime") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "LastRenewalTime") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *ManagedCertificate) MarshalJSON() ([]byte, error) {
type NoMethod ManagedCertificate
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ManualScaling: A service with manual scaling runs continuously,
// allowing you to perform complex initialization and rely on the state
// of its memory over time.
type ManualScaling struct {
// Instances: Number of instances to assign to the service at the start.
// This number can later be altered by using the Modules API
// (https://cloud.google.com/appengine/docs/python/modules/functions)
// set_num_instances() function.
Instances int64 `json:"instances,omitempty"`
// ForceSendFields is a list of field names (e.g. "Instances") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Instances") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ManualScaling) MarshalJSON() ([]byte, error) {
type NoMethod ManualScaling
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Network: Extra network settings. Only applicable in the App Engine
// flexible environment.
type Network struct {
// ForwardedPorts: List of ports, or port pairs, to forward from the
// virtual machine to the application container. Only applicable in the
// App Engine flexible environment.
ForwardedPorts []string `json:"forwardedPorts,omitempty"`
// InstanceIpMode: The IP mode for instances. Only applicable in the App
// Engine flexible environment.
//
// Possible values:
// "INSTANCE_IP_MODE_UNSPECIFIED" - Unspecified should be treated as
// EXTERNAL
// "EXTERNAL" - VMs should be created with external and internal IPs
// "INTERNAL" - VMs should be created with internal IPs only
InstanceIpMode string `json:"instanceIpMode,omitempty"`
// InstanceTag: Tag to apply to the instance during creation. Only
// applicable in the App Engine flexible environment.
InstanceTag string `json:"instanceTag,omitempty"`
// Name: Google Compute Engine network where the virtual machines are
// created. Specify the short name, not the resource path.Defaults to
// default.
Name string `json:"name,omitempty"`
// SessionAffinity: Enable session affinity. Only applicable in the App
// Engine flexible environment.
SessionAffinity bool `json:"sessionAffinity,omitempty"`
// SubnetworkName: Google Cloud Platform sub-network where the virtual
// machines are created. Specify the short name, not the resource
// path.If a subnetwork name is specified, a network name will also be
// required unless it is for the default network. If the network that
// the instance is being created in is a Legacy network, then the IP
// address is allocated from the IPv4Range. If the network that the
// instance is being created in is an auto Subnet Mode Network, then
// only network name should be specified (not the subnetwork_name) and
// the IP address is created from the IPCidrRange of the subnetwork that
// exists in that zone for that network. If the network that the
// instance is being created in is a custom Subnet Mode Network, then
// the subnetwork_name must be specified and the IP address is created
// from the IPCidrRange of the subnetwork.If specified, the subnetwork
// must exist in the same region as the App Engine flexible environment
// application.
SubnetworkName string `json:"subnetworkName,omitempty"`
// ForceSendFields is a list of field names (e.g. "ForwardedPorts") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ForwardedPorts") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *Network) MarshalJSON() ([]byte, error) {
type NoMethod Network
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// NetworkSettings: A NetworkSettings resource is a container for
// ingress settings for a version or service.
type NetworkSettings struct {
// IngressTrafficAllowed: The ingress settings for version or service.
//
// Possible values:
// "INGRESS_TRAFFIC_ALLOWED_UNSPECIFIED" - Unspecified
// "INGRESS_TRAFFIC_ALLOWED_ALL" - Allow HTTP traffic from public and
// private sources.
// "INGRESS_TRAFFIC_ALLOWED_INTERNAL_ONLY" - Allow HTTP traffic from
// only private VPC sources.
// "INGRESS_TRAFFIC_ALLOWED_INTERNAL_AND_LB" - Allow HTTP traffic from
// private VPC sources and through load balancers.
IngressTrafficAllowed string `json:"ingressTrafficAllowed,omitempty"`
// ForceSendFields is a list of field names (e.g.
// "IngressTrafficAllowed") to unconditionally include in API requests.
// By default, fields with empty or default values are omitted from API
// requests. However, any non-pointer, non-interface field appearing in
// ForceSendFields will be sent to the server regardless of whether the
// field is empty or not. This may be used to include empty fields in
// Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "IngressTrafficAllowed") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *NetworkSettings) MarshalJSON() ([]byte, error) {
type NoMethod NetworkSettings
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// NetworkUtilization: Target scaling by network usage. Only applicable
// in the App Engine flexible environment.
type NetworkUtilization struct {
// TargetReceivedBytesPerSecond: Target bytes received per second.
TargetReceivedBytesPerSecond int64 `json:"targetReceivedBytesPerSecond,omitempty"`
// TargetReceivedPacketsPerSecond: Target packets received per second.
TargetReceivedPacketsPerSecond int64 `json:"targetReceivedPacketsPerSecond,omitempty"`
// TargetSentBytesPerSecond: Target bytes sent per second.
TargetSentBytesPerSecond int64 `json:"targetSentBytesPerSecond,omitempty"`
// TargetSentPacketsPerSecond: Target packets sent per second.
TargetSentPacketsPerSecond int64 `json:"targetSentPacketsPerSecond,omitempty"`
// ForceSendFields is a list of field names (e.g.
// "TargetReceivedBytesPerSecond") to unconditionally include in API
// requests. By default, fields with empty or default values are omitted
// from API requests. However, any non-pointer, non-interface field
// appearing in ForceSendFields will be sent to the server regardless of
// whether the field is empty or not. This may be used to include empty
// fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g.
// "TargetReceivedBytesPerSecond") to include in API requests with the
// JSON null value. By default, fields with empty values are omitted
// from API requests. However, any field with an empty value appearing
// in NullFields will be sent to the server as null. It is an error if a
// field in this list has a non-empty value. This may be used to include
// null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *NetworkUtilization) MarshalJSON() ([]byte, error) {
type NoMethod NetworkUtilization
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Operation: This resource represents a long-running operation that is
// the result of a network API call.
type Operation struct {
// Done: If the value is false, it means the operation is still in
// progress. If true, the operation is completed, and either error or
// response is available.
Done bool `json:"done,omitempty"`
// Error: The error result of the operation in case of failure or
// cancellation.
Error *Status `json:"error,omitempty"`
// Metadata: Service-specific metadata associated with the operation. It
// typically contains progress information and common metadata such as
// create time. Some services might not provide such metadata. Any
// method that returns a long-running operation should document the
// metadata type, if any.
Metadata googleapi.RawMessage `json:"metadata,omitempty"`
// Name: The server-assigned name, which is only unique within the same
// service that originally returns it. If you use the default HTTP
// mapping, the name should be a resource name ending with
// operations/{unique_id}.
Name string `json:"name,omitempty"`
// Response: The normal response of the operation in case of success. If
// the original method returns no data on success, such as Delete, the
// response is google.protobuf.Empty. If the original method is standard
// Get/Create/Update, the response should be the resource. For other
// methods, the response should have the type XxxResponse, where Xxx is
// the original method name. For example, if the original method name is
// TakeSnapshot(), the inferred response type is TakeSnapshotResponse.
Response googleapi.RawMessage `json:"response,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Done") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Done") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Operation) MarshalJSON() ([]byte, error) {
type NoMethod Operation
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// OperationMetadataV1: Metadata for the given
// google.longrunning.Operation.
type OperationMetadataV1 struct {
CreateVersionMetadata *CreateVersionMetadataV1 `json:"createVersionMetadata,omitempty"`
// EndTime: Time that this operation completed.@OutputOnly
EndTime string `json:"endTime,omitempty"`
// EphemeralMessage: Ephemeral message that may change every time the
// operation is polled. @OutputOnly
EphemeralMessage string `json:"ephemeralMessage,omitempty"`
// InsertTime: Time that this operation was created.@OutputOnly
InsertTime string `json:"insertTime,omitempty"`
// Method: API method that initiated this operation. Example:
// google.appengine.v1.Versions.CreateVersion.@OutputOnly
Method string `json:"method,omitempty"`
// Target: Name of the resource that this operation is acting on.
// Example: apps/myapp/services/default.@OutputOnly
Target string `json:"target,omitempty"`
// User: User who requested this operation.@OutputOnly
User string `json:"user,omitempty"`
// Warning: Durable messages that persist on every operation poll.
// @OutputOnly
Warning []string `json:"warning,omitempty"`
// ForceSendFields is a list of field names (e.g.
// "CreateVersionMetadata") to unconditionally include in API requests.
// By default, fields with empty or default values are omitted from API
// requests. However, any non-pointer, non-interface field appearing in
// ForceSendFields will be sent to the server regardless of whether the
// field is empty or not. This may be used to include empty fields in
// Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CreateVersionMetadata") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *OperationMetadataV1) MarshalJSON() ([]byte, error) {
type NoMethod OperationMetadataV1
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// OperationMetadataV1Alpha: Metadata for the given
// google.longrunning.Operation.
type OperationMetadataV1Alpha struct {
CreateVersionMetadata *CreateVersionMetadataV1Alpha `json:"createVersionMetadata,omitempty"`
// EndTime: Time that this operation completed.@OutputOnly
EndTime string `json:"endTime,omitempty"`
// EphemeralMessage: Ephemeral message that may change every time the
// operation is polled. @OutputOnly
EphemeralMessage string `json:"ephemeralMessage,omitempty"`
// InsertTime: Time that this operation was created.@OutputOnly
InsertTime string `json:"insertTime,omitempty"`
// Method: API method that initiated this operation. Example:
// google.appengine.v1alpha.Versions.CreateVersion.@OutputOnly
Method string `json:"method,omitempty"`
// Target: Name of the resource that this operation is acting on.
// Example: apps/myapp/services/default.@OutputOnly
Target string `json:"target,omitempty"`
// User: User who requested this operation.@OutputOnly
User string `json:"user,omitempty"`
// Warning: Durable messages that persist on every operation poll.
// @OutputOnly
Warning []string `json:"warning,omitempty"`
// ForceSendFields is a list of field names (e.g.
// "CreateVersionMetadata") to unconditionally include in API requests.
// By default, fields with empty or default values are omitted from API
// requests. However, any non-pointer, non-interface field appearing in
// ForceSendFields will be sent to the server regardless of whether the
// field is empty or not. This may be used to include empty fields in
// Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CreateVersionMetadata") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *OperationMetadataV1Alpha) MarshalJSON() ([]byte, error) {
type NoMethod OperationMetadataV1Alpha
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// OperationMetadataV1Beta: Metadata for the given
// google.longrunning.Operation.
type OperationMetadataV1Beta struct {
CreateVersionMetadata *CreateVersionMetadataV1Beta `json:"createVersionMetadata,omitempty"`
// EndTime: Time that this operation completed.@OutputOnly
EndTime string `json:"endTime,omitempty"`
// EphemeralMessage: Ephemeral message that may change every time the
// operation is polled. @OutputOnly
EphemeralMessage string `json:"ephemeralMessage,omitempty"`
// InsertTime: Time that this operation was created.@OutputOnly
InsertTime string `json:"insertTime,omitempty"`
// Method: API method that initiated this operation. Example:
// google.appengine.v1beta.Versions.CreateVersion.@OutputOnly
Method string `json:"method,omitempty"`
// Target: Name of the resource that this operation is acting on.
// Example: apps/myapp/services/default.@OutputOnly
Target string `json:"target,omitempty"`
// User: User who requested this operation.@OutputOnly
User string `json:"user,omitempty"`
// Warning: Durable messages that persist on every operation poll.
// @OutputOnly
Warning []string `json:"warning,omitempty"`
// ForceSendFields is a list of field names (e.g.
// "CreateVersionMetadata") to unconditionally include in API requests.
// By default, fields with empty or default values are omitted from API
// requests. However, any non-pointer, non-interface field appearing in
// ForceSendFields will be sent to the server regardless of whether the
// field is empty or not. This may be used to include empty fields in
// Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CreateVersionMetadata") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *OperationMetadataV1Beta) MarshalJSON() ([]byte, error) {
type NoMethod OperationMetadataV1Beta
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ReadinessCheck: Readiness checking configuration for VM instances.
// Unhealthy instances are removed from traffic rotation.
type ReadinessCheck struct {
// AppStartTimeout: A maximum time limit on application initialization,
// measured from moment the application successfully replies to a
// healthcheck until it is ready to serve traffic.
AppStartTimeout string `json:"appStartTimeout,omitempty"`
// CheckInterval: Interval between health checks.
CheckInterval string `json:"checkInterval,omitempty"`
// FailureThreshold: Number of consecutive failed checks required before
// removing traffic.
FailureThreshold int64 `json:"failureThreshold,omitempty"`
// Host: Host header to send when performing a HTTP Readiness check.
// Example: "myapp.appspot.com"
Host string `json:"host,omitempty"`
// Path: The request path.
Path string `json:"path,omitempty"`
// SuccessThreshold: Number of consecutive successful checks required
// before receiving traffic.
SuccessThreshold int64 `json:"successThreshold,omitempty"`
// Timeout: Time before the check is considered failed.
Timeout string `json:"timeout,omitempty"`
// ForceSendFields is a list of field names (e.g. "AppStartTimeout") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "AppStartTimeout") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *ReadinessCheck) MarshalJSON() ([]byte, error) {
type NoMethod ReadinessCheck
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// RepairApplicationRequest: Request message for
// 'Applications.RepairApplication'.
type RepairApplicationRequest struct {
}
// RequestUtilization: Target scaling by request utilization. Only
// applicable in the App Engine flexible environment.
type RequestUtilization struct {
// TargetConcurrentRequests: Target number of concurrent requests.
TargetConcurrentRequests int64 `json:"targetConcurrentRequests,omitempty"`
// TargetRequestCountPerSecond: Target requests per second.
TargetRequestCountPerSecond int64 `json:"targetRequestCountPerSecond,omitempty"`
// ForceSendFields is a list of field names (e.g.
// "TargetConcurrentRequests") to unconditionally include in API
// requests. By default, fields with empty or default values are omitted
// from API requests. However, any non-pointer, non-interface field
// appearing in ForceSendFields will be sent to the server regardless of
// whether the field is empty or not. This may be used to include empty
// fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "TargetConcurrentRequests")
// to include in API requests with the JSON null value. By default,
// fields with empty values are omitted from API requests. However, any
// field with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *RequestUtilization) MarshalJSON() ([]byte, error) {
type NoMethod RequestUtilization
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ResourceRecord: A DNS resource record.
type ResourceRecord struct {
// Name: Relative name of the object affected by this record. Only
// applicable for CNAME records. Example: 'www'.
Name string `json:"name,omitempty"`
// Rrdata: Data for this record. Values vary by record type, as defined
// in RFC 1035 (section 5) and RFC 1034 (section 3.6.1).
Rrdata string `json:"rrdata,omitempty"`
// Type: Resource record type. Example: AAAA.
//
// Possible values:
// "A" - An A resource record. Data is an IPv4 address.
// "AAAA" - An AAAA resource record. Data is an IPv6 address.
// "CNAME" - A CNAME resource record. Data is a domain name to be
// aliased.
Type string `json:"type,omitempty"`
// ForceSendFields is a list of field names (e.g. "Name") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Name") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ResourceRecord) MarshalJSON() ([]byte, error) {
type NoMethod ResourceRecord
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Resources: Machine resources for a version.
type Resources struct {
// Cpu: Number of CPU cores needed.
Cpu float64 `json:"cpu,omitempty"`
// DiskGb: Disk size (GB) needed.
DiskGb float64 `json:"diskGb,omitempty"`
// KmsKeyReference: The name of the encryption key that is stored in
// Google Cloud KMS. Only should be used by Cloud Composer to encrypt
// the vm disk
KmsKeyReference string `json:"kmsKeyReference,omitempty"`
// MemoryGb: Memory (GB) needed.
MemoryGb float64 `json:"memoryGb,omitempty"`
// Volumes: User specified volumes.
Volumes []*Volume `json:"volumes,omitempty"`
// ForceSendFields is a list of field names (e.g. "Cpu") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Cpu") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Resources) MarshalJSON() ([]byte, error) {
type NoMethod Resources
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *Resources) UnmarshalJSON(data []byte) error {
type NoMethod Resources
var s1 struct {
Cpu gensupport.JSONFloat64 `json:"cpu"`
DiskGb gensupport.JSONFloat64 `json:"diskGb"`
MemoryGb gensupport.JSONFloat64 `json:"memoryGb"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.Cpu = float64(s1.Cpu)
s.DiskGb = float64(s1.DiskGb)
s.MemoryGb = float64(s1.MemoryGb)
return nil
}
// ScriptHandler: Executes a script to handle the request that matches
// the URL pattern.
type ScriptHandler struct {
// ScriptPath: Path to the script from the application root directory.
ScriptPath string `json:"scriptPath,omitempty"`
// ForceSendFields is a list of field names (e.g. "ScriptPath") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ScriptPath") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ScriptHandler) MarshalJSON() ([]byte, error) {
type NoMethod ScriptHandler
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Service: A Service resource is a logical component of an application
// that can share state and communicate in a secure fashion with other
// services. For example, an application that handles customer requests
// might include separate services to handle tasks such as backend data
// analysis or API requests from mobile devices. Each service has a
// collection of versions that define a specific set of code used to
// implement the functionality of that service.
type Service struct {
// Id: Relative name of the service within the application. Example:
// default.@OutputOnly
Id string `json:"id,omitempty"`
// Labels: A set of labels to apply to this service. Labels are
// key/value pairs that describe the service and all resources that
// belong to it (e.g., versions). The labels can be used to search and
// group resources, and are propagated to the usage and billing reports,
// enabling fine-grain analysis of costs. An example of using labels is
// to tag resources belonging to different environments (e.g.,
// "env=prod", "env=qa"). Label keys and values can be no longer than 63
// characters and can only contain lowercase letters, numeric
// characters, underscores, dashes, and international characters. Label
// keys must start with a lowercase letter or an international
// character. Each service can have at most 32 labels.
Labels map[string]string `json:"labels,omitempty"`
// Name: Full path to the Service resource in the API. Example:
// apps/myapp/services/default.@OutputOnly
Name string `json:"name,omitempty"`
// NetworkSettings: Ingress settings for this service. Will apply to all
// versions.
NetworkSettings *NetworkSettings `json:"networkSettings,omitempty"`
// Split: Mapping that defines fractional HTTP traffic diversion to
// different versions within the service.
Split *TrafficSplit `json:"split,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "Id") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Id") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Service) MarshalJSON() ([]byte, error) {
type NoMethod Service
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// SslSettings: SSL configuration for a DomainMapping resource.
type SslSettings struct {
// CertificateId: ID of the AuthorizedCertificate resource configuring
// SSL for the application. Clearing this field will remove SSL
// support.By default, a managed certificate is automatically created
// for every domain mapping. To omit SSL support or to configure SSL
// manually, specify SslManagementType.MANUAL on a CREATE or UPDATE
// request. You must be authorized to administer the
// AuthorizedCertificate resource to manually map it to a DomainMapping
// resource. Example: 12345.
CertificateId string `json:"certificateId,omitempty"`
// PendingManagedCertificateId: ID of the managed AuthorizedCertificate
// resource currently being provisioned, if applicable. Until the new
// managed certificate has been successfully provisioned, the previous
// SSL state will be preserved. Once the provisioning process completes,
// the certificate_id field will reflect the new managed certificate and
// this field will be left empty. To remove SSL support while there is
// still a pending managed certificate, clear the certificate_id field
// with an UpdateDomainMappingRequest.@OutputOnly
PendingManagedCertificateId string `json:"pendingManagedCertificateId,omitempty"`
// SslManagementType: SSL management type for this domain. If AUTOMATIC,
// a managed certificate is automatically provisioned. If MANUAL,
// certificate_id must be manually specified in order to configure SSL
// for this domain.
//
// Possible values:
// "AUTOMATIC" - SSL support for this domain is configured
// automatically. The mapped SSL certificate will be automatically
// renewed.
// "MANUAL" - SSL support for this domain is configured manually by
// the user. Either the domain has no SSL support or a user-obtained SSL
// certificate has been explictly mapped to this domain.
SslManagementType string `json:"sslManagementType,omitempty"`
// ForceSendFields is a list of field names (e.g. "CertificateId") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "CertificateId") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *SslSettings) MarshalJSON() ([]byte, error) {
type NoMethod SslSettings
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// StandardSchedulerSettings: Scheduler settings for standard
// environment.
type StandardSchedulerSettings struct {
// MaxInstances: Maximum number of instances to run for this version.
// Set to zero to disable max_instances configuration.
MaxInstances int64 `json:"maxInstances,omitempty"`
// MinInstances: Minimum number of instances to run for this version.
// Set to zero to disable min_instances configuration.
MinInstances int64 `json:"minInstances,omitempty"`
// TargetCpuUtilization: Target CPU utilization ratio to maintain when
// scaling.
TargetCpuUtilization float64 `json:"targetCpuUtilization,omitempty"`
// TargetThroughputUtilization: Target throughput utilization ratio to
// maintain when scaling
TargetThroughputUtilization float64 `json:"targetThroughputUtilization,omitempty"`
// ForceSendFields is a list of field names (e.g. "MaxInstances") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "MaxInstances") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *StandardSchedulerSettings) MarshalJSON() ([]byte, error) {
type NoMethod StandardSchedulerSettings
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *StandardSchedulerSettings) UnmarshalJSON(data []byte) error {
type NoMethod StandardSchedulerSettings
var s1 struct {
TargetCpuUtilization gensupport.JSONFloat64 `json:"targetCpuUtilization"`
TargetThroughputUtilization gensupport.JSONFloat64 `json:"targetThroughputUtilization"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.TargetCpuUtilization = float64(s1.TargetCpuUtilization)
s.TargetThroughputUtilization = float64(s1.TargetThroughputUtilization)
return nil
}
// StaticFilesHandler: Files served directly to the user for a given
// URL, such as images, CSS stylesheets, or JavaScript source files.
// Static file handlers describe which files in the application
// directory are static files, and which URLs serve them.
type StaticFilesHandler struct {
// ApplicationReadable: Whether files should also be uploaded as code
// data. By default, files declared in static file handlers are uploaded
// as static data and are only served to end users; they cannot be read
// by the application. If enabled, uploads are charged against both your
// code and static data storage resource quotas.
ApplicationReadable bool `json:"applicationReadable,omitempty"`
// Expiration: Time a static file served by this handler should be
// cached by web proxies and browsers.
Expiration string `json:"expiration,omitempty"`
// HttpHeaders: HTTP headers to use for all responses from these URLs.
HttpHeaders map[string]string `json:"httpHeaders,omitempty"`
// MimeType: MIME type used to serve all files served by this
// handler.Defaults to file-specific MIME types, which are derived from
// each file's filename extension.
MimeType string `json:"mimeType,omitempty"`
// Path: Path to the static files matched by the URL pattern, from the
// application root directory. The path can refer to text matched in
// groupings in the URL pattern.
Path string `json:"path,omitempty"`
// RequireMatchingFile: Whether this handler should match the request if
// the file referenced by the handler does not exist.
RequireMatchingFile bool `json:"requireMatchingFile,omitempty"`
// UploadPathRegex: Regular expression that matches the file paths for
// all files that should be referenced by this handler.
UploadPathRegex string `json:"uploadPathRegex,omitempty"`
// ForceSendFields is a list of field names (e.g. "ApplicationReadable")
// to unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ApplicationReadable") to
// include in API requests with the JSON null value. By default, fields
// with empty values are omitted from API requests. However, any field
// with an empty value appearing in NullFields will be sent to the
// server as null. It is an error if a field in this list has a
// non-empty value. This may be used to include null fields in Patch
// requests.
NullFields []string `json:"-"`
}
func (s *StaticFilesHandler) MarshalJSON() ([]byte, error) {
type NoMethod StaticFilesHandler
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Status: The Status type defines a logical error model that is
// suitable for different programming environments, including REST APIs
// and RPC APIs. It is used by gRPC (https://github.com/grpc). Each
// Status message contains three pieces of data: error code, error
// message, and error details.You can find out more about this error
// model and how to work with it in the API Design Guide
// (https://cloud.google.com/apis/design/errors).
type Status struct {
// Code: The status code, which should be an enum value of
// google.rpc.Code.
Code int64 `json:"code,omitempty"`
// Details: A list of messages that carry the error details. There is a
// common set of message types for APIs to use.
Details []googleapi.RawMessage `json:"details,omitempty"`
// Message: A developer-facing error message, which should be in
// English. Any user-facing error message should be localized and sent
// in the google.rpc.Status.details field, or localized by the client.
Message string `json:"message,omitempty"`
// ForceSendFields is a list of field names (e.g. "Code") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Code") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Status) MarshalJSON() ([]byte, error) {
type NoMethod Status
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// TrafficSplit: Traffic routing configuration for versions within a
// single service. Traffic splits define how traffic directed to the
// service is assigned to versions.
type TrafficSplit struct {
// Allocations: Mapping from version IDs within the service to
// fractional (0.000, 1] allocations of traffic for that version. Each
// version can be specified only once, but some versions in the service
// may not have any traffic allocation. Services that have traffic
// allocated cannot be deleted until either the service is deleted or
// their traffic allocation is removed. Allocations must sum to 1. Up to
// two decimal place precision is supported for IP-based splits and up
// to three decimal places is supported for cookie-based splits.
Allocations map[string]float64 `json:"allocations,omitempty"`
// ShardBy: Mechanism used to determine which version a request is sent
// to. The traffic selection algorithm will be stable for either type
// until allocations are changed.
//
// Possible values:
// "UNSPECIFIED" - Diversion method unspecified.
// "COOKIE" - Diversion based on a specially named cookie,
// "GOOGAPPUID." The cookie must be set by the application itself or no
// diversion will occur.
// "IP" - Diversion based on applying the modulus operation to a
// fingerprint of the IP address.
// "RANDOM" - Diversion based on weighted random assignment. An
// incoming request is randomly routed to a version in the traffic
// split, with probability proportional to the version's traffic share.
ShardBy string `json:"shardBy,omitempty"`
// ForceSendFields is a list of field names (e.g. "Allocations") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Allocations") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *TrafficSplit) MarshalJSON() ([]byte, error) {
type NoMethod TrafficSplit
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// UrlDispatchRule: Rules to match an HTTP request and dispatch that
// request to a service.
type UrlDispatchRule struct {
// Domain: Domain name to match against. The wildcard "*" is supported
// if specified before a period: "*.".Defaults to matching all domains:
// "*".
Domain string `json:"domain,omitempty"`
// Path: Pathname within the host. Must start with a "/". A single "*"
// can be included at the end of the path.The sum of the lengths of the
// domain and path may not exceed 100 characters.
Path string `json:"path,omitempty"`
// Service: Resource ID of a service in this application that should
// serve the matched request. The service must already exist. Example:
// default.
Service string `json:"service,omitempty"`
// ForceSendFields is a list of field names (e.g. "Domain") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Domain") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *UrlDispatchRule) MarshalJSON() ([]byte, error) {
type NoMethod UrlDispatchRule
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// UrlMap: URL pattern and description of how the URL should be handled.
// App Engine can handle URLs by executing application code or by
// serving static files uploaded with the version, such as images, CSS,
// or JavaScript.
type UrlMap struct {
// ApiEndpoint: Uses API Endpoints to handle requests.
ApiEndpoint *ApiEndpointHandler `json:"apiEndpoint,omitempty"`
// AuthFailAction: Action to take when users access resources that
// require authentication. Defaults to redirect.
//
// Possible values:
// "AUTH_FAIL_ACTION_UNSPECIFIED" - Not specified.
// AUTH_FAIL_ACTION_REDIRECT is assumed.
// "AUTH_FAIL_ACTION_REDIRECT" - Redirects user to
// "accounts.google.com". The user is redirected back to the application
// URL after signing in or creating an account.
// "AUTH_FAIL_ACTION_UNAUTHORIZED" - Rejects request with a 401 HTTP
// status code and an error message.
AuthFailAction string `json:"authFailAction,omitempty"`
// Login: Level of login required to access this resource. Not supported
// for Node.js in the App Engine standard environment.
//
// Possible values:
// "LOGIN_UNSPECIFIED" - Not specified. LOGIN_OPTIONAL is assumed.
// "LOGIN_OPTIONAL" - Does not require that the user is signed in.
// "LOGIN_ADMIN" - If the user is not signed in, the auth_fail_action
// is taken. In addition, if the user is not an administrator for the
// application, they are given an error message regardless of
// auth_fail_action. If the user is an administrator, the handler
// proceeds.
// "LOGIN_REQUIRED" - If the user has signed in, the handler proceeds
// normally. Otherwise, the auth_fail_action is taken.
Login string `json:"login,omitempty"`
// RedirectHttpResponseCode: 30x code to use when performing redirects
// for the secure field. Defaults to 302.
//
// Possible values:
// "REDIRECT_HTTP_RESPONSE_CODE_UNSPECIFIED" - Not specified. 302 is
// assumed.
// "REDIRECT_HTTP_RESPONSE_CODE_301" - 301 Moved Permanently code.
// "REDIRECT_HTTP_RESPONSE_CODE_302" - 302 Moved Temporarily code.
// "REDIRECT_HTTP_RESPONSE_CODE_303" - 303 See Other code.
// "REDIRECT_HTTP_RESPONSE_CODE_307" - 307 Temporary Redirect code.
RedirectHttpResponseCode string `json:"redirectHttpResponseCode,omitempty"`
// Script: Executes a script to handle the requests that match this URL
// pattern. Only the auto value is supported for Node.js in the App
// Engine standard environment, for example "script": "auto".
Script *ScriptHandler `json:"script,omitempty"`
// SecurityLevel: Security (HTTPS) enforcement for this URL.
//
// Possible values:
// "SECURE_UNSPECIFIED" - Not specified.
// "SECURE_DEFAULT" - Both HTTP and HTTPS requests with URLs that
// match the handler succeed without redirects. The application can
// examine the request to determine which protocol was used, and respond
// accordingly.
// "SECURE_NEVER" - Requests for a URL that match this handler that
// use HTTPS are automatically redirected to the HTTP equivalent URL.
// "SECURE_OPTIONAL" - Both HTTP and HTTPS requests with URLs that
// match the handler succeed without redirects. The application can
// examine the request to determine which protocol was used and respond
// accordingly.
// "SECURE_ALWAYS" - Requests for a URL that match this handler that
// do not use HTTPS are automatically redirected to the HTTPS URL with
// the same path. Query parameters are reserved for the redirect.
SecurityLevel string `json:"securityLevel,omitempty"`
// StaticFiles: Returns the contents of a file, such as an image, as the
// response.
StaticFiles *StaticFilesHandler `json:"staticFiles,omitempty"`
// UrlRegex: URL prefix. Uses regular expression syntax, which means
// regexp special characters must be escaped, but should not contain
// groupings. All URLs that begin with this prefix are handled by this
// handler, using the portion of the URL after the prefix as part of the
// file path.
UrlRegex string `json:"urlRegex,omitempty"`
// ForceSendFields is a list of field names (e.g. "ApiEndpoint") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ApiEndpoint") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *UrlMap) MarshalJSON() ([]byte, error) {
type NoMethod UrlMap
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Version: A Version resource is a specific set of source code and
// configuration files that are deployed into a service.
type Version struct {
// ApiConfig: Serving configuration for Google Cloud Endpoints
// (https://cloud.google.com/appengine/docs/python/endpoints/).Only
// returned in GET requests if view=FULL is set.
ApiConfig *ApiConfigHandler `json:"apiConfig,omitempty"`
// AppEngineApis: app_engine_apis allows second generation runtimes to
// access the App Engine APIs.
AppEngineApis bool `json:"appEngineApis,omitempty"`
// AutomaticScaling: Automatic scaling is based on request rate,
// response latencies, and other application metrics. Instances are
// dynamically created and destroyed as needed in order to handle
// traffic.
AutomaticScaling *AutomaticScaling `json:"automaticScaling,omitempty"`
// BasicScaling: A service with basic scaling will create an instance
// when the application receives a request. The instance will be turned
// down when the app becomes idle. Basic scaling is ideal for work that
// is intermittent or driven by user activity.
BasicScaling *BasicScaling `json:"basicScaling,omitempty"`
// BetaSettings: Metadata settings that are supplied to this version to
// enable beta runtime features.
BetaSettings map[string]string `json:"betaSettings,omitempty"`
// BuildEnvVariables: Environment variables available to the build
// environment.Only returned in GET requests if view=FULL is set.
BuildEnvVariables map[string]string `json:"buildEnvVariables,omitempty"`
// CreateTime: Time that this version was created.@OutputOnly
CreateTime string `json:"createTime,omitempty"`
// CreatedBy: Email address of the user who created this
// version.@OutputOnly
CreatedBy string `json:"createdBy,omitempty"`
// DefaultExpiration: Duration that static files should be cached by web
// proxies and browsers. Only applicable if the corresponding
// StaticFilesHandler
// (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#StaticFilesHandler)
// does not specify its own expiration time.Only returned in GET
// requests if view=FULL is set.
DefaultExpiration string `json:"defaultExpiration,omitempty"`
// Deployment: Code and application artifacts that make up this
// version.Only returned in GET requests if view=FULL is set.
Deployment *Deployment `json:"deployment,omitempty"`
// DiskUsageBytes: Total size in bytes of all the files that are
// included in this version and currently hosted on the App Engine
// disk.@OutputOnly
DiskUsageBytes int64 `json:"diskUsageBytes,omitempty,string"`
// EndpointsApiService: Cloud Endpoints configuration.If
// endpoints_api_service is set, the Cloud Endpoints Extensible Service
// Proxy will be provided to serve the API implemented by the app.
EndpointsApiService *EndpointsApiService `json:"endpointsApiService,omitempty"`
// Entrypoint: The entrypoint for the application.
Entrypoint *Entrypoint `json:"entrypoint,omitempty"`
// Env: App Engine execution environment for this version.Defaults to
// standard.
Env string `json:"env,omitempty"`
// EnvVariables: Environment variables available to the application.Only
// returned in GET requests if view=FULL is set.
EnvVariables map[string]string `json:"envVariables,omitempty"`
// ErrorHandlers: Custom static error pages. Limited to 10KB per
// page.Only returned in GET requests if view=FULL is set.
ErrorHandlers []*ErrorHandler `json:"errorHandlers,omitempty"`
// Handlers: An ordered list of URL-matching patterns that should be
// applied to incoming requests. The first matching URL handles the
// request and other request handlers are not attempted.Only returned in
// GET requests if view=FULL is set.
Handlers []*UrlMap `json:"handlers,omitempty"`
// HealthCheck: Configures health checking for instances. Unhealthy
// instances are stopped and replaced with new instances. Only
// applicable in the App Engine flexible environment.Only returned in
// GET requests if view=FULL is set.
HealthCheck *HealthCheck `json:"healthCheck,omitempty"`
// Id: Relative name of the version within the service. Example: v1.
// Version names can contain only lowercase letters, numbers, or
// hyphens. Reserved names: "default", "latest", and any name with the
// prefix "ah-".
Id string `json:"id,omitempty"`
// InboundServices: Before an application can receive email or XMPP
// messages, the application must be configured to enable the service.
//
// Possible values:
// "INBOUND_SERVICE_UNSPECIFIED" - Not specified.
// "INBOUND_SERVICE_MAIL" - Allows an application to receive mail.
// "INBOUND_SERVICE_MAIL_BOUNCE" - Allows an application to receive
// email-bound notifications.
// "INBOUND_SERVICE_XMPP_ERROR" - Allows an application to receive
// error stanzas.
// "INBOUND_SERVICE_XMPP_MESSAGE" - Allows an application to receive
// instant messages.
// "INBOUND_SERVICE_XMPP_SUBSCRIBE" - Allows an application to receive
// user subscription POSTs.
// "INBOUND_SERVICE_XMPP_PRESENCE" - Allows an application to receive
// a user's chat presence.
// "INBOUND_SERVICE_CHANNEL_PRESENCE" - Registers an application for
// notifications when a client connects or disconnects from a channel.
// "INBOUND_SERVICE_WARMUP" - Enables warmup requests.
InboundServices []string `json:"inboundServices,omitempty"`
// InstanceClass: Instance class that is used to run this version. Valid
// values are: AutomaticScaling: F1, F2, F4, F4_1G ManualScaling or
// BasicScaling: B1, B2, B4, B8, B4_1GDefaults to F1 for
// AutomaticScaling and B1 for ManualScaling or BasicScaling.
InstanceClass string `json:"instanceClass,omitempty"`
// Libraries: Configuration for third-party Python runtime libraries
// that are required by the application.Only returned in GET requests if
// view=FULL is set.
Libraries []*Library `json:"libraries,omitempty"`
// LivenessCheck: Configures liveness health checking for instances.
// Unhealthy instances are stopped and replaced with new instancesOnly
// returned in GET requests if view=FULL is set.
LivenessCheck *LivenessCheck `json:"livenessCheck,omitempty"`
// ManualScaling: A service with manual scaling runs continuously,
// allowing you to perform complex initialization and rely on the state
// of its memory over time. Manually scaled versions are sometimes
// referred to as "backends".
ManualScaling *ManualScaling `json:"manualScaling,omitempty"`
// Name: Full path to the Version resource in the API. Example:
// apps/myapp/services/default/versions/v1.@OutputOnly
Name string `json:"name,omitempty"`
// Network: Extra network settings. Only applicable in the App Engine
// flexible environment.
Network *Network `json:"network,omitempty"`
// NobuildFilesRegex: Files that match this pattern will not be built
// into this version. Only applicable for Go runtimes.Only returned in
// GET requests if view=FULL is set.
NobuildFilesRegex string `json:"nobuildFilesRegex,omitempty"`
// ReadinessCheck: Configures readiness health checking for instances.
// Unhealthy instances are not put into the backend traffic
// rotation.Only returned in GET requests if view=FULL is set.
ReadinessCheck *ReadinessCheck `json:"readinessCheck,omitempty"`
// Resources: Machine resources for this version. Only applicable in the
// App Engine flexible environment.
Resources *Resources `json:"resources,omitempty"`
// Runtime: Desired runtime. Example: python27.
Runtime string `json:"runtime,omitempty"`
// RuntimeApiVersion: The version of the API in the given runtime
// environment. Please see the app.yaml reference for valid values at
// https://cloud.google.com/appengine/docs/standard//config/appref
RuntimeApiVersion string `json:"runtimeApiVersion,omitempty"`
// RuntimeChannel: The channel of the runtime to use. Only available for
// some runtimes. Defaults to the default channel.
RuntimeChannel string `json:"runtimeChannel,omitempty"`
// RuntimeMainExecutablePath: The path or name of the app's main
// executable.
RuntimeMainExecutablePath string `json:"runtimeMainExecutablePath,omitempty"`
// ServiceAccount: The identity that the deployed version will run as.
// Admin API will use the App Engine Appspot service account as default
// if this field is neither provided in app.yaml file nor through CLI
// flag.
ServiceAccount string `json:"serviceAccount,omitempty"`
// ServingStatus: Current serving status of this version. Only the
// versions with a SERVING status create instances and can be
// billed.SERVING_STATUS_UNSPECIFIED is an invalid value. Defaults to
// SERVING.
//
// Possible values:
// "SERVING_STATUS_UNSPECIFIED" - Not specified.
// "SERVING" - Currently serving. Instances are created according to
// the scaling settings of the version.
// "STOPPED" - Disabled. No instances will be created and the scaling
// settings are ignored until the state of the version changes to
// SERVING.
ServingStatus string `json:"servingStatus,omitempty"`
// Threadsafe: Whether multiple requests can be dispatched to this
// version at once.
Threadsafe bool `json:"threadsafe,omitempty"`
// VersionUrl: Serving URL for this version. Example:
// "https://myversion-dot-myservice-dot-myapp.appspot.com"@OutputOnly
VersionUrl string `json:"versionUrl,omitempty"`
// Vm: Whether to deploy this version in a container on a virtual
// machine.
Vm bool `json:"vm,omitempty"`
// VpcAccessConnector: Enables VPC connectivity for standard apps.
VpcAccessConnector *VpcAccessConnector `json:"vpcAccessConnector,omitempty"`
// Zones: The Google Compute Engine zones that are supported by this
// version in the App Engine flexible environment. Deprecated.
Zones []string `json:"zones,omitempty"`
// ServerResponse contains the HTTP response code and headers from the
// server.
googleapi.ServerResponse `json:"-"`
// ForceSendFields is a list of field names (e.g. "ApiConfig") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "ApiConfig") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Version) MarshalJSON() ([]byte, error) {
type NoMethod Version
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// Volume: Volumes mounted within the app container. Only applicable in
// the App Engine flexible environment.
type Volume struct {
// Name: Unique name for the volume.
Name string `json:"name,omitempty"`
// SizeGb: Volume size in gigabytes.
SizeGb float64 `json:"sizeGb,omitempty"`
// VolumeType: Underlying volume type, e.g. 'tmpfs'.
VolumeType string `json:"volumeType,omitempty"`
// ForceSendFields is a list of field names (e.g. "Name") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "Name") to include in API
// requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *Volume) MarshalJSON() ([]byte, error) {
type NoMethod Volume
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
func (s *Volume) UnmarshalJSON(data []byte) error {
type NoMethod Volume
var s1 struct {
SizeGb gensupport.JSONFloat64 `json:"sizeGb"`
*NoMethod
}
s1.NoMethod = (*NoMethod)(s)
if err := json.Unmarshal(data, &s1); err != nil {
return err
}
s.SizeGb = float64(s1.SizeGb)
return nil
}
// VpcAccessConnector: VPC access connector specification.
type VpcAccessConnector struct {
// EgressSetting: The egress setting for the connector, controlling what
// traffic is diverted through it.
//
// Possible values:
// "EGRESS_SETTING_UNSPECIFIED"
// "ALL_TRAFFIC" - Force the use of VPC Access for all egress traffic
// from the function.
// "PRIVATE_IP_RANGES" - Use the VPC Access Connector for private IP
// space from RFC1918.
EgressSetting string `json:"egressSetting,omitempty"`
// Name: Full Serverless VPC Access Connector name e.g.
// /projects/my-project/locations/us-central1/connectors/c1.
Name string `json:"name,omitempty"`
// ForceSendFields is a list of field names (e.g. "EgressSetting") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "EgressSetting") to include
// in API requests with the JSON null value. By default, fields with
// empty values are omitted from API requests. However, any field with
// an empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *VpcAccessConnector) MarshalJSON() ([]byte, error) {
type NoMethod VpcAccessConnector
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// ZipInfo: The zip file information for a zip deployment.
type ZipInfo struct {
// FilesCount: An estimate of the number of files in a zip for a zip
// deployment. If set, must be greater than or equal to the actual
// number of files. Used for optimizing performance; if not provided,
// deployment may be slow.
FilesCount int64 `json:"filesCount,omitempty"`
// SourceUrl: URL of the zip file to deploy from. Must be a URL to a
// resource in Google Cloud Storage in the form
// 'http(s)://storage.googleapis.com//'.
SourceUrl string `json:"sourceUrl,omitempty"`
// ForceSendFields is a list of field names (e.g. "FilesCount") to
// unconditionally include in API requests. By default, fields with
// empty or default values are omitted from API requests. However, any
// non-pointer, non-interface field appearing in ForceSendFields will be
// sent to the server regardless of whether the field is empty or not.
// This may be used to include empty fields in Patch requests.
ForceSendFields []string `json:"-"`
// NullFields is a list of field names (e.g. "FilesCount") to include in
// API requests with the JSON null value. By default, fields with empty
// values are omitted from API requests. However, any field with an
// empty value appearing in NullFields will be sent to the server as
// null. It is an error if a field in this list has a non-empty value.
// This may be used to include null fields in Patch requests.
NullFields []string `json:"-"`
}
func (s *ZipInfo) MarshalJSON() ([]byte, error) {
type NoMethod ZipInfo
raw := NoMethod(*s)
return gensupport.MarshalJSON(raw, s.ForceSendFields, s.NullFields)
}
// method id "appengine.apps.create":
type AppsCreateCall struct {
s *APIService
application *Application
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Create: Creates an App Engine application for a Google Cloud Platform
// project. Required fields: id - The ID of the target Cloud Platform
// project. location - The region
// (https://cloud.google.com/appengine/docs/locations) where you want
// the App Engine application located.For more information about App
// Engine applications, see Managing Projects, Applications, and Billing
// (https://cloud.google.com/appengine/docs/standard/python/console/).
func (r *AppsService) Create(application *Application) *AppsCreateCall {
c := &AppsCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.application = application
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsCreateCall) Fields(s ...googleapi.Field) *AppsCreateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsCreateCall) Context(ctx context.Context) *AppsCreateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsCreateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsCreateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.application)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.create" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *AppsCreateCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Creates an App Engine application for a Google Cloud Platform project. Required fields: id - The ID of the target Cloud Platform project. location - The region (https://cloud.google.com/appengine/docs/locations) where you want the App Engine application located.For more information about App Engine applications, see Managing Projects, Applications, and Billing (https://cloud.google.com/appengine/docs/standard/python/console/).",
// "flatPath": "v1beta/apps",
// "httpMethod": "POST",
// "id": "appengine.apps.create",
// "parameterOrder": [],
// "parameters": {},
// "path": "v1beta/apps",
// "request": {
// "$ref": "Application"
// },
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "appengine.apps.get":
type AppsGetCall struct {
s *APIService
appsId string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Gets information about an application.
//
// - appsId: Part of `name`. Name of the Application resource to get.
// Example: apps/myapp.
func (r *AppsService) Get(appsId string) *AppsGetCall {
c := &AppsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsGetCall) Fields(s ...googleapi.Field) *AppsGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *AppsGetCall) IfNoneMatch(entityTag string) *AppsGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsGetCall) Context(ctx context.Context) *AppsGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.get" call.
// Exactly one of *Application or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Application.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *AppsGetCall) Do(opts ...googleapi.CallOption) (*Application, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Application{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets information about an application.",
// "flatPath": "v1beta/apps/{appsId}",
// "httpMethod": "GET",
// "id": "appengine.apps.get",
// "parameterOrder": [
// "appsId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `name`. Name of the Application resource to get. Example: apps/myapp.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}",
// "response": {
// "$ref": "Application"
// },
// "scopes": [
// "https://www.googleapis.com/auth/appengine.admin",
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only"
// ]
// }
}
// method id "appengine.apps.patch":
type AppsPatchCall struct {
s *APIService
appsId string
application *Application
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Patch: Updates the specified Application resource. You can update the
// following fields: auth_domain - Google authentication domain for
// controlling user access to the application. default_cookie_expiration
// - Cookie expiration policy for the application. iap - Identity-Aware
// Proxy properties for the application.
//
// - appsId: Part of `name`. Name of the Application resource to update.
// Example: apps/myapp.
func (r *AppsService) Patch(appsId string, application *Application) *AppsPatchCall {
c := &AppsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
c.application = application
return c
}
// UpdateMask sets the optional parameter "updateMask": Required.
// Standard field mask for the set of fields to be updated.
func (c *AppsPatchCall) UpdateMask(updateMask string) *AppsPatchCall {
c.urlParams_.Set("updateMask", updateMask)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsPatchCall) Fields(s ...googleapi.Field) *AppsPatchCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsPatchCall) Context(ctx context.Context) *AppsPatchCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsPatchCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsPatchCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.application)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("PATCH", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.patch" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *AppsPatchCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates the specified Application resource. You can update the following fields: auth_domain - Google authentication domain for controlling user access to the application. default_cookie_expiration - Cookie expiration policy for the application. iap - Identity-Aware Proxy properties for the application.",
// "flatPath": "v1beta/apps/{appsId}",
// "httpMethod": "PATCH",
// "id": "appengine.apps.patch",
// "parameterOrder": [
// "appsId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `name`. Name of the Application resource to update. Example: apps/myapp.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "updateMask": {
// "description": "Required. Standard field mask for the set of fields to be updated.",
// "format": "google-fieldmask",
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}",
// "request": {
// "$ref": "Application"
// },
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "appengine.apps.repair":
type AppsRepairCall struct {
s *APIService
appsId string
repairapplicationrequest *RepairApplicationRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Repair: Recreates the required App Engine features for the specified
// App Engine application, for example a Cloud Storage bucket or App
// Engine service account. Use this method if you receive an error
// message about a missing feature, for example, Error retrieving the
// App Engine service account. If you have deleted your App Engine
// service account, this will not be able to recreate it. Instead, you
// should attempt to use the IAM undelete API if possible at
// https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/undelete?apix_params=%7B"name"%3A"projects%2F-%2FserviceAccounts%2Funique_id"%2C"resource"%3A%7B%7D%7D
// . If the deletion was recent, the numeric ID can be found in the
// Cloud Console Activity Log.
//
// - appsId: Part of `name`. Name of the application to repair. Example:
// apps/myapp.
func (r *AppsService) Repair(appsId string, repairapplicationrequest *RepairApplicationRequest) *AppsRepairCall {
c := &AppsRepairCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
c.repairapplicationrequest = repairapplicationrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsRepairCall) Fields(s ...googleapi.Field) *AppsRepairCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsRepairCall) Context(ctx context.Context) *AppsRepairCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsRepairCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsRepairCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.repairapplicationrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}:repair")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.repair" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *AppsRepairCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Recreates the required App Engine features for the specified App Engine application, for example a Cloud Storage bucket or App Engine service account. Use this method if you receive an error message about a missing feature, for example, Error retrieving the App Engine service account. If you have deleted your App Engine service account, this will not be able to recreate it. Instead, you should attempt to use the IAM undelete API if possible at https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/undelete?apix_params=%7B\"name\"%3A\"projects%2F-%2FserviceAccounts%2Funique_id\"%2C\"resource\"%3A%7B%7D%7D . If the deletion was recent, the numeric ID can be found in the Cloud Console Activity Log.",
// "flatPath": "v1beta/apps/{appsId}:repair",
// "httpMethod": "POST",
// "id": "appengine.apps.repair",
// "parameterOrder": [
// "appsId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `name`. Name of the application to repair. Example: apps/myapp",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}:repair",
// "request": {
// "$ref": "RepairApplicationRequest"
// },
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "appengine.apps.authorizedCertificates.create":
type AppsAuthorizedCertificatesCreateCall struct {
s *APIService
appsId string
authorizedcertificate *AuthorizedCertificate
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Create: Uploads the specified SSL certificate.
//
// - appsId: Part of `parent`. Name of the parent Application resource.
// Example: apps/myapp.
func (r *AppsAuthorizedCertificatesService) Create(appsId string, authorizedcertificate *AuthorizedCertificate) *AppsAuthorizedCertificatesCreateCall {
c := &AppsAuthorizedCertificatesCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
c.authorizedcertificate = authorizedcertificate
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsAuthorizedCertificatesCreateCall) Fields(s ...googleapi.Field) *AppsAuthorizedCertificatesCreateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsAuthorizedCertificatesCreateCall) Context(ctx context.Context) *AppsAuthorizedCertificatesCreateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsAuthorizedCertificatesCreateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsAuthorizedCertificatesCreateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.authorizedcertificate)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}/authorizedCertificates")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.authorizedCertificates.create" call.
// Exactly one of *AuthorizedCertificate or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *AuthorizedCertificate.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *AppsAuthorizedCertificatesCreateCall) Do(opts ...googleapi.CallOption) (*AuthorizedCertificate, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &AuthorizedCertificate{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Uploads the specified SSL certificate.",
// "flatPath": "v1beta/apps/{appsId}/authorizedCertificates",
// "httpMethod": "POST",
// "id": "appengine.apps.authorizedCertificates.create",
// "parameterOrder": [
// "appsId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `parent`. Name of the parent Application resource. Example: apps/myapp.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}/authorizedCertificates",
// "request": {
// "$ref": "AuthorizedCertificate"
// },
// "response": {
// "$ref": "AuthorizedCertificate"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "appengine.apps.authorizedCertificates.delete":
type AppsAuthorizedCertificatesDeleteCall struct {
s *APIService
appsId string
authorizedCertificatesId string
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Deletes the specified SSL certificate.
//
// - appsId: Part of `name`. Name of the resource to delete. Example:
// apps/myapp/authorizedCertificates/12345.
// - authorizedCertificatesId: Part of `name`. See documentation of
// `appsId`.
func (r *AppsAuthorizedCertificatesService) Delete(appsId string, authorizedCertificatesId string) *AppsAuthorizedCertificatesDeleteCall {
c := &AppsAuthorizedCertificatesDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
c.authorizedCertificatesId = authorizedCertificatesId
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsAuthorizedCertificatesDeleteCall) Fields(s ...googleapi.Field) *AppsAuthorizedCertificatesDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsAuthorizedCertificatesDeleteCall) Context(ctx context.Context) *AppsAuthorizedCertificatesDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsAuthorizedCertificatesDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsAuthorizedCertificatesDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}/authorizedCertificates/{authorizedCertificatesId}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("DELETE", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
"authorizedCertificatesId": c.authorizedCertificatesId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.authorizedCertificates.delete" call.
// Exactly one of *Empty or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Empty.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *AppsAuthorizedCertificatesDeleteCall) Do(opts ...googleapi.CallOption) (*Empty, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Empty{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Deletes the specified SSL certificate.",
// "flatPath": "v1beta/apps/{appsId}/authorizedCertificates/{authorizedCertificatesId}",
// "httpMethod": "DELETE",
// "id": "appengine.apps.authorizedCertificates.delete",
// "parameterOrder": [
// "appsId",
// "authorizedCertificatesId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `name`. Name of the resource to delete. Example: apps/myapp/authorizedCertificates/12345.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "authorizedCertificatesId": {
// "description": "Part of `name`. See documentation of `appsId`.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}/authorizedCertificates/{authorizedCertificatesId}",
// "response": {
// "$ref": "Empty"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "appengine.apps.authorizedCertificates.get":
type AppsAuthorizedCertificatesGetCall struct {
s *APIService
appsId string
authorizedCertificatesId string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Gets the specified SSL certificate.
//
// - appsId: Part of `name`. Name of the resource requested. Example:
// apps/myapp/authorizedCertificates/12345.
// - authorizedCertificatesId: Part of `name`. See documentation of
// `appsId`.
func (r *AppsAuthorizedCertificatesService) Get(appsId string, authorizedCertificatesId string) *AppsAuthorizedCertificatesGetCall {
c := &AppsAuthorizedCertificatesGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
c.authorizedCertificatesId = authorizedCertificatesId
return c
}
// View sets the optional parameter "view": Controls the set of fields
// returned in the GET response.
//
// Possible values:
// "BASIC_CERTIFICATE" - Basic certificate information, including
// applicable domains and expiration date.
// "FULL_CERTIFICATE" - The information from BASIC_CERTIFICATE, plus
// detailed information on the domain mappings that have this
// certificate mapped.
func (c *AppsAuthorizedCertificatesGetCall) View(view string) *AppsAuthorizedCertificatesGetCall {
c.urlParams_.Set("view", view)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsAuthorizedCertificatesGetCall) Fields(s ...googleapi.Field) *AppsAuthorizedCertificatesGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *AppsAuthorizedCertificatesGetCall) IfNoneMatch(entityTag string) *AppsAuthorizedCertificatesGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsAuthorizedCertificatesGetCall) Context(ctx context.Context) *AppsAuthorizedCertificatesGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsAuthorizedCertificatesGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsAuthorizedCertificatesGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}/authorizedCertificates/{authorizedCertificatesId}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
"authorizedCertificatesId": c.authorizedCertificatesId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.authorizedCertificates.get" call.
// Exactly one of *AuthorizedCertificate or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *AuthorizedCertificate.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *AppsAuthorizedCertificatesGetCall) Do(opts ...googleapi.CallOption) (*AuthorizedCertificate, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &AuthorizedCertificate{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets the specified SSL certificate.",
// "flatPath": "v1beta/apps/{appsId}/authorizedCertificates/{authorizedCertificatesId}",
// "httpMethod": "GET",
// "id": "appengine.apps.authorizedCertificates.get",
// "parameterOrder": [
// "appsId",
// "authorizedCertificatesId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `name`. Name of the resource requested. Example: apps/myapp/authorizedCertificates/12345.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "authorizedCertificatesId": {
// "description": "Part of `name`. See documentation of `appsId`.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "view": {
// "description": "Controls the set of fields returned in the GET response.",
// "enum": [
// "BASIC_CERTIFICATE",
// "FULL_CERTIFICATE"
// ],
// "enumDescriptions": [
// "Basic certificate information, including applicable domains and expiration date.",
// "The information from BASIC_CERTIFICATE, plus detailed information on the domain mappings that have this certificate mapped."
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}/authorizedCertificates/{authorizedCertificatesId}",
// "response": {
// "$ref": "AuthorizedCertificate"
// },
// "scopes": [
// "https://www.googleapis.com/auth/appengine.admin",
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only"
// ]
// }
}
// method id "appengine.apps.authorizedCertificates.list":
type AppsAuthorizedCertificatesListCall struct {
s *APIService
appsId string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Lists all SSL certificates the user is authorized to
// administer.
//
// - appsId: Part of `parent`. Name of the parent Application resource.
// Example: apps/myapp.
func (r *AppsAuthorizedCertificatesService) List(appsId string) *AppsAuthorizedCertificatesListCall {
c := &AppsAuthorizedCertificatesListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
return c
}
// PageSize sets the optional parameter "pageSize": Maximum results to
// return per page.
func (c *AppsAuthorizedCertificatesListCall) PageSize(pageSize int64) *AppsAuthorizedCertificatesListCall {
c.urlParams_.Set("pageSize", fmt.Sprint(pageSize))
return c
}
// PageToken sets the optional parameter "pageToken": Continuation token
// for fetching the next page of results.
func (c *AppsAuthorizedCertificatesListCall) PageToken(pageToken string) *AppsAuthorizedCertificatesListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// View sets the optional parameter "view": Controls the set of fields
// returned in the LIST response.
//
// Possible values:
// "BASIC_CERTIFICATE" - Basic certificate information, including
// applicable domains and expiration date.
// "FULL_CERTIFICATE" - The information from BASIC_CERTIFICATE, plus
// detailed information on the domain mappings that have this
// certificate mapped.
func (c *AppsAuthorizedCertificatesListCall) View(view string) *AppsAuthorizedCertificatesListCall {
c.urlParams_.Set("view", view)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsAuthorizedCertificatesListCall) Fields(s ...googleapi.Field) *AppsAuthorizedCertificatesListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *AppsAuthorizedCertificatesListCall) IfNoneMatch(entityTag string) *AppsAuthorizedCertificatesListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsAuthorizedCertificatesListCall) Context(ctx context.Context) *AppsAuthorizedCertificatesListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsAuthorizedCertificatesListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsAuthorizedCertificatesListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}/authorizedCertificates")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.authorizedCertificates.list" call.
// Exactly one of *ListAuthorizedCertificatesResponse or error will be
// non-nil. Any non-2xx status code is an error. Response headers are in
// either *ListAuthorizedCertificatesResponse.ServerResponse.Header or
// (if a response was returned at all) in
// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check
// whether the returned error was because http.StatusNotModified was
// returned.
func (c *AppsAuthorizedCertificatesListCall) Do(opts ...googleapi.CallOption) (*ListAuthorizedCertificatesResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ListAuthorizedCertificatesResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Lists all SSL certificates the user is authorized to administer.",
// "flatPath": "v1beta/apps/{appsId}/authorizedCertificates",
// "httpMethod": "GET",
// "id": "appengine.apps.authorizedCertificates.list",
// "parameterOrder": [
// "appsId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `parent`. Name of the parent Application resource. Example: apps/myapp.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "pageSize": {
// "description": "Maximum results to return per page.",
// "format": "int32",
// "location": "query",
// "type": "integer"
// },
// "pageToken": {
// "description": "Continuation token for fetching the next page of results.",
// "location": "query",
// "type": "string"
// },
// "view": {
// "description": "Controls the set of fields returned in the LIST response.",
// "enum": [
// "BASIC_CERTIFICATE",
// "FULL_CERTIFICATE"
// ],
// "enumDescriptions": [
// "Basic certificate information, including applicable domains and expiration date.",
// "The information from BASIC_CERTIFICATE, plus detailed information on the domain mappings that have this certificate mapped."
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}/authorizedCertificates",
// "response": {
// "$ref": "ListAuthorizedCertificatesResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/appengine.admin",
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *AppsAuthorizedCertificatesListCall) Pages(ctx context.Context, f func(*ListAuthorizedCertificatesResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "appengine.apps.authorizedCertificates.patch":
type AppsAuthorizedCertificatesPatchCall struct {
s *APIService
appsId string
authorizedCertificatesId string
authorizedcertificate *AuthorizedCertificate
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Patch: Updates the specified SSL certificate. To renew a certificate
// and maintain its existing domain mappings, update certificate_data
// with a new certificate. The new certificate must be applicable to the
// same domains as the original certificate. The certificate
// display_name may also be updated.
//
// - appsId: Part of `name`. Name of the resource to update. Example:
// apps/myapp/authorizedCertificates/12345.
// - authorizedCertificatesId: Part of `name`. See documentation of
// `appsId`.
func (r *AppsAuthorizedCertificatesService) Patch(appsId string, authorizedCertificatesId string, authorizedcertificate *AuthorizedCertificate) *AppsAuthorizedCertificatesPatchCall {
c := &AppsAuthorizedCertificatesPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
c.authorizedCertificatesId = authorizedCertificatesId
c.authorizedcertificate = authorizedcertificate
return c
}
// UpdateMask sets the optional parameter "updateMask": Standard field
// mask for the set of fields to be updated. Updates are only supported
// on the certificate_raw_data and display_name fields.
func (c *AppsAuthorizedCertificatesPatchCall) UpdateMask(updateMask string) *AppsAuthorizedCertificatesPatchCall {
c.urlParams_.Set("updateMask", updateMask)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsAuthorizedCertificatesPatchCall) Fields(s ...googleapi.Field) *AppsAuthorizedCertificatesPatchCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsAuthorizedCertificatesPatchCall) Context(ctx context.Context) *AppsAuthorizedCertificatesPatchCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsAuthorizedCertificatesPatchCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsAuthorizedCertificatesPatchCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.authorizedcertificate)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}/authorizedCertificates/{authorizedCertificatesId}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("PATCH", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
"authorizedCertificatesId": c.authorizedCertificatesId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.authorizedCertificates.patch" call.
// Exactly one of *AuthorizedCertificate or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *AuthorizedCertificate.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *AppsAuthorizedCertificatesPatchCall) Do(opts ...googleapi.CallOption) (*AuthorizedCertificate, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &AuthorizedCertificate{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates the specified SSL certificate. To renew a certificate and maintain its existing domain mappings, update certificate_data with a new certificate. The new certificate must be applicable to the same domains as the original certificate. The certificate display_name may also be updated.",
// "flatPath": "v1beta/apps/{appsId}/authorizedCertificates/{authorizedCertificatesId}",
// "httpMethod": "PATCH",
// "id": "appengine.apps.authorizedCertificates.patch",
// "parameterOrder": [
// "appsId",
// "authorizedCertificatesId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `name`. Name of the resource to update. Example: apps/myapp/authorizedCertificates/12345.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "authorizedCertificatesId": {
// "description": "Part of `name`. See documentation of `appsId`.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "updateMask": {
// "description": "Standard field mask for the set of fields to be updated. Updates are only supported on the certificate_raw_data and display_name fields.",
// "format": "google-fieldmask",
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}/authorizedCertificates/{authorizedCertificatesId}",
// "request": {
// "$ref": "AuthorizedCertificate"
// },
// "response": {
// "$ref": "AuthorizedCertificate"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "appengine.apps.authorizedDomains.list":
type AppsAuthorizedDomainsListCall struct {
s *APIService
appsId string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Lists all domains the user is authorized to administer.
//
// - appsId: Part of `parent`. Name of the parent Application resource.
// Example: apps/myapp.
func (r *AppsAuthorizedDomainsService) List(appsId string) *AppsAuthorizedDomainsListCall {
c := &AppsAuthorizedDomainsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
return c
}
// PageSize sets the optional parameter "pageSize": Maximum results to
// return per page.
func (c *AppsAuthorizedDomainsListCall) PageSize(pageSize int64) *AppsAuthorizedDomainsListCall {
c.urlParams_.Set("pageSize", fmt.Sprint(pageSize))
return c
}
// PageToken sets the optional parameter "pageToken": Continuation token
// for fetching the next page of results.
func (c *AppsAuthorizedDomainsListCall) PageToken(pageToken string) *AppsAuthorizedDomainsListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsAuthorizedDomainsListCall) Fields(s ...googleapi.Field) *AppsAuthorizedDomainsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *AppsAuthorizedDomainsListCall) IfNoneMatch(entityTag string) *AppsAuthorizedDomainsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsAuthorizedDomainsListCall) Context(ctx context.Context) *AppsAuthorizedDomainsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsAuthorizedDomainsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsAuthorizedDomainsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}/authorizedDomains")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.authorizedDomains.list" call.
// Exactly one of *ListAuthorizedDomainsResponse or error will be
// non-nil. Any non-2xx status code is an error. Response headers are in
// either *ListAuthorizedDomainsResponse.ServerResponse.Header or (if a
// response was returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *AppsAuthorizedDomainsListCall) Do(opts ...googleapi.CallOption) (*ListAuthorizedDomainsResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ListAuthorizedDomainsResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Lists all domains the user is authorized to administer.",
// "flatPath": "v1beta/apps/{appsId}/authorizedDomains",
// "httpMethod": "GET",
// "id": "appengine.apps.authorizedDomains.list",
// "parameterOrder": [
// "appsId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `parent`. Name of the parent Application resource. Example: apps/myapp.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "pageSize": {
// "description": "Maximum results to return per page.",
// "format": "int32",
// "location": "query",
// "type": "integer"
// },
// "pageToken": {
// "description": "Continuation token for fetching the next page of results.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}/authorizedDomains",
// "response": {
// "$ref": "ListAuthorizedDomainsResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/appengine.admin",
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *AppsAuthorizedDomainsListCall) Pages(ctx context.Context, f func(*ListAuthorizedDomainsResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "appengine.apps.domainMappings.create":
type AppsDomainMappingsCreateCall struct {
s *APIService
appsId string
domainmapping *DomainMapping
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Create: Maps a domain to an application. A user must be authorized to
// administer a domain in order to map it to an application. For a list
// of available authorized domains, see
// AuthorizedDomains.ListAuthorizedDomains.
//
// - appsId: Part of `parent`. Name of the parent Application resource.
// Example: apps/myapp.
func (r *AppsDomainMappingsService) Create(appsId string, domainmapping *DomainMapping) *AppsDomainMappingsCreateCall {
c := &AppsDomainMappingsCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
c.domainmapping = domainmapping
return c
}
// OverrideStrategy sets the optional parameter "overrideStrategy":
// Whether the domain creation should override any existing mappings for
// this domain. By default, overrides are rejected.
//
// Possible values:
// "UNSPECIFIED_DOMAIN_OVERRIDE_STRATEGY" - Strategy unspecified.
// Defaults to STRICT.
// "STRICT" - Overrides not allowed. If a mapping already exists for
// the specified domain, the request will return an ALREADY_EXISTS
// (409).
// "OVERRIDE" - Overrides allowed. If a mapping already exists for the
// specified domain, the request will overwrite it. Note that this might
// stop another Google product from serving. For example, if the domain
// is mapped to another App Engine application, that app will no longer
// serve from that domain.
func (c *AppsDomainMappingsCreateCall) OverrideStrategy(overrideStrategy string) *AppsDomainMappingsCreateCall {
c.urlParams_.Set("overrideStrategy", overrideStrategy)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsDomainMappingsCreateCall) Fields(s ...googleapi.Field) *AppsDomainMappingsCreateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsDomainMappingsCreateCall) Context(ctx context.Context) *AppsDomainMappingsCreateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsDomainMappingsCreateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsDomainMappingsCreateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.domainmapping)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}/domainMappings")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.domainMappings.create" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *AppsDomainMappingsCreateCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Maps a domain to an application. A user must be authorized to administer a domain in order to map it to an application. For a list of available authorized domains, see AuthorizedDomains.ListAuthorizedDomains.",
// "flatPath": "v1beta/apps/{appsId}/domainMappings",
// "httpMethod": "POST",
// "id": "appengine.apps.domainMappings.create",
// "parameterOrder": [
// "appsId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `parent`. Name of the parent Application resource. Example: apps/myapp.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "overrideStrategy": {
// "description": "Whether the domain creation should override any existing mappings for this domain. By default, overrides are rejected.",
// "enum": [
// "UNSPECIFIED_DOMAIN_OVERRIDE_STRATEGY",
// "STRICT",
// "OVERRIDE"
// ],
// "enumDescriptions": [
// "Strategy unspecified. Defaults to STRICT.",
// "Overrides not allowed. If a mapping already exists for the specified domain, the request will return an ALREADY_EXISTS (409).",
// "Overrides allowed. If a mapping already exists for the specified domain, the request will overwrite it. Note that this might stop another Google product from serving. For example, if the domain is mapped to another App Engine application, that app will no longer serve from that domain."
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}/domainMappings",
// "request": {
// "$ref": "DomainMapping"
// },
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "appengine.apps.domainMappings.delete":
type AppsDomainMappingsDeleteCall struct {
s *APIService
appsId string
domainMappingsId string
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Deletes the specified domain mapping. A user must be
// authorized to administer the associated domain in order to delete a
// DomainMapping resource.
//
// - appsId: Part of `name`. Name of the resource to delete. Example:
// apps/myapp/domainMappings/example.com.
// - domainMappingsId: Part of `name`. See documentation of `appsId`.
func (r *AppsDomainMappingsService) Delete(appsId string, domainMappingsId string) *AppsDomainMappingsDeleteCall {
c := &AppsDomainMappingsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
c.domainMappingsId = domainMappingsId
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsDomainMappingsDeleteCall) Fields(s ...googleapi.Field) *AppsDomainMappingsDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsDomainMappingsDeleteCall) Context(ctx context.Context) *AppsDomainMappingsDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsDomainMappingsDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsDomainMappingsDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}/domainMappings/{domainMappingsId}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("DELETE", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
"domainMappingsId": c.domainMappingsId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.domainMappings.delete" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *AppsDomainMappingsDeleteCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Deletes the specified domain mapping. A user must be authorized to administer the associated domain in order to delete a DomainMapping resource.",
// "flatPath": "v1beta/apps/{appsId}/domainMappings/{domainMappingsId}",
// "httpMethod": "DELETE",
// "id": "appengine.apps.domainMappings.delete",
// "parameterOrder": [
// "appsId",
// "domainMappingsId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `name`. Name of the resource to delete. Example: apps/myapp/domainMappings/example.com.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "domainMappingsId": {
// "description": "Part of `name`. See documentation of `appsId`.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}/domainMappings/{domainMappingsId}",
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "appengine.apps.domainMappings.get":
type AppsDomainMappingsGetCall struct {
s *APIService
appsId string
domainMappingsId string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Gets the specified domain mapping.
//
// - appsId: Part of `name`. Name of the resource requested. Example:
// apps/myapp/domainMappings/example.com.
// - domainMappingsId: Part of `name`. See documentation of `appsId`.
func (r *AppsDomainMappingsService) Get(appsId string, domainMappingsId string) *AppsDomainMappingsGetCall {
c := &AppsDomainMappingsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
c.domainMappingsId = domainMappingsId
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsDomainMappingsGetCall) Fields(s ...googleapi.Field) *AppsDomainMappingsGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *AppsDomainMappingsGetCall) IfNoneMatch(entityTag string) *AppsDomainMappingsGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsDomainMappingsGetCall) Context(ctx context.Context) *AppsDomainMappingsGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsDomainMappingsGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsDomainMappingsGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}/domainMappings/{domainMappingsId}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
"domainMappingsId": c.domainMappingsId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.domainMappings.get" call.
// Exactly one of *DomainMapping or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *DomainMapping.ServerResponse.Header or (if a response was returned
// at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *AppsDomainMappingsGetCall) Do(opts ...googleapi.CallOption) (*DomainMapping, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &DomainMapping{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets the specified domain mapping.",
// "flatPath": "v1beta/apps/{appsId}/domainMappings/{domainMappingsId}",
// "httpMethod": "GET",
// "id": "appengine.apps.domainMappings.get",
// "parameterOrder": [
// "appsId",
// "domainMappingsId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `name`. Name of the resource requested. Example: apps/myapp/domainMappings/example.com.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "domainMappingsId": {
// "description": "Part of `name`. See documentation of `appsId`.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}/domainMappings/{domainMappingsId}",
// "response": {
// "$ref": "DomainMapping"
// },
// "scopes": [
// "https://www.googleapis.com/auth/appengine.admin",
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only"
// ]
// }
}
// method id "appengine.apps.domainMappings.list":
type AppsDomainMappingsListCall struct {
s *APIService
appsId string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Lists the domain mappings on an application.
//
// - appsId: Part of `parent`. Name of the parent Application resource.
// Example: apps/myapp.
func (r *AppsDomainMappingsService) List(appsId string) *AppsDomainMappingsListCall {
c := &AppsDomainMappingsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
return c
}
// PageSize sets the optional parameter "pageSize": Maximum results to
// return per page.
func (c *AppsDomainMappingsListCall) PageSize(pageSize int64) *AppsDomainMappingsListCall {
c.urlParams_.Set("pageSize", fmt.Sprint(pageSize))
return c
}
// PageToken sets the optional parameter "pageToken": Continuation token
// for fetching the next page of results.
func (c *AppsDomainMappingsListCall) PageToken(pageToken string) *AppsDomainMappingsListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsDomainMappingsListCall) Fields(s ...googleapi.Field) *AppsDomainMappingsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *AppsDomainMappingsListCall) IfNoneMatch(entityTag string) *AppsDomainMappingsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsDomainMappingsListCall) Context(ctx context.Context) *AppsDomainMappingsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsDomainMappingsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsDomainMappingsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}/domainMappings")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.domainMappings.list" call.
// Exactly one of *ListDomainMappingsResponse or error will be non-nil.
// Any non-2xx status code is an error. Response headers are in either
// *ListDomainMappingsResponse.ServerResponse.Header or (if a response
// was returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *AppsDomainMappingsListCall) Do(opts ...googleapi.CallOption) (*ListDomainMappingsResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ListDomainMappingsResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Lists the domain mappings on an application.",
// "flatPath": "v1beta/apps/{appsId}/domainMappings",
// "httpMethod": "GET",
// "id": "appengine.apps.domainMappings.list",
// "parameterOrder": [
// "appsId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `parent`. Name of the parent Application resource. Example: apps/myapp.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "pageSize": {
// "description": "Maximum results to return per page.",
// "format": "int32",
// "location": "query",
// "type": "integer"
// },
// "pageToken": {
// "description": "Continuation token for fetching the next page of results.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}/domainMappings",
// "response": {
// "$ref": "ListDomainMappingsResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/appengine.admin",
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *AppsDomainMappingsListCall) Pages(ctx context.Context, f func(*ListDomainMappingsResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "appengine.apps.domainMappings.patch":
type AppsDomainMappingsPatchCall struct {
s *APIService
appsId string
domainMappingsId string
domainmapping *DomainMapping
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Patch: Updates the specified domain mapping. To map an SSL
// certificate to a domain mapping, update certificate_id to point to an
// AuthorizedCertificate resource. A user must be authorized to
// administer the associated domain in order to update a DomainMapping
// resource.
//
// - appsId: Part of `name`. Name of the resource to update. Example:
// apps/myapp/domainMappings/example.com.
// - domainMappingsId: Part of `name`. See documentation of `appsId`.
func (r *AppsDomainMappingsService) Patch(appsId string, domainMappingsId string, domainmapping *DomainMapping) *AppsDomainMappingsPatchCall {
c := &AppsDomainMappingsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
c.domainMappingsId = domainMappingsId
c.domainmapping = domainmapping
return c
}
// UpdateMask sets the optional parameter "updateMask": Required.
// Standard field mask for the set of fields to be updated.
func (c *AppsDomainMappingsPatchCall) UpdateMask(updateMask string) *AppsDomainMappingsPatchCall {
c.urlParams_.Set("updateMask", updateMask)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsDomainMappingsPatchCall) Fields(s ...googleapi.Field) *AppsDomainMappingsPatchCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsDomainMappingsPatchCall) Context(ctx context.Context) *AppsDomainMappingsPatchCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsDomainMappingsPatchCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsDomainMappingsPatchCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.domainmapping)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}/domainMappings/{domainMappingsId}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("PATCH", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
"domainMappingsId": c.domainMappingsId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.domainMappings.patch" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *AppsDomainMappingsPatchCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates the specified domain mapping. To map an SSL certificate to a domain mapping, update certificate_id to point to an AuthorizedCertificate resource. A user must be authorized to administer the associated domain in order to update a DomainMapping resource.",
// "flatPath": "v1beta/apps/{appsId}/domainMappings/{domainMappingsId}",
// "httpMethod": "PATCH",
// "id": "appengine.apps.domainMappings.patch",
// "parameterOrder": [
// "appsId",
// "domainMappingsId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `name`. Name of the resource to update. Example: apps/myapp/domainMappings/example.com.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "domainMappingsId": {
// "description": "Part of `name`. See documentation of `appsId`.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "updateMask": {
// "description": "Required. Standard field mask for the set of fields to be updated.",
// "format": "google-fieldmask",
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}/domainMappings/{domainMappingsId}",
// "request": {
// "$ref": "DomainMapping"
// },
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "appengine.apps.firewall.ingressRules.batchUpdate":
type AppsFirewallIngressRulesBatchUpdateCall struct {
s *APIService
appsId string
batchupdateingressrulesrequest *BatchUpdateIngressRulesRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// BatchUpdate: Replaces the entire firewall ruleset in one bulk
// operation. This overrides and replaces the rules of an existing
// firewall with the new rules.If the final rule does not match traffic
// with the '*' wildcard IP range, then an "allow all" rule is
// explicitly added to the end of the list.
//
// - appsId: Part of `name`. Name of the Firewall collection to set.
// Example: apps/myapp/firewall/ingressRules.
func (r *AppsFirewallIngressRulesService) BatchUpdate(appsId string, batchupdateingressrulesrequest *BatchUpdateIngressRulesRequest) *AppsFirewallIngressRulesBatchUpdateCall {
c := &AppsFirewallIngressRulesBatchUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
c.batchupdateingressrulesrequest = batchupdateingressrulesrequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsFirewallIngressRulesBatchUpdateCall) Fields(s ...googleapi.Field) *AppsFirewallIngressRulesBatchUpdateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsFirewallIngressRulesBatchUpdateCall) Context(ctx context.Context) *AppsFirewallIngressRulesBatchUpdateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsFirewallIngressRulesBatchUpdateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsFirewallIngressRulesBatchUpdateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.batchupdateingressrulesrequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}/firewall/ingressRules:batchUpdate")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.firewall.ingressRules.batchUpdate" call.
// Exactly one of *BatchUpdateIngressRulesResponse or error will be
// non-nil. Any non-2xx status code is an error. Response headers are in
// either *BatchUpdateIngressRulesResponse.ServerResponse.Header or (if
// a response was returned at all) in error.(*googleapi.Error).Header.
// Use googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *AppsFirewallIngressRulesBatchUpdateCall) Do(opts ...googleapi.CallOption) (*BatchUpdateIngressRulesResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &BatchUpdateIngressRulesResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Replaces the entire firewall ruleset in one bulk operation. This overrides and replaces the rules of an existing firewall with the new rules.If the final rule does not match traffic with the '*' wildcard IP range, then an \"allow all\" rule is explicitly added to the end of the list.",
// "flatPath": "v1beta/apps/{appsId}/firewall/ingressRules:batchUpdate",
// "httpMethod": "POST",
// "id": "appengine.apps.firewall.ingressRules.batchUpdate",
// "parameterOrder": [
// "appsId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `name`. Name of the Firewall collection to set. Example: apps/myapp/firewall/ingressRules.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}/firewall/ingressRules:batchUpdate",
// "request": {
// "$ref": "BatchUpdateIngressRulesRequest"
// },
// "response": {
// "$ref": "BatchUpdateIngressRulesResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "appengine.apps.firewall.ingressRules.create":
type AppsFirewallIngressRulesCreateCall struct {
s *APIService
appsId string
firewallrule *FirewallRule
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Create: Creates a firewall rule for the application.
//
// - appsId: Part of `parent`. Name of the parent Firewall collection in
// which to create a new rule. Example:
// apps/myapp/firewall/ingressRules.
func (r *AppsFirewallIngressRulesService) Create(appsId string, firewallrule *FirewallRule) *AppsFirewallIngressRulesCreateCall {
c := &AppsFirewallIngressRulesCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
c.firewallrule = firewallrule
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsFirewallIngressRulesCreateCall) Fields(s ...googleapi.Field) *AppsFirewallIngressRulesCreateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsFirewallIngressRulesCreateCall) Context(ctx context.Context) *AppsFirewallIngressRulesCreateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsFirewallIngressRulesCreateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsFirewallIngressRulesCreateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.firewallrule)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}/firewall/ingressRules")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.firewall.ingressRules.create" call.
// Exactly one of *FirewallRule or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *FirewallRule.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *AppsFirewallIngressRulesCreateCall) Do(opts ...googleapi.CallOption) (*FirewallRule, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &FirewallRule{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Creates a firewall rule for the application.",
// "flatPath": "v1beta/apps/{appsId}/firewall/ingressRules",
// "httpMethod": "POST",
// "id": "appengine.apps.firewall.ingressRules.create",
// "parameterOrder": [
// "appsId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `parent`. Name of the parent Firewall collection in which to create a new rule. Example: apps/myapp/firewall/ingressRules.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}/firewall/ingressRules",
// "request": {
// "$ref": "FirewallRule"
// },
// "response": {
// "$ref": "FirewallRule"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "appengine.apps.firewall.ingressRules.delete":
type AppsFirewallIngressRulesDeleteCall struct {
s *APIService
appsId string
ingressRulesId string
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Deletes the specified firewall rule.
//
// - appsId: Part of `name`. Name of the Firewall resource to delete.
// Example: apps/myapp/firewall/ingressRules/100.
// - ingressRulesId: Part of `name`. See documentation of `appsId`.
func (r *AppsFirewallIngressRulesService) Delete(appsId string, ingressRulesId string) *AppsFirewallIngressRulesDeleteCall {
c := &AppsFirewallIngressRulesDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
c.ingressRulesId = ingressRulesId
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsFirewallIngressRulesDeleteCall) Fields(s ...googleapi.Field) *AppsFirewallIngressRulesDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsFirewallIngressRulesDeleteCall) Context(ctx context.Context) *AppsFirewallIngressRulesDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsFirewallIngressRulesDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsFirewallIngressRulesDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}/firewall/ingressRules/{ingressRulesId}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("DELETE", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
"ingressRulesId": c.ingressRulesId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.firewall.ingressRules.delete" call.
// Exactly one of *Empty or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Empty.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *AppsFirewallIngressRulesDeleteCall) Do(opts ...googleapi.CallOption) (*Empty, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Empty{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Deletes the specified firewall rule.",
// "flatPath": "v1beta/apps/{appsId}/firewall/ingressRules/{ingressRulesId}",
// "httpMethod": "DELETE",
// "id": "appengine.apps.firewall.ingressRules.delete",
// "parameterOrder": [
// "appsId",
// "ingressRulesId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `name`. Name of the Firewall resource to delete. Example: apps/myapp/firewall/ingressRules/100.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "ingressRulesId": {
// "description": "Part of `name`. See documentation of `appsId`.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}/firewall/ingressRules/{ingressRulesId}",
// "response": {
// "$ref": "Empty"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "appengine.apps.firewall.ingressRules.get":
type AppsFirewallIngressRulesGetCall struct {
s *APIService
appsId string
ingressRulesId string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Gets the specified firewall rule.
//
// - appsId: Part of `name`. Name of the Firewall resource to retrieve.
// Example: apps/myapp/firewall/ingressRules/100.
// - ingressRulesId: Part of `name`. See documentation of `appsId`.
func (r *AppsFirewallIngressRulesService) Get(appsId string, ingressRulesId string) *AppsFirewallIngressRulesGetCall {
c := &AppsFirewallIngressRulesGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
c.ingressRulesId = ingressRulesId
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsFirewallIngressRulesGetCall) Fields(s ...googleapi.Field) *AppsFirewallIngressRulesGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *AppsFirewallIngressRulesGetCall) IfNoneMatch(entityTag string) *AppsFirewallIngressRulesGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsFirewallIngressRulesGetCall) Context(ctx context.Context) *AppsFirewallIngressRulesGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsFirewallIngressRulesGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsFirewallIngressRulesGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}/firewall/ingressRules/{ingressRulesId}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
"ingressRulesId": c.ingressRulesId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.firewall.ingressRules.get" call.
// Exactly one of *FirewallRule or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *FirewallRule.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *AppsFirewallIngressRulesGetCall) Do(opts ...googleapi.CallOption) (*FirewallRule, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &FirewallRule{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets the specified firewall rule.",
// "flatPath": "v1beta/apps/{appsId}/firewall/ingressRules/{ingressRulesId}",
// "httpMethod": "GET",
// "id": "appengine.apps.firewall.ingressRules.get",
// "parameterOrder": [
// "appsId",
// "ingressRulesId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `name`. Name of the Firewall resource to retrieve. Example: apps/myapp/firewall/ingressRules/100.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "ingressRulesId": {
// "description": "Part of `name`. See documentation of `appsId`.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}/firewall/ingressRules/{ingressRulesId}",
// "response": {
// "$ref": "FirewallRule"
// },
// "scopes": [
// "https://www.googleapis.com/auth/appengine.admin",
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only"
// ]
// }
}
// method id "appengine.apps.firewall.ingressRules.list":
type AppsFirewallIngressRulesListCall struct {
s *APIService
appsId string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Lists the firewall rules of an application.
//
// - appsId: Part of `parent`. Name of the Firewall collection to
// retrieve. Example: apps/myapp/firewall/ingressRules.
func (r *AppsFirewallIngressRulesService) List(appsId string) *AppsFirewallIngressRulesListCall {
c := &AppsFirewallIngressRulesListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
return c
}
// MatchingAddress sets the optional parameter "matchingAddress": A
// valid IP Address. If set, only rules matching this address will be
// returned. The first returned rule will be the rule that fires on
// requests from this IP.
func (c *AppsFirewallIngressRulesListCall) MatchingAddress(matchingAddress string) *AppsFirewallIngressRulesListCall {
c.urlParams_.Set("matchingAddress", matchingAddress)
return c
}
// PageSize sets the optional parameter "pageSize": Maximum results to
// return per page.
func (c *AppsFirewallIngressRulesListCall) PageSize(pageSize int64) *AppsFirewallIngressRulesListCall {
c.urlParams_.Set("pageSize", fmt.Sprint(pageSize))
return c
}
// PageToken sets the optional parameter "pageToken": Continuation token
// for fetching the next page of results.
func (c *AppsFirewallIngressRulesListCall) PageToken(pageToken string) *AppsFirewallIngressRulesListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsFirewallIngressRulesListCall) Fields(s ...googleapi.Field) *AppsFirewallIngressRulesListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *AppsFirewallIngressRulesListCall) IfNoneMatch(entityTag string) *AppsFirewallIngressRulesListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsFirewallIngressRulesListCall) Context(ctx context.Context) *AppsFirewallIngressRulesListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsFirewallIngressRulesListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsFirewallIngressRulesListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}/firewall/ingressRules")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.firewall.ingressRules.list" call.
// Exactly one of *ListIngressRulesResponse or error will be non-nil.
// Any non-2xx status code is an error. Response headers are in either
// *ListIngressRulesResponse.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *AppsFirewallIngressRulesListCall) Do(opts ...googleapi.CallOption) (*ListIngressRulesResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ListIngressRulesResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Lists the firewall rules of an application.",
// "flatPath": "v1beta/apps/{appsId}/firewall/ingressRules",
// "httpMethod": "GET",
// "id": "appengine.apps.firewall.ingressRules.list",
// "parameterOrder": [
// "appsId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `parent`. Name of the Firewall collection to retrieve. Example: apps/myapp/firewall/ingressRules.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "matchingAddress": {
// "description": "A valid IP Address. If set, only rules matching this address will be returned. The first returned rule will be the rule that fires on requests from this IP.",
// "location": "query",
// "type": "string"
// },
// "pageSize": {
// "description": "Maximum results to return per page.",
// "format": "int32",
// "location": "query",
// "type": "integer"
// },
// "pageToken": {
// "description": "Continuation token for fetching the next page of results.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}/firewall/ingressRules",
// "response": {
// "$ref": "ListIngressRulesResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/appengine.admin",
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *AppsFirewallIngressRulesListCall) Pages(ctx context.Context, f func(*ListIngressRulesResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "appengine.apps.firewall.ingressRules.patch":
type AppsFirewallIngressRulesPatchCall struct {
s *APIService
appsId string
ingressRulesId string
firewallrule *FirewallRule
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Patch: Updates the specified firewall rule.
//
// - appsId: Part of `name`. Name of the Firewall resource to update.
// Example: apps/myapp/firewall/ingressRules/100.
// - ingressRulesId: Part of `name`. See documentation of `appsId`.
func (r *AppsFirewallIngressRulesService) Patch(appsId string, ingressRulesId string, firewallrule *FirewallRule) *AppsFirewallIngressRulesPatchCall {
c := &AppsFirewallIngressRulesPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
c.ingressRulesId = ingressRulesId
c.firewallrule = firewallrule
return c
}
// UpdateMask sets the optional parameter "updateMask": Standard field
// mask for the set of fields to be updated.
func (c *AppsFirewallIngressRulesPatchCall) UpdateMask(updateMask string) *AppsFirewallIngressRulesPatchCall {
c.urlParams_.Set("updateMask", updateMask)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsFirewallIngressRulesPatchCall) Fields(s ...googleapi.Field) *AppsFirewallIngressRulesPatchCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsFirewallIngressRulesPatchCall) Context(ctx context.Context) *AppsFirewallIngressRulesPatchCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsFirewallIngressRulesPatchCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsFirewallIngressRulesPatchCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.firewallrule)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}/firewall/ingressRules/{ingressRulesId}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("PATCH", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
"ingressRulesId": c.ingressRulesId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.firewall.ingressRules.patch" call.
// Exactly one of *FirewallRule or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *FirewallRule.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *AppsFirewallIngressRulesPatchCall) Do(opts ...googleapi.CallOption) (*FirewallRule, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &FirewallRule{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates the specified firewall rule.",
// "flatPath": "v1beta/apps/{appsId}/firewall/ingressRules/{ingressRulesId}",
// "httpMethod": "PATCH",
// "id": "appengine.apps.firewall.ingressRules.patch",
// "parameterOrder": [
// "appsId",
// "ingressRulesId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `name`. Name of the Firewall resource to update. Example: apps/myapp/firewall/ingressRules/100.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "ingressRulesId": {
// "description": "Part of `name`. See documentation of `appsId`.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "updateMask": {
// "description": "Standard field mask for the set of fields to be updated.",
// "format": "google-fieldmask",
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}/firewall/ingressRules/{ingressRulesId}",
// "request": {
// "$ref": "FirewallRule"
// },
// "response": {
// "$ref": "FirewallRule"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "appengine.apps.locations.get":
type AppsLocationsGetCall struct {
s *APIService
appsId string
locationsId string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Gets information about a location.
//
// - appsId: Part of `name`. Resource name for the location.
// - locationsId: Part of `name`. See documentation of `appsId`.
func (r *AppsLocationsService) Get(appsId string, locationsId string) *AppsLocationsGetCall {
c := &AppsLocationsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
c.locationsId = locationsId
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsLocationsGetCall) Fields(s ...googleapi.Field) *AppsLocationsGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *AppsLocationsGetCall) IfNoneMatch(entityTag string) *AppsLocationsGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsLocationsGetCall) Context(ctx context.Context) *AppsLocationsGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsLocationsGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsLocationsGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}/locations/{locationsId}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
"locationsId": c.locationsId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.locations.get" call.
// Exactly one of *Location or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Location.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *AppsLocationsGetCall) Do(opts ...googleapi.CallOption) (*Location, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Location{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets information about a location.",
// "flatPath": "v1beta/apps/{appsId}/locations/{locationsId}",
// "httpMethod": "GET",
// "id": "appengine.apps.locations.get",
// "parameterOrder": [
// "appsId",
// "locationsId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `name`. Resource name for the location.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "locationsId": {
// "description": "Part of `name`. See documentation of `appsId`.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}/locations/{locationsId}",
// "response": {
// "$ref": "Location"
// },
// "scopes": [
// "https://www.googleapis.com/auth/appengine.admin",
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only"
// ]
// }
}
// method id "appengine.apps.locations.list":
type AppsLocationsListCall struct {
s *APIService
appsId string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Lists information about the supported locations for this
// service.
//
// - appsId: Part of `name`. The resource that owns the locations
// collection, if applicable.
func (r *AppsLocationsService) List(appsId string) *AppsLocationsListCall {
c := &AppsLocationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
return c
}
// Filter sets the optional parameter "filter": A filter to narrow down
// results to a preferred subset. The filtering language accepts strings
// like "displayName=tokyo", and is documented in more detail in AIP-160
// (https://google.aip.dev/160).
func (c *AppsLocationsListCall) Filter(filter string) *AppsLocationsListCall {
c.urlParams_.Set("filter", filter)
return c
}
// PageSize sets the optional parameter "pageSize": The maximum number
// of results to return. If not set, the service selects a default.
func (c *AppsLocationsListCall) PageSize(pageSize int64) *AppsLocationsListCall {
c.urlParams_.Set("pageSize", fmt.Sprint(pageSize))
return c
}
// PageToken sets the optional parameter "pageToken": A page token
// received from the next_page_token field in the response. Send that
// page token to receive the subsequent page.
func (c *AppsLocationsListCall) PageToken(pageToken string) *AppsLocationsListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsLocationsListCall) Fields(s ...googleapi.Field) *AppsLocationsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *AppsLocationsListCall) IfNoneMatch(entityTag string) *AppsLocationsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsLocationsListCall) Context(ctx context.Context) *AppsLocationsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsLocationsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsLocationsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}/locations")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.locations.list" call.
// Exactly one of *ListLocationsResponse or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ListLocationsResponse.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *AppsLocationsListCall) Do(opts ...googleapi.CallOption) (*ListLocationsResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ListLocationsResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Lists information about the supported locations for this service.",
// "flatPath": "v1beta/apps/{appsId}/locations",
// "httpMethod": "GET",
// "id": "appengine.apps.locations.list",
// "parameterOrder": [
// "appsId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `name`. The resource that owns the locations collection, if applicable.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "filter": {
// "description": "A filter to narrow down results to a preferred subset. The filtering language accepts strings like \"displayName=tokyo\", and is documented in more detail in AIP-160 (https://google.aip.dev/160).",
// "location": "query",
// "type": "string"
// },
// "pageSize": {
// "description": "The maximum number of results to return. If not set, the service selects a default.",
// "format": "int32",
// "location": "query",
// "type": "integer"
// },
// "pageToken": {
// "description": "A page token received from the next_page_token field in the response. Send that page token to receive the subsequent page.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}/locations",
// "response": {
// "$ref": "ListLocationsResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/appengine.admin",
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *AppsLocationsListCall) Pages(ctx context.Context, f func(*ListLocationsResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "appengine.apps.operations.get":
type AppsOperationsGetCall struct {
s *APIService
appsId string
operationsId string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Gets the latest state of a long-running operation. Clients can
// use this method to poll the operation result at intervals as
// recommended by the API service.
//
// - appsId: Part of `name`. The name of the operation resource.
// - operationsId: Part of `name`. See documentation of `appsId`.
func (r *AppsOperationsService) Get(appsId string, operationsId string) *AppsOperationsGetCall {
c := &AppsOperationsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
c.operationsId = operationsId
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsOperationsGetCall) Fields(s ...googleapi.Field) *AppsOperationsGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *AppsOperationsGetCall) IfNoneMatch(entityTag string) *AppsOperationsGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsOperationsGetCall) Context(ctx context.Context) *AppsOperationsGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsOperationsGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsOperationsGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}/operations/{operationsId}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
"operationsId": c.operationsId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.operations.get" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *AppsOperationsGetCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service.",
// "flatPath": "v1beta/apps/{appsId}/operations/{operationsId}",
// "httpMethod": "GET",
// "id": "appengine.apps.operations.get",
// "parameterOrder": [
// "appsId",
// "operationsId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `name`. The name of the operation resource.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "operationsId": {
// "description": "Part of `name`. See documentation of `appsId`.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}/operations/{operationsId}",
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/appengine.admin",
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only"
// ]
// }
}
// method id "appengine.apps.operations.list":
type AppsOperationsListCall struct {
s *APIService
appsId string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Lists operations that match the specified filter in the
// request. If the server doesn't support this method, it returns
// UNIMPLEMENTED.NOTE: the name binding allows API services to override
// the binding to use different resource name schemes, such as
// users/*/operations. To override the binding, API services can add a
// binding such as "/v1/{name=users/*}/operations" to their service
// configuration. For backwards compatibility, the default name includes
// the operations collection id, however overriding users must ensure
// the name binding is the parent resource, without the operations
// collection id.
//
// - appsId: Part of `name`. The name of the operation's parent
// resource.
func (r *AppsOperationsService) List(appsId string) *AppsOperationsListCall {
c := &AppsOperationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
return c
}
// Filter sets the optional parameter "filter": The standard list
// filter.
func (c *AppsOperationsListCall) Filter(filter string) *AppsOperationsListCall {
c.urlParams_.Set("filter", filter)
return c
}
// PageSize sets the optional parameter "pageSize": The standard list
// page size.
func (c *AppsOperationsListCall) PageSize(pageSize int64) *AppsOperationsListCall {
c.urlParams_.Set("pageSize", fmt.Sprint(pageSize))
return c
}
// PageToken sets the optional parameter "pageToken": The standard list
// page token.
func (c *AppsOperationsListCall) PageToken(pageToken string) *AppsOperationsListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsOperationsListCall) Fields(s ...googleapi.Field) *AppsOperationsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *AppsOperationsListCall) IfNoneMatch(entityTag string) *AppsOperationsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsOperationsListCall) Context(ctx context.Context) *AppsOperationsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsOperationsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsOperationsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}/operations")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.operations.list" call.
// Exactly one of *ListOperationsResponse or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ListOperationsResponse.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *AppsOperationsListCall) Do(opts ...googleapi.CallOption) (*ListOperationsResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ListOperationsResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns UNIMPLEMENTED.NOTE: the name binding allows API services to override the binding to use different resource name schemes, such as users/*/operations. To override the binding, API services can add a binding such as \"/v1/{name=users/*}/operations\" to their service configuration. For backwards compatibility, the default name includes the operations collection id, however overriding users must ensure the name binding is the parent resource, without the operations collection id.",
// "flatPath": "v1beta/apps/{appsId}/operations",
// "httpMethod": "GET",
// "id": "appengine.apps.operations.list",
// "parameterOrder": [
// "appsId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `name`. The name of the operation's parent resource.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "filter": {
// "description": "The standard list filter.",
// "location": "query",
// "type": "string"
// },
// "pageSize": {
// "description": "The standard list page size.",
// "format": "int32",
// "location": "query",
// "type": "integer"
// },
// "pageToken": {
// "description": "The standard list page token.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}/operations",
// "response": {
// "$ref": "ListOperationsResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/appengine.admin",
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *AppsOperationsListCall) Pages(ctx context.Context, f func(*ListOperationsResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "appengine.apps.services.delete":
type AppsServicesDeleteCall struct {
s *APIService
appsId string
servicesId string
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Deletes the specified service and all enclosed versions.
//
// - appsId: Part of `name`. Name of the resource requested. Example:
// apps/myapp/services/default.
// - servicesId: Part of `name`. See documentation of `appsId`.
func (r *AppsServicesService) Delete(appsId string, servicesId string) *AppsServicesDeleteCall {
c := &AppsServicesDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
c.servicesId = servicesId
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsServicesDeleteCall) Fields(s ...googleapi.Field) *AppsServicesDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsServicesDeleteCall) Context(ctx context.Context) *AppsServicesDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsServicesDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsServicesDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}/services/{servicesId}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("DELETE", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
"servicesId": c.servicesId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.services.delete" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *AppsServicesDeleteCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Deletes the specified service and all enclosed versions.",
// "flatPath": "v1beta/apps/{appsId}/services/{servicesId}",
// "httpMethod": "DELETE",
// "id": "appengine.apps.services.delete",
// "parameterOrder": [
// "appsId",
// "servicesId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `name`. Name of the resource requested. Example: apps/myapp/services/default.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "servicesId": {
// "description": "Part of `name`. See documentation of `appsId`.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}/services/{servicesId}",
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "appengine.apps.services.get":
type AppsServicesGetCall struct {
s *APIService
appsId string
servicesId string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Gets the current configuration of the specified service.
//
// - appsId: Part of `name`. Name of the resource requested. Example:
// apps/myapp/services/default.
// - servicesId: Part of `name`. See documentation of `appsId`.
func (r *AppsServicesService) Get(appsId string, servicesId string) *AppsServicesGetCall {
c := &AppsServicesGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
c.servicesId = servicesId
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsServicesGetCall) Fields(s ...googleapi.Field) *AppsServicesGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *AppsServicesGetCall) IfNoneMatch(entityTag string) *AppsServicesGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsServicesGetCall) Context(ctx context.Context) *AppsServicesGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsServicesGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsServicesGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}/services/{servicesId}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
"servicesId": c.servicesId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.services.get" call.
// Exactly one of *Service or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Service.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *AppsServicesGetCall) Do(opts ...googleapi.CallOption) (*Service, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Service{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets the current configuration of the specified service.",
// "flatPath": "v1beta/apps/{appsId}/services/{servicesId}",
// "httpMethod": "GET",
// "id": "appengine.apps.services.get",
// "parameterOrder": [
// "appsId",
// "servicesId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `name`. Name of the resource requested. Example: apps/myapp/services/default.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "servicesId": {
// "description": "Part of `name`. See documentation of `appsId`.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}/services/{servicesId}",
// "response": {
// "$ref": "Service"
// },
// "scopes": [
// "https://www.googleapis.com/auth/appengine.admin",
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only"
// ]
// }
}
// method id "appengine.apps.services.list":
type AppsServicesListCall struct {
s *APIService
appsId string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Lists all the services in the application.
//
// - appsId: Part of `parent`. Name of the parent Application resource.
// Example: apps/myapp.
func (r *AppsServicesService) List(appsId string) *AppsServicesListCall {
c := &AppsServicesListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
return c
}
// PageSize sets the optional parameter "pageSize": Maximum results to
// return per page.
func (c *AppsServicesListCall) PageSize(pageSize int64) *AppsServicesListCall {
c.urlParams_.Set("pageSize", fmt.Sprint(pageSize))
return c
}
// PageToken sets the optional parameter "pageToken": Continuation token
// for fetching the next page of results.
func (c *AppsServicesListCall) PageToken(pageToken string) *AppsServicesListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsServicesListCall) Fields(s ...googleapi.Field) *AppsServicesListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *AppsServicesListCall) IfNoneMatch(entityTag string) *AppsServicesListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsServicesListCall) Context(ctx context.Context) *AppsServicesListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsServicesListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsServicesListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}/services")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.services.list" call.
// Exactly one of *ListServicesResponse or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ListServicesResponse.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *AppsServicesListCall) Do(opts ...googleapi.CallOption) (*ListServicesResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ListServicesResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Lists all the services in the application.",
// "flatPath": "v1beta/apps/{appsId}/services",
// "httpMethod": "GET",
// "id": "appengine.apps.services.list",
// "parameterOrder": [
// "appsId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `parent`. Name of the parent Application resource. Example: apps/myapp.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "pageSize": {
// "description": "Maximum results to return per page.",
// "format": "int32",
// "location": "query",
// "type": "integer"
// },
// "pageToken": {
// "description": "Continuation token for fetching the next page of results.",
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}/services",
// "response": {
// "$ref": "ListServicesResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/appengine.admin",
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *AppsServicesListCall) Pages(ctx context.Context, f func(*ListServicesResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "appengine.apps.services.patch":
type AppsServicesPatchCall struct {
s *APIService
appsId string
servicesId string
service *Service
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Patch: Updates the configuration of the specified service.
//
// - appsId: Part of `name`. Name of the resource to update. Example:
// apps/myapp/services/default.
// - servicesId: Part of `name`. See documentation of `appsId`.
func (r *AppsServicesService) Patch(appsId string, servicesId string, service *Service) *AppsServicesPatchCall {
c := &AppsServicesPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
c.servicesId = servicesId
c.service = service
return c
}
// MigrateTraffic sets the optional parameter "migrateTraffic": Set to
// true to gradually shift traffic to one or more versions that you
// specify. By default, traffic is shifted immediately. For gradual
// traffic migration, the target versions must be located within
// instances that are configured for both warmup requests
// (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#InboundServiceType)
// and automatic scaling
// (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#AutomaticScaling).
// You must specify the shardBy
// (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services#ShardBy)
// field in the Service resource. Gradual traffic migration is not
// supported in the App Engine flexible environment. For examples, see
// Migrating and Splitting Traffic
// (https://cloud.google.com/appengine/docs/admin-api/migrating-splitting-traffic).
func (c *AppsServicesPatchCall) MigrateTraffic(migrateTraffic bool) *AppsServicesPatchCall {
c.urlParams_.Set("migrateTraffic", fmt.Sprint(migrateTraffic))
return c
}
// UpdateMask sets the optional parameter "updateMask": Required.
// Standard field mask for the set of fields to be updated.
func (c *AppsServicesPatchCall) UpdateMask(updateMask string) *AppsServicesPatchCall {
c.urlParams_.Set("updateMask", updateMask)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsServicesPatchCall) Fields(s ...googleapi.Field) *AppsServicesPatchCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsServicesPatchCall) Context(ctx context.Context) *AppsServicesPatchCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsServicesPatchCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsServicesPatchCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.service)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}/services/{servicesId}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("PATCH", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
"servicesId": c.servicesId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.services.patch" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *AppsServicesPatchCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates the configuration of the specified service.",
// "flatPath": "v1beta/apps/{appsId}/services/{servicesId}",
// "httpMethod": "PATCH",
// "id": "appengine.apps.services.patch",
// "parameterOrder": [
// "appsId",
// "servicesId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `name`. Name of the resource to update. Example: apps/myapp/services/default.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "migrateTraffic": {
// "description": "Set to true to gradually shift traffic to one or more versions that you specify. By default, traffic is shifted immediately. For gradual traffic migration, the target versions must be located within instances that are configured for both warmup requests (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#InboundServiceType) and automatic scaling (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#AutomaticScaling). You must specify the shardBy (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services#ShardBy) field in the Service resource. Gradual traffic migration is not supported in the App Engine flexible environment. For examples, see Migrating and Splitting Traffic (https://cloud.google.com/appengine/docs/admin-api/migrating-splitting-traffic).",
// "location": "query",
// "type": "boolean"
// },
// "servicesId": {
// "description": "Part of `name`. See documentation of `appsId`.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "updateMask": {
// "description": "Required. Standard field mask for the set of fields to be updated.",
// "format": "google-fieldmask",
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}/services/{servicesId}",
// "request": {
// "$ref": "Service"
// },
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "appengine.apps.services.versions.create":
type AppsServicesVersionsCreateCall struct {
s *APIService
appsId string
servicesId string
version *Version
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Create: Deploys code and resource files to a new version.
//
// - appsId: Part of `parent`. Name of the parent resource to create
// this version under. Example: apps/myapp/services/default.
// - servicesId: Part of `parent`. See documentation of `appsId`.
func (r *AppsServicesVersionsService) Create(appsId string, servicesId string, version *Version) *AppsServicesVersionsCreateCall {
c := &AppsServicesVersionsCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
c.servicesId = servicesId
c.version = version
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsServicesVersionsCreateCall) Fields(s ...googleapi.Field) *AppsServicesVersionsCreateCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsServicesVersionsCreateCall) Context(ctx context.Context) *AppsServicesVersionsCreateCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsServicesVersionsCreateCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsServicesVersionsCreateCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.version)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}/services/{servicesId}/versions")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
"servicesId": c.servicesId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.services.versions.create" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *AppsServicesVersionsCreateCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Deploys code and resource files to a new version.",
// "flatPath": "v1beta/apps/{appsId}/services/{servicesId}/versions",
// "httpMethod": "POST",
// "id": "appengine.apps.services.versions.create",
// "parameterOrder": [
// "appsId",
// "servicesId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `parent`. Name of the parent resource to create this version under. Example: apps/myapp/services/default.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "servicesId": {
// "description": "Part of `parent`. See documentation of `appsId`.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}/services/{servicesId}/versions",
// "request": {
// "$ref": "Version"
// },
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "appengine.apps.services.versions.delete":
type AppsServicesVersionsDeleteCall struct {
s *APIService
appsId string
servicesId string
versionsId string
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Deletes an existing Version resource.
//
// - appsId: Part of `name`. Name of the resource requested. Example:
// apps/myapp/services/default/versions/v1.
// - servicesId: Part of `name`. See documentation of `appsId`.
// - versionsId: Part of `name`. See documentation of `appsId`.
func (r *AppsServicesVersionsService) Delete(appsId string, servicesId string, versionsId string) *AppsServicesVersionsDeleteCall {
c := &AppsServicesVersionsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
c.servicesId = servicesId
c.versionsId = versionsId
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsServicesVersionsDeleteCall) Fields(s ...googleapi.Field) *AppsServicesVersionsDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsServicesVersionsDeleteCall) Context(ctx context.Context) *AppsServicesVersionsDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsServicesVersionsDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsServicesVersionsDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}/services/{servicesId}/versions/{versionsId}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("DELETE", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
"servicesId": c.servicesId,
"versionsId": c.versionsId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.services.versions.delete" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *AppsServicesVersionsDeleteCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Deletes an existing Version resource.",
// "flatPath": "v1beta/apps/{appsId}/services/{servicesId}/versions/{versionsId}",
// "httpMethod": "DELETE",
// "id": "appengine.apps.services.versions.delete",
// "parameterOrder": [
// "appsId",
// "servicesId",
// "versionsId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `name`. Name of the resource requested. Example: apps/myapp/services/default/versions/v1.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "servicesId": {
// "description": "Part of `name`. See documentation of `appsId`.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "versionsId": {
// "description": "Part of `name`. See documentation of `appsId`.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}/services/{servicesId}/versions/{versionsId}",
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "appengine.apps.services.versions.get":
type AppsServicesVersionsGetCall struct {
s *APIService
appsId string
servicesId string
versionsId string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Gets the specified Version resource. By default, only a
// BASIC_VIEW will be returned. Specify the FULL_VIEW parameter to get
// the full resource.
//
// - appsId: Part of `name`. Name of the resource requested. Example:
// apps/myapp/services/default/versions/v1.
// - servicesId: Part of `name`. See documentation of `appsId`.
// - versionsId: Part of `name`. See documentation of `appsId`.
func (r *AppsServicesVersionsService) Get(appsId string, servicesId string, versionsId string) *AppsServicesVersionsGetCall {
c := &AppsServicesVersionsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
c.servicesId = servicesId
c.versionsId = versionsId
return c
}
// View sets the optional parameter "view": Controls the set of fields
// returned in the Get response.
//
// Possible values:
// "BASIC" - Basic version information including scaling and inbound
// services, but not detailed deployment information.
// "FULL" - The information from BASIC, plus detailed information
// about the deployment. This format is required when creating
// resources, but is not returned in Get or List by default.
func (c *AppsServicesVersionsGetCall) View(view string) *AppsServicesVersionsGetCall {
c.urlParams_.Set("view", view)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsServicesVersionsGetCall) Fields(s ...googleapi.Field) *AppsServicesVersionsGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *AppsServicesVersionsGetCall) IfNoneMatch(entityTag string) *AppsServicesVersionsGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsServicesVersionsGetCall) Context(ctx context.Context) *AppsServicesVersionsGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsServicesVersionsGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsServicesVersionsGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}/services/{servicesId}/versions/{versionsId}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
"servicesId": c.servicesId,
"versionsId": c.versionsId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.services.versions.get" call.
// Exactly one of *Version or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Version.ServerResponse.Header or (if a response was returned at all)
// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to
// check whether the returned error was because http.StatusNotModified
// was returned.
func (c *AppsServicesVersionsGetCall) Do(opts ...googleapi.CallOption) (*Version, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Version{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets the specified Version resource. By default, only a BASIC_VIEW will be returned. Specify the FULL_VIEW parameter to get the full resource.",
// "flatPath": "v1beta/apps/{appsId}/services/{servicesId}/versions/{versionsId}",
// "httpMethod": "GET",
// "id": "appengine.apps.services.versions.get",
// "parameterOrder": [
// "appsId",
// "servicesId",
// "versionsId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `name`. Name of the resource requested. Example: apps/myapp/services/default/versions/v1.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "servicesId": {
// "description": "Part of `name`. See documentation of `appsId`.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "versionsId": {
// "description": "Part of `name`. See documentation of `appsId`.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "view": {
// "description": "Controls the set of fields returned in the Get response.",
// "enum": [
// "BASIC",
// "FULL"
// ],
// "enumDescriptions": [
// "Basic version information including scaling and inbound services, but not detailed deployment information.",
// "The information from BASIC, plus detailed information about the deployment. This format is required when creating resources, but is not returned in Get or List by default."
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}/services/{servicesId}/versions/{versionsId}",
// "response": {
// "$ref": "Version"
// },
// "scopes": [
// "https://www.googleapis.com/auth/appengine.admin",
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only"
// ]
// }
}
// method id "appengine.apps.services.versions.list":
type AppsServicesVersionsListCall struct {
s *APIService
appsId string
servicesId string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Lists the versions of a service.
//
// - appsId: Part of `parent`. Name of the parent Service resource.
// Example: apps/myapp/services/default.
// - servicesId: Part of `parent`. See documentation of `appsId`.
func (r *AppsServicesVersionsService) List(appsId string, servicesId string) *AppsServicesVersionsListCall {
c := &AppsServicesVersionsListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
c.servicesId = servicesId
return c
}
// PageSize sets the optional parameter "pageSize": Maximum results to
// return per page.
func (c *AppsServicesVersionsListCall) PageSize(pageSize int64) *AppsServicesVersionsListCall {
c.urlParams_.Set("pageSize", fmt.Sprint(pageSize))
return c
}
// PageToken sets the optional parameter "pageToken": Continuation token
// for fetching the next page of results.
func (c *AppsServicesVersionsListCall) PageToken(pageToken string) *AppsServicesVersionsListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// View sets the optional parameter "view": Controls the set of fields
// returned in the List response.
//
// Possible values:
// "BASIC" - Basic version information including scaling and inbound
// services, but not detailed deployment information.
// "FULL" - The information from BASIC, plus detailed information
// about the deployment. This format is required when creating
// resources, but is not returned in Get or List by default.
func (c *AppsServicesVersionsListCall) View(view string) *AppsServicesVersionsListCall {
c.urlParams_.Set("view", view)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsServicesVersionsListCall) Fields(s ...googleapi.Field) *AppsServicesVersionsListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *AppsServicesVersionsListCall) IfNoneMatch(entityTag string) *AppsServicesVersionsListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsServicesVersionsListCall) Context(ctx context.Context) *AppsServicesVersionsListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsServicesVersionsListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsServicesVersionsListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}/services/{servicesId}/versions")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
"servicesId": c.servicesId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.services.versions.list" call.
// Exactly one of *ListVersionsResponse or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ListVersionsResponse.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *AppsServicesVersionsListCall) Do(opts ...googleapi.CallOption) (*ListVersionsResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ListVersionsResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Lists the versions of a service.",
// "flatPath": "v1beta/apps/{appsId}/services/{servicesId}/versions",
// "httpMethod": "GET",
// "id": "appengine.apps.services.versions.list",
// "parameterOrder": [
// "appsId",
// "servicesId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `parent`. Name of the parent Service resource. Example: apps/myapp/services/default.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "pageSize": {
// "description": "Maximum results to return per page.",
// "format": "int32",
// "location": "query",
// "type": "integer"
// },
// "pageToken": {
// "description": "Continuation token for fetching the next page of results.",
// "location": "query",
// "type": "string"
// },
// "servicesId": {
// "description": "Part of `parent`. See documentation of `appsId`.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "view": {
// "description": "Controls the set of fields returned in the List response.",
// "enum": [
// "BASIC",
// "FULL"
// ],
// "enumDescriptions": [
// "Basic version information including scaling and inbound services, but not detailed deployment information.",
// "The information from BASIC, plus detailed information about the deployment. This format is required when creating resources, but is not returned in Get or List by default."
// ],
// "location": "query",
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}/services/{servicesId}/versions",
// "response": {
// "$ref": "ListVersionsResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/appengine.admin",
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *AppsServicesVersionsListCall) Pages(ctx context.Context, f func(*ListVersionsResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
// method id "appengine.apps.services.versions.patch":
type AppsServicesVersionsPatchCall struct {
s *APIService
appsId string
servicesId string
versionsId string
version *Version
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Patch: Updates the specified Version resource. You can specify the
// following fields depending on the App Engine environment and type of
// scaling that the version resource uses:Standard environment
// instance_class
// (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#Version.FIELDS.instance_class)automatic
// scaling in the standard environment:
// automatic_scaling.min_idle_instances
// (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#Version.FIELDS.automatic_scaling)
// automatic_scaling.max_idle_instances
// (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#Version.FIELDS.automatic_scaling)
// automaticScaling.standard_scheduler_settings.max_instances
// (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#StandardSchedulerSettings)
// automaticScaling.standard_scheduler_settings.min_instances
// (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#StandardSchedulerSettings)
// automaticScaling.standard_scheduler_settings.target_cpu_utilization
// (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#StandardSchedulerSettings)
// automaticScaling.standard_scheduler_settings.target_throughput_utiliza
// tion
// (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#StandardSchedulerSettings)basic
// scaling or manual scaling in the standard environment: serving_status
// (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#Version.FIELDS.serving_status)
// manual_scaling.instances
// (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#manualscaling)Flexible
// environment serving_status
// (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#Version.FIELDS.serving_status)automatic
// scaling in the flexible environment:
// automatic_scaling.min_total_instances
// (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#Version.FIELDS.automatic_scaling)
// automatic_scaling.max_total_instances
// (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#Version.FIELDS.automatic_scaling)
// automatic_scaling.cool_down_period_sec
// (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#Version.FIELDS.automatic_scaling)
// automatic_scaling.cpu_utilization.target_utilization
// (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#Version.FIELDS.automatic_scaling)manual
// scaling in the flexible environment: manual_scaling.instances
// (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#manualscaling)
//
// - appsId: Part of `name`. Name of the resource to update. Example:
// apps/myapp/services/default/versions/1.
// - servicesId: Part of `name`. See documentation of `appsId`.
// - versionsId: Part of `name`. See documentation of `appsId`.
func (r *AppsServicesVersionsService) Patch(appsId string, servicesId string, versionsId string, version *Version) *AppsServicesVersionsPatchCall {
c := &AppsServicesVersionsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
c.servicesId = servicesId
c.versionsId = versionsId
c.version = version
return c
}
// UpdateMask sets the optional parameter "updateMask": Standard field
// mask for the set of fields to be updated.
func (c *AppsServicesVersionsPatchCall) UpdateMask(updateMask string) *AppsServicesVersionsPatchCall {
c.urlParams_.Set("updateMask", updateMask)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsServicesVersionsPatchCall) Fields(s ...googleapi.Field) *AppsServicesVersionsPatchCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsServicesVersionsPatchCall) Context(ctx context.Context) *AppsServicesVersionsPatchCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsServicesVersionsPatchCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsServicesVersionsPatchCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.version)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}/services/{servicesId}/versions/{versionsId}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("PATCH", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
"servicesId": c.servicesId,
"versionsId": c.versionsId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.services.versions.patch" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *AppsServicesVersionsPatchCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Updates the specified Version resource. You can specify the following fields depending on the App Engine environment and type of scaling that the version resource uses:Standard environment instance_class (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#Version.FIELDS.instance_class)automatic scaling in the standard environment: automatic_scaling.min_idle_instances (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#Version.FIELDS.automatic_scaling) automatic_scaling.max_idle_instances (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#Version.FIELDS.automatic_scaling) automaticScaling.standard_scheduler_settings.max_instances (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#StandardSchedulerSettings) automaticScaling.standard_scheduler_settings.min_instances (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#StandardSchedulerSettings) automaticScaling.standard_scheduler_settings.target_cpu_utilization (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#StandardSchedulerSettings) automaticScaling.standard_scheduler_settings.target_throughput_utilization (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#StandardSchedulerSettings)basic scaling or manual scaling in the standard environment: serving_status (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#Version.FIELDS.serving_status) manual_scaling.instances (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#manualscaling)Flexible environment serving_status (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#Version.FIELDS.serving_status)automatic scaling in the flexible environment: automatic_scaling.min_total_instances (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#Version.FIELDS.automatic_scaling) automatic_scaling.max_total_instances (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#Version.FIELDS.automatic_scaling) automatic_scaling.cool_down_period_sec (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#Version.FIELDS.automatic_scaling) automatic_scaling.cpu_utilization.target_utilization (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#Version.FIELDS.automatic_scaling)manual scaling in the flexible environment: manual_scaling.instances (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta/apps.services.versions#manualscaling)",
// "flatPath": "v1beta/apps/{appsId}/services/{servicesId}/versions/{versionsId}",
// "httpMethod": "PATCH",
// "id": "appengine.apps.services.versions.patch",
// "parameterOrder": [
// "appsId",
// "servicesId",
// "versionsId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `name`. Name of the resource to update. Example: apps/myapp/services/default/versions/1.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "servicesId": {
// "description": "Part of `name`. See documentation of `appsId`.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "updateMask": {
// "description": "Standard field mask for the set of fields to be updated.",
// "format": "google-fieldmask",
// "location": "query",
// "type": "string"
// },
// "versionsId": {
// "description": "Part of `name`. See documentation of `appsId`.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}/services/{servicesId}/versions/{versionsId}",
// "request": {
// "$ref": "Version"
// },
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "appengine.apps.services.versions.instances.debug":
type AppsServicesVersionsInstancesDebugCall struct {
s *APIService
appsId string
servicesId string
versionsId string
instancesId string
debuginstancerequest *DebugInstanceRequest
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Debug: Enables debugging on a VM instance. This allows you to use the
// SSH command to connect to the virtual machine where the instance
// lives. While in "debug mode", the instance continues to serve live
// traffic. You should delete the instance when you are done debugging
// and then allow the system to take over and determine if another
// instance should be started.Only applicable for instances in App
// Engine flexible environment.
//
// - appsId: Part of `name`. Name of the resource requested. Example:
// apps/myapp/services/default/versions/v1/instances/instance-1.
// - instancesId: Part of `name`. See documentation of `appsId`.
// - servicesId: Part of `name`. See documentation of `appsId`.
// - versionsId: Part of `name`. See documentation of `appsId`.
func (r *AppsServicesVersionsInstancesService) Debug(appsId string, servicesId string, versionsId string, instancesId string, debuginstancerequest *DebugInstanceRequest) *AppsServicesVersionsInstancesDebugCall {
c := &AppsServicesVersionsInstancesDebugCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
c.servicesId = servicesId
c.versionsId = versionsId
c.instancesId = instancesId
c.debuginstancerequest = debuginstancerequest
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsServicesVersionsInstancesDebugCall) Fields(s ...googleapi.Field) *AppsServicesVersionsInstancesDebugCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsServicesVersionsInstancesDebugCall) Context(ctx context.Context) *AppsServicesVersionsInstancesDebugCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsServicesVersionsInstancesDebugCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsServicesVersionsInstancesDebugCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
body, err := googleapi.WithoutDataWrapper.JSONReader(c.debuginstancerequest)
if err != nil {
return nil, err
}
reqHeaders.Set("Content-Type", "application/json")
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}/services/{servicesId}/versions/{versionsId}/instances/{instancesId}:debug")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("POST", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
"servicesId": c.servicesId,
"versionsId": c.versionsId,
"instancesId": c.instancesId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.services.versions.instances.debug" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *AppsServicesVersionsInstancesDebugCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Enables debugging on a VM instance. This allows you to use the SSH command to connect to the virtual machine where the instance lives. While in \"debug mode\", the instance continues to serve live traffic. You should delete the instance when you are done debugging and then allow the system to take over and determine if another instance should be started.Only applicable for instances in App Engine flexible environment.",
// "flatPath": "v1beta/apps/{appsId}/services/{servicesId}/versions/{versionsId}/instances/{instancesId}:debug",
// "httpMethod": "POST",
// "id": "appengine.apps.services.versions.instances.debug",
// "parameterOrder": [
// "appsId",
// "servicesId",
// "versionsId",
// "instancesId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `name`. Name of the resource requested. Example: apps/myapp/services/default/versions/v1/instances/instance-1.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "instancesId": {
// "description": "Part of `name`. See documentation of `appsId`.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "servicesId": {
// "description": "Part of `name`. See documentation of `appsId`.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "versionsId": {
// "description": "Part of `name`. See documentation of `appsId`.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}/services/{servicesId}/versions/{versionsId}/instances/{instancesId}:debug",
// "request": {
// "$ref": "DebugInstanceRequest"
// },
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "appengine.apps.services.versions.instances.delete":
type AppsServicesVersionsInstancesDeleteCall struct {
s *APIService
appsId string
servicesId string
versionsId string
instancesId string
urlParams_ gensupport.URLParams
ctx_ context.Context
header_ http.Header
}
// Delete: Stops a running instance.The instance might be automatically
// recreated based on the scaling settings of the version. For more
// information, see "How Instances are Managed" (standard environment
// (https://cloud.google.com/appengine/docs/standard/python/how-instances-are-managed)
// | flexible environment
// (https://cloud.google.com/appengine/docs/flexible/python/how-instances-are-managed)).To
// ensure that instances are not re-created and avoid getting billed,
// you can stop all instances within the target version by changing the
// serving status of the version to STOPPED with the
// apps.services.versions.patch
// (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions/patch)
// method.
//
// - appsId: Part of `name`. Name of the resource requested. Example:
// apps/myapp/services/default/versions/v1/instances/instance-1.
// - instancesId: Part of `name`. See documentation of `appsId`.
// - servicesId: Part of `name`. See documentation of `appsId`.
// - versionsId: Part of `name`. See documentation of `appsId`.
func (r *AppsServicesVersionsInstancesService) Delete(appsId string, servicesId string, versionsId string, instancesId string) *AppsServicesVersionsInstancesDeleteCall {
c := &AppsServicesVersionsInstancesDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
c.servicesId = servicesId
c.versionsId = versionsId
c.instancesId = instancesId
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsServicesVersionsInstancesDeleteCall) Fields(s ...googleapi.Field) *AppsServicesVersionsInstancesDeleteCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsServicesVersionsInstancesDeleteCall) Context(ctx context.Context) *AppsServicesVersionsInstancesDeleteCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsServicesVersionsInstancesDeleteCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsServicesVersionsInstancesDeleteCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}/services/{servicesId}/versions/{versionsId}/instances/{instancesId}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("DELETE", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
"servicesId": c.servicesId,
"versionsId": c.versionsId,
"instancesId": c.instancesId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.services.versions.instances.delete" call.
// Exactly one of *Operation or error will be non-nil. Any non-2xx
// status code is an error. Response headers are in either
// *Operation.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *AppsServicesVersionsInstancesDeleteCall) Do(opts ...googleapi.CallOption) (*Operation, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Operation{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Stops a running instance.The instance might be automatically recreated based on the scaling settings of the version. For more information, see \"How Instances are Managed\" (standard environment (https://cloud.google.com/appengine/docs/standard/python/how-instances-are-managed) | flexible environment (https://cloud.google.com/appengine/docs/flexible/python/how-instances-are-managed)).To ensure that instances are not re-created and avoid getting billed, you can stop all instances within the target version by changing the serving status of the version to STOPPED with the apps.services.versions.patch (https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1/apps.services.versions/patch) method.",
// "flatPath": "v1beta/apps/{appsId}/services/{servicesId}/versions/{versionsId}/instances/{instancesId}",
// "httpMethod": "DELETE",
// "id": "appengine.apps.services.versions.instances.delete",
// "parameterOrder": [
// "appsId",
// "servicesId",
// "versionsId",
// "instancesId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `name`. Name of the resource requested. Example: apps/myapp/services/default/versions/v1/instances/instance-1.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "instancesId": {
// "description": "Part of `name`. See documentation of `appsId`.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "servicesId": {
// "description": "Part of `name`. See documentation of `appsId`.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "versionsId": {
// "description": "Part of `name`. See documentation of `appsId`.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}/services/{servicesId}/versions/{versionsId}/instances/{instancesId}",
// "response": {
// "$ref": "Operation"
// },
// "scopes": [
// "https://www.googleapis.com/auth/cloud-platform"
// ]
// }
}
// method id "appengine.apps.services.versions.instances.get":
type AppsServicesVersionsInstancesGetCall struct {
s *APIService
appsId string
servicesId string
versionsId string
instancesId string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// Get: Gets instance information.
//
// - appsId: Part of `name`. Name of the resource requested. Example:
// apps/myapp/services/default/versions/v1/instances/instance-1.
// - instancesId: Part of `name`. See documentation of `appsId`.
// - servicesId: Part of `name`. See documentation of `appsId`.
// - versionsId: Part of `name`. See documentation of `appsId`.
func (r *AppsServicesVersionsInstancesService) Get(appsId string, servicesId string, versionsId string, instancesId string) *AppsServicesVersionsInstancesGetCall {
c := &AppsServicesVersionsInstancesGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
c.servicesId = servicesId
c.versionsId = versionsId
c.instancesId = instancesId
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsServicesVersionsInstancesGetCall) Fields(s ...googleapi.Field) *AppsServicesVersionsInstancesGetCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *AppsServicesVersionsInstancesGetCall) IfNoneMatch(entityTag string) *AppsServicesVersionsInstancesGetCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsServicesVersionsInstancesGetCall) Context(ctx context.Context) *AppsServicesVersionsInstancesGetCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsServicesVersionsInstancesGetCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsServicesVersionsInstancesGetCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}/services/{servicesId}/versions/{versionsId}/instances/{instancesId}")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
"servicesId": c.servicesId,
"versionsId": c.versionsId,
"instancesId": c.instancesId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.services.versions.instances.get" call.
// Exactly one of *Instance or error will be non-nil. Any non-2xx status
// code is an error. Response headers are in either
// *Instance.ServerResponse.Header or (if a response was returned at
// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified
// to check whether the returned error was because
// http.StatusNotModified was returned.
func (c *AppsServicesVersionsInstancesGetCall) Do(opts ...googleapi.CallOption) (*Instance, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &Instance{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Gets instance information.",
// "flatPath": "v1beta/apps/{appsId}/services/{servicesId}/versions/{versionsId}/instances/{instancesId}",
// "httpMethod": "GET",
// "id": "appengine.apps.services.versions.instances.get",
// "parameterOrder": [
// "appsId",
// "servicesId",
// "versionsId",
// "instancesId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `name`. Name of the resource requested. Example: apps/myapp/services/default/versions/v1/instances/instance-1.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "instancesId": {
// "description": "Part of `name`. See documentation of `appsId`.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "servicesId": {
// "description": "Part of `name`. See documentation of `appsId`.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "versionsId": {
// "description": "Part of `name`. See documentation of `appsId`.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}/services/{servicesId}/versions/{versionsId}/instances/{instancesId}",
// "response": {
// "$ref": "Instance"
// },
// "scopes": [
// "https://www.googleapis.com/auth/appengine.admin",
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only"
// ]
// }
}
// method id "appengine.apps.services.versions.instances.list":
type AppsServicesVersionsInstancesListCall struct {
s *APIService
appsId string
servicesId string
versionsId string
urlParams_ gensupport.URLParams
ifNoneMatch_ string
ctx_ context.Context
header_ http.Header
}
// List: Lists the instances of a version.Tip: To aggregate details
// about instances over time, see the Stackdriver Monitoring API
// (https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.timeSeries/list).
//
// - appsId: Part of `parent`. Name of the parent Version resource.
// Example: apps/myapp/services/default/versions/v1.
// - servicesId: Part of `parent`. See documentation of `appsId`.
// - versionsId: Part of `parent`. See documentation of `appsId`.
func (r *AppsServicesVersionsInstancesService) List(appsId string, servicesId string, versionsId string) *AppsServicesVersionsInstancesListCall {
c := &AppsServicesVersionsInstancesListCall{s: r.s, urlParams_: make(gensupport.URLParams)}
c.appsId = appsId
c.servicesId = servicesId
c.versionsId = versionsId
return c
}
// PageSize sets the optional parameter "pageSize": Maximum results to
// return per page.
func (c *AppsServicesVersionsInstancesListCall) PageSize(pageSize int64) *AppsServicesVersionsInstancesListCall {
c.urlParams_.Set("pageSize", fmt.Sprint(pageSize))
return c
}
// PageToken sets the optional parameter "pageToken": Continuation token
// for fetching the next page of results.
func (c *AppsServicesVersionsInstancesListCall) PageToken(pageToken string) *AppsServicesVersionsInstancesListCall {
c.urlParams_.Set("pageToken", pageToken)
return c
}
// Fields allows partial responses to be retrieved. See
// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse
// for more information.
func (c *AppsServicesVersionsInstancesListCall) Fields(s ...googleapi.Field) *AppsServicesVersionsInstancesListCall {
c.urlParams_.Set("fields", googleapi.CombineFields(s))
return c
}
// IfNoneMatch sets the optional parameter which makes the operation
// fail if the object's ETag matches the given value. This is useful for
// getting updates only after the object has changed since the last
// request. Use googleapi.IsNotModified to check whether the response
// error from Do is the result of In-None-Match.
func (c *AppsServicesVersionsInstancesListCall) IfNoneMatch(entityTag string) *AppsServicesVersionsInstancesListCall {
c.ifNoneMatch_ = entityTag
return c
}
// Context sets the context to be used in this call's Do method. Any
// pending HTTP request will be aborted if the provided context is
// canceled.
func (c *AppsServicesVersionsInstancesListCall) Context(ctx context.Context) *AppsServicesVersionsInstancesListCall {
c.ctx_ = ctx
return c
}
// Header returns an http.Header that can be modified by the caller to
// add HTTP headers to the request.
func (c *AppsServicesVersionsInstancesListCall) Header() http.Header {
if c.header_ == nil {
c.header_ = make(http.Header)
}
return c.header_
}
func (c *AppsServicesVersionsInstancesListCall) doRequest(alt string) (*http.Response, error) {
reqHeaders := make(http.Header)
reqHeaders.Set("x-goog-api-client", "gl-go/"+gensupport.GoVersion()+" gdcl/20211027")
for k, v := range c.header_ {
reqHeaders[k] = v
}
reqHeaders.Set("User-Agent", c.s.userAgent())
if c.ifNoneMatch_ != "" {
reqHeaders.Set("If-None-Match", c.ifNoneMatch_)
}
var body io.Reader = nil
c.urlParams_.Set("alt", alt)
c.urlParams_.Set("prettyPrint", "false")
urls := googleapi.ResolveRelative(c.s.BasePath, "v1beta/apps/{appsId}/services/{servicesId}/versions/{versionsId}/instances")
urls += "?" + c.urlParams_.Encode()
req, err := http.NewRequest("GET", urls, body)
if err != nil {
return nil, err
}
req.Header = reqHeaders
googleapi.Expand(req.URL, map[string]string{
"appsId": c.appsId,
"servicesId": c.servicesId,
"versionsId": c.versionsId,
})
return gensupport.SendRequest(c.ctx_, c.s.client, req)
}
// Do executes the "appengine.apps.services.versions.instances.list" call.
// Exactly one of *ListInstancesResponse or error will be non-nil. Any
// non-2xx status code is an error. Response headers are in either
// *ListInstancesResponse.ServerResponse.Header or (if a response was
// returned at all) in error.(*googleapi.Error).Header. Use
// googleapi.IsNotModified to check whether the returned error was
// because http.StatusNotModified was returned.
func (c *AppsServicesVersionsInstancesListCall) Do(opts ...googleapi.CallOption) (*ListInstancesResponse, error) {
gensupport.SetOptions(c.urlParams_, opts...)
res, err := c.doRequest("json")
if res != nil && res.StatusCode == http.StatusNotModified {
if res.Body != nil {
res.Body.Close()
}
return nil, &googleapi.Error{
Code: res.StatusCode,
Header: res.Header,
}
}
if err != nil {
return nil, err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
return nil, err
}
ret := &ListInstancesResponse{
ServerResponse: googleapi.ServerResponse{
Header: res.Header,
HTTPStatusCode: res.StatusCode,
},
}
target := &ret
if err := gensupport.DecodeResponse(target, res); err != nil {
return nil, err
}
return ret, nil
// {
// "description": "Lists the instances of a version.Tip: To aggregate details about instances over time, see the Stackdriver Monitoring API (https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.timeSeries/list).",
// "flatPath": "v1beta/apps/{appsId}/services/{servicesId}/versions/{versionsId}/instances",
// "httpMethod": "GET",
// "id": "appengine.apps.services.versions.instances.list",
// "parameterOrder": [
// "appsId",
// "servicesId",
// "versionsId"
// ],
// "parameters": {
// "appsId": {
// "description": "Part of `parent`. Name of the parent Version resource. Example: apps/myapp/services/default/versions/v1.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "pageSize": {
// "description": "Maximum results to return per page.",
// "format": "int32",
// "location": "query",
// "type": "integer"
// },
// "pageToken": {
// "description": "Continuation token for fetching the next page of results.",
// "location": "query",
// "type": "string"
// },
// "servicesId": {
// "description": "Part of `parent`. See documentation of `appsId`.",
// "location": "path",
// "required": true,
// "type": "string"
// },
// "versionsId": {
// "description": "Part of `parent`. See documentation of `appsId`.",
// "location": "path",
// "required": true,
// "type": "string"
// }
// },
// "path": "v1beta/apps/{appsId}/services/{servicesId}/versions/{versionsId}/instances",
// "response": {
// "$ref": "ListInstancesResponse"
// },
// "scopes": [
// "https://www.googleapis.com/auth/appengine.admin",
// "https://www.googleapis.com/auth/cloud-platform",
// "https://www.googleapis.com/auth/cloud-platform.read-only"
// ]
// }
}
// Pages invokes f for each page of results.
// A non-nil error returned from f will halt the iteration.
// The provided context supersedes any context provided to the Context method.
func (c *AppsServicesVersionsInstancesListCall) Pages(ctx context.Context, f func(*ListInstancesResponse) error) error {
c.ctx_ = ctx
defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point
for {
x, err := c.Do()
if err != nil {
return err
}
if err := f(x); err != nil {
return err
}
if x.NextPageToken == "" {
return nil
}
c.PageToken(x.NextPageToken)
}
}
| NewService |
app-routing.module.ts | import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LoginComponent } from '@app/login/login.component';
import { AdminComponent } from '@app/admin/admin.component';
import { AuthGuardService } from '@core/services';
const routes: Routes = [
{ path: 'login', component: LoginComponent },
{
path: '',
redirectTo: 'dashboard',
pathMatch: 'full',
},
{
path: '',
component: AdminComponent,
canActivateChild: [AuthGuardService],
children: [
{
path: '',
// loadChildren: '@app/admin/admin.module#AdminModule'
loadChildren: () => import('@app/admin/admin.module').then(m => m.AdminModule)
}
]
},
{ path: '**', redirectTo: 'login' },
];
@NgModule({
imports: [RouterModule.forRoot(routes, { useHash: true, relativeLinkResolution: 'legacy'})],
exports: [RouterModule]
})
export class | {}
| AppRoutingModule |
main.rs | use axum::{
extract::{Extension, Path, Query},
handler::Handler,
http::StatusCode,
response::{IntoResponse, Json},
routing::get,
Router,
};
mod endpoints;
mod error;
mod models;
mod schemas;
use mongodb::Client;
use schemas::GetUser;
use serde_json::{json, Value};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let db_client = Client::with_uri_str("mongodb://admin:[email protected]:27017")
.await
.expect("can't connect to database")
.database("production");
// build our application with a single route
let app = Router::new()
.route("/hello-world", get(get_hello_world))
.route("/users/:id_or_email", get(get_user))
.route("/users", get(get_users))
.layer(Extension(db_client));
// 404 fallback service
let app = app.fallback(handler_404.into_service());
// run it with hyper on localhost:3000
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
Ok(())
}
async fn | (Path(id_or_email): Path<String>) -> impl IntoResponse {
let user = schemas::GetUser {
first_name: "Joe".into(),
last_name: "Krywicki".into(),
email: "[email protected]".into(),
id: "0001".into(),
};
let id_or_email = Value::from(id_or_email);
if id_or_email != user.id && id_or_email != user.email {
return (
StatusCode::NOT_FOUND,
Json(
json!({"message": "User not found", "detail": format!("User {} could not be found", id_or_email)}),
),
);
}
(StatusCode::OK, Json(user))
}
async fn get_users() -> impl IntoResponse {
(StatusCode::OK, Json(json!([])))
}
async fn get_hello_world() -> impl IntoResponse {}
async fn handler_404() -> impl IntoResponse {
(
StatusCode::NOT_FOUND,
Json(json!({"message": StatusCode::NOT_FOUND.canonical_reason()})),
)
}
| get_user |
integer.rs | use crate::*;
use alloc::borrow::Cow;
use alloc::vec;
use core::convert::{TryFrom, TryInto};
#[cfg(feature = "bigint")]
#[cfg_attr(docsrs, doc(cfg(feature = "bigint")))]
pub use num_bigint::{BigInt, BigUint, Sign};
/// Decode an unsigned integer into a big endian byte slice with all leading
/// zeroes removed (if positive) and extra 0xff remove (if negative)
fn trim_slice<'a>(any: &'a Any<'_>) -> Result<&'a [u8]> {
let bytes = any.data;
if bytes.is_empty() || (bytes[0] != 0x00 && bytes[0] != 0xff) {
return Ok(bytes);
}
match bytes.iter().position(|&b| b != 0) {
// first byte is not 0
Some(0) => (),
// all bytes are 0
None => return Ok(&bytes[bytes.len() - 1..]),
Some(first) => return Ok(&bytes[first..]),
}
// same for negative integers : skip byte 0->n if byte 0->n = 0xff AND byte n+1 >= 0x80
match bytes.windows(2).position(|s| match s {
&[a, b] => !(a == 0xff && b >= 0x80),
_ => true,
}) {
// first byte is not 0xff
Some(0) => (),
// all bytes are 0xff
None => return Ok(&bytes[bytes.len() - 1..]),
Some(first) => return Ok(&bytes[first..]),
}
Ok(bytes)
}
/// Decode an unsigned integer into a byte array of the requested size
/// containing a big endian integer.
fn decode_array_uint<const N: usize>(any: &Any<'_>) -> Result<[u8; N]> {
if is_highest_bit_set(any.data) {
return Err(Error::IntegerNegative);
}
let input = trim_slice(any)?;
if input.len() > N {
return Err(Error::IntegerTooLarge);
}
// Input has leading zeroes removed, so we need to add them back
let mut output = [0u8; N];
assert!(input.len() <= N);
output[N.saturating_sub(input.len())..].copy_from_slice(input);
Ok(output)
}
/// Decode an unsigned integer of the specified size.
///
/// Returns a byte array of the requested size containing a big endian integer.
fn decode_array_int<const N: usize>(any: &Any<'_>) -> Result<[u8; N]> {
if any.data.len() > N {
return Err(Error::IntegerTooLarge);
}
// any.tag().assert_eq(Tag::Integer)?;
let mut output = [0xFFu8; N];
let offset = N.saturating_sub(any.as_bytes().len());
output[offset..].copy_from_slice(any.as_bytes());
Ok(output)
}
/// Is the highest bit of the first byte in the slice 1? (if present)
#[inline]
fn is_highest_bit_set(bytes: &[u8]) -> bool {
bytes
.get(0)
.map(|byte| byte & 0b10000000 != 0)
.unwrap_or(false)
}
macro_rules! impl_int {
($uint:ty => $int:ty) => {
impl<'a> TryFrom<Any<'a>> for $int {
type Error = Error;
fn try_from(any: Any<'a>) -> Result<Self> {
TryFrom::try_from(&any)
}
}
impl<'a, 'b> TryFrom<&'b Any<'a>> for $int {
type Error = Error;
fn try_from(any: &'b Any<'a>) -> Result<Self> {
any.tag().assert_eq(Self::TAG)?;
any.header.assert_primitive()?;
let result = if is_highest_bit_set(any.as_bytes()) {
<$uint>::from_be_bytes(decode_array_int(&any)?) as $int
} else {
Self::from_be_bytes(decode_array_uint(&any)?)
};
Ok(result)
}
}
impl<'a> CheckDerConstraints for $int {
fn check_constraints(any: &Any) -> Result<()> {
check_der_int_constraints(any)
}
}
impl Tagged for $int {
const TAG: Tag = Tag::Integer;
}
#[cfg(feature = "std")]
impl ToDer for $int {
fn to_der_len(&self) -> Result<usize> {
let int = Integer::from(*self);
int.to_der_len()
}
fn write_der(&self, writer: &mut dyn std::io::Write) -> SerializeResult<usize> {
let int = Integer::from(*self);
int.write_der(writer)
}
fn write_der_header(&self, writer: &mut dyn std::io::Write) -> SerializeResult<usize> {
let int = Integer::from(*self);
int.write_der_header(writer)
}
fn write_der_content(&self, writer: &mut dyn std::io::Write) -> SerializeResult<usize> {
let int = Integer::from(*self);
int.write_der_content(writer)
}
}
};
}
macro_rules! impl_uint {
($ty:ty) => {
impl<'a> TryFrom<Any<'a>> for $ty {
type Error = Error;
fn try_from(any: Any<'a>) -> Result<Self> {
TryFrom::try_from(&any)
}
}
impl<'a, 'b> TryFrom<&'b Any<'a>> for $ty {
type Error = Error;
fn try_from(any: &'b Any<'a>) -> Result<Self> {
any.tag().assert_eq(Self::TAG)?;
any.header.assert_primitive()?;
let result = Self::from_be_bytes(decode_array_uint(any)?);
Ok(result)
}
}
impl<'a> CheckDerConstraints for $ty {
fn check_constraints(any: &Any) -> Result<()> {
check_der_int_constraints(any)
}
}
impl Tagged for $ty {
const TAG: Tag = Tag::Integer;
}
#[cfg(feature = "std")]
impl ToDer for $ty {
fn to_der_len(&self) -> Result<usize> {
let int = Integer::from(*self);
int.to_der_len()
}
fn write_der(&self, writer: &mut dyn std::io::Write) -> SerializeResult<usize> {
let int = Integer::from(*self);
int.write_der(writer)
}
fn write_der_header(&self, writer: &mut dyn std::io::Write) -> SerializeResult<usize> {
let int = Integer::from(*self);
int.write_der_header(writer)
}
fn write_der_content(&self, writer: &mut dyn std::io::Write) -> SerializeResult<usize> {
let int = Integer::from(*self);
int.write_der_content(writer)
}
}
};
}
impl_uint!(u8);
impl_uint!(u16);
impl_uint!(u32);
impl_uint!(u64);
impl_uint!(u128);
impl_int!(u8 => i8);
impl_int!(u16 => i16);
impl_int!(u32 => i32);
impl_int!(u64 => i64);
impl_int!(u128 => i128);
/// ASN.1 `INTEGER` type
///
/// Generic representation for integer types.
/// BER/DER integers can be of any size, so it is not possible to store them as simple integers (they
/// are stored as raw bytes).
///
/// The internal representation can be obtained using `.as_ref()`.
///
/// # Note
///
/// Methods from/to BER and DER encodings are also implemented for primitive types
/// (`u8`, `u16` to `u128`, and `i8` to `i128`).
/// In most cases, it is easier to use these types directly.
///
/// # Examples
///
/// Creating an `Integer`
///
/// ```
/// use asn1_rs::Integer;
///
/// // unsigned
/// let i = Integer::from(4);
/// assert_eq!(i.as_ref(), &[4]);
/// // signed
/// let j = Integer::from(-2);
/// assert_eq!(j.as_ref(), &[0x0, 0xff, 0xff, 0xff, 0xfe]);
/// ```
///
/// Converting an `Integer` to a primitive type (using the `TryInto` trait)
///
/// ```
/// use asn1_rs::{Error, Integer};
/// use std::convert::TryInto;
///
/// let i = Integer::new(&[0x12, 0x34, 0x56, 0x78]);
/// // converts to an u32
/// let n: u32 = i.try_into().unwrap();
///
/// // Same, but converting to an u16: will fail, value cannot fit into an u16
/// let i = Integer::new(&[0x12, 0x34, 0x56, 0x78]);
/// assert_eq!(i.try_into() as Result<u16, _>, Err(Error::IntegerTooLarge));
/// ```
///
/// Encoding an `Integer` to DER
///
/// ```
/// use asn1_rs::{Integer, ToDer};
///
/// let i = Integer::from(4);
/// let v = i.to_der_vec().unwrap();
/// assert_eq!(&v, &[2, 1, 4]);
///
/// // same, with primitive types
/// let v = 4.to_der_vec().unwrap();
/// assert_eq!(&v, &[2, 1, 4]);
/// ```
#[derive(Debug, Eq, PartialEq)]
pub struct Integer<'a> {
pub(crate) data: Cow<'a, [u8]>,
}
impl<'a> Integer<'a> {
/// Creates a new `Integer` containing the given value (borrowed).
#[inline]
pub const fn new(s: &'a [u8]) -> Self {
Integer {
data: Cow::Borrowed(s),
}
}
/// Creates a borrowed `Any` for this object
#[inline]
pub fn any(&'a self) -> Any<'a> {
Any::from_tag_and_data(Self::TAG, &self.data)
}
/// Returns a `BigInt` built from this `Integer` value.
#[cfg(feature = "bigint")]
#[cfg_attr(docsrs, doc(cfg(feature = "bigint")))]
pub fn as_bigint(&self) -> BigInt {
BigInt::from_signed_bytes_be(&self.data)
}
/// Returns a `BigUint` built from this `Integer` value.
#[cfg(feature = "bigint")]
#[cfg_attr(docsrs, doc(cfg(feature = "bigint")))]
pub fn as_biguint(&self) -> Result<BigUint> {
if is_highest_bit_set(&self.data) {
Err(Error::IntegerNegative)
} else {
Ok(BigUint::from_bytes_be(&self.data))
}
}
/// Build an `Integer` from a constant array of bytes representation of an integer.
pub fn from_const_array<const N: usize>(b: [u8; N]) -> Self {
let mut idx = 0;
// skip leading 0s
while idx < b.len() {
if b[idx] == 0 {
idx += 1;
continue;
}
break;
}
if idx == b.len() {
Integer {
data: Cow::Borrowed(&[0]),
}
} else {
Integer {
data: Cow::Owned(b[idx..].to_vec()),
}
}
}
fn from_const_array_negative<const N: usize>(b: [u8; N]) -> Self {
let mut out = vec![0];
out.extend_from_slice(&b);
Integer {
data: Cow::Owned(out),
}
}
}
macro_rules! impl_from_to {
($ty:ty, $sty:expr, $from:ident, $to:ident) => {
impl From<$ty> for Integer<'_> {
fn from(i: $ty) -> Self {
Self::$from(i)
}
}
impl TryFrom<Integer<'_>> for $ty {
type Error = Error;
fn try_from(value: Integer<'_>) -> Result<Self> {
value.$to()
}
}
impl Integer<'_> {
#[doc = "Attempts to convert an `Integer` to a `"]
#[doc = $sty]
#[doc = "`."]
#[doc = ""]
#[doc = "This function returns an `IntegerTooLarge` error if the integer will not fit into the output type."]
pub fn $to(&self) -> Result<$ty> {
self.any().try_into()
}
}
};
(IMPL SIGNED $ty:ty, $sty:expr, $from:ident, $to:ident) => {
impl_from_to!($ty, $sty, $from, $to);
impl Integer<'_> {
#[doc = "Converts a `"]
#[doc = $sty]
#[doc = "` to an `Integer`"]
#[doc = ""]
#[doc = "Note: this function allocates data."]
pub fn $from(i: $ty) -> Self {
let b = i.to_be_bytes();
if i >= 0 {
Self::from_const_array(b)
} else {
Self::from_const_array_negative(b)
}
}
}
};
(IMPL UNSIGNED $ty:ty, $sty:expr, $from:ident, $to:ident) => {
impl_from_to!($ty, $sty, $from, $to);
impl Integer<'_> {
#[doc = "Converts a `"]
#[doc = $sty]
#[doc = "` to an `Integer`"]
#[doc = ""]
#[doc = "Note: this function allocates data."]
pub fn $from(i: $ty) -> Self {
Self::from_const_array(i.to_be_bytes())
}
}
};
(SIGNED $ty:ty, $from:ident, $to:ident) => {
impl_from_to!(IMPL SIGNED $ty, stringify!($ty), $from, $to);
};
(UNSIGNED $ty:ty, $from:ident, $to:ident) => {
impl_from_to!(IMPL UNSIGNED $ty, stringify!($ty), $from, $to);
};
}
impl_from_to!(SIGNED i8, from_i8, as_i8);
impl_from_to!(SIGNED i16, from_i16, as_i16);
impl_from_to!(SIGNED i32, from_i32, as_i32);
impl_from_to!(SIGNED i64, from_i64, as_i64);
impl_from_to!(SIGNED i128, from_i128, as_i128);
impl_from_to!(UNSIGNED u8, from_u8, as_u8);
impl_from_to!(UNSIGNED u16, from_u16, as_u16);
impl_from_to!(UNSIGNED u32, from_u32, as_u32);
impl_from_to!(UNSIGNED u64, from_u64, as_u64);
impl_from_to!(UNSIGNED u128, from_u128, as_u128);
impl<'a> AsRef<[u8]> for Integer<'a> {
fn as_ref(&self) -> &[u8] {
&self.data
}
}
impl<'a> TryFrom<Any<'a>> for Integer<'a> {
type Error = Error;
fn try_from(any: Any<'a>) -> Result<Integer<'a>> {
TryFrom::try_from(&any)
}
}
impl<'a, 'b> TryFrom<&'b Any<'a>> for Integer<'a> {
type Error = Error;
fn try_from(any: &'b Any<'a>) -> Result<Integer<'a>> {
any.tag().assert_eq(Self::TAG)?;
Ok(Integer {
data: Cow::Borrowed(any.data),
})
}
}
impl<'a> CheckDerConstraints for Integer<'a> {
fn check_constraints(any: &Any) -> Result<()> {
check_der_int_constraints(any)
}
}
fn check_der_int_constraints(any: &Any) -> Result<()> {
any.header.assert_primitive()?;
any.header.length.assert_definite()?;
match any.as_bytes() {
[] => Err(Error::DerConstraintFailed(DerConstraint::IntegerEmpty)),
[0] => Ok(()),
// leading zeroes
[0, byte, ..] if *byte < 0x80 => Err(Error::DerConstraintFailed(
DerConstraint::IntegerLeadingZeroes,
)),
// negative integer with non-minimal encoding
[0xff, byte, ..] if *byte >= 0x80 => {
Err(Error::DerConstraintFailed(DerConstraint::IntegerLeadingFF))
}
_ => Ok(()),
}
}
impl<'a> Tagged for Integer<'a> {
const TAG: Tag = Tag::Integer;
}
#[cfg(feature = "std")]
impl ToDer for Integer<'_> {
fn to_der_len(&self) -> Result<usize> {
let sz = self.data.len();
if sz < 127 {
// 1 (class+tag) + 1 (length) + len
Ok(2 + sz)
} else {
// hmm, a very long integer. anyway:
// 1 (class+tag) + n (length) + len
let n = Length::Definite(sz).to_der_len()?;
Ok(1 + n + sz)
}
}
fn write_der_header(&self, writer: &mut dyn std::io::Write) -> SerializeResult<usize> {
let header = Header::new(
Class::Universal,
false,
Self::TAG,
Length::Definite(self.data.len()),
);
header.write_der_header(writer).map_err(Into::into)
}
fn write_der_content(&self, writer: &mut dyn std::io::Write) -> SerializeResult<usize> {
writer.write(&self.data).map_err(Into::into)
}
}
/// Helper macro to declare integers at compile-time
///
/// [`Integer`] stores the encoded representation of the integer, so declaring
/// an integer requires to either use a runtime function or provide the encoded value.
/// This macro simplifies this task by encoding the value.
/// It can be used the following ways:
///
/// - `int!(1234)`: Create a const expression for the corresponding `Integer<'static>`
/// - `int!(raw 1234)`: Return the DER encoded form as a byte array (hex-encoded, big-endian
/// representation from the integer, with leading zeroes removed).
///
/// # Examples
///
/// ```rust
/// use asn1_rs::{int, Integer};
///
/// const INT0: Integer = int!(1234);
/// ```
#[macro_export]
macro_rules! int {
(raw $item:expr) => {
$crate::exports::asn1_rs_impl::encode_int!($item)
};
(rel $item:expr) => {
$crate::exports::asn1_rs_impl::encode_int!(rel $item)
};
($item:expr) => {
$crate::Integer::new(
&$crate::int!(raw $item),
)
};
}
#[cfg(test)]
mod tests {
use crate::{Any, FromDer, Header, Tag};
use std::convert::TryInto;
// Vectors from Section 5.7 of:
// https://luca.ntop.org/Teaching/Appunti/asn1.html
pub(crate) const I0_BYTES: &[u8] = &[0x02, 0x01, 0x00];
pub(crate) const I127_BYTES: &[u8] = &[0x02, 0x01, 0x7F];
pub(crate) const I128_BYTES: &[u8] = &[0x02, 0x02, 0x00, 0x80];
pub(crate) const I256_BYTES: &[u8] = &[0x02, 0x02, 0x01, 0x00];
pub(crate) const INEG128_BYTES: &[u8] = &[0x02, 0x01, 0x80];
pub(crate) const INEG129_BYTES: &[u8] = &[0x02, 0x02, 0xFF, 0x7F];
// Additional vectors
pub(crate) const I255_BYTES: &[u8] = &[0x02, 0x02, 0x00, 0xFF];
pub(crate) const I32767_BYTES: &[u8] = &[0x02, 0x02, 0x7F, 0xFF];
pub(crate) const I65535_BYTES: &[u8] = &[0x02, 0x03, 0x00, 0xFF, 0xFF];
pub(crate) const INEG32768_BYTES: &[u8] = &[0x02, 0x02, 0x80, 0x00];
#[test] | assert_eq!(127, i8::from_der(I127_BYTES).unwrap().1);
assert_eq!(-128, i8::from_der(INEG128_BYTES).unwrap().1);
}
#[test]
fn decode_i16() {
assert_eq!(0, i16::from_der(I0_BYTES).unwrap().1);
assert_eq!(127, i16::from_der(I127_BYTES).unwrap().1);
assert_eq!(128, i16::from_der(I128_BYTES).unwrap().1);
assert_eq!(255, i16::from_der(I255_BYTES).unwrap().1);
assert_eq!(256, i16::from_der(I256_BYTES).unwrap().1);
assert_eq!(32767, i16::from_der(I32767_BYTES).unwrap().1);
assert_eq!(-128, i16::from_der(INEG128_BYTES).unwrap().1);
assert_eq!(-129, i16::from_der(INEG129_BYTES).unwrap().1);
assert_eq!(-32768, i16::from_der(INEG32768_BYTES).unwrap().1);
}
#[test]
fn decode_u8() {
assert_eq!(0, u8::from_der(I0_BYTES).unwrap().1);
assert_eq!(127, u8::from_der(I127_BYTES).unwrap().1);
assert_eq!(255, u8::from_der(I255_BYTES).unwrap().1);
}
#[test]
fn decode_u16() {
assert_eq!(0, u16::from_der(I0_BYTES).unwrap().1);
assert_eq!(127, u16::from_der(I127_BYTES).unwrap().1);
assert_eq!(255, u16::from_der(I255_BYTES).unwrap().1);
assert_eq!(256, u16::from_der(I256_BYTES).unwrap().1);
assert_eq!(32767, u16::from_der(I32767_BYTES).unwrap().1);
assert_eq!(65535, u16::from_der(I65535_BYTES).unwrap().1);
}
/// Integers must be encoded with a minimum number of octets
#[test]
fn reject_non_canonical() {
assert!(i8::from_der(&[0x02, 0x02, 0x00, 0x00]).is_err());
assert!(i16::from_der(&[0x02, 0x02, 0x00, 0x00]).is_err());
assert!(u8::from_der(&[0x02, 0x02, 0x00, 0x00]).is_err());
assert!(u16::from_der(&[0x02, 0x02, 0x00, 0x00]).is_err());
}
#[test]
fn declare_int() {
let int = super::int!(1234);
assert_eq!(int.try_into(), Ok(1234));
}
#[test]
fn trim_slice() {
use super::trim_slice;
let h = Header::new_simple(Tag(0));
// no zero nor ff - nothing to remove
let input: &[u8] = &[0x7f, 0xff, 0x00, 0x02];
assert_eq!(Ok(input), trim_slice(&Any::new(h.clone(), input)));
//
// 0x00
//
// empty - nothing to remove
let input: &[u8] = &[];
assert_eq!(Ok(input), trim_slice(&Any::new(h.clone(), input)));
// one zero - nothing to remove
let input: &[u8] = &[0];
assert_eq!(Ok(input), trim_slice(&Any::new(h.clone(), input)));
// all zeroes - keep only one
let input: &[u8] = &[0, 0, 0];
assert_eq!(Ok(&input[2..]), trim_slice(&Any::new(h.clone(), input)));
// some zeroes - keep only the non-zero part
let input: &[u8] = &[0, 0, 1];
assert_eq!(Ok(&input[2..]), trim_slice(&Any::new(h.clone(), input)));
//
// 0xff
//
// one ff - nothing to remove
let input: &[u8] = &[0xff];
assert_eq!(Ok(input), trim_slice(&Any::new(h.clone(), input)));
// all ff - keep only one
let input: &[u8] = &[0xff, 0xff, 0xff];
assert_eq!(Ok(&input[2..]), trim_slice(&Any::new(h.clone(), input)));
// some ff - keep only the non-zero part
let input: &[u8] = &[0xff, 0xff, 1];
assert_eq!(Ok(&input[1..]), trim_slice(&Any::new(h.clone(), input)));
// some ff and a MSB 1 - keep only the non-zero part
let input: &[u8] = &[0xff, 0xff, 0x80, 1];
assert_eq!(Ok(&input[2..]), trim_slice(&Any::new(h.clone(), input)));
}
} | fn decode_i8() {
assert_eq!(0, i8::from_der(I0_BYTES).unwrap().1); |
continuous_binning.py | """
Optimal piecewise binning for continuous target.
"""
# Guillermo Navas-Palencia <[email protected]>
# Copyright (C) 2020
import time
import numpy as np
from .base import _check_parameters
from .base import BasePWBinning
from .binning_statistics import PWContinuousBinningTable
from .metrics import continuous_metrics
from .transformations import transform_continuous_target
class ContinuousOptimalPWBinning(BasePWBinning):
"""Optimal Piecewise binning of a numerical variable with respect to a
binary target.
Parameters
----------
name : str, optional (default="")
The variable name.
objective : str, optional (default="l2")
The objective function. Supported objectives are "l2", "l1", "huber"
and "quantile". Note that "l1", "huber" and "quantile" are robust
objective functions.
degree : int (default=1)
The degree of the polynomials.
* degree = 0: piecewise constant functions.
* degree = 1: piecewise linear functions.
* degree > 1: piecewise polynomial functions.
continuous : bool (default=True)
Whether to fit a continuous or discontinuous piecewise regression.
prebinning_method : str, optional (default="cart")
The pre-binning method. Supported methods are "cart" for a CART
decision tree, "quantile" to generate prebins with approximately same
frequency and "uniform" to generate prebins with equal width. Method
"cart" uses `sklearn.tree.DecistionTreeClassifier
<https://scikit-learn.org/stable/modules/generated/sklearn.tree.
DecisionTreeClassifier.html>`_.
max_n_prebins : int (default=20)
The maximum number of bins after pre-binning (prebins).
min_prebin_size : float (default=0.05)
The fraction of mininum number of records for each prebin.
min_n_bins : int or None, optional (default=None)
The minimum number of bins. If None, then ``min_n_bins`` is
a value in ``[0, max_n_prebins]``.
max_n_bins : int or None, optional (default=None)
The maximum number of bins. If None, then ``max_n_bins`` is
a value in ``[0, max_n_prebins]``.
min_bin_size : float or None, optional (default=None)
The fraction of minimum number of records for each bin. If None,
``min_bin_size = min_prebin_size``.
max_bin_size : float or None, optional (default=None)
The fraction of maximum number of records for each bin. If None,
``max_bin_size = 1.0``.
monotonic_trend : str or None, optional (default="auto")
The monotonic trend. Supported trends are “auto”, "auto_heuristic" and
"auto_asc_desc" to automatically determine the trend maximizing IV
using a machine learning classifier, "ascending", "descending",
"concave", "convex", "peak" and "peak_heuristic" to allow a peak change
point, and "valley" and "valley_heuristic" to allow a valley change
point. Trends "auto_heuristic", "peak_heuristic" and "valley_heuristic"
use a heuristic to determine the change point, and are significantly
faster for large size instances (``max_n_prebins > 20``). Trend
"auto_asc_desc" is used to automatically select the best monotonic
trend between "ascending" and "descending". If None, then the
monotonic constraint is disabled.
n_subsamples : int or None (default=None)
Number of subsamples to fit the piecewise regression algorithm. If
None, all values are considered.
max_pvalue : float or None, optional (default=0.05)
The maximum p-value among bins. The Z-test is used to detect bins
not satisfying the p-value constraint. Option supported by solvers
"cp" and "mip".
max_pvalue_policy : str, optional (default="consecutive")
The method to determine bins not satisfying the p-value constraint.
Supported methods are "consecutive" to compare consecutive bins and
"all" to compare all bins.
outlier_detector : str or None, optional (default=None)
The outlier detection method. Supported methods are "range" to use
the interquartile range based method or "zcore" to use the modified
Z-score method.
outlier_params : dict or None, optional (default=None)
Dictionary of parameters to pass to the outlier detection method.
user_splits : array-like or None, optional (default=None)
The list of pre-binning split points when ``dtype`` is "numerical" or
the list of prebins when ``dtype`` is "categorical".
user_splits_fixed : array-like or None (default=None)
The list of pre-binning split points that must be fixed.
special_codes : array-like or None, optional (default=None)
List of special codes. Use special codes to specify the data values
that must be treated separately.
split_digits : int or None, optional (default=None)
The significant digits of the split points. If ``split_digits`` is set
to 0, the split points are integers. If None, then all significant
digits in the split points are considered.
solver : str, optional (default="auto")
The optimizer to solve the underlying mathematical optimization
problem. Supported solvers are `"ecos"
<https://github.com/embotech/ecos>`_, `"osqp"
<https://github.com/oxfordcontrol/osqp>`_, "direct", to choose the
direct solver, and "auto", to choose the most appropriate solver for
the problem.
h_epsilon: float (default=1.35)
The parameter h_epsilon used when ``objective="huber"``, controls the
number of samples that should be classified as outliers.
quantile : float (default=0.5)
The parameter quantile is the q-th quantile to be used when
``objective="quantile"``.
regularization: str or None (default=None)
Type of regularization. Supported regularization are "l1" (Lasso) and
"l2" (Ridge). If None, no regularization is applied.
reg_l1 : float (default=1.0)
L1 regularization term. Increasing this value will smooth the
regression model. Only applicable if ``regularization="l1"``.
reg_l2 : float (default=1.0)
L2 regularization term. Increasing this value will smooth the
regression model. Only applicable if ``regularization="l2"``.
random_state : int, RandomState instance or None, (default=None)
If ``n_subsamples < n_samples``, controls the shuffling applied to the
data before applying the split.
verbose : bool (default=False)
Enable verbose output.
"""
def __init__(self, name="", objective="l2", degree=1,
continuous=True, prebinning_method="cart", max_n_prebins=20,
min_prebin_size=0.05, min_n_bins=None, max_n_bins=None,
min_bin_size=None, max_bin_size=None, monotonic_trend="auto",
n_subsamples=None, max_pvalue=None,
max_pvalue_policy="consecutive", outlier_detector=None,
outlier_params=None, user_splits=None, user_splits_fixed=None,
special_codes=None, split_digits=None, solver="auto",
h_epsilon=1.35, quantile=0.5, regularization=None, reg_l1=1.0,
reg_l2=1.0, random_state=None, verbose=False):
super().__init__(name, None, objective, degree, continuous,
prebinning_method, max_n_prebins, min_prebin_size,
min_n_bins, max_n_bins, min_bin_size, max_bin_size,
monotonic_trend, n_subsamples, max_pvalue,
max_pvalue_policy, outlier_detector, outlier_params,
user_splits, user_splits_fixed, special_codes,
split_digits, solver, h_epsilon, quantile,
regularization, reg_l1, reg_l2, random_state, verbose)
self._problem_type = "regression"
self._n_records_missing = None
self._n_records_special = None
self._sum_special = None
self._sum_missing = None
self._std_special = None
self._std_missing = None
self._min_target_missing = None
self._min_target_special = None
self._max_target_missing = None
self._max_target_special = None
self._n_zeros_missing = None
self._n_zeros_special = None
def fit_ | f, x, y, metric_special=0, metric_missing=0,
lb=None, ub=None, check_input=False):
"""Fit the optimal piecewise binning according to the given training
data, then transform it.
Parameters
----------
x : array-like, shape = (n_samples,)
Training vector, where n_samples is the number of samples.
y : array-like, shape = (n_samples,)
Target vector relative to x.
metric_special : float or str (default=0)
The metric value to transform special codes in the input vector.
Supported metrics are "empirical" to use the empirical mean and any
numerical value.
metric_missing : float or str (default=0)
The metric value to transform missing values in the input vector.
Supported metrics are "empirical" to use the empirical mean and any
numerical value.
lb : float or None (default=None)
Avoid values below the lower bound lb.
ub : float or None (default=None)
Avoid values above the upper bound ub.
check_input : bool (default=False)
Whether to check input arrays.
Returns
-------
x_new : numpy array, shape = (n_samples,)
Transformed array.
"""
return self.fit(x, y, check_input).transform(
x, metric_special, metric_missing, lb, ub, check_input)
def transform(self, x, metric_special=0, metric_missing=0,
lb=None, ub=None, check_input=False):
"""Transform given data using bins from the fitted optimal piecewise
binning.
Parameters
----------
x : array-like, shape = (n_samples,)
Training vector, where n_samples is the number of samples.
metric_special : float or str (default=0)
The metric value to transform special codes in the input vector.
Supported metrics are "empirical" to use the empirical mean and any
numerical value.
metric_missing : float or str (default=0)
The metric value to transform missing values in the input vector.
Supported metrics are "empirical" to use the empirical mean and any
numerical value.
lb : float or None (default=None)
Avoid values below the lower bound lb.
ub : float or None (default=None)
Avoid values above the upper bound ub.
check_input : bool (default=False)
Whether to check input arrays.
Returns
-------
x_new : numpy array, shape = (n_samples,)
Transformed array.
"""
self._check_is_fitted()
return transform_continuous_target(
self._optb.splits, x, self._c, lb, ub, self._n_records_special,
self._sum_special, self._n_records_missing, self._sum_missing,
self.special_codes, metric_special, metric_missing, check_input)
def _fit(self, x, y, lb, ub, check_input):
time_init = time.perf_counter()
if self.verbose:
self._logger.info("Optimal piecewise binning started.")
self._logger.info("Options: check parameters.")
_check_parameters(**self.get_params(deep=False), estimator=None,
problem_type=self._problem_type)
# Pre-processing
if self.verbose:
self._logger.info("Pre-processing started.")
self._n_samples = len(x)
if self.verbose:
self._logger.info("Pre-processing: number of samples: {}"
.format(self._n_samples))
time_preprocessing = time.perf_counter()
[x_clean, y_clean, x_missing, y_missing, x_special, y_special,
_, _, _, _, _, _, _] = self._fit_preprocessing(x, y, check_input)
self._time_preprocessing = time.perf_counter() - time_preprocessing
if self.verbose:
n_clean = len(x_clean)
n_missing = len(x_missing)
n_special = len(x_special)
self._logger.info("Pre-processing: number of clean samples: {}"
.format(n_clean))
self._logger.info("Pre-processing: number of missing samples: {}"
.format(n_missing))
self._logger.info("Pre-processing: number of special samples: {}"
.format(n_special))
if self.outlier_detector is not None:
n_outlier = self._n_samples-(n_clean + n_missing + n_special)
self._logger.info("Pre-processing: number of outlier samples: "
"{}".format(n_outlier))
self._logger.info("Pre-processing terminated. Time: {:.4f}s"
.format(self._time_preprocessing))
# Pre-binning
self._time_estimator = 0
# Fit optimal binning algorithm for continuous target. Use optimal
# split points to compute optimal piecewise functions
self._fit_binning(x_clean, y_clean, y_clean, lb, ub)
# Post-processing
if self.verbose:
self._logger.info("Post-processing started.")
self._logger.info("Post-processing: compute binning information.")
time_postprocessing = time.perf_counter()
# Compute n_records and sum for special and missing
self._n_records_special = len(y_special)
self._sum_special = np.sum(y_special)
self._n_zeros_special = np.count_nonzero(y_special == 0)
if len(y_special):
self._std_special = np.std(y_special)
self._min_target_special = np.min(y_special)
self._max_target_special = np.max(y_special)
self._n_records_missing = len(y_missing)
self._sum_missing = np.sum(y_missing)
self._n_zeros_missing = np.count_nonzero(y_missing == 0)
if len(y_missing):
self._std_missing = np.std(y_missing)
self._min_target_missing = np.min(y_missing)
self._max_target_missing = np.max(y_missing)
bt = self._optb.binning_table.build(add_totals=False)
n_records = bt["Count"].values
sums = bt["Sum"].values
stds = bt["Std"].values
min_target = bt["Min"].values
max_target = bt["Max"].values
n_zeros = bt["Zeros count"].values
n_records[self._n_bins] = self._n_records_special
n_records[self._n_bins + 1] = self._n_records_missing
sums[self._n_bins] = self._sum_special
sums[self._n_bins + 1] = self._sum_missing
stds[self._n_bins] = self._std_special
stds[self._n_bins + 1] = self._std_missing
min_target[self._n_bins] = self._min_target_special
min_target[self._n_bins + 1] = self._min_target_missing
max_target[self._n_bins] = self._max_target_special
max_target[self._n_bins + 1] = self._max_target_missing
n_zeros[self._n_bins] = self._n_zeros_special
n_zeros[self._n_bins + 1] = self._n_zeros_missing
# Compute metrics
if self.verbose:
self._logger.info("Post-processing: compute performance metrics.")
d_metrics = continuous_metrics(
x_clean, y_clean, self._optb.splits, self._c, lb, ub,
self._n_records_special, self._sum_special,
self._n_records_missing, self._sum_missing, self.special_codes)
# Binning table
self._binning_table = PWContinuousBinningTable(
self.name, self._optb.splits, self._c, n_records, sums, stds,
min_target, max_target, n_zeros, lb, ub, x_clean.min(),
x_clean.max(), d_metrics)
self._time_postprocessing = time.perf_counter() - time_postprocessing
if self.verbose:
self._logger.info("Post-processing terminated. Time: {:.4f}s"
.format(self._time_postprocessing))
self._time_total = time.perf_counter() - time_init
if self.verbose:
self._logger.info("Optimal piecewise binning terminated. "
"Status: {}. Time: {:.4f}s"
.format(self._status, self._time_total))
# Completed successfully
self._class_logger.close()
self._is_fitted = True
return self
| transform(sel |
doc_trpl_functions_md_0023.rs | fn main() {
fn plus_one(i: i32) -> i32 |
let f = plus_one;
let six = f(5);
}
| { i + 1 } |
playqueue.controller.ts | import {PlayQueue} from './playqueue.model';
import {BodyParams, Controller, Ctx, Get, Post, QueryParams} from '../../modules/rest';
import {UserRole} from '../../types/enums';
import {IncludesTrackArgs} from '../track/track.args';
import {IncludesPlayQueueArgs, PlayQueueSetArgs} from './playqueue.args';
import {IncludesEpisodeArgs} from '../episode/episode.args';
import {Context} from '../../modules/engine/rest/context';
@Controller('/playqueue', {tags: ['PlayQueue'], roles: [UserRole.stream]})
export class | {
@Get('/get',
() => PlayQueue,
{description: 'Get a PlayQueue for the calling user', summary: 'Get PlayQueue'}
)
async get(
@QueryParams() playqueueArgs: IncludesPlayQueueArgs,
@QueryParams() trackArgs: IncludesTrackArgs,
@QueryParams() episodeArgs: IncludesEpisodeArgs,
@Ctx() {orm, engine, user}: Context
): Promise<PlayQueue> {
return engine.transform.playQueue(
orm, await engine.playQueue.get(orm, user),
playqueueArgs, trackArgs, episodeArgs, user
);
}
@Post('/set',
{description: 'Create/update the PlayQueue for the calling user', summary: 'Set PlayQueue'}
)
async set(
@BodyParams() args: PlayQueueSetArgs,
@Ctx() {req, engine, orm, user}: Context
): Promise<void> {
await engine.playQueue.set(orm, args, user, req.session?.client || 'unknown');
}
@Post('/clear',
{description: 'Clear the PlayQueue for the calling user', summary: 'Clear PlayQueue'}
)
async clear(
@Ctx() {orm, engine, user}: Context
): Promise<void> {
await engine.playQueue.clear(orm, user);
}
}
| PlayQueueController |
ReferenceEditor.tsx | import * as React from 'react';
import deepEqual from 'deep-equal';
import { FieldConnector } from '@contentful/field-editor-shared';
import { EntityProvider } from './EntityStore';
import { Action, ActionLabels, FieldExtensionSDK, ViewType } from '../types';
import type { LinkActionsProps } from '../components';
import { CustomCardRenderer, RenderCustomMissingEntityCard } from './customCardTypes';
// TODO: Rename common base for reference/media editors to something neutral,
// e.g. `LinkEditor<T>`.
export interface ReferenceEditorProps {
/**
* Whether or not the field should be disabled initially.
*/
isInitiallyDisabled: boolean;
hasCardEditActions: boolean;
hasCardMoveActions?: boolean;
hasCardRemoveActions?: boolean;
sdk: FieldExtensionSDK;
viewType: ViewType;
renderCustomCard?: CustomCardRenderer;
renderCustomActions?: (props: CustomActionProps) => React.ReactElement;
renderCustomMissingEntityCard?: RenderCustomMissingEntityCard;
getEntityUrl?: (entryId: string) => string;
onAction?: (action: Action) => void;
actionLabels?: Partial<ActionLabels>; | bulkEditing?: boolean;
};
};
}
export type CustomActionProps = LinkActionsProps;
export function ReferenceEditor<T>(
props: ReferenceEditorProps & {
children: FieldConnector<T>['props']['children'];
}
) {
return (
<EntityProvider sdk={props.sdk}>
<FieldConnector<T>
throttle={0}
field={props.sdk.field}
isInitiallyDisabled={props.isInitiallyDisabled}
isEqualValues={(value1, value2) => {
return deepEqual(value1, value2);
}}>
{props.children}
</FieldConnector>
</EntityProvider>
);
}
ReferenceEditor.defaultProps = {
isInitiallyDisabled: true,
hasCardEditActions: true,
}; | parameters: {
instance: {
showCreateEntityAction?: boolean;
showLinkEntityAction?: boolean; |
program.py | # valid ranges
rules = []
while True:
try:
ln = input()
if not ln.strip():
break
rule = [x.split("-") for x in ln.split(": ")[1].split(" or ")] | for r in rule:
rules.append([int(x) for x in r])
except EOFError:
break
while True:
if not input().strip(): break
input()
inval_sum = 0
while True:
try:
ln = input()
vals = ln.split(',')
for v in vals:
if not any(r[0] <= int(v) <= r[1] for r in rules):
inval_sum += int(v)
except EOFError:
break
print(inval_sum) | |
ptr_arith_offset.rs | fn main() {
let v = [1i16, 2];
let x = &v as *const i16; | let x = x.wrapping_offset(1);
assert_eq!(unsafe { *x }, 2);
} |
|
train.py | import sys
import numpy as np
from keras.callbacks import ModelCheckpoint, CSVLogger, LearningRateScheduler
from keras.models import Model
from keras.layers import Input, Activation, Conv1D, BatchNormalization
from keras.optimizers import Adam
from learning_to_adapt.model import LHUC, Renorm
from learning_to_adapt.utils import load_dataset, load_utt_to_spk, load_utt_to_pdfs, load_lda
import keras
import tensorflow as tf
config = tf.ConfigProto()
config.intra_op_parallelism_threads=1
config.inter_op_parallelism_threads=1
keras.backend.tensorflow_backend.set_session(tf.Session(config=config))
def create_model(hidden_dim=350, lda_path=None):
|
if __name__ == '__main__':
train_data = sys.argv[1]
val_data = sys.argv[2]
utt2spk = sys.argv[3]
pdfs = sys.argv[4]
left_context = int(sys.argv[5])
right_context = int(sys.argv[6])
lda_path = sys.argv[7]
output_path = sys.argv[8]
num_epochs = 400
batch_size = 256
learning_rate = 0.0015
utt_to_spk = load_utt_to_spk(utt2spk)
utt_to_pdfs = load_utt_to_pdfs(pdfs)
train_dataset = load_dataset(train_data, utt_to_spk, utt_to_pdfs, chunk_size=8, subsampling_factor=1, left_context=left_context, right_context=right_context)
train_dataset = train_dataset.batch(batch_size, drop_remainder=True)
train_dataset = train_dataset.prefetch(1024)
x, _, y = train_dataset.make_one_shot_iterator().get_next()
val_dataset = load_dataset(val_data, utt_to_spk, utt_to_pdfs, chunk_size=8, subsampling_factor=1, left_context=left_context, right_context=right_context)
val_dataset = val_dataset.batch(batch_size, drop_remainder=True)
val_dataset = val_dataset.take(512).cache().repeat()
val_x, _, val_y = val_dataset.make_one_shot_iterator().get_next()
model = create_model(600, lda_path)
model.compile(
loss='sparse_categorical_crossentropy',
metrics=['accuracy'],
optimizer=Adam(lr=learning_rate, amsgrad=True, clipvalue=1.)
)
callbacks = [
CSVLogger(output_path + "model.csv"),
ModelCheckpoint(filepath=output_path + "model.{epoch:02d}.h5", save_best_only=False, period=10),
ModelCheckpoint(filepath=output_path + "model.best.h5", save_best_only=True),
LearningRateScheduler(lambda epoch, lr: learning_rate - epoch * (learning_rate - learning_rate / 10) / num_epochs, verbose=0)
]
model.fit(x, y,
steps_per_epoch=2000,
epochs=num_epochs,
validation_data=(val_x, val_y),
validation_steps=512,
callbacks=callbacks
)
| lda, bias = load_lda(lda_path)
lda = lda.reshape((5, 40, 200))
feats = Input(shape=(None, 40))
x = Conv1D(200, kernel_size=5, name="lda", trainable=False, weights=[lda, bias])(feats)
layers = [(1, 1), (2, 3), (2, 6), (2, 9), (2, 6), (1, 1)]
for i, (kernel_size, dilation_rate) in enumerate(layers):
name = "tdnn%d" % (i + 1)
x = Conv1D(hidden_dim, kernel_size=kernel_size, dilation_rate=dilation_rate, activation="relu", name="%s.affine" % name)(x)
x = BatchNormalization(name="%s.batchnorm" % name)(x)
x = LHUC(name="lhuc.%s" % name, trainable=False)(x)
y = Conv1D(4208, kernel_size=1, activation="softmax", name="output.affine")(x)
return Model(inputs=[feats], outputs=[y]) |
main.go | package main
import (
"context"
"fmt"
"time"
"github.com/flandiayingman/arkwaifu/internal/app"
"github.com/flandiayingman/arkwaifu/internal/app/updateloop"
log "github.com/sirupsen/logrus"
"go.uber.org/fx"
)
type updateloopTicker struct {
ticker *time.Ticker
done chan struct{}
}
func newUpdateloopTicker() *updateloopTicker {
return &updateloopTicker{
ticker: time.NewTicker(5 * time.Minute),
done: make(chan struct{}),
}
}
func (uc *updateloopTicker) close() {
uc.ticker.Stop()
uc.done <- struct{}{}
}
func | () {
var options []fx.Option
options = append(options, app.ProvideOptions()...)
options = append(options,
fx.Provide(newUpdateloopTicker),
fx.Invoke(run),
)
fxApp := fx.New(options...)
fxApp.Run()
err := fxApp.Start(context.Background())
if err != nil {
panic(err)
}
}
func run(lc fx.Lifecycle, ut *updateloopTicker, uc *updateloop.Service) {
lc.Append(fx.Hook{
OnStart: func(ctx context.Context) error {
go updateResourcesLoop(ut, uc)
return nil
},
OnStop: func(ctx context.Context) error {
ut.close()
return nil
},
})
}
func updateResourcesLoop(ut *updateloopTicker, uc *updateloop.Service) {
// the ticker wouldn't emit a tick instantly, so update resources at first manually
updateResources(uc)
for {
select {
case <-ut.ticker.C:
updateResources(uc)
case <-ut.done:
break
}
}
}
func updateResources(uc *updateloop.Service) {
err := uc.AttemptUpdate(context.Background())
if err != nil {
log.WithField("error", fmt.Sprintf("%+v", err)).
Error("error occurs during update resources")
}
}
| main |
draggable.directive.d.ts | import { EventEmitter, NgZone, OnDestroy, OnInit } from '@angular/core';
import { MapMouseEvent } from 'mapbox-gl';
import { LayerComponent } from '../layer/layer.component';
import { MapService } from '../map/map.service';
import { FeatureComponent } from '../source/geojson/feature.component';
import * as ɵngcc0 from '@angular/core';
export declare class D | implements OnInit, OnDestroy {
private MapService;
private NgZone;
private FeatureComponent?;
layer?: LayerComponent;
featureDragStart: EventEmitter<MapMouseEvent>;
featureDragEnd: EventEmitter<MapMouseEvent>;
featureDrag: EventEmitter<MapMouseEvent>;
/**
* @deprecated Use featureDragStart instead
*/
dragStart: EventEmitter<MapMouseEvent>;
/**
* @deprecated Use featureDragEnd instead
*/
dragEnd: EventEmitter<MapMouseEvent>;
/**
* @deprecated Use featureDrag instead
*/
drag: EventEmitter<MapMouseEvent>;
private sub;
constructor(MapService: MapService, NgZone: NgZone, FeatureComponent?: FeatureComponent | undefined);
ngOnInit(): void;
ngOnDestroy(): void;
private handleDraggable;
private filterFeature;
private warnDeprecatedOutputs;
static ɵfac: ɵngcc0.ɵɵFactoryDef<DraggableDirective, [null, null, { optional: true; host: true; }]>;
static ɵdir: ɵngcc0.ɵɵDirectiveDefWithMeta<DraggableDirective, "[mglDraggable]", never, { "layer": "mglDraggable"; }, { "featureDragStart": "featureDragStart"; "featureDragEnd": "featureDragEnd"; "featureDrag": "featureDrag"; "dragStart": "dragStart"; "dragEnd": "dragEnd"; "drag": "drag"; }, never>;
}
//# sourceMappingURL=draggable.directive.d.ts.map | raggableDirective |
strategy_default.go | package consent
import (
"context"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
"github.com/driver005/oauth/config"
"github.com/ory/x/errorsx"
"github.com/ory/x/sqlcon"
"github.com/gorilla/sessions"
"github.com/pborman/uuid"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/ory/x/sqlxx"
"github.com/ory/x/httpx"
"github.com/ory/fosite"
"github.com/ory/fosite/handler/openid"
"github.com/ory/fosite/token/jwt"
"github.com/ory/x/mapx"
"github.com/ory/x/stringslice"
"github.com/ory/x/stringsx"
"github.com/ory/x/urlx"
"github.com/driver005/oauth/helpers"
"github.com/driver005/oauth/models"
)
const (
CookieAuthenticationName = "oauth2_authentication_session"
CookieAuthenticationSIDName = "sid"
cookieAuthenticationCSRFName = "oauth2_authentication_csrf"
cookieConsentCSRFName = "oauth2_consent_csrf"
)
type DefaultStrategy struct {
c *config.Provider
r InternalRegistry
}
func NewStrategy(
r InternalRegistry,
c *config.Provider,
) *DefaultStrategy |
var ErrAbortOAuth2Request = errors.New("the OAuth 2.0 Authorization request must be aborted")
var ErrNoPreviousConsentFound = errors.New("no previous OAuth 2.0 Consent could be found for this access request")
var ErrNoAuthenticationSessionFound = errors.New("no previous login session was found")
var ErrHintDoesNotMatchAuthentication = errors.New("subject from hint does not match subject from session")
func (s *DefaultStrategy) matchesValueFromSession(ctx context.Context, c fosite.Client, hintSubject string, sessionSubject string) error {
obfuscatedUserID, err := s.obfuscateSubjectIdentifier(c, sessionSubject, "")
if err != nil {
return err
}
var forcedObfuscatedUserID string
if s, err := s.r.ConsentManager().GetForcedObfuscatedLoginSession(ctx, c.GetID(), hintSubject); errors.Is(err, helpers.ErrNotFound) {
// do nothing
} else if err != nil {
return err
} else {
forcedObfuscatedUserID = s.SubjectObfuscated
}
if hintSubject != sessionSubject && hintSubject != obfuscatedUserID && hintSubject != forcedObfuscatedUserID {
return ErrHintDoesNotMatchAuthentication
}
return nil
}
func (s *DefaultStrategy) authenticationSession(w http.ResponseWriter, r *http.Request) (*LoginSession, error) {
// We try to open the session cookie. If it does not exist (indicated by the error), we must authenticate the user.
cookie, err := s.r.CookieStore().Get(r, CookieName(s.c.TLS(config.PublicInterface).Enabled(), CookieAuthenticationName))
if err != nil {
s.r.Logger().
WithRequest(r).
WithError(err).Debug("User logout skipped because cookie store returned an error.")
return nil, errorsx.WithStack(ErrNoAuthenticationSessionFound)
}
sessionID := mapx.GetStringDefault(cookie.Values, CookieAuthenticationSIDName, "")
if sessionID == "" {
s.r.Logger().
WithRequest(r).
Debug("User logout skipped because cookie exists but session value is empty.")
return nil, errorsx.WithStack(ErrNoAuthenticationSessionFound)
}
session, err := s.r.ConsentManager().GetRememberedLoginSession(r.Context(), sessionID)
if errors.Is(err, helpers.ErrNotFound) {
s.r.Logger().WithRequest(r).WithError(err).
Debug("User logout skipped because cookie exists and session value exist but are not remembered any more.")
return nil, errorsx.WithStack(ErrNoAuthenticationSessionFound)
} else if err != nil {
return nil, err
}
return session, nil
}
func (s *DefaultStrategy) requestAuthentication(w http.ResponseWriter, r *http.Request, ar fosite.AuthorizeRequester) error {
prompt := stringsx.Splitx(ar.GetRequestForm().Get("prompt"), " ")
if stringslice.Has(prompt, "login") {
return s.forwardAuthenticationRequest(w, r, ar, "", time.Time{}, nil)
}
session, err := s.authenticationSession(w, r)
if errors.Is(err, ErrNoAuthenticationSessionFound) {
return s.forwardAuthenticationRequest(w, r, ar, "", time.Time{}, nil)
} else if err != nil {
return err
}
maxAge := int64(0)
if ma := ar.GetRequestForm().Get("max_age"); len(ma) > 0 {
var err error
maxAge, err = strconv.ParseInt(ma, 10, 64)
if err != nil {
return err
}
}
if maxAge > 0 && time.Time(session.AuthenticatedAt).UTC().Add(time.Second*time.Duration(maxAge)).Before(time.Now().UTC()) {
if stringslice.Has(prompt, "none") {
return errorsx.WithStack(fosite.ErrLoginRequired.WithHint("Request failed because prompt is set to 'none' and authentication time reached 'max_age'."))
}
return s.forwardAuthenticationRequest(w, r, ar, "", time.Time{}, nil)
}
idTokenHint := ar.GetRequestForm().Get("id_token_hint")
if idTokenHint == "" {
return s.forwardAuthenticationRequest(w, r, ar, session.Subject, time.Time(session.AuthenticatedAt), session)
}
hintSub, err := s.getSubjectFromIDTokenHint(r.Context(), idTokenHint)
if err != nil {
return err
}
if err := s.matchesValueFromSession(r.Context(), ar.GetClient(), hintSub, session.Subject); errors.Is(err, ErrHintDoesNotMatchAuthentication) {
return errorsx.WithStack(fosite.ErrLoginRequired.WithHint("Request failed because subject claim from id_token_hint does not match subject from authentication session."))
}
return s.forwardAuthenticationRequest(w, r, ar, session.Subject, time.Time(session.AuthenticatedAt), session)
}
func (s *DefaultStrategy) getIDTokenHintClaims(ctx context.Context, idTokenHint string) (jwt.MapClaims, error) {
token, err := s.r.OpenIDJWTStrategy().Decode(ctx, idTokenHint)
if ve := new(jwt.ValidationError); errors.As(err, &ve) && ve.Errors == jwt.ValidationErrorExpired {
// Expired is ok
} else if err != nil {
return nil, errorsx.WithStack(fosite.ErrInvalidRequest.WithHint(err.Error()))
}
return token.Claims, nil
}
func (s *DefaultStrategy) getSubjectFromIDTokenHint(ctx context.Context, idTokenHint string) (string, error) {
claims, err := s.getIDTokenHintClaims(ctx, idTokenHint)
if err != nil {
return "", err
}
sub, _ := claims["sub"].(string)
if sub == "" {
return "", errorsx.WithStack(fosite.ErrInvalidRequest.WithHint("Failed to validate OpenID Connect request because provided id token from id_token_hint does not have a subject."))
}
return sub, nil
}
func (s *DefaultStrategy) forwardAuthenticationRequest(w http.ResponseWriter, r *http.Request, ar fosite.AuthorizeRequester, subject string, authenticatedAt time.Time, session *LoginSession) error {
if (subject != "" && authenticatedAt.IsZero()) || (subject == "" && !authenticatedAt.IsZero()) {
return errorsx.WithStack(fosite.ErrServerError.WithHint("Consent strategy returned a non-empty subject with an empty auth date, or an empty subject with a non-empty auth date."))
}
skip := false
if subject != "" {
skip = true
}
// Let'id validate that prompt is actually not "none" if we can't skip authentication
prompt := stringsx.Splitx(ar.GetRequestForm().Get("prompt"), " ")
if stringslice.Has(prompt, "none") && !skip {
return errorsx.WithStack(fosite.ErrLoginRequired.WithHint(`Prompt 'none' was requested, but no existing login session was found.`))
}
// Set up csrf/challenge/verifier values
verifier := strings.Replace(uuid.New(), "-", "", -1)
challenge := strings.Replace(uuid.New(), "-", "", -1)
csrf := strings.Replace(uuid.New(), "-", "", -1)
// Generate the request URL
iu := s.c.OAuth2AuthURL()
iu.RawQuery = r.URL.RawQuery
var idTokenHintClaims jwt.MapClaims
if idTokenHint := ar.GetRequestForm().Get("id_token_hint"); len(idTokenHint) > 0 {
claims, err := s.getIDTokenHintClaims(r.Context(), idTokenHint)
if err != nil {
return err
}
idTokenHintClaims = claims
}
sessionID := uuid.New()
if session != nil {
sessionID = session.ID
} else {
// Create a stub session so that we can later update it.
if err := s.r.ConsentManager().CreateLoginSession(r.Context(), &LoginSession{ID: sessionID}); err != nil {
return err
}
}
// Set the session
if err := s.r.ConsentManager().CreateLoginRequest(
r.Context(),
&LoginRequest{
ID: challenge,
Verifier: verifier,
CSRF: csrf,
Skip: skip,
RequestedScope: []string(ar.GetRequestedScopes()),
RequestedAudience: []string(ar.GetRequestedAudience()),
Subject: subject,
Client: sanitizeClientFromRequest(ar),
RequestURL: iu.String(),
AuthenticatedAt: sqlxx.NullTime(authenticatedAt),
RequestedAt: time.Now().Truncate(time.Second).UTC(),
SessionID: sqlxx.NullString(sessionID),
OpenIDConnectContext: &OpenIDConnectContext{
IDTokenHintClaims: idTokenHintClaims,
ACRValues: stringsx.Splitx(ar.GetRequestForm().Get("acr_values"), " "),
UILocales: stringsx.Splitx(ar.GetRequestForm().Get("ui_locales"), " "),
Display: ar.GetRequestForm().Get("display"),
LoginHint: ar.GetRequestForm().Get("login_hint"),
},
},
); err != nil {
return errorsx.WithStack(err)
}
if err := createCsrfSession(w, r, s.r.CookieStore(), cookieAuthenticationCSRFName, csrf, s.c.TLS(config.PublicInterface).Enabled(), s.c.CookieSameSiteMode(), s.c.CookieSameSiteLegacyWorkaround()); err != nil {
return errorsx.WithStack(err)
}
http.Redirect(w, r, urlx.SetQuery(s.c.LoginURL(), url.Values{"login_challenge": {challenge}}).String(), http.StatusFound)
// generate the verifier
return errorsx.WithStack(ErrAbortOAuth2Request)
}
func (s *DefaultStrategy) revokeAuthenticationSession(w http.ResponseWriter, r *http.Request) error {
sid, err := s.revokeAuthenticationCookie(w, r, s.r.CookieStore())
if err != nil {
return err
}
if sid == "" {
return nil
}
return s.r.ConsentManager().DeleteLoginSession(r.Context(), sid)
}
func (s *DefaultStrategy) revokeAuthenticationCookie(w http.ResponseWriter, r *http.Request, ss sessions.Store) (string, error) {
cookie, _ := ss.Get(r, CookieName(s.c.TLS(config.PublicInterface).Enabled(), CookieAuthenticationName))
sid, _ := mapx.GetString(cookie.Values, CookieAuthenticationSIDName)
cookie.Values[CookieAuthenticationSIDName] = ""
cookie.Options.HttpOnly = true
cookie.Options.SameSite = s.c.CookieSameSiteMode()
cookie.Options.Secure = s.c.TLS(config.PublicInterface).Enabled()
cookie.Options.MaxAge = -1
if err := cookie.Save(r, w); err != nil {
return "", errorsx.WithStack(err)
}
return sid, nil
}
func (s *DefaultStrategy) obfuscateSubjectIdentifier(cl fosite.Client, subject, forcedIdentifier string) (string, error) {
if c, ok := cl.(*models.Client); ok && c.SubjectType == "pairwise" {
algorithm, ok := s.r.SubjectIdentifierAlgorithm()[c.SubjectType]
if !ok {
return "", errorsx.WithStack(fosite.ErrInvalidRequest.WithHintf(`Subject Identifier Algorithm '%s' was requested by OAuth 2.0 Client '%s' but is not configured.`, c.SubjectType, c.OutfacingID))
}
if len(forcedIdentifier) > 0 {
return forcedIdentifier, nil
}
return algorithm.Obfuscate(subject, c)
} else if !ok {
return "", errors.New("Unable to type assert OAuth 2.0 Client to *client.Client")
}
return subject, nil
}
func (s *DefaultStrategy) verifyAuthentication(w http.ResponseWriter, r *http.Request, req fosite.AuthorizeRequester, verifier string) (*HandledLoginRequest, error) {
ctx := r.Context()
session, err := s.r.ConsentManager().VerifyAndInvalidateLoginRequest(ctx, verifier)
if errors.Is(err, sqlcon.ErrNoRows) {
return nil, errorsx.WithStack(fosite.ErrAccessDenied.WithHint("The login verifier has already been used, has not been granted, or is invalid."))
} else if err != nil {
return nil, err
}
if session.HasError() {
session.Error.SetDefaults(loginRequestDeniedErrorName)
return nil, errorsx.WithStack(session.Error.toRFCError())
}
if session.RequestedAt.Add(s.c.ConsentRequestMaxAge()).Before(time.Now()) {
return nil, errorsx.WithStack(fosite.ErrRequestUnauthorized.WithHint("The login request has expired. Please try again."))
}
if err := validateCsrfSession(r, s.r.CookieStore(), cookieAuthenticationCSRFName, session.LoginRequest.CSRF, s.c.CookieSameSiteLegacyWorkaround(), s.c.TLS(config.PublicInterface).Enabled()); err != nil {
return nil, err
}
if session.LoginRequest.Skip && !session.Remember {
return nil, errorsx.WithStack(fosite.ErrServerError.WithHint("The login request was previously remembered and can only be forgotten using the reject feature."))
}
if session.LoginRequest.Skip && session.Subject != session.LoginRequest.Subject {
// Revoke the session because there's clearly a mix up wrt the subject that's being authenticated
if err := s.revokeAuthenticationSession(w, r); err != nil {
return nil, err
}
return nil, errorsx.WithStack(fosite.ErrServerError.WithHint("The login request is marked as remember, but the subject from the login confirmation does not match the original subject from the cookie."))
}
subjectIdentifier, err := s.obfuscateSubjectIdentifier(req.GetClient(), session.Subject, session.ForceSubjectIdentifier)
if err != nil {
return nil, err
}
sessionID := session.LoginRequest.SessionID.String()
if err := s.r.OpenIDConnectRequestValidator().ValidatePrompt(ctx, &fosite.AuthorizeRequest{
ResponseTypes: req.GetResponseTypes(),
RedirectURI: req.GetRedirectURI(),
State: req.GetState(),
// HandledResponseTypes, this can be safely ignored because it's not being used by validation
Request: fosite.Request{
ID: req.GetID(),
RequestedAt: req.GetRequestedAt(),
Client: req.GetClient(),
RequestedAudience: req.GetRequestedAudience(),
GrantedAudience: req.GetGrantedAudience(),
RequestedScope: req.GetRequestedScopes(),
GrantedScope: req.GetGrantedScopes(),
Form: req.GetRequestForm(),
Session: &openid.DefaultSession{
Claims: &jwt.IDTokenClaims{
Subject: subjectIdentifier,
IssuedAt: time.Now().UTC(), // doesn't matter
ExpiresAt: time.Now().Add(time.Hour).UTC(), // doesn't matter
AuthTime: time.Time(session.AuthenticatedAt),
RequestedAt: session.RequestedAt,
},
Headers: &jwt.Headers{},
Subject: session.Subject,
},
},
}); errors.Is(err, fosite.ErrLoginRequired) {
// This indicates that something went wrong with checking the subject id - let's destroy the session to be safe
if err := s.revokeAuthenticationSession(w, r); err != nil {
return nil, err
}
return nil, err
} else if err != nil {
return nil, err
}
if session.ForceSubjectIdentifier != "" {
if err := s.r.ConsentManager().CreateForcedObfuscatedLoginSession(r.Context(), &ForcedObfuscatedLoginSession{
Subject: session.Subject,
ClientID: req.GetClient().GetID(),
SubjectObfuscated: session.ForceSubjectIdentifier,
}); err != nil {
return nil, err
}
}
if !session.LoginRequest.Skip {
if time.Time(session.AuthenticatedAt).IsZero() {
return nil, errorsx.WithStack(fosite.ErrServerError.WithHint("Expected the handled login request to contain a valid authenticated_at value but it was zero. This is a bug which should be reported to https://github.com/ory/hydra."))
}
if err := s.r.ConsentManager().ConfirmLoginSession(r.Context(), sessionID, time.Time(session.AuthenticatedAt), session.Subject, session.Remember); err != nil {
return nil, err
}
}
if !session.Remember && !session.LoginRequest.Skip {
// If the session should not be remembered (and we're actually not skipping), than the user clearly don't
// wants us to store a cookie. So let's bust the authentication session (if one exists).
if err := s.revokeAuthenticationSession(w, r); err != nil {
return nil, err
}
}
if !session.Remember || session.LoginRequest.Skip {
// If the user doesn't want to remember the session, we do not store a cookie.
// If login was skipped, it means an authentication cookie was present and
// we don't want to touch it (in order to preserve its original expiry date)
return session, nil
}
// Not a skipped login and the user asked to remember its session, store a cookie
cookie, _ := s.r.CookieStore().Get(r, CookieName(s.c.TLS(config.PublicInterface).Enabled(), CookieAuthenticationName))
cookie.Values[CookieAuthenticationSIDName] = sessionID
if session.RememberFor >= 0 {
cookie.Options.MaxAge = session.RememberFor
}
cookie.Options.HttpOnly = true
cookie.Options.SameSite = s.c.CookieSameSiteMode()
cookie.Options.Secure = s.c.TLS(config.PublicInterface).Enabled()
if err := cookie.Save(r, w); err != nil {
return nil, errorsx.WithStack(err)
}
s.r.Logger().WithRequest(r).
WithFields(logrus.Fields{
"cookie_name": CookieName(s.c.TLS(config.PublicInterface).Enabled(), CookieAuthenticationName),
"cookie_http_only": true,
"cookie_same_site": s.c.CookieSameSiteMode(),
"cookie_secure": s.c.TLS(config.PublicInterface).Enabled(),
}).Debug("Authentication session cookie was set.")
return session, nil
}
func (s *DefaultStrategy) requestConsent(w http.ResponseWriter, r *http.Request, ar fosite.AuthorizeRequester, authenticationSession *HandledLoginRequest) error {
prompt := stringsx.Splitx(ar.GetRequestForm().Get("prompt"), " ")
if stringslice.Has(prompt, "consent") {
return s.forwardConsentRequest(w, r, ar, authenticationSession, nil)
}
// https://tools.ietf.org/html/rfc6749
//
// As stated in Section 10.2 of OAuth 2.0 [RFC6749], the authorization
// server SHOULD NOT process authorization requests automatically
// without user consent or interaction, except when the identity of the
// client can be assured. This includes the case where the user has
// previously approved an authorization request for a given client id --
// unless the identity of the client can be proven, the request SHOULD
// be processed as if no previous request had been approved.
//
// Measures such as claimed "https" scheme redirects MAY be accepted by
// authorization servers as identity proof. Some operating systems may
// offer alternative platform-specific identity features that MAY be
// accepted, as appropriate.
if ar.GetClient().IsPublic() {
// The OpenID Connect Test Tool fails if this returns `consent_required` when `prompt=none` is used.
// According to the quote above, it should be ok to allow https to skip consent.
//
// This is tracked as issue: https://github.com/ory/hydra/issues/866
// This is also tracked as upstream issue: https://github.com/openid-certification/oidctest/issues/97
if !(ar.GetRedirectURI().Scheme == "https" || (fosite.IsLocalhost(ar.GetRedirectURI()) && ar.GetRedirectURI().Scheme == "http")) {
return s.forwardConsentRequest(w, r, ar, authenticationSession, nil)
}
}
// This breaks OIDC Conformity Tests and is probably a bit paranoid.
//
// if ar.GetResponseTypes().Has("token") {
// // We're probably requesting the implicit or hybrid flow in which case we MUST authenticate and authorize the request
// return s.forwardConsentRequest(w, r, ar, authenticationSession, nil)
// }
consentSessions, err := s.r.ConsentManager().FindGrantedAndRememberedConsentRequests(r.Context(), ar.GetClient().GetID(), authenticationSession.Subject)
if errors.Is(err, ErrNoPreviousConsentFound) {
return s.forwardConsentRequest(w, r, ar, authenticationSession, nil)
} else if err != nil {
return err
}
if found := matchScopes(s.r.ScopeStrategy(), consentSessions, ar.GetRequestedScopes()); found != nil {
return s.forwardConsentRequest(w, r, ar, authenticationSession, found)
}
return s.forwardConsentRequest(w, r, ar, authenticationSession, nil)
}
func (s *DefaultStrategy) forwardConsentRequest(w http.ResponseWriter, r *http.Request, ar fosite.AuthorizeRequester, as *HandledLoginRequest, cs *HandledConsentRequest) error {
skip := false
if cs != nil {
skip = true
}
prompt := stringsx.Splitx(ar.GetRequestForm().Get("prompt"), " ")
if stringslice.Has(prompt, "none") && !skip {
return errorsx.WithStack(fosite.ErrConsentRequired.WithHint(`Prompt 'none' was requested, but no previous consent was found.`))
}
// Set up csrf/challenge/verifier values
verifier := strings.Replace(uuid.New(), "-", "", -1)
challenge := strings.Replace(uuid.New(), "-", "", -1)
csrf := strings.Replace(uuid.New(), "-", "", -1)
if err := s.r.ConsentManager().CreateConsentRequest(
r.Context(),
&ConsentRequest{
ID: challenge,
ACR: as.ACR,
Verifier: verifier,
CSRF: csrf,
Skip: skip,
RequestedScope: []string(ar.GetRequestedScopes()),
RequestedAudience: []string(ar.GetRequestedAudience()),
Subject: as.Subject,
Client: sanitizeClientFromRequest(ar),
RequestURL: as.LoginRequest.RequestURL,
AuthenticatedAt: as.AuthenticatedAt,
RequestedAt: as.RequestedAt,
ForceSubjectIdentifier: as.ForceSubjectIdentifier,
OpenIDConnectContext: as.LoginRequest.OpenIDConnectContext,
LoginSessionID: as.LoginRequest.SessionID,
LoginChallenge: sqlxx.NullString(as.LoginRequest.ID),
Context: as.Context,
},
); err != nil {
return errorsx.WithStack(err)
}
if err := createCsrfSession(w, r, s.r.CookieStore(), cookieConsentCSRFName, csrf, s.c.TLS(config.PublicInterface).Enabled(), s.c.CookieSameSiteMode(), s.c.CookieSameSiteLegacyWorkaround()); err != nil {
return errorsx.WithStack(err)
}
http.Redirect(
w, r,
urlx.SetQuery(s.c.ConsentURL(), url.Values{"consent_challenge": {challenge}}).String(),
http.StatusFound,
)
// generate the verifier
return errorsx.WithStack(ErrAbortOAuth2Request)
}
func (s *DefaultStrategy) verifyConsent(w http.ResponseWriter, r *http.Request, req fosite.AuthorizeRequester, verifier string) (*HandledConsentRequest, error) {
session, err := s.r.ConsentManager().VerifyAndInvalidateConsentRequest(r.Context(), verifier)
if errors.Is(err, sqlcon.ErrNoRows) {
return nil, errorsx.WithStack(fosite.ErrAccessDenied.WithHint("The consent verifier has already been used, has not been granted, or is invalid."))
} else if err != nil {
return nil, err
}
if session.RequestedAt.Add(s.c.ConsentRequestMaxAge()).Before(time.Now()) {
return nil, errorsx.WithStack(fosite.ErrRequestUnauthorized.WithHint("The consent request has expired, please try again."))
}
if session.HasError() {
session.Error.SetDefaults(consentRequestDeniedErrorName)
return nil, errorsx.WithStack(session.Error.toRFCError())
}
if time.Time(session.ConsentRequest.AuthenticatedAt).IsZero() {
return nil, errorsx.WithStack(fosite.ErrServerError.WithHint("The authenticatedAt value was not set."))
}
if err := validateCsrfSession(r, s.r.CookieStore(), cookieConsentCSRFName, session.ConsentRequest.CSRF, s.c.CookieSameSiteLegacyWorkaround(), s.c.TLS(config.PublicInterface).Enabled()); err != nil {
return nil, err
}
pw, err := s.obfuscateSubjectIdentifier(req.GetClient(), session.ConsentRequest.Subject, session.ConsentRequest.ForceSubjectIdentifier)
if err != nil {
return nil, err
}
if session.Session == nil {
session.Session = NewConsentRequestSessionData()
}
if session.Session.AccessToken == nil {
session.Session.AccessToken = map[string]interface{}{}
}
if session.Session.IDToken == nil {
session.Session.IDToken = map[string]interface{}{}
}
session.ConsentRequest.SubjectIdentifier = pw
session.AuthenticatedAt = session.ConsentRequest.AuthenticatedAt
return session, nil
}
func (s *DefaultStrategy) generateFrontChannelLogoutURLs(ctx context.Context, subject, sid string) ([]string, error) {
clients, err := s.r.ConsentManager().ListUserAuthenticatedClientsWithFrontChannelLogout(ctx, subject, sid)
if err != nil {
return nil, err
}
var urls []string
for _, c := range clients {
u, err := url.Parse(c.FrontChannelLogoutURI)
if err != nil {
return nil, errorsx.WithStack(fosite.ErrServerError.WithHintf("Unable to parse frontchannel_logout_uri because %s.", c.FrontChannelLogoutURI).WithDebug(err.Error()))
}
urls = append(urls, urlx.SetQuery(u, url.Values{
"iss": {s.c.IssuerURL().String()},
"sid": {sid},
}).String())
}
return urls, nil
}
func (s *DefaultStrategy) executeBackChannelLogout(ctx context.Context, r *http.Request, subject, sid string) error {
clients, err := s.r.ConsentManager().ListUserAuthenticatedClientsWithBackChannelLogout(ctx, subject, sid)
if err != nil {
return err
}
openIDKeyID, err := s.r.OpenIDJWTStrategy().GetPublicKeyID(ctx)
if err != nil {
return err
}
type task struct {
url string
token string
clientID string
}
var tasks []task
for _, c := range clients {
// Getting the forced obfuscated login session is tricky because the user id could be obfuscated with a new
// ID every time the algorithm is used. Thus, we would only get the most recent version. It therefore makes
// sense to just use the sid.
//
// s.r.ConsentManager().GetForcedObfuscatedLoginSession(context.Background(), subject, <missing>)
// sub := s.obfuscateSubjectIdentifier(c, subject, )
t, _, err := s.r.OpenIDJWTStrategy().Generate(ctx, jwt.MapClaims{
"iss": s.c.IssuerURL().String(),
"aud": []string{c.OutfacingID},
"iat": time.Now().UTC().Unix(),
"jti": uuid.New(),
"events": map[string]struct{}{"http://schemas.openid.net/event/backchannel-logout": {}},
"sid": sid,
}, &jwt.Headers{
Extra: map[string]interface{}{"kid": openIDKeyID},
})
if err != nil {
return err
}
tasks = append(tasks, task{url: c.BackChannelLogoutURI, clientID: c.OutfacingID, token: t})
}
var wg sync.WaitGroup
hc := httpx.NewResilientClient()
wg.Add(len(tasks))
var execute = func(t task) {
defer wg.Done()
res, err := hc.PostForm(t.url, url.Values{"logout_token": {t.token}})
if err != nil {
s.r.Logger().WithRequest(r).WithError(err).
WithField("client_id", t.clientID).
WithField("backchannel_logout_url", t.url).
Error("Unable to execute OpenID Connect Back-Channel Logout Request")
return
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
s.r.Logger().WithError(errors.Errorf("expected HTTP status code %d but got %d", http.StatusOK, res.StatusCode)).
WithRequest(r).
WithField("client_id", t.clientID).
WithField("backchannel_logout_url", t.url).
Error("Unable to execute OpenID Connect Back-Channel Logout Request")
return
}
}
for _, t := range tasks {
go execute(t)
}
wg.Wait()
return nil
}
func (s *DefaultStrategy) issueLogoutVerifier(w http.ResponseWriter, r *http.Request) (*LogoutResult, error) {
// There are two types of log out flows:
//
// - RP initiated logout
// - OP initiated logout
// Per default, we're redirecting to the global redirect URL. This is assuming that we're not an RP-initiated
// logout flow.
redir := s.c.LogoutRedirectURL().String()
if err := r.ParseForm(); err != nil {
return nil, errorsx.WithStack(fosite.ErrInvalidRequest.
WithHintf("Logout failed because the '%s' request could not be parsed.", r.Method),
)
}
hint := r.Form.Get("id_token_hint")
state := r.Form.Get("state")
requestedRedir := r.Form.Get("post_logout_redirect_uri")
if len(hint) == 0 {
// hint is not set, so this is an OP initiated logout
if len(state) > 0 {
// state can only be set if it's an RP-initiated logout flow. If not, we should throw an error.
return nil, errorsx.WithStack(fosite.ErrInvalidRequest.WithHint("Logout failed because query parameter state is set but id_token_hint is missing."))
}
if len(requestedRedir) > 0 {
// post_logout_redirect_uri can only be set if it's an RP-initiated logout flow. If not, we should throw an error.
return nil, errorsx.WithStack(fosite.ErrInvalidRequest.WithHint("Logout failed because query parameter post_logout_redirect_uri is set but id_token_hint is missing."))
}
session, err := s.authenticationSession(w, r)
if errors.Is(err, ErrNoAuthenticationSessionFound) {
// OP initiated log out but no session was found. Since we can not identify the user we can not call
// any RPs.
s.r.AuditLogger().
WithRequest(r).
Info("User logout skipped because no authentication session exists.")
http.Redirect(w, r, redir, http.StatusFound)
return nil, errorsx.WithStack(ErrAbortOAuth2Request)
} else if err != nil {
return nil, err
}
challenge := uuid.New()
if err := s.r.ConsentManager().CreateLogoutRequest(r.Context(), &LogoutRequest{
RequestURL: r.URL.String(),
ID: challenge,
Subject: session.Subject,
SessionID: session.ID,
Verifier: uuid.New(),
RPInitiated: false,
// PostLogoutRedirectURI is set to the value from config.Provider().LogoutRedirectURL()
PostLogoutRedirectURI: redir,
}); err != nil {
return nil, err
}
s.r.AuditLogger().
WithRequest(r).
Info("User logout requires user confirmation, redirecting to Logout UI.")
http.Redirect(w, r, urlx.SetQuery(s.c.LogoutURL(), url.Values{"logout_challenge": {challenge}}).String(), http.StatusFound)
return nil, errorsx.WithStack(ErrAbortOAuth2Request)
}
claims, err := s.getIDTokenHintClaims(r.Context(), hint)
if err != nil {
return nil, err
}
mksi := mapx.KeyStringToInterface(claims)
if !claims.VerifyIssuer(s.c.IssuerURL().String(), true) {
return nil, errorsx.WithStack(fosite.ErrInvalidRequest.
WithHintf(
`Logout failed because issuer claim value '%s' from query parameter id_token_hint does not match with issuer value from configuration '%s'.`,
mapx.GetStringDefault(mksi, "iss", ""),
s.c.IssuerURL().String(),
),
)
}
now := time.Now().UTC().Unix()
if !claims.VerifyIssuedAt(now, true) {
return nil, errorsx.WithStack(fosite.ErrInvalidRequest.
WithHintf(
`Logout failed because iat claim value '%.0f' from query parameter id_token_hint is before now ('%d').`,
mapx.GetFloat64Default(mksi, "iat", float64(0)),
now,
),
)
}
hintSid := mapx.GetStringDefault(mksi, "sid", "")
if len(hintSid) == 0 {
return nil, errorsx.WithStack(fosite.ErrInvalidRequest.WithHint("Logout failed because query parameter id_token_hint is missing sid claim."))
}
// It doesn't really make sense to use the subject value from the ID Token because it might be obfuscated.
if hintSub := mapx.GetStringDefault(mksi, "sub", ""); len(hintSub) == 0 {
return nil, errorsx.WithStack(fosite.ErrInvalidRequest.WithHint("Logout failed because query parameter id_token_hint is missing sub claim."))
}
// Let's find the client by cycling through the audiences. Typically, we only have one audience
var cl *models.Client
for _, aud := range mapx.GetStringSliceDefault(
mksi,
"aud",
[]string{
mapx.GetStringDefault(mksi, "aud", ""),
},
) {
c, err := s.r.ClientManager().GetConcreteClient(r.Context(), aud)
if errors.Is(err, helpers.ErrNotFound) {
continue
} else if err != nil {
return nil, err
}
cl = c
break
}
if cl == nil {
return nil, errorsx.WithStack(fosite.ErrInvalidRequest.
WithHint("Logout failed because none of the listed audiences is a registered OAuth 2.0 Client."))
}
if len(requestedRedir) > 0 {
var f *url.URL
for _, w := range cl.PostLogoutRedirectURIs {
if w == requestedRedir {
u, err := url.Parse(w)
if err != nil {
return nil, errorsx.WithStack(fosite.ErrServerError.WithHintf("Unable to parse post_logout_redirect_uri '%s'.", w).WithDebug(err.Error()))
}
f = u
}
}
if f == nil {
return nil, errorsx.WithStack(fosite.ErrInvalidRequest.
WithHint("Logout failed because query parameter post_logout_redirect_uri is not a whitelisted as a post_logout_redirect_uri for the client."),
)
}
params := url.Values{}
if state != "" {
params.Add("state", state)
}
redir = urlx.SetQuery(f, params).String()
}
// We do not really want to verify if the user (from id token hint) has a session here because it doesn't really matter.
// Instead, we'll check this when we're actually revoking the cookie!
session, err := s.r.ConsentManager().GetRememberedLoginSession(r.Context(), hintSid)
if errors.Is(err, helpers.ErrNotFound) {
// Such a session does not exist - maybe it has already been revoked? In any case, we can't do much except
// leaning back and redirecting back.
http.Redirect(w, r, redir, http.StatusFound)
return nil, errorsx.WithStack(ErrAbortOAuth2Request)
} else if err != nil {
return nil, err
}
challenge := uuid.New()
if err := s.r.ConsentManager().CreateLogoutRequest(r.Context(), &LogoutRequest{
RequestURL: r.URL.String(),
ID: challenge,
SessionID: hintSid,
Subject: session.Subject,
Verifier: uuid.New(),
Client: cl,
RPInitiated: true,
// PostLogoutRedirectURI is set to the value from config.Provider().LogoutRedirectURL()
PostLogoutRedirectURI: redir,
}); err != nil {
return nil, err
}
http.Redirect(w, r, urlx.SetQuery(s.c.LogoutURL(), url.Values{"logout_challenge": {challenge}}).String(), http.StatusFound)
return nil, errorsx.WithStack(ErrAbortOAuth2Request)
}
func (s *DefaultStrategy) completeLogout(w http.ResponseWriter, r *http.Request) (*LogoutResult, error) {
verifier := r.URL.Query().Get("logout_verifier")
lr, err := s.r.ConsentManager().VerifyAndInvalidateLogoutRequest(r.Context(), verifier)
if err != nil {
return nil, err
}
if !lr.RPInitiated {
// If this is true it means that no id_token_hint was given, so the session id and subject id
// came from an original cookie.
session, err := s.authenticationSession(w, r)
if errors.Is(err, ErrNoAuthenticationSessionFound) {
// If we end up here it means that the cookie was revoked between the initial logout request
// and ending up here - possibly due to a duplicate submit. In that case, we really have nothing to
// do because the logout was already completed, apparently!
// We also won't call any front- or back-channel logouts because that would mean we had called them twice!
// OP initiated log out but no session was found. So let's just redirect back...
http.Redirect(w, r, lr.PostLogoutRedirectURI, http.StatusFound)
return nil, errorsx.WithStack(ErrAbortOAuth2Request)
} else if err != nil {
return nil, err
}
if session.Subject != lr.Subject {
// If we end up here it means that the authentication cookie changed between the initial logout request
// and landing here. That could happen because the user signed in in another browser window. In that
// case there isn't really a lot to do because we don't want to sign out a different ID, so let's just
// go to the post redirect uri without actually doing anything!
http.Redirect(w, r, lr.PostLogoutRedirectURI, http.StatusFound)
return nil, errorsx.WithStack(ErrAbortOAuth2Request)
}
}
_, _ = s.revokeAuthenticationCookie(w, r, s.r.CookieStore()) // Cookie removal is optional
urls, err := s.generateFrontChannelLogoutURLs(r.Context(), lr.Subject, lr.SessionID)
if err != nil {
return nil, err
}
if err := s.executeBackChannelLogout(r.Context(), r, lr.Subject, lr.SessionID); err != nil {
return nil, err
}
// We delete the session after back channel log out has worked as the session is otherwise removed
// from the store which will break the query for finding all the channels.
//
// executeBackChannelLogout only fails on system errors so not on URL errors, so this should be fine
// even if an upstream URL fails!
if err := s.r.ConsentManager().DeleteLoginSession(r.Context(), lr.SessionID); errors.Is(err, sqlcon.ErrNoRows) {
// This is ok (session probably already revoked), do nothing!
} else if err != nil {
return nil, err
}
s.r.AuditLogger().
WithRequest(r).
WithField("subject", lr.Subject).
Info("User logout completed!")
return &LogoutResult{
RedirectTo: lr.PostLogoutRedirectURI,
FrontChannelLogoutURLs: urls,
}, nil
}
func (s *DefaultStrategy) HandleOpenIDConnectLogout(w http.ResponseWriter, r *http.Request) (*LogoutResult, error) {
verifier := r.URL.Query().Get("logout_verifier")
if verifier == "" {
return s.issueLogoutVerifier(w, r)
}
return s.completeLogout(w, r)
}
func (s *DefaultStrategy) HandleOAuth2AuthorizationRequest(w http.ResponseWriter, r *http.Request, req fosite.AuthorizeRequester) (*HandledConsentRequest, error) {
authenticationVerifier := strings.TrimSpace(req.GetRequestForm().Get("login_verifier"))
consentVerifier := strings.TrimSpace(req.GetRequestForm().Get("consent_verifier"))
if authenticationVerifier == "" && consentVerifier == "" {
// ok, we need to process this request and redirect to auth endpoint
return nil, s.requestAuthentication(w, r, req)
} else if authenticationVerifier != "" {
authSession, err := s.verifyAuthentication(w, r, req, authenticationVerifier)
if err != nil {
return nil, err
}
// ok, we need to process this request and redirect to auth endpoint
return nil, s.requestConsent(w, r, req, authSession)
}
consentSession, err := s.verifyConsent(w, r, req, consentVerifier)
if err != nil {
return nil, err
}
return consentSession, nil
}
| {
return &DefaultStrategy{
c: c,
r: r,
}
} |
channel.js | const User = require("../models/User");
const Channel = require("../models/Channel");
exports.addChannel = async (req, res, next) => {
const channelData = req.body.channelData;
const userId = req.user._id;
const username = req.user.username;
channelData.owner = {
userId: userId,
username: username,
};
channelData.members = [
{
userId: userId,
username: username,
},
];
if (channelData && userId) {
try {
const userChannelsUpdate = await User.findOneAndUpdate(
{ _id: userId }, | {
$push: {
channels: {
channelId: channelData.channelId,
channelName: channelData.name,
favorite: false,
},
},
},
{ new: true }
);
const channelNew = new Channel(channelData);
await channelNew.save((result) => {
console.log(result);
});
return res.status(200).json(userChannelsUpdate.channels);
} catch (error) {
return res.status(500).json({ err: error.message + "xD" });
}
}
};
exports.getAllChannels = async (req, res, next) => {
try {
const channels = await Channel.find().select(
"channelId name description owner"
);
return res.status(200).json(channels);
} catch (error) {
return res.status(500).json(error.message);
}
};
exports.getUserChannels = async (req, res, next) => {
const userId = req.user._id;
if (userId) {
try {
const channels = await User.findById(userId);
return res.status(200).json(channels.channels);
} catch (error) {
return res.status(500).json(error.message);
}
}
};
exports.starChannel = async (req, res, next) => {
const userId = req.user._id;
const channelId = req.body.channId;
const favoriteStan = req.body.favoriteStan;
if (userId && channelId) {
try {
await User.findOneAndUpdate(
{ _id: userId, "channels.channelId": channelId },
{
$set: {
"channels.$.favorite": !favoriteStan,
},
},
{ new: true }
);
return res.status(200).json({ msg: "Channel added to favorites" });
} catch (error) {
return res.status(500).json({ err: error.message + "xD" });
}
}
};
exports.newMessage = async (req, res, next) => {
const userId = req.user._id;
const username = req.user.username;
const messageData = req.body.newMessage;
if (messageData) {
const channel = await getChannel(req, res);
const date = new Date().toLocaleDateString();
const channelMsgs = channel.messagesByDate;
const sameDateMessages = channelMsgs.find((chDate) => chDate.date === date);
messageData.from = { userId: userId, username: username };
if (sameDateMessages) {
sameDateMessages.messages.push(messageData);
} else {
const newDateMessages = {
date: date,
messages: [messageData],
};
channelMsgs.push(newDateMessages);
}
try {
await channel.save();
return res.status(200).json({ msg: "Message sent successfully" });
} catch (error) {
return res.status(500).json({ err: error.message });
}
}
};
exports.joinChannel = async (req, res) => {
const channelData = req.body.channelData;
const userId = req.user._id;
const username = req.user.username;
if (channelData && userId && username) {
try {
const userChannelsUpdate = await User.findOneAndUpdate(
{ _id: userId },
{
$push: {
channels: channelData,
},
},
{ new: true }
);
console.log(channelData.channelId);
const channelMembersUpdate = await Channel.findOneAndUpdate(
{ channelId: channelData.channelId },
{
$push: {
members: {
userId: userId,
username: username,
},
},
},
{ new: true }
);
const data = {
usrChannels: userChannelsUpdate.channels,
channelMembers: channelMembersUpdate.members,
channelData: channelData,
};
return res.status(200).json(data);
} catch (error) {
return res.status(500).json({ err: error.message });
}
}
};
exports.leaveChannel = async (req, res) => {
const userId = req.user._id;
const activeChannel = req.body;
if (activeChannel && userId) {
try {
await User.findOneAndUpdate(
{ _id: userId },
{
$pull: {
channels: { channelId: activeChannel.channelId },
},
}
);
await Channel.findOneAndUpdate(
{ channelId: activeChannel.channelId },
{
$pull: {
members: { userId: userId },
},
$unset: {
"owner.userId": { userId: userId },
},
}
);
return res.status(200).json({ response: "Channel left" });
} catch (error) {
return res.status(500).json({ err: error.message });
}
}
};
exports.getExactChannel = async (req, res) => {
const channelId = req.params.channelId;
try {
const exactChannel = await Channel.findOne({ channelId: channelId });
return res.status(200).json({ channel: exactChannel });
} catch (error) {
return res.status(500).json({ err: error.message });
}
};
const getChannel = async (req, res) => {
const channelId = req.body.channId;
try {
const exactChannel = await Channel.findOne({ channelId: channelId });
return exactChannel;
} catch (error) {
return res.status(500).json({ err: error.message });
}
}; | |
ImageViewing.tsx | /**
* Copyright (c) JOB TODAY S.A. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import React, { ComponentType, useCallback, useEffect } from "react";
import {
Animated,
Dimensions,
StyleSheet,
View,
VirtualizedList,
ModalProps,
Modal,
} from "react-native";
import ImageItem from "./components/ImageItem/ImageItem";
import ImageDefaultHeader from "./components/ImageDefaultHeader";
import StatusBarManager from "./components/StatusBarManager";
import useAnimatedComponents from "./hooks/useAnimatedComponents";
import useImageIndexChange from "./hooks/useImageIndexChange";
import useRequestClose from "./hooks/useRequestClose";
import { ImageSource } from "./@types";
type Props = {
images: ImageSource[];
imageIndex: number;
visible: boolean;
onRequestClose: () => void;
onLongPress?: (image: ImageSource) => void;
onImageIndexChange?: (imageIndex: number) => void;
presentationStyle?: ModalProps["presentationStyle"];
animationType?: ModalProps["animationType"];
backgroundColor?: string;
swipeToCloseEnabled?: boolean;
doubleTapToZoomEnabled?: boolean;
delayLongPress?: number;
HeaderComponent?: ComponentType<{ imageIndex: number }>;
FooterComponent?: ComponentType<{ imageIndex: number }>;
};
const DEFAULT_ANIMATION_TYPE = "fade";
const DEFAULT_BG_COLOR = "#000";
const DEFAULT_DELAY_LONG_PRESS = 800;
const SCREEN = Dimensions.get("screen");
const SCREEN_WIDTH = SCREEN.width;
function ImageViewing({
images,
imageIndex,
visible,
onRequestClose,
onLongPress = () => {},
onImageIndexChange,
animationType = DEFAULT_ANIMATION_TYPE,
backgroundColor = DEFAULT_BG_COLOR,
presentationStyle,
swipeToCloseEnabled,
doubleTapToZoomEnabled,
delayLongPress = DEFAULT_DELAY_LONG_PRESS,
HeaderComponent,
FooterComponent,
}: Props) {
const imageList = React.createRef<VirtualizedList<ImageSource>>();
const [opacity, onRequestCloseEnhanced] = useRequestClose(onRequestClose);
const [currentImageIndex, onScroll] = useImageIndexChange(imageIndex, SCREEN);
const [
headerTransform,
footerTransform,
toggleBarsVisible,
] = useAnimatedComponents();
useEffect(() => {
if (onImageIndexChange) {
onImageIndexChange(currentImageIndex);
}
}, [currentImageIndex]);
const onZoom = useCallback(
(isScaled: boolean) => {
// @ts-ignore
imageList?.current?.setNativeProps({ scrollEnabled: !isScaled });
toggleBarsVisible(!isScaled);
},
[imageList],
);
if (!visible) {
return null;
}
return (
<Modal
transparent={presentationStyle === "overFullScreen"}
visible={visible}
presentationStyle={presentationStyle}
animationType={animationType}
onRequestClose={onRequestCloseEnhanced}
supportedOrientations={["portrait"]}
hardwareAccelerated
>
<StatusBarManager presentationStyle={presentationStyle} />
<View style={[styles.container, { opacity, backgroundColor }]}>
<Animated.View style={[styles.header, { transform: headerTransform }]}>
{typeof HeaderComponent !== "undefined"
? (
React.createElement(HeaderComponent, {
imageIndex: currentImageIndex,
})
)
: (
<ImageDefaultHeader onRequestClose={onRequestCloseEnhanced} />
)}
</Animated.View>
<VirtualizedList
ref={imageList}
data={images}
horizontal
pagingEnabled
windowSize={2}
initialNumToRender={1}
maxToRenderPerBatch={1}
showsHorizontalScrollIndicator={false}
showsVerticalScrollIndicator={false}
initialScrollIndex={imageIndex}
getItem={(_, index) => images[index]}
getItemCount={() => images.length}
getItemLayout={(_, index) => ({
length: SCREEN_WIDTH,
offset: SCREEN_WIDTH * index,
index,
})}
renderItem={({ item: imageSrc }) => (
<ImageItem
onZoom={onZoom}
imageSrc={imageSrc}
onRequestClose={onRequestCloseEnhanced}
onLongPress={onLongPress}
delayLongPress={delayLongPress}
swipeToCloseEnabled={swipeToCloseEnabled} | doubleTapToZoomEnabled={doubleTapToZoomEnabled}
/>
)}
onMomentumScrollEnd={onScroll}
//@ts-ignore
keyExtractor={(imageSrc) => imageSrc.uri || `${imageSrc}`}
/>
{typeof FooterComponent !== "undefined" && (
<Animated.View
style={[styles.footer, { transform: footerTransform }]}
>
{React.createElement(FooterComponent, {
imageIndex: currentImageIndex,
})}
</Animated.View>
)}
</View>
</Modal>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#000",
},
header: {
position: "absolute",
width: "100%",
zIndex: 1,
top: 0,
},
footer: {
position: "absolute",
width: "100%",
zIndex: 1,
bottom: 0,
},
});
const EnhancedImageViewing = (props: Props) => (
<ImageViewing key={props.imageIndex} {...props} />
);
export default EnhancedImageViewing; | |
index.js | import countryList from "./country-names.json!";
import uniqueRandomArray from 'unique-random-array';
//let log = console.log.bind(console);
let countryInfoArray = countryList.countries.country;
let targetCountry = uniqueRandomArray(countryInfoArray)();
export function random () {
return targetCountry.countryName + ': ' + targetCountry.countryCode;
}
export function | () {
let tempArr = [];
countryInfoArray.forEach(x => {
tempArr.push(x.countryName);
});
return tempArr;
} | all |
pythontask.py | from tasks.models import Task, TaskTaken
from issues.models import Issue
from django.conf import settings
from django.db.models import Q
from django.db import transaction
from django.shortcuts import render_to_response, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from django.utils.translation import ugettext_lazy as _
import datetime
class PythonTaskStat(object):
def __init__(self, course_tasks):
self.tasks = course_tasks
self.group_stat = {}
self.course_stat = {
'total': 0.0,
'active_students': 0,
'avg_score': 0.0,
}
def update(self, group):
self._group_update(group)
self._course_update(group)
def get_group_stat(self):
return [(group, stat['student_stat']) for (group, stat) in self.group_stat.iteritems()]
def get_course_stat(self):
stat = [
(group, stat['total'], stat['active_students'], stat['avg_score'])
for (group, stat) in self.group_stat.iteritems()
]
stat.append(
(None, self.course_stat['total'], self.course_stat['active_students'], self.course_stat['avg_score'])
)
return stat
def _student_stat(self, tasks):
total = 0.0
tasks_list = []
for task in tasks:
total += task.score
tasks_list.append((task.task, task.score))
return (total, tasks_list)
def _group_update(self, group):
stat = {
'total': 0.0,
'active_students': 0,
'avg_score': 0.0,
'student_stat': [],
}
group_students = []
for student in group.students.filter(is_active=True).order_by('last_name', 'first_name'):
tasks = TaskTaken.objects.filter(user=student).filter(task__in=self.tasks) \
.filter(Q(Q(status=TaskTaken.STATUS_TAKEN) | Q(status=TaskTaken.STATUS_SCORED)))
if tasks.count() > 0:
stat['active_students'] += 1
scores, student_tasks = self._student_stat(tasks)
group_students.append((student, scores, student_tasks))
stat['total'] += scores
stat['student_stat'] = group_students
if stat['active_students'] > 0:
stat['avg_score'] = stat['total'] / stat['active_students']
self.group_stat[group] = stat
def _course_update(self, group):
stat = self.group_stat[group]
self.course_stat['total'] += stat['total']
self.course_stat['active_students'] += stat['active_students']
if self.course_stat['active_students'] > 0:
self.course_stat['avg_score'] = self.course_stat['total'] / self.course_stat['active_students']
else:
self.course_stat['avg_score'] = 0.0
def tasks_list(request, course):
user = request.user
course.can_edit = course.user_can_edit_course(user)
delta = datetime.timedelta(days=settings.PYTHONTASK_MAX_DAYS_WITHOUT_SCORES)
task_and_task_taken = []
for task in Task.objects.filter(course=course).filter(parent_task=None).order_by('title'):
task.add_user_properties(user)
if task.task_text is None:
task.task_text = ''
task_taken_list = []
for task_taken in TaskTaken.objects.filter(task=task).exclude(task__is_hidden=True).filter(
Q(Q(status=TaskTaken.STATUS_TAKEN) | Q(status=TaskTaken.STATUS_SCORED))):
if settings.PYTHONTASK_MAX_DAYS_WITHOUT_SCORES and task_taken.status == TaskTaken.STATUS_TAKEN:
task_taken.cancel_date = task_taken.taken_time + delta
task_taken_list.append(task_taken)
if task.has_subtasks():
subtask_and_task_takens = []
for subtask in Task.objects.filter(parent_task=task).order_by('title'):
subtask.add_user_properties(user)
if subtask.task_text is None:
subtask.task_text = ''
subtask_takens = list(TaskTaken.objects.filter(task=subtask).exclude(task__is_hidden=True).exclude(
task__parent_task__is_hidden=True).filter(
Q(Q(status=TaskTaken.STATUS_TAKEN) | Q(status=TaskTaken.STATUS_SCORED))))
if settings.PYTHONTASK_MAX_DAYS_WITHOUT_SCORES:
for subtask_taken in filter(lambda x: x.status == TaskTaken.STATUS_TAKEN, subtask_takens):
subtask_taken.cancel_date = subtask_taken.taken_time + delta
subtask_and_task_takens.append((subtask, subtask_takens))
task_and_task_taken.append((task, subtask_and_task_takens))
else:
task_and_task_taken.append((task, task_taken_list))
context = {
'course': course,
'user': user,
'tasks_taken': task_and_task_taken,
'user_is_teacher': course.user_is_teacher(user),
'STATUS_TAKEN': TaskTaken.STATUS_TAKEN,
'STATUS_SCORED': TaskTaken.STATUS_SCORED,
}
return render_to_response('course_tasks_potok.html', context, context_instance=RequestContext(request))
def python_stat(request, course):
tasks = Task.objects.filter(course=course)
stat = PythonTaskStat(tasks)
for group in course.groups.all().order_by('name'):
stat.update(group)
context = {
'course': course,
'group_stat': stat.get_group_stat(),
'course_stat': stat.get_course_stat()
}
return render_to_response('statistics.html', context, context_instance=RequestContext(request))
@login_required
@transaction.commit_on_success
def get_task(request, course_id, task_id):
user = request.user
task = get_object_or_404(Task, id=task_id)
user_can_take_task, reason = task.user_can_take_task(user)
if user_can_take_task:
task_taken, created = TaskTaken.objects.get_or_create(user=user, task=task)
task_taken.take()
|
task_taken.issue.add_comment(unicode(_("zapisalsya_na_task")))
return redirect('courses.views.course_page', course_id=course_id)
@login_required
def cancel_task(request, course_id, task_id):
user = request.user
task = get_object_or_404(Task, id=task_id)
if task.user_can_cancel_task(user):
task_taken = get_object_or_404(TaskTaken, user=user, task=task)
task_taken.cancel()
if not task_taken.issue:
issue, created = Issue.objects.get_or_create(task=task, student=user)
task_taken.issue = issue
task_taken.save()
task_taken.issue.add_comment(u"{} {} {}".format(user.first_name, user.last_name, _("otkazalsya_ot_taska")))
return redirect('courses.views.course_page', course_id=course_id) | if not task_taken.issue:
issue, created = Issue.objects.get_or_create(task=task, student=user)
task_taken.issue = issue
task_taken.save() |
test_particle_conserving_u2.py | # Copyright 2018-2021 Xanadu Quantum Technologies Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Unit tests for the ParticleConservingU2 template.
"""
import pytest
import numpy as np
import pennylane as qml
from pennylane import numpy as pnp
class TestDecomposition:
"""Tests that the template defines the correct decomposition."""
@pytest.mark.parametrize(
"layers, qubits, init_state",
[
(2, 4, np.array([1, 1, 0, 0])),
(1, 6, np.array([1, 1, 0, 0, 0, 0])),
(1, 5, np.array([1, 1, 0, 0, 0])),
],
)
def test_operations(self, layers, qubits, init_state):
"""Test the correctness of the ParticleConservingU2 template including the gate count
and order, the wires each operation acts on and the correct use of parameters
in the circuit."""
weights = np.random.normal(0, 2 * np.pi, (layers, 2 * qubits - 1))
n_gates = 1 + (qubits + (qubits - 1) * 3) * layers
exp_gates = (
[qml.RZ] * qubits + ([qml.CNOT] + [qml.CRX] + [qml.CNOT]) * (qubits - 1)
) * layers
op = qml.templates.ParticleConservingU2(weights, wires=range(qubits), init_state=init_state)
queue = op.expand().operations
# number of gates
assert len(queue) == n_gates
# initialization
assert isinstance(queue[0], qml.BasisState)
# order of gates
for op1, op2 in zip(queue[1:], exp_gates):
assert isinstance(op1, op2)
# gate parameter
params = np.array(
[queue[i].parameters for i in range(1, n_gates) if queue[i].parameters != []]
)
weights[:, qubits:] = weights[:, qubits:] * 2
assert np.allclose(params.flatten(), weights.flatten())
# gate wires
wires = range(qubits)
nm_wires = [wires[l : l + 2] for l in range(0, qubits - 1, 2)]
nm_wires += [wires[l : l + 2] for l in range(1, qubits - 1, 2)]
exp_wires = []
for _ in range(layers):
for i in range(qubits):
exp_wires.append([wires[i]])
for j in nm_wires:
exp_wires.append(list(j))
exp_wires.append(list(j[::-1]))
exp_wires.append(list(j))
res_wires = [queue[i].wires.tolist() for i in range(1, n_gates)]
assert res_wires == exp_wires
@pytest.mark.parametrize(
("init_state", "exp_state"),
[
(np.array([0, 0]), np.array([1.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j])),
(
np.array([0, 1]),
np.array([0.0 + 0.0j, 0.862093 + 0.0j, 0.0 - 0.506749j, 0.0 + 0.0j]),
),
(
np.array([1, 0]),
np.array([0.0 + 0.0j, 0.0 - 0.506749j, 0.862093 + 0.0j, 0.0 + 0.0j]),
),
(np.array([1, 1]), np.array([0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 1.0 + 0.0j])),
],
)
def test_decomposition_u2ex(self, init_state, exp_state, tol):
"""Test the decomposition of the U_{2, ex}` exchange gate by asserting the prepared
state."""
N = 2
wires = range(N)
weight = 0.53141
dev = qml.device("default.qubit", wires=N)
@qml.qnode(dev)
def circuit(weight):
qml.BasisState(init_state, wires=wires)
qml.templates.layers.particle_conserving_u2.u2_ex_gate(weight, wires)
return qml.expval(qml.PauliZ(0))
circuit(weight)
assert np.allclose(circuit.device.state, exp_state, atol=tol)
def test_custom_wire_labels(self, tol):
"""Test that template can deal with non-numeric, nonconsecutive wire labels."""
weights = np.random.random(size=(1, 5))
init_state = np.array([1, 1, 0])
dev = qml.device("default.qubit", wires=3)
dev2 = qml.device("default.qubit", wires=["z", "a", "k"])
@qml.qnode(dev)
def circuit():
qml.templates.ParticleConservingU2(weights, wires=range(3), init_state=init_state)
return qml.expval(qml.Identity(0))
@qml.qnode(dev2)
def circuit2():
qml.templates.ParticleConservingU2(
weights, wires=["z", "a", "k"], init_state=init_state
)
return qml.expval(qml.Identity("z"))
circuit()
circuit2()
assert np.allclose(dev.state, dev2.state, atol=tol, rtol=0)
class TestInputs:
"""Test inputs and pre-processing."""
@pytest.mark.parametrize(
("weights", "wires", "msg_match"),
[
(
np.array([[-0.080, 2.629, -0.710, 5.383, 0.646, -2.872, -3.856]]),
[0],
"This template requires the number of qubits to be greater than one",
),
(
np.array([[-0.080, 2.629, -0.710, 5.383]]),
[0, 1, 2, 3],
"Weights tensor must",
),
(
np.array(
[
[-0.080, 2.629, -0.710, 5.383, 0.646, -2.872],
[-0.080, 2.629, -0.710, 5.383, 0.646, -2.872],
]
),
[0, 1, 2, 3],
"Weights tensor must",
),
(
np.array([-0.080, 2.629, -0.710, 5.383, 0.646, -2.872]),
[0, 1, 2, 3],
"Weights tensor must be 2-dimensional",
),
],
)
def test_exceptions(self, weights, wires, msg_match):
"""Test that ParticleConservingU2 throws an exception if the parameters have illegal
shapes, types or values."""
N = len(wires)
init_state = np.array([1, 1, 0, 0])
dev = qml.device("default.qubit", wires=N)
@qml.qnode(dev)
def circuit():
qml.templates.ParticleConservingU2(
weights=weights,
wires=wires,
init_state=init_state,
)
return qml.expval(qml.PauliZ(0))
with pytest.raises(ValueError, match=msg_match):
circuit()
class TestAttributes:
"""Tests additional methods and attributes"""
@pytest.mark.parametrize(
"n_layers, n_wires, expected_shape",
[
(2, 3, (2, 5)),
(2, 2, (2, 3)),
(1, 3, (1, 5)),
],
)
def test_shape(self, n_layers, n_wires, expected_shape):
"""Test that the shape method returns the correct shape of the weights tensor"""
shape = qml.templates.ParticleConservingU2.shape(n_layers, n_wires)
assert shape == expected_shape
def test_shape_exception_not_enough_qubits(self):
"""Test that the shape function warns if there are not enough qubits."""
with pytest.raises(ValueError, match="The number of qubits must be greater than one"):
qml.templates.ParticleConservingU2.shape(3, 1)
def circuit_template(weights):
qml.templates.ParticleConservingU2(weights, range(2), init_state=np.array([1, 1]))
return qml.expval(qml.PauliZ(0))
def circuit_decomposed(weights):
qml.BasisState(np.array([1, 1]), wires=[0, 1])
qml.RZ(weights[0, 0], wires=[0])
qml.RZ(weights[0, 1], wires=[1])
qml.CNOT(wires=[0, 1])
qml.CRX(weights[0, 2], wires=[1, 0])
qml.CNOT(wires=[0, 1])
return qml.expval(qml.PauliZ(0))
class TestInterfaces:
"""Tests that the template is compatible with all interfaces, including the computation
of gradients."""
def test_list_and_tuples(self, tol):
"""Tests common iterables as inputs."""
weights = [[0.1, -1.1, 0.2]]
dev = qml.device("default.qubit", wires=2)
circuit = qml.QNode(circuit_template, dev)
circuit2 = qml.QNode(circuit_decomposed, dev)
res = circuit(weights)
res2 = circuit2(weights)
assert qml.math.allclose(res, res2, atol=tol, rtol=0)
weights_tuple = [tuple(weights[0])]
res = circuit(weights_tuple)
res2 = circuit2(weights_tuple)
assert qml.math.allclose(res, res2, atol=tol, rtol=0)
def test_autograd(self, tol):
"""Tests the autograd interface."""
weights = np.random.random(size=(1, 3))
weights = pnp.array(weights, requires_grad=True)
dev = qml.device("default.qubit", wires=2)
circuit = qml.QNode(circuit_template, dev) |
res = circuit(weights)
res2 = circuit2(weights)
assert qml.math.allclose(res, res2, atol=tol, rtol=0)
grad_fn = qml.grad(circuit)
grads = grad_fn(weights)
grad_fn2 = qml.grad(circuit2)
grads2 = grad_fn2(weights)
assert np.allclose(grads[0], grads2[0], atol=tol, rtol=0)
def test_jax(self, tol):
"""Tests the jax interface."""
jax = pytest.importorskip("jax")
import jax.numpy as jnp
weights = jnp.array(np.random.random(size=(1, 3)))
dev = qml.device("default.qubit", wires=2)
circuit = qml.QNode(circuit_template, dev, interface="jax")
circuit2 = qml.QNode(circuit_decomposed, dev, interface="jax")
res = circuit(weights)
res2 = circuit2(weights)
assert qml.math.allclose(res, res2, atol=tol, rtol=0)
grad_fn = jax.grad(circuit)
grads = grad_fn(weights)
grad_fn2 = jax.grad(circuit2)
grads2 = grad_fn2(weights)
assert np.allclose(grads[0], grads2[0], atol=tol, rtol=0)
def test_tf(self, tol):
"""Tests the tf interface."""
tf = pytest.importorskip("tensorflow")
weights = tf.Variable(np.random.random(size=(1, 3)))
dev = qml.device("default.qubit", wires=2)
circuit = qml.QNode(circuit_template, dev, interface="tf")
circuit2 = qml.QNode(circuit_decomposed, dev, interface="tf")
res = circuit(weights)
res2 = circuit2(weights)
assert qml.math.allclose(res, res2, atol=tol, rtol=0)
with tf.GradientTape() as tape:
res = circuit(weights)
grads = tape.gradient(res, [weights])
with tf.GradientTape() as tape2:
res2 = circuit2(weights)
grads2 = tape2.gradient(res2, [weights])
assert np.allclose(grads[0], grads2[0], atol=tol, rtol=0)
def test_torch(self, tol):
"""Tests the torch interface."""
torch = pytest.importorskip("torch")
weights = torch.tensor(np.random.random(size=(1, 3)), requires_grad=True)
dev = qml.device("default.qubit", wires=2)
circuit = qml.QNode(circuit_template, dev, interface="torch")
circuit2 = qml.QNode(circuit_decomposed, dev, interface="torch")
res = circuit(weights)
res2 = circuit2(weights)
assert qml.math.allclose(res, res2, atol=tol, rtol=0)
res = circuit(weights)
res.backward()
grads = [weights.grad]
res2 = circuit2(weights)
res2.backward()
grads2 = [weights.grad]
assert np.allclose(grads[0], grads2[0], atol=tol, rtol=0) | circuit2 = qml.QNode(circuit_decomposed, dev) |
admin.py | from django.contrib import admin
from symposion.conference.models import Conference, Section
class SectionInline(admin.TabularInline):
model = Section
prepopulated_fields = {"slug": ("name",)}
extra = 1
class ConferenceAdmin(admin.ModelAdmin):
list_display = ("title", "start_date", "end_date")
inlines = [SectionInline, ]
admin.site.register(Conference, ConferenceAdmin)
admin.site.register(
Section,
prepopulated_fields={"slug": ("name",)}, | list_display=("name", "conference", "start_date", "end_date")
) |
|
run_model_778.py | import numpy as np
from math import *
import pymultinest
import sys
sys.path.insert(0, '/home/kochenma/pysb')
from pysb.integrate import Solver
import csv
import datetime
import time as tm
from model_778 import model
from pysb.pathfinder import set_path
set_path('bng', '/home/kochenma/BioNetGen')
data_object = []
with open('earm_data.csv') as data_file:
reader = csv.reader(data_file)
line = list(reader)
for each in line:
data_object.append(each)
for i, each in enumerate(data_object):
if i > 0:
for j, item in enumerate(each):
data_object[i][j] = float(data_object[i][j])
data_object = data_object[1:]
time = []
for each in data_object:
time.append(float(each[0]))
model_solver = Solver(model, time, integrator='vode', integrator_options={'atol': 1e-12, 'rtol': 1e-12})
def prior(cube, ndim, nparams):
for k, every in enumerate(model.parameters):
if every.name[-3:] == '1kf':
cube[k] = cube[k]*4 - 4
if every.name[-3:] == '2kf':
cube[k] = cube[k]*4 - 8
if every.name[-3:] == '1kr':
cube[k] = cube[k]*4 - 4
if every.name[-3:] == '1kc':
cube[k] = cube[k]*4 - 1
postfixes = ['1kf', '2kf', '1kr', '1kc']
def loglike(cube, ndim, nparams):
point = []
cube_index = 0
for k, every in enumerate(model.parameters):
if every.name[-3:] in postfixes:
point.append(10**cube[cube_index])
cube_index += 1
else:
point.append(model.parameters[k].value)
model_solver.run(point)
failed = False
for every in model_solver.yobs:
for thing in every:
if thing <= -0.00000001 or np.isnan(thing):
failed = True
if failed:
return ['fail', -10000.0]
else:
parpc = model_solver.yobs[-1][6]/(model_solver.yobs[-1][1] + model_solver.yobs[-1][6])
if (parpc > 0.0) and (parpc < 1.00000001):
print log(parpc), point
return ['sim', log(parpc)]
else:
return ['fail', -10000.0]
n_params = 0
for m, lotsa in enumerate(model.parameters): | if lotsa.name[-3:] == '1kf':
n_params += 1
if lotsa.name[-3:] == '2kf':
n_params += 1
if lotsa.name[-3:] == '1kr':
n_params += 1
if lotsa.name[-3:] == '1kc':
n_params += 1
start_time = tm.clock()
counts = [0, 0]
pymultinest.run(loglike, prior, n_params, evidence_tolerance=0.0001, n_live_points=16000, log_zero=-1e3, sampling_efficiency=0.3, outputfiles_basename='/scratch/kochenma/log_casp_act/778/', resume = False, verbose = False, counts=counts)
print counts
print 'start time', start_time
print 'end time', tm.clock() | |
dataOrganization.ts | import * as _ from "lodash";
import * as fs from "fs";
const handlebars = require("handlebars");
import { Signer } from "ethers";
import { Address } from "../../utils/types";
import { ASSETS } from "../assetInfo";
import { PRECISE_UNIT, ZERO } from "../../utils/constants";
import {
RebalanceReport,
RebalanceSummary,
StrategyInfo,
StrategyObject,
AssetStrategy
} from "index-rebalances/types";
import {
GeneralIndexModule,
SetToken,
} from "../../utils/contracts/setV2";
import DeployHelper from "../../utils/deploys";
import { getTokenDecimals } from "./tokenHelpers";
export async function createStrategyObject(
setToken: SetToken,
strategyInfo: StrategyInfo,
owner: Signer
): Promise<StrategyObject> {
const strategyObject: StrategyObject = {};
const currentPositions: any[] = await setToken.getPositions();
const deployHelper: DeployHelper = new DeployHelper(owner);
const filteredConstants = _.pick(_.merge(ASSETS, strategyInfo), Object.keys(strategyInfo));
const keys = Object.keys(filteredConstants);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const position = currentPositions.filter(obj => obj.component.toLowerCase() == filteredConstants[key].address.toLowerCase())[0];
if (position) { filteredConstants[key].currentUnit = position.unit; }
const decimals = await getTokenDecimals(deployHelper, filteredConstants[key].address);
strategyObject[key] = {} as AssetStrategy;
strategyObject[key].address = filteredConstants[key].address;
strategyObject[key].price = filteredConstants[key].price;
strategyObject[key].maxTradeSize = filteredConstants[key].maxTradeSize.mul(decimals).div(PRECISE_UNIT);
strategyObject[key].exchange = filteredConstants[key].exchange;
strategyObject[key].coolOffPeriod = filteredConstants[key].coolOffPeriod;
strategyObject[key].input = filteredConstants[key].input;
strategyObject[key].currentUnit = position ? position.unit : ZERO;
strategyObject[key].decimals = decimals;
}
| }
export async function generateReports(
rebalanceData: RebalanceSummary[],
tradeOrder: string,
strategyInfo: StrategyInfo,
setToken: SetToken,
indexModule: GeneralIndexModule
): Promise<RebalanceReport> {
// Generate trade order for backend and new components params for rebalance()
const newComponents: Address[] = [];
const newComponentsTargetUnits: string[] = [];
const oldComponentsTargetUnits: string[] = [];
for (let i = 0; i < rebalanceData.length; i++) {
const asset = rebalanceData[i].asset;
tradeOrder = tradeOrder.replace(new RegExp(asset, "g"), ASSETS[asset].id);
if (rebalanceData[i].currentUnit == ZERO) {
newComponents.push(ASSETS[rebalanceData[i].asset].address);
newComponentsTargetUnits.push(rebalanceData[i].newUnit.toString());
}
}
// Generate old component rebalance() params
const components = await setToken.getComponents();
for (let j = 0; j < components.length; j++) {
const [[asset, ]] = Object.entries(ASSETS).filter(([key, obj]) =>
obj.address.toLowerCase() == components[j].toLowerCase()
);
oldComponentsTargetUnits.push(
rebalanceData.filter(obj => obj.asset == asset)[0].newUnit.toString()
);
}
// Generate params for setAssetMaximums and setAssetExchanges
const tradeSizeComponents: Address[] = [];
const tradeSizeValue: string[] = [];
const exchangeComponents: Address[] = [];
const exchangeValue: string[] = [];
const coolOffComponents: Address[] = [];
const coolOffValue: string[] = [];
await Promise.all(Object.entries(strategyInfo).map(async ([key, obj]) => {
const address = obj.address;
const info: any = await indexModule.executionInfo(setToken.address, address);
if (info.maxSize.toString() != obj.maxTradeSize.toString()) {
tradeSizeComponents.push(address);
tradeSizeValue.push(obj.maxTradeSize.toString());
}
if (info.exchangeName.toString() != obj.exchange.toString()) {
exchangeComponents.push(address);
exchangeValue.push(obj.exchange.toString());
}
if (info.coolOffPeriod.toString() != obj.coolOffPeriod.toString()) {
coolOffComponents.push(address);
coolOffValue.push(obj.coolOffPeriod.toString());
}
}));
// Refill fields in rebalanceData altered during trade scheduling
const totalSupply = await setToken.totalSupply();
for (let k = 0; k < rebalanceData.length; k++) {
rebalanceData[k].notionalInToken =
rebalanceData[k].newUnit.sub(rebalanceData[k].currentUnit).mul(totalSupply).div(PRECISE_UNIT);
rebalanceData[k].tradeCount = rebalanceData[k].notionalInToken.div(
strategyInfo[rebalanceData[k].asset].maxTradeSize
).abs().add(1);
}
const positionMultiplier = (await setToken.positionMultiplier()).toString();
return {
summary: rebalanceData,
maxTradeSizeParams: {
components: tradeSizeComponents,
values: tradeSizeValue,
data: indexModule.interface.encodeFunctionData(
"setTradeMaximums",
[setToken.address, tradeSizeComponents, tradeSizeValue]
),
},
exchangeParams: {
components: exchangeComponents,
values: exchangeValue,
data: indexModule.interface.encodeFunctionData(
"setExchanges",
[setToken.address, exchangeComponents, exchangeValue]
),
},
coolOffPeriodParams: {
components: coolOffComponents,
values: coolOffValue,
data: indexModule.interface.encodeFunctionData(
"setCoolOffPeriods",
[setToken.address, coolOffComponents, coolOffValue]
),
},
rebalanceParams: {
newComponents,
newComponentUnits: newComponentsTargetUnits,
oldComponentUnits: oldComponentsTargetUnits,
positionMultiplier: positionMultiplier,
data: indexModule.interface.encodeFunctionData(
"startRebalance",
[
setToken.address,
newComponents,
newComponentsTargetUnits,
oldComponentsTargetUnits,
positionMultiplier,
]
),
},
tradeOrder,
} as RebalanceReport;
}
export function writeToOutputs(report: RebalanceReport, path: string) {
const content = getNamedContent("index-rebalances/report.mustache");
const templateScript = handlebars.compile(content);
fs.writeFileSync(path + ".txt", templateScript(report));
fs.writeFileSync(path + ".json", JSON.stringify(report));
}
function getNamedContent(filename: string) {
try {
const content = fs.readFileSync(filename).toString();
return content;
} catch (err) {
throw new Error(`Failed to read ${filename}: ${err}`);
}
} | return strategyObject; |
redact.test.js | 'use strict'
const { test } = require('tap')
const { sink, once } = require('./helper')
const pino = require('../')
test('redact option – throws if not array', async ({ throws }) => {
throws(() => {
pino({ redact: 'req.headers.cookie' })
})
})
test('redact option – throws if array does not only contain strings', async ({ throws }) => {
throws(() => {
pino({ redact: ['req.headers.cookie', {}] })
})
})
test('redact option – throws if array contains an invalid path', async ({ throws }) => {
throws(() => {
pino({ redact: ['req,headers.cookie'] })
})
})
test('redact.paths option – throws if not array', async ({ throws }) => {
throws(() => {
pino({ redact: { paths: 'req.headers.cookie' } })
})
})
test('redact.paths option – throws if array does not only contain strings', async ({ throws }) => {
throws(() => {
pino({ redact: { paths: ['req.headers.cookie', {}] } })
})
})
test('redact.paths option – throws if array contains an invalid path', async ({ throws }) => {
throws(() => {
pino({ redact: { paths: ['req,headers.cookie'] } })
})
})
test('redact option – top level key', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['key'] }, stream)
instance.info({
key: { redact: 'me' }
})
const { key } = await once(stream, 'data')
equal(key, '[Redacted]')
})
test('redact option – top level key next level key', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['key', 'key.foo'] }, stream)
instance.info({
key: { redact: 'me' }
})
const { key } = await once(stream, 'data')
equal(key, '[Redacted]')
})
test('redact option – next level key then top level key', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['key.foo', 'key'] }, stream)
instance.info({
key: { redact: 'me' }
})
const { key } = await once(stream, 'data')
equal(key, '[Redacted]')
})
test('redact option – object', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['req.headers.cookie'] }, stream)
instance.info({
req: {
id: 7915,
method: 'GET',
url: '/',
headers: {
host: 'localhost:3000',
connection: 'keep-alive',
cookie: 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;'
},
remoteAddress: '::ffff:127.0.0.1',
remotePort: 58022
}
})
const { req } = await once(stream, 'data')
equal(req.headers.cookie, '[Redacted]')
})
test('redact option – child object', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['req.headers.cookie'] }, stream)
instance.child({
req: {
id: 7915,
method: 'GET',
url: '/',
headers: {
host: 'localhost:3000',
connection: 'keep-alive',
cookie: 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;'
},
remoteAddress: '::ffff:127.0.0.1',
remotePort: 58022
}
}).info('message completed')
const { req } = await once(stream, 'data')
equal(req.headers.cookie, '[Redacted]')
})
test('redact option – interpolated object', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['req.headers.cookie'] }, stream)
instance.info('test %j', {
req: {
id: 7915,
method: 'GET',
url: '/',
headers: {
host: 'localhost:3000',
connection: 'keep-alive',
cookie: 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;'
},
remoteAddress: '::ffff:127.0.0.1',
remotePort: 58022
}
})
const { msg } = await once(stream, 'data')
equal(JSON.parse(msg.replace(/test /, '')).req.headers.cookie, '[Redacted]')
})
test('redact.paths option – object', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: { paths: ['req.headers.cookie'] } }, stream)
instance.info({
req: {
id: 7915,
method: 'GET',
url: '/',
headers: {
host: 'localhost:3000',
connection: 'keep-alive',
cookie: 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;'
},
remoteAddress: '::ffff:127.0.0.1',
remotePort: 58022
}
})
const { req } = await once(stream, 'data')
equal(req.headers.cookie, '[Redacted]')
})
test('redact.paths option – child object', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: { paths: ['req.headers.cookie'] } }, stream)
instance.child({
req: {
id: 7915,
method: 'GET',
url: '/',
headers: {
host: 'localhost:3000',
connection: 'keep-alive',
cookie: 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;'
},
remoteAddress: '::ffff:127.0.0.1',
remotePort: 58022
}
}).info('message completed')
const { req } = await once(stream, 'data')
equal(req.headers.cookie, '[Redacted]')
})
test('redact.paths option – interpolated object', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: { paths: ['req.headers.cookie'] } }, stream)
instance.info('test %j', {
req: {
id: 7915,
method: 'GET',
url: '/',
headers: {
host: 'localhost:3000',
connection: 'keep-alive',
cookie: 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;'
},
remoteAddress: '::ffff:127.0.0.1', | }
})
const { msg } = await once(stream, 'data')
equal(JSON.parse(msg.replace(/test /, '')).req.headers.cookie, '[Redacted]')
})
test('redact.censor option – sets the redact value', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: { paths: ['req.headers.cookie'], censor: 'test' } }, stream)
instance.info({
req: {
id: 7915,
method: 'GET',
url: '/',
headers: {
host: 'localhost:3000',
connection: 'keep-alive',
cookie: 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;'
},
remoteAddress: '::ffff:127.0.0.1',
remotePort: 58022
}
})
const { req } = await once(stream, 'data')
equal(req.headers.cookie, 'test')
})
test('redact.censor option – can be a function that accepts value and path arguments', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: { paths: ['topLevel'], censor: (value, path) => value + ' ' + path.join('.') } }, stream)
instance.info({
topLevel: 'test'
})
const { topLevel } = await once(stream, 'data')
equal(topLevel, 'test topLevel')
})
test('redact.censor option – can be a function that accepts value and path arguments (nested path)', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: { paths: ['req.headers.cookie'], censor: (value, path) => value + ' ' + path.join('.') } }, stream)
instance.info({
req: {
id: 7915,
method: 'GET',
url: '/',
headers: {
host: 'localhost:3000',
connection: 'keep-alive',
cookie: 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;'
},
remoteAddress: '::ffff:127.0.0.1',
remotePort: 58022
}
})
const { req } = await once(stream, 'data')
equal(req.headers.cookie, 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1; req.headers.cookie')
})
test('redact.remove option – removes both key and value', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: { paths: ['req.headers.cookie'], remove: true } }, stream)
instance.info({
req: {
id: 7915,
method: 'GET',
url: '/',
headers: {
host: 'localhost:3000',
connection: 'keep-alive',
cookie: 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;'
},
remoteAddress: '::ffff:127.0.0.1',
remotePort: 58022
}
})
const { req } = await once(stream, 'data')
equal('cookie' in req.headers, false)
})
test('redact.remove – top level key - object value', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: { paths: ['key'], remove: true } }, stream)
instance.info({
key: { redact: 'me' }
})
const o = await once(stream, 'data')
equal('key' in o, false)
})
test('redact.remove – top level key - number value', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: { paths: ['key'], remove: true } }, stream)
instance.info({
key: 1
})
const o = await once(stream, 'data')
equal('key' in o, false)
})
test('redact.remove – top level key - boolean value', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: { paths: ['key'], remove: true } }, stream)
instance.info({
key: false
})
const o = await once(stream, 'data')
equal('key' in o, false)
})
test('redact.remove – top level key in child logger', async ({ equal }) => {
const stream = sink()
const opts = { redact: { paths: ['key'], remove: true } }
const instance = pino(opts, stream).child({ key: { redact: 'me' } })
instance.info('test')
const o = await once(stream, 'data')
equal('key' in o, false)
})
test('redact.paths preserves original object values after the log write', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['req.headers.cookie'] }, stream)
const obj = {
req: {
id: 7915,
method: 'GET',
url: '/',
headers: {
host: 'localhost:3000',
connection: 'keep-alive',
cookie: 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;'
},
remoteAddress: '::ffff:127.0.0.1',
remotePort: 58022
}
}
instance.info(obj)
const o = await once(stream, 'data')
equal(o.req.headers.cookie, '[Redacted]')
equal(obj.req.headers.cookie, 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;')
})
test('redact.paths preserves original object values after the log write', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: { paths: ['req.headers.cookie'] } }, stream)
const obj = {
req: {
id: 7915,
method: 'GET',
url: '/',
headers: {
host: 'localhost:3000',
connection: 'keep-alive',
cookie: 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;'
},
remoteAddress: '::ffff:127.0.0.1',
remotePort: 58022
}
}
instance.info(obj)
const o = await once(stream, 'data')
equal(o.req.headers.cookie, '[Redacted]')
equal(obj.req.headers.cookie, 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;')
})
test('redact.censor preserves original object values after the log write', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: { paths: ['req.headers.cookie'], censor: 'test' } }, stream)
const obj = {
req: {
id: 7915,
method: 'GET',
url: '/',
headers: {
host: 'localhost:3000',
connection: 'keep-alive',
cookie: 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;'
},
remoteAddress: '::ffff:127.0.0.1',
remotePort: 58022
}
}
instance.info(obj)
const o = await once(stream, 'data')
equal(o.req.headers.cookie, 'test')
equal(obj.req.headers.cookie, 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;')
})
test('redact.remove preserves original object values after the log write', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: { paths: ['req.headers.cookie'], remove: true } }, stream)
const obj = {
req: {
id: 7915,
method: 'GET',
url: '/',
headers: {
host: 'localhost:3000',
connection: 'keep-alive',
cookie: 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;'
},
remoteAddress: '::ffff:127.0.0.1',
remotePort: 58022
}
}
instance.info(obj)
const o = await once(stream, 'data')
equal('cookie' in o.req.headers, false)
equal('cookie' in obj.req.headers, true)
})
test('redact – supports last position wildcard paths', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['req.headers.*'] }, stream)
instance.info({
req: {
id: 7915,
method: 'GET',
url: '/',
headers: {
host: 'localhost:3000',
connection: 'keep-alive',
cookie: 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;'
},
remoteAddress: '::ffff:127.0.0.1',
remotePort: 58022
}
})
const { req } = await once(stream, 'data')
equal(req.headers.cookie, '[Redacted]')
equal(req.headers.host, '[Redacted]')
equal(req.headers.connection, '[Redacted]')
})
test('redact – supports first position wildcard paths', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['*.headers'] }, stream)
instance.info({
req: {
id: 7915,
method: 'GET',
url: '/',
headers: {
host: 'localhost:3000',
connection: 'keep-alive',
cookie: 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;'
},
remoteAddress: '::ffff:127.0.0.1',
remotePort: 58022
}
})
const { req } = await once(stream, 'data')
equal(req.headers, '[Redacted]')
})
test('redact – supports first position wildcards before other paths', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['*.headers.cookie', 'req.id'] }, stream)
instance.info({
req: {
id: 7915,
method: 'GET',
url: '/',
headers: {
host: 'localhost:3000',
connection: 'keep-alive',
cookie: 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;'
},
remoteAddress: '::ffff:127.0.0.1',
remotePort: 58022
}
})
const { req } = await once(stream, 'data')
equal(req.headers.cookie, '[Redacted]')
equal(req.id, '[Redacted]')
})
test('redact – supports first position wildcards after other paths', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['req.id', '*.headers.cookie'] }, stream)
instance.info({
req: {
id: 7915,
method: 'GET',
url: '/',
headers: {
host: 'localhost:3000',
connection: 'keep-alive',
cookie: 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;'
},
remoteAddress: '::ffff:127.0.0.1',
remotePort: 58022
}
})
const { req } = await once(stream, 'data')
equal(req.headers.cookie, '[Redacted]')
equal(req.id, '[Redacted]')
})
test('redact – supports first position wildcards after top level keys', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['key', '*.headers.cookie'] }, stream)
instance.info({
req: {
id: 7915,
method: 'GET',
url: '/',
headers: {
host: 'localhost:3000',
connection: 'keep-alive',
cookie: 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;'
},
remoteAddress: '::ffff:127.0.0.1',
remotePort: 58022
}
})
const { req } = await once(stream, 'data')
equal(req.headers.cookie, '[Redacted]')
})
test('redact – supports top level wildcard', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['*'] }, stream)
instance.info({
req: {
id: 7915,
method: 'GET',
url: '/',
headers: {
host: 'localhost:3000',
connection: 'keep-alive',
cookie: 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;'
},
remoteAddress: '::ffff:127.0.0.1',
remotePort: 58022
}
})
const { req } = await once(stream, 'data')
equal(req, '[Redacted]')
})
test('redact – supports top level wildcard with a censor function', async ({ equal }) => {
const stream = sink()
const instance = pino({
redact: {
paths: ['*'],
censor: () => '[Redacted]'
}
}, stream)
instance.info({
req: {
id: 7915,
method: 'GET',
url: '/',
headers: {
host: 'localhost:3000',
connection: 'keep-alive',
cookie: 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;'
},
remoteAddress: '::ffff:127.0.0.1',
remotePort: 58022
}
})
const { req } = await once(stream, 'data')
equal(req, '[Redacted]')
})
test('redact – supports top level wildcard and leading wildcard', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['*', '*.req'] }, stream)
instance.info({
req: {
id: 7915,
method: 'GET',
url: '/',
headers: {
host: 'localhost:3000',
connection: 'keep-alive',
cookie: 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;'
},
remoteAddress: '::ffff:127.0.0.1',
remotePort: 58022
}
})
const { req } = await once(stream, 'data')
equal(req, '[Redacted]')
})
test('redact – supports intermediate wildcard paths', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['req.*.cookie'] }, stream)
instance.info({
req: {
id: 7915,
method: 'GET',
url: '/',
headers: {
host: 'localhost:3000',
connection: 'keep-alive',
cookie: 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;'
},
remoteAddress: '::ffff:127.0.0.1',
remotePort: 58022
}
})
const { req } = await once(stream, 'data')
equal(req.headers.cookie, '[Redacted]')
})
test('redacts numbers at the top level', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['id'] }, stream)
const obj = {
id: 7915
}
instance.info(obj)
const o = await once(stream, 'data')
equal(o.id, '[Redacted]')
})
test('redacts booleans at the top level', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['maybe'] }, stream)
const obj = {
maybe: true
}
instance.info(obj)
const o = await once(stream, 'data')
equal(o.maybe, '[Redacted]')
})
test('redacts strings at the top level', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['s'] }, stream)
const obj = {
s: 's'
}
instance.info(obj)
const o = await once(stream, 'data')
equal(o.s, '[Redacted]')
})
test('does not redact primitives if not objects', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['a.b'] }, stream)
const obj = {
a: 42
}
instance.info(obj)
const o = await once(stream, 'data')
equal(o.a, 42)
})
test('redacts null at the top level', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['n'] }, stream)
const obj = {
n: null
}
instance.info(obj)
const o = await once(stream, 'data')
equal(o.n, '[Redacted]')
})
test('supports bracket notation', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['a["b.b"]'] }, stream)
const obj = {
a: { 'b.b': 'c' }
}
instance.info(obj)
const o = await once(stream, 'data')
equal(o.a['b.b'], '[Redacted]')
})
test('supports bracket notation with further nesting', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['a["b.b"].c'] }, stream)
const obj = {
a: { 'b.b': { c: 'd' } }
}
instance.info(obj)
const o = await once(stream, 'data')
equal(o.a['b.b'].c, '[Redacted]')
})
test('supports bracket notation with empty string as path segment', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['a[""].c'] }, stream)
const obj = {
a: { '': { c: 'd' } }
}
instance.info(obj)
const o = await once(stream, 'data')
equal(o.a[''].c, '[Redacted]')
})
test('supports leading bracket notation (single quote)', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['[\'a.a\'].b'] }, stream)
const obj = {
'a.a': { b: 'c' }
}
instance.info(obj)
const o = await once(stream, 'data')
equal(o['a.a'].b, '[Redacted]')
})
test('supports leading bracket notation (double quote)', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['["a.a"].b'] }, stream)
const obj = {
'a.a': { b: 'c' }
}
instance.info(obj)
const o = await once(stream, 'data')
equal(o['a.a'].b, '[Redacted]')
})
test('supports leading bracket notation (backtick quote)', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['[`a.a`].b'] }, stream)
const obj = {
'a.a': { b: 'c' }
}
instance.info(obj)
const o = await once(stream, 'data')
equal(o['a.a'].b, '[Redacted]')
})
test('supports leading bracket notation (single-segment path)', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['[`a.a`]'] }, stream)
const obj = {
'a.a': { b: 'c' }
}
instance.info(obj)
const o = await once(stream, 'data')
equal(o['a.a'], '[Redacted]')
})
test('supports leading bracket notation (single-segment path, wilcard)', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['[*]'] }, stream)
const obj = {
'a.a': { b: 'c' }
}
instance.info(obj)
const o = await once(stream, 'data')
equal(o['a.a'], '[Redacted]')
})
test('child bindings are redacted using wildcard path', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['*.headers.cookie'] }, stream)
instance.child({
req: {
method: 'GET',
url: '/',
headers: {
cookie: 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;'
}
}
}).info('message completed')
const { req } = await once(stream, 'data')
equal(req.headers.cookie, '[Redacted]')
})
test('child bindings are redacted using wildcard and plain path keys', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['req.method', '*.headers.cookie'] }, stream)
instance.child({
req: {
method: 'GET',
url: '/',
headers: {
cookie: 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;'
}
}
}).info('message completed')
const { req } = await once(stream, 'data')
equal(req.headers.cookie, '[Redacted]')
equal(req.method, '[Redacted]')
})
test('redacts boolean at the top level', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['msg'] }, stream)
const obj = {
s: 's'
}
instance.info(obj, true)
const o = await once(stream, 'data')
equal(o.s, 's')
equal(o.msg, '[Redacted]')
})
test('child can customize redact', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['req.method', '*.headers.cookie'] }, stream)
instance.child({
req: {
method: 'GET',
url: '/',
headers: {
cookie: 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;'
}
}
}, {
redact: ['req.url']
}).info('message completed')
const { req } = await once(stream, 'data')
equal(req.headers.cookie, 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;')
equal(req.method, 'GET')
equal(req.url, '[Redacted]')
})
test('child can remove parent redact by array', async ({ equal }) => {
const stream = sink()
const instance = pino({ redact: ['req.method', '*.headers.cookie'] }, stream)
instance.child({
req: {
method: 'GET',
url: '/',
headers: {
cookie: 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;'
}
}
}, {
redact: []
}).info('message completed')
const { req } = await once(stream, 'data')
equal(req.headers.cookie, 'SESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1;')
equal(req.method, 'GET')
}) | remotePort: 58022 |
ichannel.go | package client
import (
"star-edge-cloud/edge/transport/client/configuration"
"star-edge-cloud/edge/transport/coding"
)
// IChannel -
type IChannel interface {
SetConfig(config *configuration.ChannelConfig)
SetDecoder(coding.IDecoder) | SetEncoder(coding.IEncoder)
Send(string, interface{}, map[string]interface{}) (interface{}, error)
} | |
test_management.py | from datetime import datetime
from io import StringIO
from unittest.mock import patch
from django.conf import settings
from django.core import mail
from django.core.management import call_command
from django.test import TestCase
from django.utils import timezone
from main import models
from main.management.commands import mail_exports, process_notifications
class EnqueueNotificationsTest(TestCase):
"""
Test that the enqueue_notifications management command, creates NotificationRecords
to the blog_user subscribers.
"""
def setUp(self):
self.user = models.User.objects.create(
username="alice", email="[email protected]", notifications_on=True
)
post_data = {
"title": "Old post",
"slug": "old-post",
"body": "Content sentence.",
"published_at": timezone.make_aware(datetime(2019, 1, 2)),
}
models.Post.objects.create(owner=self.user, **post_data)
post_data = {
"title": "Yesterday post",
"slug": "yesterday-post",
"body": "Content sentence.",
"published_at": timezone.make_aware(datetime(2020, 1, 1)),
}
models.Post.objects.create(owner=self.user, **post_data)
# as inactive, it should be ignored by the enqueue functionality
models.Notification.objects.create(
blog_user=self.user,
email="[email protected]",
is_active=False,
)
self.notification = models.Notification.objects.create(
blog_user=self.user, email="[email protected]"
)
def test_command(self):
output = StringIO()
with patch.object(timezone, "now", return_value=datetime(2020, 1, 2, 9, 00)):
call_command("enqueue_notifications", stdout=output)
# notification records
self.assertEqual(len(models.NotificationRecord.objects.all()), 1)
self.assertEqual(
models.NotificationRecord.objects.first().notification.email,
self.notification.email,
)
self.assertEqual(
models.NotificationRecord.objects.first().post.title, "Yesterday post"
)
self.assertIsNone(models.NotificationRecord.objects.first().sent_at)
# logging
self.assertIn("Enqueuing notifications started.", output.getvalue())
self.assertIn(
"Adding notification record for 'Yesterday post' to '[email protected]'",
output.getvalue(),
)
self.assertIn("Enqueuing complete for 'Yesterday post'", output.getvalue())
self.assertIn("Enqueuing finished.", output.getvalue())
def tearDown(self):
models.User.objects.all().delete()
models.Post.objects.all().delete()
class ProcessNotificationsTest(TestCase):
"""
Test process_notifications sends emails to the subscibers of the
NotificationRecords that exist.
"""
def setUp(self):
self.user = models.User.objects.create(
username="alice", email="[email protected]", notifications_on=True
)
post_data = {
"title": "Yesterday post",
"slug": "yesterday-post",
"body": "Content sentence.",
"published_at": timezone.make_aware(datetime(2020, 1, 1)),
}
self.post_yesterday = models.Post.objects.create(owner=self.user, **post_data)
post_data = {
"title": "Today post",
"slug": "today-post",
"body": "Content sentence.",
"published_at": timezone.make_aware(datetime(2020, 1, 2)),
}
self.post_today = models.Post.objects.create(owner=self.user, **post_data)
self.notification = models.Notification.objects.create(
blog_user=self.user, email="[email protected]"
)
# notification records
self.notificationrecord_yesterday = models.NotificationRecord.objects.create(
notification=self.notification,
post=self.post_yesterday,
sent_at=None,
)
self.notificationrecord_today = models.NotificationRecord.objects.create(
notification=self.notification,
post=self.post_today,
sent_at=None,
)
def test_mail_backend(self):
connection = process_notifications.get_mail_connection()
self.assertEqual(connection.host, settings.EMAIL_HOST_BROADCASTS)
def | (self):
output = StringIO()
with patch.object(
timezone, "now", return_value=datetime(2020, 1, 2, 13, 00)
), patch.object(
# Django default test runner overrides SMTP EmailBackend with locmem,
# but because we re-import the SMTP backend in
# process_notifications.get_mail_connection, we need to mock it here too.
process_notifications,
"get_mail_connection",
return_value=mail.get_connection(
"django.core.mail.backends.locmem.EmailBackend"
),
):
call_command("process_notifications", stdout=output)
# notification records
records = models.NotificationRecord.objects.all()
self.assertEqual(len(records), 2)
# notification record for yesterday's post
self.assertEqual(
records.filter(sent_at__isnull=False).first().notification.email,
self.notificationrecord_today.notification.email,
)
self.assertEqual(
records.filter(sent_at__isnull=False).first().post.title, "Yesterday post"
)
# notification record for today's post
records = models.NotificationRecord.objects.all()
self.assertEqual(
records.filter(sent_at__isnull=True).first().notification.email,
self.notificationrecord_today.notification.email,
)
self.assertEqual(
records.filter(sent_at__isnull=True).first().post.title, "Today post"
)
# logging
self.assertIn("Processing notifications.", output.getvalue())
self.assertIn("Broadcast sent. Total 1 emails.", output.getvalue())
self.assertIn(
"Adding notification record for 'Yesterday post' to '[email protected]'",
output.getvalue(),
)
# email
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].subject, "Yesterday post")
self.assertIn("To unsubscribe", mail.outbox[0].body)
# email headers
self.assertEqual(mail.outbox[0].to, [self.notification.email])
self.assertEqual(mail.outbox[0].reply_to, [self.user.email])
self.assertEqual(
mail.outbox[0].from_email,
f"{self.user.username} <{self.user.username}@{settings.EMAIL_FROM_HOST}>",
)
self.assertEqual(
mail.outbox[0].extra_headers["X-PM-Message-Stream"], "newsletters"
)
self.assertIn(
"/newsletter/unsubscribe/",
mail.outbox[0].extra_headers["List-Unsubscribe"],
)
self.assertEqual(
mail.outbox[0].extra_headers["List-Unsubscribe-Post"],
"List-Unsubscribe=One-Click",
)
def tearDown(self):
models.User.objects.all().delete()
models.Post.objects.all().delete()
class MailExportsTest(TestCase):
"""
Test mail_export sends emails to users with `mail_export_on` enabled.
"""
def setUp(self):
self.user = models.User.objects.create(
username="alice", email="[email protected]", mail_export_on=True
)
post_data = {
"title": "A post",
"slug": "a-post",
"body": "Content sentence.",
"published_at": timezone.make_aware(datetime(2020, 1, 1)),
}
self.post_a = models.Post.objects.create(owner=self.user, **post_data)
post_data = {
"title": "Second post",
"slug": "second-post",
"body": "Content sentence two.",
"published_at": timezone.make_aware(datetime(2020, 1, 2)),
}
self.post_b = models.Post.objects.create(owner=self.user, **post_data)
def test_mail_backend(self):
connection = mail_exports.get_mail_connection()
self.assertEqual(connection.host, settings.EMAIL_HOST_BROADCASTS)
def test_command(self):
output = StringIO()
with patch.object(
timezone, "now", return_value=datetime(2020, 1, 3, 00, 00)
), patch.object(
# Django default test runner overrides SMTP EmailBackend with locmem,
# but because we re-import the SMTP backend in
# process_notifications.get_mail_connection, we need to mock it here too.
mail_exports,
"get_mail_connection",
return_value=mail.get_connection(
"django.core.mail.backends.locmem.EmailBackend"
),
):
call_command("mail_exports", stdout=output)
# export records
records = models.ExportRecord.objects.all()
self.assertEqual(len(records), 1)
self.assertEqual(records[0].user, self.user)
self.assertIn("export-markdown-", records[0].name)
# logging
self.assertIn("Processing email exports.", output.getvalue())
self.assertIn(f"Processing user {self.user.username}.", output.getvalue())
self.assertIn(f"Export sent to {self.user.username}.", output.getvalue())
self.assertIn(
f"Logging export record for '{records[0].name}'.", output.getvalue()
)
self.assertIn("Emailing all exports complete.", output.getvalue())
# email
self.assertEqual(len(mail.outbox), 1)
self.assertIn("Mataroa export", mail.outbox[0].subject)
self.assertIn("Unsubscribe", mail.outbox[0].body)
# email headers
self.assertEqual(mail.outbox[0].to, [self.user.email])
self.assertEqual(
mail.outbox[0].from_email,
settings.DEFAULT_FROM_EMAIL,
)
self.assertEqual(mail.outbox[0].extra_headers["X-PM-Message-Stream"], "exports")
self.assertIn(
"/export/unsubscribe/",
mail.outbox[0].extra_headers["List-Unsubscribe"],
)
self.assertEqual(
mail.outbox[0].extra_headers["List-Unsubscribe-Post"],
"List-Unsubscribe=One-Click",
)
def tearDown(self):
models.User.objects.all().delete()
models.Post.objects.all().delete()
| test_command |
peer.go | package wtmock
import (
"fmt"
"net"
"time"
"github.com/ltcsuite/lnd/watchtower/wtserver"
"github.com/ltcsuite/ltcd/btcec/v2"
)
// MockPeer emulates a single endpoint of brontide transport.
type MockPeer struct {
remotePub *btcec.PublicKey
remoteAddr net.Addr
localPub *btcec.PublicKey
localAddr net.Addr
IncomingMsgs chan []byte
OutgoingMsgs chan []byte
writeDeadline <-chan time.Time
readDeadline <-chan time.Time
RemoteQuit chan struct{}
Quit chan struct{}
}
// NewMockPeer returns a fresh MockPeer.
func NewMockPeer(lpk, rpk *btcec.PublicKey, addr net.Addr,
bufferSize int) *MockPeer |
// NewMockConn establishes a bidirectional connection between two MockPeers.
func NewMockConn(localPk, remotePk *btcec.PublicKey,
localAddr, remoteAddr net.Addr,
bufferSize int) (*MockPeer, *MockPeer) {
localPeer := &MockPeer{
remotePub: remotePk,
remoteAddr: remoteAddr,
localPub: localPk,
localAddr: localAddr,
IncomingMsgs: make(chan []byte, bufferSize),
OutgoingMsgs: make(chan []byte, bufferSize),
Quit: make(chan struct{}),
}
remotePeer := &MockPeer{
remotePub: localPk,
remoteAddr: localAddr,
localPub: remotePk,
localAddr: remoteAddr,
IncomingMsgs: localPeer.OutgoingMsgs,
OutgoingMsgs: localPeer.IncomingMsgs,
Quit: make(chan struct{}),
}
localPeer.RemoteQuit = remotePeer.Quit
remotePeer.RemoteQuit = localPeer.Quit
return localPeer, remotePeer
}
// Write sends the raw bytes as the next full message read to the remote peer.
// The write will fail if either party closes the connection or the write
// deadline expires. The passed bytes slice is copied before sending, thus the
// bytes may be reused once the method returns.
func (p *MockPeer) Write(b []byte) (n int, err error) {
bb := make([]byte, len(b))
copy(bb, b)
select {
case p.OutgoingMsgs <- bb:
return len(b), nil
case <-p.writeDeadline:
return 0, fmt.Errorf("write timeout expired")
case <-p.RemoteQuit:
return 0, fmt.Errorf("remote closed connected")
case <-p.Quit:
return 0, fmt.Errorf("connection closed")
}
}
// Close tearsdown the connection, and fails any pending reads or writes.
func (p *MockPeer) Close() error {
select {
case <-p.Quit:
return fmt.Errorf("connection already closed")
default:
close(p.Quit)
return nil
}
}
// ReadNextMessage returns the raw bytes of the next full message read from the
// remote peer. The read will fail if either party closes the connection or the
// read deadline expires.
func (p *MockPeer) ReadNextMessage() ([]byte, error) {
select {
case b := <-p.IncomingMsgs:
return b, nil
case <-p.readDeadline:
return nil, fmt.Errorf("read timeout expired")
case <-p.RemoteQuit:
return nil, fmt.Errorf("remote closed connected")
case <-p.Quit:
return nil, fmt.Errorf("connection closed")
}
}
// SetWriteDeadline initializes a timer that will cause any pending writes to
// fail at time t. If t is zero, the deadline is infinite.
func (p *MockPeer) SetWriteDeadline(t time.Time) error {
if t.IsZero() {
p.writeDeadline = nil
return nil
}
duration := time.Until(t)
p.writeDeadline = time.After(duration)
return nil
}
// SetReadDeadline initializes a timer that will cause any pending reads to fail
// at time t. If t is zero, the deadline is infinite.
func (p *MockPeer) SetReadDeadline(t time.Time) error {
if t.IsZero() {
p.readDeadline = nil
return nil
}
duration := time.Until(t)
p.readDeadline = time.After(duration)
return nil
}
// RemotePub returns the public key of the remote peer.
func (p *MockPeer) RemotePub() *btcec.PublicKey {
return p.remotePub
}
// RemoteAddr returns the net address of the remote peer.
func (p *MockPeer) RemoteAddr() net.Addr {
return p.remoteAddr
}
// LocalAddr returns the local net address of the peer.
func (p *MockPeer) LocalAddr() net.Addr {
return p.localAddr
}
// Read is not implemented.
func (p *MockPeer) Read(dst []byte) (int, error) {
panic("not implemented")
}
// SetDeadline is not implemented.
func (p *MockPeer) SetDeadline(t time.Time) error {
panic("not implemented")
}
// Compile-time constraint ensuring the MockPeer implements the wserver.Peer
// interface.
var _ wtserver.Peer = (*MockPeer)(nil)
// Compile-time constraint ensuring the MockPeer implements the net.Conn
// interface.
var _ net.Conn = (*MockPeer)(nil)
| {
return &MockPeer{
remotePub: rpk,
remoteAddr: addr,
localAddr: &net.TCPAddr{
IP: net.IP{0x32, 0x31, 0x30, 0x29},
Port: 36723,
},
localPub: lpk,
IncomingMsgs: make(chan []byte, bufferSize),
OutgoingMsgs: make(chan []byte, bufferSize),
Quit: make(chan struct{}),
}
} |
Twitter.js | import React, { useState } from 'react'
import BaseProvider from './BaseProvider'
import FilterTable from '../components/FilterTable';
const TwitterPage = () => {
const [data, setData] = useState();
return (
<BaseProvider
pageTitle='Twitter mentions'
connectionName='twitter'
endpoint='twitter'
setData={setData}>
<TweetTable data={data} setData={setData}/>
</BaseProvider>
)
}
const TweetTable = ({data, setData}) => {
const urlFormatter = (cell, row) => {
const tweetId = `https://twitter.com/i/web/status/${row.id_str}`;
return <a href={tweetId} target="_">{cell}</a>
}
const typeFormatter = (cell, row, rowIndex, formatExtraData) => {
return (
<i className={ formatExtraData[cell] } />
)
}
const columns = [{
dataField: 'date',
text: 'Date',
sort: true,
headerStyle: (column, colIndex) => {
return { width: '200px' };
}
}, { | dataField: 'type',
text: 'Type',
sort: true,
headerStyle: (column, colIndex) => {
return { width: '80px' };
},
align: 'center',
formatter: typeFormatter,
formatExtraData: {
positive: 'fa fa-thumbs-up fa-2x text-success',
neutral: 'fa fa-minus fa-2x text-warning',
negative: 'fa fa-thumbs-down fa-2x text-danger'
}
}, {
dataField: 'user',
text: 'User',
sort: true,
headerStyle: (column, colIndex) => {
return { width: '120px' };
}
}, {
dataField: 'name',
text: 'Name',
sort: true,
headerStyle: (column, colIndex) => {
return { width: '100px' };
}
}, {
dataField: 'text',
text: 'Text',
formatter: urlFormatter
}];
const tweets = data && data.map && data.map(item => {
return {
id_str: item.id_str,
date: new Date(item.created_at).toLocaleString(),
user: item.user.screen_name,
name: item.user.name,
type: item.__sentiment,
text: item.text
}
});
return (
tweets ?
<FilterTable
data={data}
setData={setData}
dataRows={tweets}
columns={columns}
keyField="id_str"
path="twitter/mentions"
maxHeight="calc(100vh - 220px)"
/>
: <div/>
)
}
export default TwitterPage | |
slider-handle.component.ts | import {
Component,
OnInit,
ElementRef,
Input,
Output,
EventEmitter,
HostListener,
OnDestroy,
ViewEncapsulation
} from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Component({
selector: 'SliderHandle, nzm-slider-handle',
templateUrl: './slider-handle.component.html',
encapsulation: ViewEncapsulation.None
})
export class | implements OnInit, OnDestroy {
left: number;
private _min: number;
private _max: number;
private _step: number;
private _value: number;
private _disabled: boolean = false;
private _marks: object = {};
private _handleStyle: object;
private _sliderLength: number;
private _sliderStart: number;
private _minBound: number;
private _maxBound: number;
private _startX: number;
private _isDraging: boolean = false;
private _handleStatus: string;
private _handleOffsetX: number;
private _oldValue: number;
@Input()
set min(value: number) {
this._min = value;
}
@Input()
set max(value: number) {
this._max = value;
}
@Input()
set minBound(value: number) {
this._minBound = value;
}
@Input()
set maxBound(value: number) {
this._maxBound = value;
}
@Input()
set step(value: number) {
this._step = value;
}
@Input()
set value(value: number) {
this._value = value;
if (this._value) {
this.left = this.calcOffset(this._value);
}
}
@Input()
set disabled(value: boolean) {
this._disabled = value;
}
@Input()
set sliderLength(value: number) {
this._sliderLength = value;
}
@Input()
set sliderStart(value: number) {
this._sliderStart = value;
}
@Input()
get handleStyle(): object {
return this._handleStyle;
}
set handleStyle(value: object) {
this._handleStyle = value;
}
@Output()
onChange = new EventEmitter<any>();
@Output()
onAfterChange = new EventEmitter<any>();
/* 手势操作 */
@HostListener('touchstart', ['$event'])
panstart(event) {
event.preventDefault();
if (!this._disabled) {
this._startX = event && event.changedTouches && event.changedTouches[0] && event.changedTouches[0].clientX;
this._handleStatus = 'start';
this._isDraging = true;
}
}
@HostListener('touchmove', ['$event'])
panmove(event) {
event.preventDefault();
if (!this._disabled && this._isDraging) {
const pos = event.changedTouches[0].clientX;
this._value = Math.round(this.calcValueByPos(pos));
this.left = this.calcOffset(this._value);
if (this._oldValue !== this._value) {
this._oldValue = this._value;
this.onChange.emit(this._value);
}
}
}
@HostListener('touchend', ['$event'])
panend(event) {
event.preventDefault();
if (!this._disabled && this._isDraging) {
this._handleStatus = 'end';
this._isDraging = false;
const pos = event.changedTouches[0].clientX;
this._value = Math.round(this.calcValueByPos(pos));
this.left = this.calcOffset(this._value);
this.onAfterChange.emit(this._value);
}
}
constructor(private _elf: ElementRef, private _sanitizer: DomSanitizer) {}
mouseDown = event => {
if (!this._disabled && this.isMouseTarget(event)) {
this._startX = event.clientX;
this._handleStatus = 'start';
this._isDraging = true;
document.addEventListener('mousemove', this.mouseMove, false);
document.addEventListener('mouseup', this.mouseUp, false);
this.pauseEvent(event);
}
}
mouseMove = event => {
if (!this._disabled && this._isDraging) {
this.pauseEvent(event);
const pos = event.clientX;
this._value = Math.round(this.calcValueByPos(pos));
this.left = this.calcOffset(this._value);
if (this._oldValue !== this._value) {
this._oldValue = this._value;
this.onChange.emit(this._value);
}
}
}
mouseUp = event => {
if (!this._disabled && this._isDraging) {
this._handleStatus = 'end';
this._isDraging = false;
const pos = event.clientX;
this._value = Math.round(this.calcValueByPos(pos));
this.left = this.calcOffset(this._value);
this.onAfterChange.emit(this._value);
}
}
calcValueByPos(pos) {
const offset = pos - this._sliderStart;
let value = this.calcValue(offset);
if (value <= this._minBound) {
value = this._minBound;
}
if (value >= this._maxBound) {
value = this._maxBound;
}
const closestPoint = this.getClosestPoint(value);
return this._step === null ? closestPoint : parseFloat(closestPoint.toFixed(this.getPrecision(this._step)));
}
calcValue(offset) {
const ratio = Math.abs(Math.max(offset, 0) / this._sliderLength);
const value = ratio * (this._max - this._min) + this._min;
return value;
}
getClosestPoint(val) {
const points = Object.keys(this._marks).map(parseFloat);
if (this._step !== null) {
const closestStep = Math.round((val - this._min) / this._step) * this._step + this._min;
points.push(closestStep);
}
const diffs = points.map(function(point) {
return Math.abs(val - point);
});
return points[diffs.indexOf(Math.min.apply(Math, this.toConsumableArray(diffs)))];
}
getPrecision(step) {
const stepString = step.toString();
let precision = 0;
if (stepString.indexOf('.') >= 0) {
precision = stepString.length - stepString.indexOf('.') - 1;
}
return precision;
}
calcOffset(value) {
const ratio = (value - this._min) / (this._max - this._min);
return ratio * 100;
}
pauseEvent(e) {
e.stopPropagation();
e.preventDefault();
}
isMouseTarget(event) {
let target = event.target;
let parentFound = false;
while (target !== null && !parentFound) {
if (target === this._elf.nativeElement) {
parentFound = true;
}
target = target.parentElement;
}
return parentFound;
}
toConsumableArray(arr) {
if (Array.isArray(arr)) {
const arr2 = Array(arr.length);
for (let i = 0; i < arr.length; i++) {
arr2[i] = arr[i];
}
return arr2;
}
}
ngOnInit() {
const self = this;
this._elf.nativeElement.addEventListener('mousedown', this.mouseDown, false);
this._handleOffsetX = this._elf.nativeElement.getBoundingClientRect().x;
this.left = this.calcOffset(this._value);
this._minBound = this._minBound === undefined ? this._min : this._minBound;
this._maxBound = this._maxBound === undefined ? this._max : this._maxBound;
}
ngOnDestroy() {
document.removeEventListener('mousemove', this.mouseMove, false);
document.removeEventListener('mouseup', this.mouseUp, false);
}
}
| SliderHandle |
views.py | import random
import string
import json
from django.shortcuts import render, redirect, reverse
from django.urls.exceptions import NoReverseMatch
from django.contrib.auth import login, authenticate
from django.conf import settings
from django.views.decorators.http import require_http_methods
from django.http import JsonResponse, HttpResponseBadRequest
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.csrf import csrf_exempt
from django.http.request import split_domain_port
from scatterauth.forms import LoginForm, SignupForm
from scatterauth.settings import app_settings
def get_redirect_url(request):
if request.GET.get('next'):
return request.GET.get('next')
elif request.POST.get('next'):
return request.POST.get('next')
elif settings.LOGIN_REDIRECT_URL:
try:
url = reverse(settings.LOGIN_REDIRECT_URL)
except NoReverseMatch:
url = settings.LOGIN_REDIRECT_URL
return url
@require_http_methods(['POST'])
def login_api(request):
form = LoginForm(request.POST)
if not form.is_valid():
return JsonResponse({'success': False, 'error': json.loads(form.errors.as_json())})
public_key = form.cleaned_data.get('public_key')
nonce = form.cleaned_data.get('nonce')
res = form.cleaned_data.get('res')
if not nonce or not res or not public_key:
return JsonResponse({'error': _(
'Please pass message, signed message, and public key'),
'success': False})
user = authenticate(request, public_key=public_key, nonce=nonce, res=res)
if user:
login(request, user, 'scatterauth.backend.ScatterAuthBackend')
return JsonResponse({'success': True, 'redirect_url': get_redirect_url(request)})
else:
error = _("Can't find a user for the provided signature with public key {public_key}").format(
public_key=public_key)
return JsonResponse({'success': False, 'error': error})
@require_http_methods(['POST'])
def signup_api(request):
if not app_settings.SCATTERAUTH_SIGNUP_ENABLED:
return JsonResponse({'success': False, 'error': _("Sorry, signup's are currently disabled")})
form = SignupForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
setattr(user, username, form.cleaned_data['publicKey'])
user.save()
login(request, user, 'scatterauth.backend.ScatterAuthBackend')
return JsonResponse({'success': True, 'redirect_url': get_redirect_url(request)})
else:
return JsonResponse({'success': False, 'error': json.loads(form.errors.as_json())})
@require_http_methods(['GET', 'POST'])
def signup_view(request, template_name='scatterauth/signup.html'):
'''
1. Creates an instance of a SignupForm.
2. Checks if the registration is enabled.
3. If the registration is closed or form has errors, returns form with errors
4. If the form is valid, saves the user without saving to DB
5. Sets the user address from the form, saves it to DB
6. Logins the user using scatterauth.backend.ScatterAuthBackend
7. Redirects the user to LOGIN_REDIRECT_URL or 'next' in get or post params
:param request: Django request
:param template_name: Template to render
:return: rendered template with form
'''
form = SignupForm()
if not app_settings.SCATTERAUTH_SIGNUP_ENABLED:
form.add_error(None, _("Sorry, signup's are currently disabled"))
else:
if request.method == 'POST':
form = SignupForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
pubkey_field = app_settings.SCATTERAUTH_USER_PUBKEY_FIELD
setattr(user, pubkey_field, form.cleaned_data[pubkey_field])
user.save()
print(pubkey_field)
print(user.email)
login(request, user, 'scatterauth.backend.ScatterAuthBackend')
return redirect(get_redirect_url(request)) | return render(request, template_name, {'form': form}) | |
backend_helpers.go | package endpoints
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
"github.com/nortonlifelock/crypto"
"github.com/nortonlifelock/domain"
"github.com/pkg/errors"
)
// These consts tie an endpoint to it's method. It's used to discern which apiRequest landed at which endpoint in the DBLog table
const (
unauthenticated = "unauthenticated"
getAllJobsEndpoint = "getAllJobs"
getAllLogTypesEndpoint = "GetAllJobTypes"
getLogsEndpoint = "GetAllLogs"
deleteJConfigEndpoint = "DeleteConfig"
createJConfigEndpoint = "CreateConfig"
updateJConfigEndpoint = "UpdateConfig"
getAllJobConfigsEndpoint = "GetAllConfigJobs"
getSourceInByJobIDEndpoint = "GetSourceInForJob"
getSourceOutByJobIDEndpoint = "GetSourceOutByJobID"
getJCAuditHistoryEndpoint = "GetJobConfigAuditHistory"
deleteHistoryEndpoint = "DeleteHistory"
updateHistoryEndpoint = "UpdateHistory"
createHistoryEndpoint = "CreateHistory"
getHistoriesEndpoint = "GetHistories"
getHistoryByIDEndpoint = "getJobHistoryByID"
updateOrgEndpoint = "updateOrg"
deleteOrgEndpoint = "deleteOrg"
createOrgEndpoint = "createOrg"
getAllOrgsEndpoint = "GetAllOrgs"
getOrgForUserEndpoint = "getOrgForUser"
getMyOrgEndpoint = "getMyOrg"
updateSourceEndpoint = "UpdateSource"
deleteSourceEndpoint = "DeleteSource"
createSourceEndpoint = "CreateSource"
getSourcesEndpoint = "GetSources"
updateUserEndpoint = "updateUser"
deleteUserEndpoint = "deleteUser"
createUserEndpoint = "createUser"
getAllUsersEndpoint = "getAllUsers"
getUserByIDEndpoint = "getUserByID"
getUsersNameEndpoint = "GetUsersName"
getUserPermEndpoint = "GetUserPermissionsByUserId"
updateUserPermEndpoint = "UpdateUserPermissionsByUserId"
getPermListEndpoint = "getPermissionList"
createUserPermEndpoint = "CreateUserPermission"
getScansEndpoint = "GetScans"
getAgsEndpoint = "GetGroups"
createScanWebsocketEndpoint = "ScanWebsocket"
loginEndpoint = "login"
logoutEndpoint = "logout"
bulkUpdateEndpoint = "BulkUpdateJob"
bulkUpdateUploadEndpoint = "bulkUpdateUpload"
createWSConnectionEndpoint = "connect"
internalWSEndpoint = "InternalWebSocket"
getVulnBySourceEndpoint = "GetVulnBySource"
getMatchedVulnsEndpoint = "getMatchedVulns"
getTicketStatusCountEndpoint = "GetTicketStatusCount"
burnDownWebSocketEndpoint = "BurnDownWebSocket"
getFieldsForProjectEndpoint = "GetFieldsForProject"
getJIRAURLSEndpoint = "getJiraUrls"
getStatusMapsEndpoint = "getStatusMaps"
getFieldMapsEndpoint = "getFieldMaps"
attachCERFToTicketEndpoint = "attachCERFToTicket"
getAzureTagsEndpoint = "GetAzureTags"
getAWSTagsEndpoint = "GetAWSTags"
createAWSTagsEndpoint = "createAwsTags"
updateAWSTagsEndpoint = "updateAwsTags"
deleteAWSTagsEndpoint = "deleteAwsTags"
getTagsFromDBEndpoint = "getTagsFromDb"
deleteExceptionEndpoint = "DeleteException"
updateExceptionEndpoint = "UpdateException"
postAllJobConfig = "PostAllConfigJobs"
getAllSourceConfigsEndpoint = "GetAllSourceConfigs"
getAllSourcesEndpoint = "GetAllSources"
getJIRAURLsEndpoint = "GetJiraUrls"
getAllExceptionsEndpoint = "GetAllExcepts"
getAllExceptionTypeEndpoints = "GetAllExceptTypes"
deleteExceptionEndpoints = "DeleteException"
updateExceptionEndpoints = "UpdateException"
createExceptionEndpoints = "CreateException"
)
// handleRequest unmarshals the apiRequest body into the provided interface, and logs that fact to the db
func handleRequest(w http.ResponseWriter, r *http.Request, endpoint string) (bearerToken string, ep endpoint, originalBody string, err error) {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
var body []byte
var bearerTokens []string
var exists bool
var user domain.User
bearerTokens, exists = r.Header["Authorization"]
if exists && len(bearerTokens) >= 1 {
bearerToken = bearerTokens[0]
bearerToken = strings.TrimPrefix(bearerToken, "Bearer ")
user, _, err = validateToken(bearerToken)
if err == nil {
body, err = ioutil.ReadAll(io.LimitReader(r.Body, mbSize))
if err == nil {
err = r.Body.Close()
if err == nil | else {
err = fmt.Errorf("error while processing apiRequest [%s]", err.Error())
}
} else {
err = fmt.Errorf("error while processing apiRequest [%s]", err.Error())
}
if err == nil {
// TODO have some sort of flag that distinguishes between errors an activity logs
err = createDBLogForRequest(body, endpoint, r, user)
}
} else {
err = fmt.Errorf("error while processing session bearerToken [%s]", err.Error())
}
} else {
err = errors.New("must include JWT as a bearer token in authorization field")
}
return bearerToken, ep, originalBody, err
}
func grabEndpointFromRequest(request *apiRequest, endpoint string, originalBody string) (ep endpoint, err error) {
if request.Organization != nil {
ep = request.Organization
} else if request.Source != nil {
ep = request.Source
} else if request.Config != nil {
ep = request.Config
} else if request.History != nil {
ep = request.History
} else if request.Histories != nil {
ep = request.Histories
} else if request.Users != nil {
ep = request.Users
} else if request.Tag != nil {
ep = request.Tag
} else if request.JobConfigs != nil {
ep = request.JobConfigs
} else if request.Exceptions != nil {
ep = request.Exceptions
} else if request.BulkUpdateJob != nil {
// do nothing, we'll just use the body of the apiRequest
} else if request.BulkUpdateFile != nil {
// do nothing, we'll just use the body of the apiRequest
} else if request.Permission != nil {
// do nothing, we'll just use the body of the apiRequest
} else if endpoint == getLogsEndpoint {
// do nothing, we'll just use the body of the apiRequest
} else {
err = fmt.Errorf("could not identify apiRequest type - %s", originalBody)
}
return ep, err
}
func createDBLogForRequest(body []byte, endpoint string, r *http.Request, user domain.User) (err error) {
var bodyString = string(body)
// Bulk updates are too long to store in the DB, just take the description line
if endpoint == bulkUpdateUploadEndpoint {
bodyString, err = modifyDBEntryForBulkUpdate(body)
}
var messageToLog string
messageToLog = createMessageToLog(bodyString, messageToLog, r)
_, _, err = Ms.CreateDBLog(sord(user.Username()), messageToLog, endpoint)
if err != nil {
fmt.Printf("error while creating database log [%s]\n", err.Error())
}
return err
}
func createMessageToLog(bodyString string, messageToLog string, r *http.Request) string {
if strings.Contains(strings.ToLower(bodyString), "\"password\":") {
messageToLog = fmt.Sprintf("%s - apiRequest body contained sensitive information and was removed", r.Method)
} else {
messageToLog = fmt.Sprintf("%s - %s", r.Method, bodyString)
}
return messageToLog
}
func modifyDBEntryForBulkUpdate(body []byte) (bodyString string, err error) {
var foundDescLine = false
var req = &apiRequest{}
err = json.Unmarshal(body, req)
if err == nil {
if req.BulkUpdateFile != nil {
var descLineIndex = strings.Index(req.BulkUpdateFile.Contents, "\n")
if descLineIndex > 0 {
bodyString = req.BulkUpdateFile.Contents[0:descLineIndex]
foundDescLine = true
}
}
}
if !foundDescLine {
bodyString = "Could not grab description line from bulk update req"
}
return bodyString, err
}
func respondToUserWithStatusCode(user domain.User, resp *GeneralResp, w http.ResponseWriter, wrapper errorWrapper, endpoint string, status int) {
if wrapper.detailedError != nil {
var username string
if user != nil {
username = sord(user.Username())
} else {
username = unauthenticated
}
_, _, err := Ms.CreateDBLog(username, wrapper.detailedError.Error(), endpoint)
if err == nil {
if wrapper.friendlyError != nil {
resp.Message = wrapper.friendlyError.Error()
} else {
resp.Message = "could not ascertain error information"
}
}
}
var respByte []byte
var err error
respByte, err = json.Marshal(resp)
if err == nil {
w.WriteHeader(status)
_, _ = fmt.Fprintln(w, string(respByte))
} else {
w.WriteHeader(http.StatusUnprocessableEntity)
_ = json.NewEncoder(w).Encode(err)
}
}
func respondToUser(user domain.User, generalResp *GeneralResp, w http.ResponseWriter, wrapper errorWrapper, endpoint string) {
respondToUserWithStatusCode(user, generalResp, w, wrapper, endpoint, http.StatusOK)
}
func validateToken(sessionToken string) (user domain.User, permission domain.Permission, err error) {
var session domain.Session
session, err = Ms.GetSessionByToken(sessionToken)
if err == nil {
if session != nil {
if !session.IsDisabled() {
user, err = Ms.GetUserAnyOrg(session.UserID())
if err == nil {
if !user.IsDisabled() {
user, err = encryptOrDecryptUser(user, crypto.DecryptMode)
if err == nil {
//var claims *customClaims
_, err = checkJWT(sessionToken)
if err == nil {
permission, err = gatherHierarchicalPermissions(user.ID(), session.OrgID())
}
} else {
err = fmt.Errorf("error while decrypting user information - %s", err.Error())
}
} else {
err = errors.New("user is marked as disabled")
}
} else {
err = errors.New("error while retrieving user information [" + err.Error() + "]")
}
} else {
err = errors.New("session marked as disabled")
}
} else {
err = errors.New("could not find matching session token [" + sessionToken + "] in the database")
}
} else {
err = errors.New("error while retrieving session from database [" + err.Error() + "]")
}
return user, permission, err
}
type permissionWithParent struct {
domain.Permission
parent domain.Permission
}
// ParentOrgPermission creates a linked list of organizations from parent to child
func (p *permissionWithParent) ParentOrgPermission() domain.Permission {
return p.parent
}
func gatherHierarchicalPermissions(userID string, orgID string) (basePermission domain.Permission, err error) {
if len(userID) > 0 && len(orgID) > 0 {
var org domain.Organization
org, err = Ms.GetOrganizationByID(orgID)
var nextPermission domain.Permission
for org != nil && err == nil {
nextPermission, err = Ms.GetPermissionByUserOrgID(userID, org.ID())
if err == nil {
if basePermission == nil {
basePermission = nextPermission
} else {
var traverse = basePermission
for traverse.ParentOrgPermission() != nil {
traverse = traverse.ParentOrgPermission()
}
// TODO not sure if this works - should test before pushing
//traverse.SetParentOrgPermission(nextPermission)
traverse = &permissionWithParent{traverse, nextPermission}
}
if len(sord(org.ParentOrgID())) > 0 {
org, err = Ms.GetOrganizationByID(sord(org.ParentOrgID()))
} else {
break
}
}
}
} else {
err = errors.New("could not properly retrieve user information off session token")
}
return basePermission, err
}
| {
if r.Method == http.MethodGet || r.Method == http.MethodDelete {
} else {
originalBody = string(body)
var req = &apiRequest{}
err = json.Unmarshal(body, req)
if err == nil {
ep, err = grabEndpointFromRequest(req, endpoint, originalBody)
} else {
err = fmt.Errorf("error while unmarshalling req [%s]", err.Error())
}
}
} |
ApduControlDisconnect.go | //
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF 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.
//
package model
import (
"encoding/xml"
"github.com/apache/plc4x/plc4go/internal/plc4go/spi/utils"
"io"
)
// Code generated by build-utils. DO NOT EDIT.
// The data-structure of this message
type ApduControlDisconnect struct {
Parent *ApduControl
IApduControlDisconnect
}
// The corresponding interface
type IApduControlDisconnect interface {
LengthInBytes() uint16
LengthInBits() uint16
Serialize(io utils.WriteBuffer) error
xml.Marshaler
}
///////////////////////////////////////////////////////////
// Accessors for discriminator values.
///////////////////////////////////////////////////////////
func (m *ApduControlDisconnect) ControlType() uint8 {
return 0x1
}
func (m *ApduControlDisconnect) InitializeParent(parent *ApduControl) {
}
func NewApduControlDisconnect() *ApduControl {
child := &ApduControlDisconnect{
Parent: NewApduControl(),
}
child.Parent.Child = child
return child.Parent
}
func CastApduControlDisconnect(structType interface{}) *ApduControlDisconnect {
castFunc := func(typ interface{}) *ApduControlDisconnect {
if casted, ok := typ.(ApduControlDisconnect); ok {
return &casted
}
if casted, ok := typ.(*ApduControlDisconnect); ok {
return casted
}
if casted, ok := typ.(ApduControl); ok {
return CastApduControlDisconnect(casted.Child)
}
if casted, ok := typ.(*ApduControl); ok {
return CastApduControlDisconnect(casted.Child)
}
return nil
}
return castFunc(structType)
}
func (m *ApduControlDisconnect) GetTypeName() string {
return "ApduControlDisconnect"
}
func (m *ApduControlDisconnect) LengthInBits() uint16 {
lengthInBits := uint16(0)
return lengthInBits
}
func (m *ApduControlDisconnect) LengthInBytes() uint16 {
return m.LengthInBits() / 8
}
func ApduControlDisconnectParse(io *utils.ReadBuffer) (*ApduControl, error) {
// Create a partially initialized instance
_child := &ApduControlDisconnect{
Parent: &ApduControl{},
}
_child.Parent.Child = _child
return _child.Parent, nil
}
func (m *ApduControlDisconnect) Serialize(io utils.WriteBuffer) error {
ser := func() error {
return nil
}
return m.Parent.SerializeParent(io, m, ser)
}
func (m *ApduControlDisconnect) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
var token xml.Token
var err error
token = start
for {
switch token.(type) {
case xml.StartElement:
tok := token.(xml.StartElement)
switch tok.Name.Local {
}
}
token, err = d.Token()
if err != nil {
if err == io.EOF {
return nil
}
return err
}
}
}
func (m *ApduControlDisconnect) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
return nil | } |
|
Receipt.py | from datetime import *
class Receipt:
def __init__(self, member_number):
# Initialize the receipt as a list for future modifications (adding and removing items)
self.member_items = []
self.member_number = member_number
self.total = 0.0
self.total_tax = 0.0
# Adds items to the member's receipt and displays the current total with tax
def add_item(self, item):
self.member_items.append(item)
item_price = item.floatPrice
self.total_tax += item.tax
self.total += item_price + item.tax
print("{0:<20} {1:>10}".format(item.name, str(item.floatPrice)))
print("TAX: %26.2f" % (self.total_tax))
print("TOTAL: %24.2f" % (self.total))
# Removes items from the receipt and displays the current total with tax
def remove_item(self, item):
if item in self.member_items:
self.member_items.remove(item)
self.total_tax -= item.tax
self.total -= item.floatPrice
print("REMOVED")
print("{0:<20} {1:>10}".format(item.name, str(item.floatPrice)))
print("TAX: %26.2f" % (self.total_tax))
print("TOTAL: %24.2f" % (self.total))
elif len(self.member_items) == 0:
|
else:
print("Item does not exist in member's receipt")
# Finalizes the receipt string and returns it to the POS
def finalize_receipt(self):
# Initialize the receipt string
final_receipt = " RECEIPT\nMembership Number: " + (self.member_number + "\n")
total = 0.0
total_tax = 0.0
final_receipt += "ITEMS:\n"
for item in self.member_items:
final_receipt += ("{0:<20} {1:>10}\n".format(item.name, str(item.floatPrice)))
total_tax += item.tax
total += total_tax + item.floatPrice
final_receipt += ("\nTAX: %26.2f\n" % (self.total_tax))
final_receipt += ("TOTAL: %24.2f\n" % (self.total))
final_receipt += str(date.today())
return final_receipt
| print("No items in the receipt") |
lib.rs | #![warn(missing_docs)]
#![allow(
clippy::return_self_not_must_use,
clippy::unit_arg,
clippy::needless_doctest_main,
clippy::too_many_arguments,
clippy::collapsible_if
)]
//! This crate provides the ability to annotate structs with a `#[derive(Inspectable)]`,
//! which opens a debug interface using [egui](https://github.com/emilk/egui) where you can visually edit the values of your struct live.
//!
//! Your struct will then be available to you as a bevy resource.
//!
//! ## Example
//! ```rust
//! use bevy_inspector_egui::Inspectable;
//!
//! #[derive(Inspectable, Default)]
//! struct Data {
//! should_render: bool,
//! text: String,
//! #[inspectable(min = 42.0, max = 100.0)]
//! size: f32,
//! }
//! ```
//! Add the [`InspectorPlugin`] to your App.
//! ```rust,no_run
//! use bevy_inspector_egui::InspectorPlugin;
//! # use bevy::prelude::*;
//!
//! # #[derive(bevy_inspector_egui::Inspectable, Default)] struct Data {}
//! fn main() {
//! App::new()
//! .add_plugins(DefaultPlugins)
//! .add_plugin(InspectorPlugin::<Data>::new())
//! .run();
//! }
//! ```
//!
//! The list of built-in attributes is documented [here](trait.Inspectable.html#default-attributes).
//!
//! ## World Inspector
//!
//! If you want to display all world entities you can add the [`WorldInspectorPlugin`]:
//! ```rust,no_run
//! use bevy::prelude::*;
//! use bevy_inspector_egui::WorldInspectorPlugin;
//!
//! fn main() {
//! App::new()
//! .add_plugins(DefaultPlugins)
//! .add_plugin(WorldInspectorPlugin::new())
//! .add_startup_system(setup)
//! .run();
//! }
//! # fn setup() {}
//! ```
//! You can configure it by inserting the [`WorldInspectorParams`] resource.
//! In order for custom components to be displayed in the world inspector, you'll need to [register](world_inspector::InspectableRegistry::register) it on the [`InspectableRegistry`](world_inspector::InspectableRegistry).
//!
//! # Features
//! - **clipboard** (enabled by default): enables `egui`'s clipboard integratoin
// //! - **rapier**: adds support for [bevy_rapier3d](https://docs.rs/bevy_rapier3d)
// //! - **rapier2d**: adds support for [bevy_rapier2d](https://docs.rs/bevy_rapier2d)
#[macro_use]
mod utils;
/// Utitly types implementing [`Inspectable`](crate::Inspectable)
pub mod widgets;
#[allow(missing_docs)]
mod impls;
/// Internals for the inspector plugins
pub mod plugin;
/// Configuration for the [`WorldInspectorPlugin`](crate::world_inspector::WorldInspectorPlugin)
pub mod world_inspector;
/// Commonly used imports
pub mod prelude {
pub use crate::{Inspectable, InspectorPlugin, RegisterInspectable, WorldInspectorPlugin};
}
use std::hash::Hasher;
use std::marker::PhantomData;
use bevy::ecs::system::Resource;
use bevy::prelude::{App, Mut, World};
use egui::CtxRef;
use utils::error_label_needs_world;
#[doc(inline)]
pub use world_inspector::{InspectableRegistry, WorldInspectorParams, WorldInspectorPlugin};
/// [`Inspectable`] implementation for foreign types implementing [`Reflect`](bevy::reflect::Reflect)
pub mod reflect;
pub use bevy_egui;
pub use bevy_egui::egui;
/// Derives the [`Inspectable`](Inspectable) trait.
pub use bevy_inspector_egui_derive::Inspectable;
#[doc(inline)]
pub use plugin::InspectorPlugin;
/// Attributes for the built-in [`Inspectable`](Inspectable) implementations
pub mod options {
pub use crate::impls::*;
pub use crate::widgets::button::ButtonAttributes;
pub use crate::widgets::new_window::WindowAttributes;
pub use crate::world_inspector::impls::EntityAttributes;
}
/// The context passed to [`Inspectable::ui`].
pub struct Context<'a> {
/// egui ui context
pub ui_ctx: Option<&'a CtxRef>,
/// The world is only available when not using `InspectablePlugin::shared()`
world: Option<*mut World>,
_world_marker: PhantomData<&'a mut ()>,
/// Something to distinguish between siblings.
pub id: Option<u64>,
}
impl<'a> Context<'a> {
/// Returns a reference to the world if the context has access to it
pub fn world(&self) -> Option<&'a World> {
self.world.map(|world| unsafe { &*world })
}
/// Get a mutable reference to the `world` if the inspector has access to it.
///
/// # Safety
/// Users of this function are only allowed to mutate resources and components,
/// but can't do any changes that would result in changes of archetypes.
pub unsafe fn world_mut(&mut self) -> Option<&'a mut World> {
match self.world {
Some(world) => Some(&mut *world),
None => None,
}
}
/// Returns the provided closure with mutable access to the world, and a context
/// that has *no* access to the world.
///
/// Will display an error message if the context doesn't have world access.
pub fn world_scope(
&mut self,
ui: &mut egui::Ui,
ty: &str,
f: impl FnOnce(&mut World, &mut egui::Ui, &mut Context) -> bool,
) -> bool {
let world = match self.world.take() {
Some(world) => world,
None => return error_label_needs_world(ui, ty),
};
let mut cx = Context {
world: None,
..*self
};
let world = unsafe { &mut *world };
let changed = f(world, ui, &mut cx);
self.world = Some(world);
changed
}
/// Like [`Context::world_scope`], but the context will have world access as well.
///
/// # Safety
/// The function must not use the world in ways that would invalidate archetypes, as
/// types like the `InspectorQuery` will rely on them being the same before and after
/// calling `Inspectable::ui`.
pub unsafe fn world_scope_unchecked(
&mut self,
ui: &mut egui::Ui,
ty: &str,
f: impl FnOnce(&mut World, &mut egui::Ui, &mut Context) -> bool,
) -> bool {
let world = match self.world {
Some(world) => &mut *world,
None => return error_label_needs_world(ui, ty),
};
let changed = f(world, ui, self);
self.world = Some(world);
changed
}
/// Temporarily removes a resource from the world and calls the provided closure with that resource
/// while still having `&mut Context` available.
///
/// Will display an error message if the context doesn't have world access.
pub fn resource_scope<T: Resource, F: FnOnce(&mut egui::Ui, &mut Context, Mut<T>) -> bool>(
&mut self,
ui: &mut egui::Ui,
ty: &str,
f: F,
) -> bool {
// Safety: the world is only used to modify a resource and doesn't change any archetypes
unsafe {
self.world_scope_unchecked(ui, ty, |world, ui, context| {
world.resource_scope(|world, res: Mut<T>| {
let mut context = context.with_world(world);
f(ui, &mut context, res)
})
})
}
}
fn take_world(&mut self) -> Option<(Context, &'a mut World)> {
let world = self.world.take()?;
let world = unsafe { &mut *world };
let context = Context {
world: None,
..*self
};
Some((context, world))
}
}
impl<'a> Context<'a> {
/// Create a new context with access to the world
pub fn new_world_access(ui_ctx: Option<&'a CtxRef>, world: &'a mut World) -> Self {
Context {
ui_ctx,
world: Some(world),
_world_marker: PhantomData,
id: None,
}
}
/// Creates a context without access to `World`
pub fn new_shared(ui_ctx: Option<&'a CtxRef>) -> Self {
Context {
ui_ctx,
world: None,
_world_marker: PhantomData,
id: None,
}
}
/// Same context but with different `world`
pub fn with_world(&self, world: &'a mut World) -> Self {
Context {
world: Some(world),
..*self
}
}
/// Same context but with a derived `id`
pub fn with_id(&mut self, id: u64) -> Context<'_> |
/// Returns the [id](struct.Context.html#structfield.id) if present, otherwise a dummy id.
pub fn id(&self) -> egui::Id {
let dummy_id = egui::Id::new(42);
match self.id {
Some(id) => egui::Id::new(id),
None => dummy_id,
}
}
}
/// This trait describes how a struct should be displayed.
/// It can be derived for structs and enums, see the [crate-level docs](index.html) for how to do that.
///
/// ## Default attributes
/// - **ignore**: hides the field in the inspector
/// - **label**: provides a label instead of using the field name
/// - **read_only**: disables the UI
/// - **collapse**: wraps the ui in an [`egui::CollapsingHeader`].
/// - **default**: only for enums, specifies the default value when selecting a new variant
/// - **wrapper**: wrap field UI in a custom function. Demo in the [rust_types example](https://github.com/jakobhellermann/bevy-inspector-egui/blob/main/examples/rust_types.rs#L20).
/// - **override_where_clause**: specifies which type bounds should be used for generics. For example `#[inspectable(override_where_clause = "") struct Struct(PhantomData<M>)` won't include a `M: Inspectable` bound.
pub trait Inspectable {
/// The `Attributes` associated type specifies what attributes can be passed to a field.
/// See the following snippet for an example:
/// ```rust,no_run
/// # use bevy_inspector_egui::{egui, Inspectable, Context};
/// struct MyCustomType;
/// # #[derive(Clone, Default)]
/// struct MyWidgetAttributes { a: f32, b: Option<String> }
///
/// impl Inspectable for MyCustomType {
/// type Attributes = MyWidgetAttributes;
///
/// fn ui(&mut self, _: &mut egui::Ui, options: MyWidgetAttributes, context: &mut Context) -> bool {
/// println!("a = {}, b = {:?}", options.a, options.b);
/// false
/// }
/// }
///
/// // ...
///
/// #[derive(Inspectable)]
/// struct InspectorData {
/// #[inspectable(a = 10.0, b = None)]
/// value: MyCustomType,
/// }
/// ```
type Attributes: Default + Clone;
/// This methods is responsible for building the egui ui.
/// Returns whether any data was modified.
fn ui(&mut self, ui: &mut egui::Ui, options: Self::Attributes, context: &mut Context) -> bool;
/// Displays the value without any context. Useful for usage outside of the plugins, where
/// there is no access to the world or [`EguiContext`](bevy_egui::EguiContext).
fn ui_raw(&mut self, ui: &mut egui::Ui, options: Self::Attributes) {
let mut empty_context = Context::new_shared(None);
self.ui(ui, options, &mut empty_context);
}
/// Required setup for the bevy application, e.g. registering events. Note that this method will run for every instance of a type.
#[allow(unused_variables)]
fn setup(app: &mut App) {}
}
/// Helper trait for enabling `app.register_inspectable::<T>()`
pub trait RegisterInspectable {
/// Register type `T` so that it can be displayed by the [`WorldInspectorPlugin`](crate::WorldInspectorPlugin).
/// Forwards to [`InspectableRegistry::register`].
fn register_inspectable<T: Inspectable + 'static>(&mut self) -> &mut Self;
}
impl RegisterInspectable for App {
fn register_inspectable<T: Inspectable + 'static>(&mut self) -> &mut Self {
self.world
.get_resource_mut::<InspectableRegistry>()
.unwrap()
.register::<T>();
self
}
}
| {
let mut hasher = std::collections::hash_map::DefaultHasher::default();
if let Some(id) = self.id {
hasher.write_u64(id);
}
hasher.write_u64(id);
let id = hasher.finish();
Context {
id: Some(id),
world: self.world.as_mut().map(|world| *world),
_world_marker: PhantomData,
ui_ctx: self.ui_ctx,
}
} |
terminal.go | // +build !windows
package main
import (
"encoding/json"
"fmt"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/gorilla/websocket"
terminal "golang.org/x/term"
)
type terminalSize struct {
Height int `json:"height"`
Width int `json:"width"`
}
func updateTerminalSize(c *websocket.Conn, writeMutex *sync.Mutex, writeWait time.Duration) error {
width, height, err := terminal.GetSize(int(os.Stdin.Fd()))
if err != nil {
return fmt.Errorf("Could not get terminal size %s\n", err)
}
resizeMessage := terminalSize{height, width}
resizeMessageBinary, err := json.Marshal(&resizeMessage)
if err != nil {
return fmt.Errorf("Could not marshal resizeMessage %s\n", err)
}
writeMutex.Lock()
c.SetWriteDeadline(time.Now().Add(writeWait))
err = c.WriteMessage(websocket.BinaryMessage, append([]byte{1}, resizeMessageBinary...))
writeMutex.Unlock()
if err != nil {
return fmt.Errorf("write: %s", err)
}
return nil
}
func | (c *websocket.Conn, done *chan bool, writeMutex *sync.Mutex, writeWait time.Duration) {
defer func() { *done <- true }()
sigc := make(chan os.Signal, 1)
signal.Notify(sigc, syscall.SIGWINCH)
for {
<-sigc
err := updateTerminalSize(c, writeMutex, writeWait)
if err != nil {
fmt.Println(err)
return
}
}
}
| handleTerminalResize |
testutils.py | try:
from configparser import RawConfigParser
except ImportError:
from ConfigParser import RawConfigParser
import logging
import os
import re
import socket
import threading
from stomp.backward import *
log = logging.getLogger('testutils.py')
config = RawConfigParser()
config.read(os.path.join(os.path.dirname(__file__), 'setup.ini'))
header_re = re.compile(r'[^:]+:.*')
if sys.hexversion >= 0x03000000: # Python 3+
from stomp.test.p3testutils import *
else: # Python 2
from stomp.test.p2testutils import *
def get_environ(name):
try:
return os.environ[name]
except:
return None
def get_default_host():
host = config.get('default', 'host')
port = config.get('default', 'port')
return [(get_environ('STD_HOST') or host, int(get_environ('STD_PORT') or port))]
def get_default_vhost():
try:
vhost = config.get('default', 'vhost')
except:
vhost = None
return get_environ('STD_VHOST') or vhost
def get_default_user():
user = config.get('default', 'user')
return get_environ('STD_USER') or user
def get_default_password():
password = config.get('default', 'password')
return get_environ('STD_PASSWORD') or password
def get_ipv6_host():
host = config.get('ipv6', 'host')
port = config.get('ipv6', 'port')
return [(get_environ('IPV6_HOST') or host, int(get_environ('IPV6_PORT') or port))]
def get_default_ssl_host():
host = config.get('default', 'host')
port = config.get('default', 'ssl_port')
return [(get_environ('STD_HOST') or host, int(get_environ('STD_SSL_PORT') or port))]
def get_sni_ssl_host():
host = config.get('sni', 'host')
port = config.get('sni', 'ssl_port')
return [(get_environ('SNI_HOST') or host, int(get_environ('SNI_SSL_PORT') or port))]
def get_rabbitmq_host():
host = config.get('rabbitmq', 'host')
port = config.get('rabbitmq', 'port')
return [(get_environ('RABBITMQ_HOST') or host, int(get_environ('RABBITMQ_PORT') or port))]
def get_rabbitmq_user():
user = config.get('rabbitmq', 'user')
return get_environ('RABBITMQ_USER') or user
def get_rabbitmq_password():
password = config.get('rabbitmq', 'password')
return get_environ('RABBITMQ_PASSWORD') or password
def get_stompserver_host():
host = config.get('stompserver', 'host')
port = config.get('stompserver', 'port')
return [(get_environ('STOMPSERVER_HOST') or host, int(get_environ('STOMPSERVER_PORT') or port))]
def get_apollo_host():
host = config.get('apollo', 'host')
port = config.get('apollo', 'port')
return [(get_environ('APOLLO_HOST') or host, int(get_environ('APOLLO_PORT') or port))]
class TestStompServer(object):
def __init__(self, host, port):
self.host = host
self.port = port
self.frames = []
def start(self):
log.debug('Starting stomp server')
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.s.bind((self.host, self.port))
self.s.listen(1)
self.running = True
thread = threading.Thread(None, self.run)
thread.daemon = True
thread.start()
self.stopped = False
log.debug('Stomp server started')
def stop(self):
log.debug('Stopping test server')
if self.conn:
try:
self.conn.shutdown(socket.SHUT_WR)
except Exception:
pass
self.conn.close()
if self.s:
self.s.close()
self.running = False
self.conn = None
self.s = None
self.stopped = True
log.debug('Connection stopped')
def get_next_frame(self):
if len(self.frames) > 0:
rtn = self.frames[0]
del self.frames[0]
return rtn
else:
return ''
def add_frame(self, frame):
self.frames.append(frame)
def run(self):
|
class TestStdin(object):
pass
class TestStdout(object):
def __init__(self, test):
self.test = test
self.expects = []
def expect(self, txt):
self.expects.insert(0, re.compile(txt))
def write(self, txt):
txt = txt.rstrip()
if txt != '':
print(txt)
if txt == '>' or txt == '' or header_re.match(txt):
return
if len(self.expects) == 0:
self.test.fail('No expectations - actual "%s"' % txt)
return
for x in range(0, len(self.expects)):
chk = self.expects[x]
if chk.match(txt):
del self.expects[x]
return
self.test.fail('"%s" was not expected' % txt)
def flush(self):
pass
| self.conn, _ = self.s.accept()
while self.running:
try:
_ = self.conn.recv(1024)
frame = self.get_next_frame()
if self.conn is None:
break
if frame is not None:
self.conn.send(encode(frame))
except Exception:
_, e, _ = sys.exc_info()
log.debug(e)
break
try:
self.conn.close()
except:
pass
self.stopped = True
log.debug('Run loop completed') |
admin-election-detail.component.spec.ts | import { ComponentFixture, TestBed } from '@angular/core/testing';
import { AdminElectionDetailComponent } from './admin-election-detail.component';
describe('AdminElectionDetailComponent', () => {
let component: AdminElectionDetailComponent;
let fixture: ComponentFixture<AdminElectionDetailComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ AdminElectionDetailComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(AdminElectionDetailComponent);
component = fixture.componentInstance;
fixture.detectChanges();
}); |
it('should create', () => {
expect(component).toBeTruthy();
});
}); | |
mod.rs | use crate::algorithms::geometry::Point;
use crate::helpers::construction::constraints::create_constraint_pipeline_with_transport;
use crate::helpers::models::domain::test_random;
use crate::helpers::models::problem::*;
use crate::helpers::models::solution::{create_route_with_activities, test_activity_with_job};
use crate::models::common::Location;
use crate::models::problem::*;
use crate::models::solution::{Registry, Route};
use crate::models::{Problem, Solution};
use crate::solver::population::create_elitism_population;
use crate::solver::RefinementContext;
use crate::utils::Environment;
use std::sync::Arc;
mod mutation;
pub use self::mutation::*;
pub fn create_default_refinement_ctx(problem: Arc<Problem>) -> RefinementContext {
let environment = Arc::new(Environment::default());
RefinementContext::new( | create_elitism_population(problem.objective.clone(), environment.clone()),
environment,
None,
)
}
/// Generates matrix routes. See `generate_matrix_routes`.
pub fn generate_matrix_routes_with_defaults(rows: usize, cols: usize, is_open_vrp: bool) -> (Problem, Solution) {
generate_matrix_routes(
rows,
cols,
is_open_vrp,
|id, location| test_single_with_id_and_location(id, location),
|v| v,
|data| (data.clone(), data),
)
}
/// Generates problem and solution which has routes distributed uniformly, e.g.:
/// r0 r1 r2 r3
/// -----------
/// 0 4 8 12
/// 1 5 9 13
/// 2 6 10 14
/// 3 7 11 15
pub fn generate_matrix_routes(
rows: usize,
cols: usize,
is_open_vrp: bool,
job_factory: impl Fn(&str, Option<Location>) -> Arc<Single>,
vehicle_modify: impl Fn(Vehicle) -> Vehicle,
matrix_modify: impl Fn(Vec<f64>) -> (Vec<f64>, Vec<f64>),
) -> (Problem, Solution) {
let fleet = Arc::new(
FleetBuilder::default()
.add_driver(test_driver_with_costs(empty_costs()))
.add_vehicles(
(0..cols)
.map(|i| {
vehicle_modify(Vehicle {
details: vec![VehicleDetail {
end: if is_open_vrp { None } else { test_vehicle_detail().end },
..test_vehicle_detail()
}],
..test_vehicle_with_id(i.to_string().as_str())
})
})
.collect(),
)
.build(),
);
let registry = Registry::new(&fleet, test_random());
let mut routes: Vec<Route> = Default::default();
let mut jobs: Vec<Job> = Default::default();
(0..cols).for_each(|i| {
routes.push(create_route_with_activities(&fleet, i.to_string().as_str(), Default::default()));
(0..rows).for_each(|j| {
let index = i * rows + j;
let single = job_factory(["c".to_string(), index.to_string()].concat().as_str(), Some(index));
let route = routes.get_mut(i).unwrap();
jobs.push(Job::Single(single.clone()));
let mut activity = test_activity_with_job(single);
activity.place.location = index;
route.tour.insert_last(activity);
});
});
let (durations, distances) = matrix_modify(generate_matrix_from_sizes(rows, cols));
let matrix_data = MatrixData::new(0, None, durations, distances);
let transport = create_matrix_transport_cost(vec![matrix_data]).unwrap();
let jobs = Jobs::new(&fleet, jobs, &transport);
let problem = Problem {
fleet,
jobs: Arc::new(jobs),
locks: vec![],
// TODO pass transport costs with constraint
constraint: Arc::new(create_constraint_pipeline_with_transport()),
activity: Arc::new(TestActivityCost::default()),
transport,
objective: Arc::new(ObjectiveCost::default()),
extras: Arc::new(Default::default()),
};
let solution = Solution { registry, routes, unassigned: Default::default(), extras: Arc::new(Default::default()) };
(problem, solution)
}
fn generate_matrix_from_sizes(rows: usize, cols: usize) -> Vec<f64> {
let size = cols * rows;
let mut data = vec![0.; size * size];
(0..size).for_each(|i| {
let (left1, right1) = (i / rows, i % rows);
((i + 1)..size).for_each(|j| {
let (left2, right2) = (j / rows, j % rows);
let left_delta = left1 as f64 - left2 as f64;
let right_delta = right1 as f64 - right2 as f64;
let value = (left_delta * left_delta + right_delta * right_delta).sqrt();
let sym_j = (j as i32 + (j as i32 - i as i32) * (size as i32 - 1)) as usize;
data[i * size + j] = value;
data[i * size + sym_j] = value;
});
});
data
}
pub fn generate_matrix_distances_from_points(points: &[Point]) -> Vec<f64> {
points.iter().cloned().flat_map(|p_a| points.iter().map(move |p_b| p_a.distance_to_point(p_b))).collect()
} | problem.clone(), |
headers.js | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as tslib_1 from "tslib";
/**
* Polyfill for [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers/Headers), as
* specified in the [Fetch Spec](https://fetch.spec.whatwg.org/#headers-class).
*
* The only known difference between this `Headers` implementation and the spec is the
* lack of an `entries` method.
*
* @usageNotes
* ### Example
*
* ```
* import {Headers} from '@angular/http';
*
* var firstHeaders = new Headers();
* firstHeaders.append('Content-Type', 'image/jpeg');
* console.log(firstHeaders.get('Content-Type')) //'image/jpeg'
*
* // Create headers from Plain Old JavaScript Object
* var secondHeaders = new Headers({
* 'X-My-Custom-Header': 'Angular'
* });
* console.log(secondHeaders.get('X-My-Custom-Header')); //'Angular'
*
* var thirdHeaders = new Headers(secondHeaders);
* console.log(thirdHeaders.get('X-My-Custom-Header')); //'Angular'
* ```
*
* @deprecated see https://angular.io/guide/http
*/
var Headers = /** @class */ (function () {
// TODO(vicb): any -> string|string[]
function | (headers) {
var _this = this;
/** @internal header names are lower case */
this._headers = new Map();
/** @internal map lower case names to actual names */
this._normalizedNames = new Map();
if (!headers) {
return;
}
if (headers instanceof Headers) {
headers.forEach(function (values, name) {
values.forEach(function (value) { return _this.append(name, value); });
});
return;
}
Object.keys(headers).forEach(function (name) {
var values = Array.isArray(headers[name]) ? headers[name] : [headers[name]];
_this.delete(name);
values.forEach(function (value) { return _this.append(name, value); });
});
}
/**
* Returns a new Headers instance from the given DOMString of Response Headers
*/
Headers.fromResponseHeaderString = function (headersString) {
var headers = new Headers();
headersString.split('\n').forEach(function (line) {
var index = line.indexOf(':');
if (index > 0) {
var name_1 = line.slice(0, index);
var value = line.slice(index + 1).trim();
headers.set(name_1, value);
}
});
return headers;
};
/**
* Appends a header to existing list of header values for a given header name.
*/
Headers.prototype.append = function (name, value) {
var values = this.getAll(name);
if (values === null) {
this.set(name, value);
}
else {
values.push(value);
}
};
/**
* Deletes all header values for the given name.
*/
Headers.prototype.delete = function (name) {
var lcName = name.toLowerCase();
this._normalizedNames.delete(lcName);
this._headers.delete(lcName);
};
Headers.prototype.forEach = function (fn) {
var _this = this;
this._headers.forEach(function (values, lcName) { return fn(values, _this._normalizedNames.get(lcName), _this._headers); });
};
/**
* Returns first header that matches given name.
*/
Headers.prototype.get = function (name) {
var values = this.getAll(name);
if (values === null) {
return null;
}
return values.length > 0 ? values[0] : null;
};
/**
* Checks for existence of header by given name.
*/
Headers.prototype.has = function (name) { return this._headers.has(name.toLowerCase()); };
/**
* Returns the names of the headers
*/
Headers.prototype.keys = function () { return Array.from(this._normalizedNames.values()); };
/**
* Sets or overrides header value for given name.
*/
Headers.prototype.set = function (name, value) {
if (Array.isArray(value)) {
if (value.length) {
this._headers.set(name.toLowerCase(), [value.join(',')]);
}
}
else {
this._headers.set(name.toLowerCase(), [value]);
}
this.mayBeSetNormalizedName(name);
};
/**
* Returns values of all headers.
*/
Headers.prototype.values = function () { return Array.from(this._headers.values()); };
/**
* Returns string of all headers.
*/
// TODO(vicb): returns {[name: string]: string[]}
Headers.prototype.toJSON = function () {
var _this = this;
var serialized = {};
this._headers.forEach(function (values, name) {
var split = [];
values.forEach(function (v) { return split.push.apply(split, tslib_1.__spread(v.split(','))); });
serialized[_this._normalizedNames.get(name)] = split;
});
return serialized;
};
/**
* Returns list of header values for a given name.
*/
Headers.prototype.getAll = function (name) {
return this.has(name) ? this._headers.get(name.toLowerCase()) || null : null;
};
/**
* This method is not implemented.
*/
Headers.prototype.entries = function () { throw new Error('"entries" method is not implemented on Headers class'); };
Headers.prototype.mayBeSetNormalizedName = function (name) {
var lcName = name.toLowerCase();
if (!this._normalizedNames.has(lcName)) {
this._normalizedNames.set(lcName, name);
}
};
return Headers;
}());
export { Headers };
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaGVhZGVycy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uLy4uLy4uLy4uLy4uL3BhY2thZ2VzL2h0dHAvc3JjL2hlYWRlcnMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7Ozs7OztHQU1HOztBQUVIOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7O0dBNEJHO0FBQ0g7SUFNRSxxQ0FBcUM7SUFDckMsaUJBQVksT0FBNEM7UUFBeEQsaUJBaUJDO1FBdkJELDRDQUE0QztRQUM1QyxhQUFRLEdBQTBCLElBQUksR0FBRyxFQUFFLENBQUM7UUFDNUMscURBQXFEO1FBQ3JELHFCQUFnQixHQUF3QixJQUFJLEdBQUcsRUFBRSxDQUFDO1FBSWhELElBQUksQ0FBQyxPQUFPLEVBQUU7WUFDWixPQUFPO1NBQ1I7UUFFRCxJQUFJLE9BQU8sWUFBWSxPQUFPLEVBQUU7WUFDOUIsT0FBTyxDQUFDLE9BQU8sQ0FBQyxVQUFDLE1BQWdCLEVBQUUsSUFBWTtnQkFDN0MsTUFBTSxDQUFDLE9BQU8sQ0FBQyxVQUFBLEtBQUssSUFBSSxPQUFBLEtBQUksQ0FBQyxNQUFNLENBQUMsSUFBSSxFQUFFLEtBQUssQ0FBQyxFQUF4QixDQUF3QixDQUFDLENBQUM7WUFDcEQsQ0FBQyxDQUFDLENBQUM7WUFDSCxPQUFPO1NBQ1I7UUFFRCxNQUFNLENBQUMsSUFBSSxDQUFDLE9BQU8sQ0FBQyxDQUFDLE9BQU8sQ0FBQyxVQUFDLElBQVk7WUFDeEMsSUFBTSxNQUFNLEdBQWEsS0FBSyxDQUFDLE9BQU8sQ0FBQyxPQUFPLENBQUMsSUFBSSxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMsT0FBTyxDQUFDLElBQUksQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLE9BQU8sQ0FBQyxJQUFJLENBQUMsQ0FBQyxDQUFDO1lBQ3hGLEtBQUksQ0FBQyxNQUFNLENBQUMsSUFBSSxDQUFDLENBQUM7WUFDbEIsTUFBTSxDQUFDLE9BQU8sQ0FBQyxVQUFBLEtBQUssSUFBSSxPQUFBLEtBQUksQ0FBQyxNQUFNLENBQUMsSUFBSSxFQUFFLEtBQUssQ0FBQyxFQUF4QixDQUF3QixDQUFDLENBQUM7UUFDcEQsQ0FBQyxDQUFDLENBQUM7SUFDTCxDQUFDO0lBRUQ7O09BRUc7SUFDSSxnQ0FBd0IsR0FBL0IsVUFBZ0MsYUFBcUI7UUFDbkQsSUFBTSxPQUFPLEdBQUcsSUFBSSxPQUFPLEVBQUUsQ0FBQztRQUU5QixhQUFhLENBQUMsS0FBSyxDQUFDLElBQUksQ0FBQyxDQUFDLE9BQU8sQ0FBQyxVQUFBLElBQUk7WUFDcEMsSUFBTSxLQUFLLEdBQUcsSUFBSSxDQUFDLE9BQU8sQ0FBQyxHQUFHLENBQUMsQ0FBQztZQUNoQyxJQUFJLEtBQUssR0FBRyxDQUFDLEVBQUU7Z0JBQ2IsSUFBTSxNQUFJLEdBQUcsSUFBSSxDQUFDLEtBQUssQ0FBQyxDQUFDLEVBQUUsS0FBSyxDQUFDLENBQUM7Z0JBQ2xDLElBQU0sS0FBSyxHQUFHLElBQUksQ0FBQyxLQUFLLENBQUMsS0FBSyxHQUFHLENBQUMsQ0FBQyxDQUFDLElBQUksRUFBRSxDQUFDO2dCQUMzQyxPQUFPLENBQUMsR0FBRyxDQUFDLE1BQUksRUFBRSxLQUFLLENBQUMsQ0FBQzthQUMxQjtRQUNILENBQUMsQ0FBQyxDQUFDO1FBRUgsT0FBTyxPQUFPLENBQUM7SUFDakIsQ0FBQztJQUVEOztPQUVHO0lBQ0gsd0JBQU0sR0FBTixVQUFPLElBQVksRUFBRSxLQUFhO1FBQ2hDLElBQU0sTUFBTSxHQUFHLElBQUksQ0FBQyxNQUFNLENBQUMsSUFBSSxDQUFDLENBQUM7UUFFakMsSUFBSSxNQUFNLEtBQUssSUFBSSxFQUFFO1lBQ25CLElBQUksQ0FBQyxHQUFHLENBQUMsSUFBSSxFQUFFLEtBQUssQ0FBQyxDQUFDO1NBQ3ZCO2FBQU07WUFDTCxNQUFNLENBQUMsSUFBSSxDQUFDLEtBQUssQ0FBQyxDQUFDO1NBQ3BCO0lBQ0gsQ0FBQztJQUVEOztPQUVHO0lBQ0gsd0JBQU0sR0FBTixVQUFRLElBQVk7UUFDbEIsSUFBTSxNQUFNLEdBQUcsSUFBSSxDQUFDLFdBQVcsRUFBRSxDQUFDO1FBQ2xDLElBQUksQ0FBQyxnQkFBZ0IsQ0FBQyxNQUFNLENBQUMsTUFBTSxDQUFDLENBQUM7UUFDckMsSUFBSSxDQUFDLFFBQVEsQ0FBQyxNQUFNLENBQUMsTUFBTSxDQUFDLENBQUM7SUFDL0IsQ0FBQztJQUVELHlCQUFPLEdBQVAsVUFBUSxFQUFzRjtRQUE5RixpQkFJQztRQUZDLElBQUksQ0FBQyxRQUFRLENBQUMsT0FBTyxDQUNqQixVQUFDLE1BQU0sRUFBRSxNQUFNLElBQUssT0FBQSxFQUFFLENBQUMsTUFBTSxFQUFFLEtBQUksQ0FBQyxnQkFBZ0IsQ0FBQyxHQUFHLENBQUMsTUFBTSxDQUFDLEVBQUUsS0FBSSxDQUFDLFFBQVEsQ0FBQyxFQUE1RCxDQUE0RCxDQUFDLENBQUM7SUFDeEYsQ0FBQztJQUVEOztPQUVHO0lBQ0gscUJBQUcsR0FBSCxVQUFJLElBQVk7UUFDZCxJQUFNLE1BQU0sR0FBRyxJQUFJLENBQUMsTUFBTSxDQUFDLElBQUksQ0FBQyxDQUFDO1FBRWpDLElBQUksTUFBTSxLQUFLLElBQUksRUFBRTtZQUNuQixPQUFPLElBQUksQ0FBQztTQUNiO1FBRUQsT0FBTyxNQUFNLENBQUMsTUFBTSxHQUFHLENBQUMsQ0FBQyxDQUFDLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQyxJQUFJLENBQUM7SUFDOUMsQ0FBQztJQUVEOztPQUVHO0lBQ0gscUJBQUcsR0FBSCxVQUFJLElBQVksSUFBYSxPQUFPLElBQUksQ0FBQyxRQUFRLENBQUMsR0FBRyxDQUFDLElBQUksQ0FBQyxXQUFXLEVBQUUsQ0FBQyxDQUFDLENBQUMsQ0FBQztJQUU1RTs7T0FFRztJQUNILHNCQUFJLEdBQUosY0FBbUIsT0FBTyxLQUFLLENBQUMsSUFBSSxDQUFDLElBQUksQ0FBQyxnQkFBZ0IsQ0FBQyxNQUFNLEVBQUUsQ0FBQyxDQUFDLENBQUMsQ0FBQztJQUV2RTs7T0FFRztJQUNILHFCQUFHLEdBQUgsVUFBSSxJQUFZLEVBQUUsS0FBc0I7UUFDdEMsSUFBSSxLQUFLLENBQUMsT0FBTyxDQUFDLEtBQUssQ0FBQyxFQUFFO1lBQ3hCLElBQUksS0FBSyxDQUFDLE1BQU0sRUFBRTtnQkFDaEIsSUFBSSxDQUFDLFFBQVEsQ0FBQyxHQUFHLENBQUMsSUFBSSxDQUFDLFdBQVcsRUFBRSxFQUFFLENBQUMsS0FBSyxDQUFDLElBQUksQ0FBQyxHQUFHLENBQUMsQ0FBQyxDQUFDLENBQUM7YUFDMUQ7U0FDRjthQUFNO1lBQ0wsSUFBSSxDQUFDLFFBQVEsQ0FBQyxHQUFHLENBQUMsSUFBSSxDQUFDLFdBQVcsRUFBRSxFQUFFLENBQUMsS0FBSyxDQUFDLENBQUMsQ0FBQztTQUNoRDtRQUNELElBQUksQ0FBQyxzQkFBc0IsQ0FBQyxJQUFJLENBQUMsQ0FBQztJQUNwQyxDQUFDO0lBRUQ7O09BRUc7SUFDSCx3QkFBTSxHQUFOLGNBQXVCLE9BQU8sS0FBSyxDQUFDLElBQUksQ0FBQyxJQUFJLENBQUMsUUFBUSxDQUFDLE1BQU0sRUFBRSxDQUFDLENBQUMsQ0FBQyxDQUFDO0lBRW5FOztPQUVHO0lBQ0gsaURBQWlEO0lBQ2pELHdCQUFNLEdBQU47UUFBQSxpQkFVQztRQVRDLElBQU0sVUFBVSxHQUErQixFQUFFLENBQUM7UUFFbEQsSUFBSSxDQUFDLFFBQVEsQ0FBQyxPQUFPLENBQUMsVUFBQyxNQUFnQixFQUFFLElBQVk7WUFDbkQsSUFBTSxLQUFLLEdBQWEsRUFBRSxDQUFDO1lBQzNCLE1BQU0sQ0FBQyxPQUFPLENBQUMsVUFBQSxDQUFDLElBQUksT0FBQSxLQUFLLENBQUMsSUFBSSxPQUFWLEtBQUssbUJBQVMsQ0FBQyxDQUFDLEtBQUssQ0FBQyxHQUFHLENBQUMsSUFBMUIsQ0FBMkIsQ0FBQyxDQUFDO1lBQ2pELFVBQVUsQ0FBQyxLQUFJLENBQUMsZ0JBQWdCLENBQUMsR0FBRyxDQUFDLElBQUksQ0FBRyxDQUFDLEdBQUcsS0FBSyxDQUFDO1FBQ3hELENBQUMsQ0FBQyxDQUFDO1FBRUgsT0FBTyxVQUFVLENBQUM7SUFDcEIsQ0FBQztJQUVEOztPQUVHO0lBQ0gsd0JBQU0sR0FBTixVQUFPLElBQVk7UUFDakIsT0FBTyxJQUFJLENBQUMsR0FBRyxDQUFDLElBQUksQ0FBQyxDQUFDLENBQUMsQ0FBQyxJQUFJLENBQUMsUUFBUSxDQUFDLEdBQUcsQ0FBQyxJQUFJLENBQUMsV0FBVyxFQUFFLENBQUMsSUFBSSxJQUFJLENBQUMsQ0FBQyxDQUFDLElBQUksQ0FBQztJQUMvRSxDQUFDO0lBRUQ7O09BRUc7SUFDSCx5QkFBTyxHQUFQLGNBQVksTUFBTSxJQUFJLEtBQUssQ0FBQyxzREFBc0QsQ0FBQyxDQUFDLENBQUMsQ0FBQztJQUU5RSx3Q0FBc0IsR0FBOUIsVUFBK0IsSUFBWTtRQUN6QyxJQUFNLE1BQU0sR0FBRyxJQUFJLENBQUMsV0FBVyxFQUFFLENBQUM7UUFFbEMsSUFBSSxDQUFDLElBQUksQ0FBQyxnQkFBZ0IsQ0FBQyxHQUFHLENBQUMsTUFBTSxDQUFDLEVBQUU7WUFDdEMsSUFBSSxDQUFDLGdCQUFnQixDQUFDLEdBQUcsQ0FBQyxNQUFNLEVBQUUsSUFBSSxDQUFDLENBQUM7U0FDekM7SUFDSCxDQUFDO0lBQ0gsY0FBQztBQUFELENBQUMsQUFySkQsSUFxSkMiLCJzb3VyY2VzQ29udGVudCI6WyIvKipcbiAqIEBsaWNlbnNlXG4gKiBDb3B5cmlnaHQgR29vZ2xlIEluYy4gQWxsIFJpZ2h0cyBSZXNlcnZlZC5cbiAqXG4gKiBVc2Ugb2YgdGhpcyBzb3VyY2UgY29kZSBpcyBnb3Zlcm5lZCBieSBhbiBNSVQtc3R5bGUgbGljZW5zZSB0aGF0IGNhbiBiZVxuICogZm91bmQgaW4gdGhlIExJQ0VOU0UgZmlsZSBhdCBodHRwczovL2FuZ3VsYXIuaW8vbGljZW5zZVxuICovXG5cbi8qKlxuICogUG9seWZpbGwgZm9yIFtIZWFkZXJzXShodHRwczovL2RldmVsb3Blci5tb3ppbGxhLm9yZy9lbi1VUy9kb2NzL1dlYi9BUEkvSGVhZGVycy9IZWFkZXJzKSwgYXNcbiAqIHNwZWNpZmllZCBpbiB0aGUgW0ZldGNoIFNwZWNdKGh0dHBzOi8vZmV0Y2guc3BlYy53aGF0d2cub3JnLyNoZWFkZXJzLWNsYXNzKS5cbiAqXG4gKiBUaGUgb25seSBrbm93biBkaWZmZXJlbmNlIGJldHdlZW4gdGhpcyBgSGVhZGVyc2AgaW1wbGVtZW50YXRpb24gYW5kIHRoZSBzcGVjIGlzIHRoZVxuICogbGFjayBvZiBhbiBgZW50cmllc2AgbWV0aG9kLlxuICpcbiAqIEB1c2FnZU5vdGVzXG4gKiAjIyMgRXhhbXBsZVxuICpcbiAqIGBgYFxuICogaW1wb3J0IHtIZWFkZXJzfSBmcm9tICdAYW5ndWxhci9odHRwJztcbiAqXG4gKiB2YXIgZmlyc3RIZWFkZXJzID0gbmV3IEhlYWRlcnMoKTtcbiAqIGZpcnN0SGVhZGVycy5hcHBlbmQoJ0NvbnRlbnQtVHlwZScsICdpbWFnZS9qcGVnJyk7XG4gKiBjb25zb2xlLmxvZyhmaXJzdEhlYWRlcnMuZ2V0KCdDb250ZW50LVR5cGUnKSkgLy8naW1hZ2UvanBlZydcbiAqXG4gKiAvLyBDcmVhdGUgaGVhZGVycyBmcm9tIFBsYWluIE9sZCBKYXZhU2NyaXB0IE9iamVjdFxuICogdmFyIHNlY29uZEhlYWRlcnMgPSBuZXcgSGVhZGVycyh7XG4gKiAgICdYLU15LUN1c3RvbS1IZWFkZXInOiAnQW5ndWxhcidcbiAqIH0pO1xuICogY29uc29sZS5sb2coc2Vjb25kSGVhZGVycy5nZXQoJ1gtTXktQ3VzdG9tLUhlYWRlcicpKTsgLy8nQW5ndWxhcidcbiAqXG4gKiB2YXIgdGhpcmRIZWFkZXJzID0gbmV3IEhlYWRlcnMoc2Vjb25kSGVhZGVycyk7XG4gKiBjb25zb2xlLmxvZyh0aGlyZEhlYWRlcnMuZ2V0KCdYLU15LUN1c3RvbS1IZWFkZXInKSk7IC8vJ0FuZ3VsYXInXG4gKiBgYGBcbiAqXG4gKiBAZGVwcmVjYXRlZCBzZWUgaHR0cHM6Ly9hbmd1bGFyLmlvL2d1aWRlL2h0dHBcbiAqL1xuZXhwb3J0IGNsYXNzIEhlYWRlcnMge1xuICAvKiogQGludGVybmFsIGhlYWRlciBuYW1lcyBhcmUgbG93ZXIgY2FzZSAqL1xuICBfaGVhZGVyczogTWFwPHN0cmluZywgc3RyaW5nW10+ID0gbmV3IE1hcCgpO1xuICAvKiogQGludGVybmFsIG1hcCBsb3dlciBjYXNlIG5hbWVzIHRvIGFjdHVhbCBuYW1lcyAqL1xuICBfbm9ybWFsaXplZE5hbWVzOiBNYXA8c3RyaW5nLCBzdHJpbmc+ID0gbmV3IE1hcCgpO1xuXG4gIC8vIFRPRE8odmljYik6IGFueSAtPiBzdHJpbmd8c3RyaW5nW11cbiAgY29uc3RydWN0b3IoaGVhZGVycz86IEhlYWRlcnN8e1tuYW1lOiBzdHJpbmddOiBhbnl9fG51bGwpIHtcbiAgICBpZiAoIWhlYWRlcnMpIHtcbiAgICAgIHJldHVybjtcbiAgICB9XG5cbiAgICBpZiAoaGVhZGVycyBpbnN0YW5jZW9mIEhlYWRlcnMpIHtcbiAgICAgIGhlYWRlcnMuZm9yRWFjaCgodmFsdWVzOiBzdHJpbmdbXSwgbmFtZTogc3RyaW5nKSA9PiB7XG4gICAgICAgIHZhbHVlcy5mb3JFYWNoKHZhbHVlID0+IHRoaXMuYXBwZW5kKG5hbWUsIHZhbHVlKSk7XG4gICAgICB9KTtcbiAgICAgIHJldHVybjtcbiAgICB9XG5cbiAgICBPYmplY3Qua2V5cyhoZWFkZXJzKS5mb3JFYWNoKChuYW1lOiBzdHJpbmcpID0+IHtcbiAgICAgIGNvbnN0IHZhbHVlczogc3RyaW5nW10gPSBBcnJheS5pc0FycmF5KGhlYWRlcnNbbmFtZV0pID8gaGVhZGVyc1tuYW1lXSA6IFtoZWFkZXJzW25hbWVdXTtcbiAgICAgIHRoaXMuZGVsZXRlKG5hbWUpO1xuICAgICAgdmFsdWVzLmZvckVhY2godmFsdWUgPT4gdGhpcy5hcHBlbmQobmFtZSwgdmFsdWUpKTtcbiAgICB9KTtcbiAgfVxuXG4gIC8qKlxuICAgKiBSZXR1cm5zIGEgbmV3IEhlYWRlcnMgaW5zdGFuY2UgZnJvbSB0aGUgZ2l2ZW4gRE9NU3RyaW5nIG9mIFJlc3BvbnNlIEhlYWRlcnNcbiAgICovXG4gIHN0YXRpYyBmcm9tUmVzcG9uc2VIZWFkZXJTdHJpbmcoaGVhZGVyc1N0cmluZzogc3RyaW5nKTogSGVhZGVycyB7XG4gICAgY29uc3QgaGVhZGVycyA9IG5ldyBIZWFkZXJzKCk7XG5cbiAgICBoZWFkZXJzU3RyaW5nLnNwbGl0KCdcXG4nKS5mb3JFYWNoKGxpbmUgPT4ge1xuICAgICAgY29uc3QgaW5kZXggPSBsaW5lLmluZGV4T2YoJzonKTtcbiAgICAgIGlmIChpbmRleCA+IDApIHtcbiAgICAgICAgY29uc3QgbmFtZSA9IGxpbmUuc2xpY2UoMCwgaW5kZXgpO1xuICAgICAgICBjb25zdCB2YWx1ZSA9IGxpbmUuc2xpY2UoaW5kZXggKyAxKS50cmltKCk7XG4gICAgICAgIGhlYWRlcnMuc2V0KG5hbWUsIHZhbHVlKTtcbiAgICAgIH1cbiAgICB9KTtcblxuICAgIHJldHVybiBoZWFkZXJzO1xuICB9XG5cbiAgLyoqXG4gICAqIEFwcGVuZHMgYSBoZWFkZXIgdG8gZXhpc3RpbmcgbGlzdCBvZiBoZWFkZXIgdmFsdWVzIGZvciBhIGdpdmVuIGhlYWRlciBuYW1lLlxuICAgKi9cbiAgYXBwZW5kKG5hbWU6IHN0cmluZywgdmFsdWU6IHN0cmluZyk6IHZvaWQge1xuICAgIGNvbnN0IHZhbHVlcyA9IHRoaXMuZ2V0QWxsKG5hbWUpO1xuXG4gICAgaWYgKHZhbHVlcyA9PT0gbnVsbCkge1xuICAgICAgdGhpcy5zZXQobmFtZSwgdmFsdWUpO1xuICAgIH0gZWxzZSB7XG4gICAgICB2YWx1ZXMucHVzaCh2YWx1ZSk7XG4gICAgfVxuICB9XG5cbiAgLyoqXG4gICAqIERlbGV0ZXMgYWxsIGhlYWRlciB2YWx1ZXMgZm9yIHRoZSBnaXZlbiBuYW1lLlxuICAgKi9cbiAgZGVsZXRlIChuYW1lOiBzdHJpbmcpOiB2b2lkIHtcbiAgICBjb25zdCBsY05hbWUgPSBuYW1lLnRvTG93ZXJDYXNlKCk7XG4gICAgdGhpcy5fbm9ybWFsaXplZE5hbWVzLmRlbGV0ZShsY05hbWUpO1xuICAgIHRoaXMuX2hlYWRlcnMuZGVsZXRlKGxjTmFtZSk7XG4gIH1cblxuICBmb3JFYWNoKGZuOiAodmFsdWVzOiBzdHJpbmdbXSwgbmFtZTogc3RyaW5nfHVuZGVmaW5lZCwgaGVhZGVyczogTWFwPHN0cmluZywgc3RyaW5nW10+KSA9PiB2b2lkKTpcbiAgICAgIHZvaWQge1xuICAgIHRoaXMuX2hlYWRlcnMuZm9yRWFjaChcbiAgICAgICAgKHZhbHVlcywgbGNOYW1lKSA9PiBmbih2YWx1ZXMsIHRoaXMuX25vcm1hbGl6ZWROYW1lcy5nZXQobGNOYW1lKSwgdGhpcy5faGVhZGVycykpO1xuICB9XG5cbiAgLyoqXG4gICAqIFJldHVybnMgZmlyc3QgaGVhZGVyIHRoYXQgbWF0Y2hlcyBnaXZlbiBuYW1lLlxuICAgKi9cbiAgZ2V0KG5hbWU6IHN0cmluZyk6IHN0cmluZ3xudWxsIHtcbiAgICBjb25zdCB2YWx1ZXMgPSB0aGlzLmdldEFsbChuYW1lKTtcblxuICAgIGlmICh2YWx1ZXMgPT09IG51bGwpIHtcbiAgICAgIHJldHVybiBudWxsO1xuICAgIH1cblxuICAgIHJldHVybiB2YWx1ZXMubGVuZ3RoID4gMCA/IHZhbHVlc1swXSA6IG51bGw7XG4gIH1cblxuICAvKipcbiAgICogQ2hlY2tzIGZvciBleGlzdGVuY2Ugb2YgaGVhZGVyIGJ5IGdpdmVuIG5hbWUuXG4gICAqL1xuICBoYXMobmFtZTogc3RyaW5nKTogYm9vbGVhbiB7IHJldHVybiB0aGlzLl9oZWFkZXJzLmhhcyhuYW1lLnRvTG93ZXJDYXNlKCkpOyB9XG5cbiAgLyoqXG4gICAqIFJldHVybnMgdGhlIG5hbWVzIG9mIHRoZSBoZWFkZXJzXG4gICAqL1xuICBrZXlzKCk6IHN0cmluZ1tdIHsgcmV0dXJuIEFycmF5LmZyb20odGhpcy5fbm9ybWFsaXplZE5hbWVzLnZhbHVlcygpKTsgfVxuXG4gIC8qKlxuICAgKiBTZXRzIG9yIG92ZXJyaWRlcyBoZWFkZXIgdmFsdWUgZm9yIGdpdmVuIG5hbWUuXG4gICAqL1xuICBzZXQobmFtZTogc3RyaW5nLCB2YWx1ZTogc3RyaW5nfHN0cmluZ1tdKTogdm9pZCB7XG4gICAgaWYgKEFycmF5LmlzQXJyYXkodmFsdWUpKSB7XG4gICAgICBpZiAodmFsdWUubGVuZ3RoKSB7XG4gICAgICAgIHRoaXMuX2hlYWRlcnMuc2V0KG5hbWUudG9Mb3dlckNhc2UoKSwgW3ZhbHVlLmpvaW4oJywnKV0pO1xuICAgICAgfVxuICAgIH0gZWxzZSB7XG4gICAgICB0aGlzLl9oZWFkZXJzLnNldChuYW1lLnRvTG93ZXJDYXNlKCksIFt2YWx1ZV0pO1xuICAgIH1cbiAgICB0aGlzLm1heUJlU2V0Tm9ybWFsaXplZE5hbWUobmFtZSk7XG4gIH1cblxuICAvKipcbiAgICogUmV0dXJucyB2YWx1ZXMgb2YgYWxsIGhlYWRlcnMuXG4gICAqL1xuICB2YWx1ZXMoKTogc3RyaW5nW11bXSB7IHJldHVybiBBcnJheS5mcm9tKHRoaXMuX2hlYWRlcnMudmFsdWVzKCkpOyB9XG5cbiAgLyoqXG4gICAqIFJldHVybnMgc3RyaW5nIG9mIGFsbCBoZWFkZXJzLlxuICAgKi9cbiAgLy8gVE9ETyh2aWNiKTogcmV0dXJucyB7W25hbWU6IHN0cmluZ106IHN0cmluZ1tdfVxuICB0b0pTT04oKToge1tuYW1lOiBzdHJpbmddOiBhbnl9IHtcbiAgICBjb25zdCBzZXJpYWxpemVkOiB7W25hbWU6IHN0cmluZ106IHN0cmluZ1tdfSA9IHt9O1xuXG4gICAgdGhpcy5faGVhZGVycy5mb3JFYWNoKCh2YWx1ZXM6IHN0cmluZ1tdLCBuYW1lOiBzdHJpbmcpID0+IHtcbiAgICAgIGNvbnN0IHNwbGl0OiBzdHJpbmdbXSA9IFtdO1xuICAgICAgdmFsdWVzLmZvckVhY2godiA9PiBzcGxpdC5wdXNoKC4uLnYuc3BsaXQoJywnKSkpO1xuICAgICAgc2VyaWFsaXplZFt0aGlzLl9ub3JtYWxpemVkTmFtZXMuZ2V0KG5hbWUpICFdID0gc3BsaXQ7XG4gICAgfSk7XG5cbiAgICByZXR1cm4gc2VyaWFsaXplZDtcbiAgfVxuXG4gIC8qKlxuICAgKiBSZXR1cm5zIGxpc3Qgb2YgaGVhZGVyIHZhbHVlcyBmb3IgYSBnaXZlbiBuYW1lLlxuICAgKi9cbiAgZ2V0QWxsKG5hbWU6IHN0cmluZyk6IHN0cmluZ1tdfG51bGwge1xuICAgIHJldHVybiB0aGlzLmhhcyhuYW1lKSA/IHRoaXMuX2hlYWRlcnMuZ2V0KG5hbWUudG9Mb3dlckNhc2UoKSkgfHwgbnVsbCA6IG51bGw7XG4gIH1cblxuICAvKipcbiAgICogVGhpcyBtZXRob2QgaXMgbm90IGltcGxlbWVudGVkLlxuICAgKi9cbiAgZW50cmllcygpIHsgdGhyb3cgbmV3IEVycm9yKCdcImVudHJpZXNcIiBtZXRob2QgaXMgbm90IGltcGxlbWVudGVkIG9uIEhlYWRlcnMgY2xhc3MnKTsgfVxuXG4gIHByaXZhdGUgbWF5QmVTZXROb3JtYWxpemVkTmFtZShuYW1lOiBzdHJpbmcpOiB2b2lkIHtcbiAgICBjb25zdCBsY05hbWUgPSBuYW1lLnRvTG93ZXJDYXNlKCk7XG5cbiAgICBpZiAoIXRoaXMuX25vcm1hbGl6ZWROYW1lcy5oYXMobGNOYW1lKSkge1xuICAgICAgdGhpcy5fbm9ybWFsaXplZE5hbWVzLnNldChsY05hbWUsIG5hbWUpO1xuICAgIH1cbiAgfVxufVxuIl19 | Headers |
logs.rs | use std::borrow::Borrow;
use std::rc::Rc;
use chrono;
use postgres;
use postgres::types::ToSql;
use super::super::super::common_rpc_types::StructuredLog;
use super::super::types::OrderBy;
use super::super::types::{Log, LogQueryParams};
pub fn insert(conn: &postgres::Connection, node_name: &str, logs: Vec<StructuredLog>) -> postgres::Result<()> {
ctrace!("Add log {} : {:?}", node_name, logs);
if logs.is_empty() {
return Ok(())
}
for log_chunk in logs.chunks(1000) {
let mut parameters_positions: Vec<String> = Vec::new();
let mut parameters: Vec<Box<ToSql>> = Vec::new();
for (row_index, log) in log_chunk.iter().enumerate() {
let base_num = row_index * 6;
parameters_positions.push(format!(
"(${}, ${}, ${}, ${}, ${}, ${})",
base_num + 1,
base_num + 2,
base_num + 3,
base_num + 4,
base_num + 5,
base_num + 6
));
let rfc3339with_nano_second = "%Y-%m-%dT%H:%M:%S.%f%z";
let datetime = chrono::DateTime::parse_from_str(&log.timestamp, rfc3339with_nano_second).unwrap();
parameters.push(Box::new(node_name));
parameters.push(Box::new(log.level.clone()));
parameters.push(Box::new(log.target.clone()));
parameters.push(Box::new(log.message.clone()));
parameters.push(Box::new(datetime));
parameters.push(Box::new(log.thread_name.clone()));
}
let full_sql = format!(
"INSERT INTO logs (name, level, target, message, timestamp, thread_name) VALUES {}",
parameters_positions.join(", ")
);
let parameters_ref: Vec<&ToSql> = parameters.iter().map(AsRef::as_ref).collect();
ctrace!("Full query is {}", full_sql);
conn.execute(&full_sql, ¶meters_ref)?;
}
Ok(())
}
pub fn search(conn: &postgres::Connection, params: LogQueryParams) -> postgres::Result<Vec<Log>> {
ctrace!("Search log with {:?}", params);
let mut parameters = Parameters::default();
let mut where_conditions = Vec::new();
if let Some(filter) = params.filter {
if !filter.node_names.is_empty() {
let node_names_index = parameters.add(Rc::new(filter.node_names));
where_conditions.push(format!("name = ANY(${})", node_names_index));
}
if !filter.levels.is_empty() {
let uppercase_levels: Vec<String> =
filter.levels.iter().map(|level| level.to_string().to_uppercase()).collect();
let filters_index = parameters.add(Rc::new(uppercase_levels));
where_conditions.push(format!("level = ANY(${})", filters_index));
}
if !filter.targets.is_empty() {
let targets_index = parameters.add(Rc::new(filter.targets));
where_conditions.push(format!("target = ANY(${})", targets_index));
}
if let Some(thread_name) = filter.thread_name {
let target_index = parameters.add(Rc::new(thread_name));
where_conditions.push(format!("thread_name = ${}", target_index));
}
}
if let Some(search) = params.search {
if search != "" |
}
if let Some(time) = params.time {
if let Some(from) = time.from_time {
let from_index = parameters.add(Rc::new(from));
where_conditions.push(format!("timestamp > ${}", from_index));
}
if let Some(to) = time.to_time {
let to_index = parameters.add(Rc::new(to));
where_conditions.push(format!("timestamp < ${}", to_index));
}
}
let where_clause = if !where_conditions.is_empty() {
"WHERE ".to_string() + &where_conditions.join(" AND ")
} else {
"".to_string()
};
let order_by = params.order_by.unwrap_or(OrderBy::ASC);
let order_by_clause = format!("ORDER BY timestamp {:?}", order_by);
let limit = params.item_per_page.unwrap_or(100);
let limit_clause = format!("LIMIT {}", limit);
// page starts from 1
let offset = params.page.unwrap_or(1) - 1;
let offset_clause = format!("OFFSET {}", offset * limit);
let query_string =
vec!["SELECT * FROM logs", &where_clause, &order_by_clause, &limit_clause, &offset_clause].join(" ");
let query_params: Vec<&ToSql> = parameters.get().iter().map(Borrow::borrow).collect();
let rows = conn.query(&query_string, &query_params[..])?;
Ok(rows
.into_iter()
.map(|row| Log {
id: row.get("id"),
node_name: row.get("name"),
level: row.get("level"),
target: row.get("target"),
timestamp: row.get("timestamp"),
message: format!("{} {}", row.get::<_, String>("thread_name"), row.get::<_, String>("message")),
})
.collect())
}
#[derive(Default)]
struct Parameters {
parameters: Vec<Rc<ToSql>>,
}
impl Parameters {
pub fn add(&mut self, param: Rc<ToSql>) -> usize {
self.parameters.push(param);
self.parameters.len()
}
pub fn get(&self) -> &Vec<Rc<ToSql>> {
&self.parameters
}
}
pub fn get_targets(conn: &postgres::Connection) -> postgres::Result<Vec<String>> {
ctrace!("Query targets");
// let rows = conn.query("SELECT DISTINCT target FROM logs", &[])?;
// Below query prints the same result with above query.
// See https://wiki.postgresql.org/wiki/Loose_indexscan
let rows = conn.query(
"
WITH RECURSIVE t AS (
(SELECT target FROM logs ORDER BY target LIMIT 1) -- parentheses required
UNION ALL
SELECT (SELECT target FROM logs WHERE target > t.target ORDER BY target LIMIT 1)
FROM t
WHERE t.target IS NOT NULL
)
SELECT target FROM t WHERE target IS NOT NULL",
&[],
)?;
Ok(rows.iter().map(|row| row.get("target")).collect())
}
| {
let search_index = parameters.add(Rc::new(format!("%{}%", search)));
where_conditions.push(format!("message ILIKE ${}", search_index));
} |
example.py | import datetime
from typing import Dict
from ..helpers import CollectionAppointment
DESCRIPTION = "Example scraper"
URL = ""
TEST_CASES: Dict[str, Dict[str, str]] = {}
class | :
def __init__(self, days=20, per_day=2, types=5):
self._days = days
self._per_day = per_day
self._types = types
def fetch(self):
now = datetime.datetime.now().date()
entries = []
ap_type = 0
for day in range(self._days):
for idx in range(self._per_day):
entries.append(
CollectionAppointment(
now + datetime.timedelta(days=day + 7),
f"Type{(ap_type % self._types) + 1}",
)
)
ap_type = ap_type + 1
return entries
| Source |
docker_api_swarm_service_test.go | // +build !windows
package main
import (
"fmt"
"path"
"strconv"
"strings"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/api/types/swarm/runtime"
"github.com/docker/docker/integration-cli/checker"
"github.com/docker/docker/integration-cli/daemon"
"github.com/docker/docker/integration-cli/fixtures/plugin"
testdaemon "github.com/docker/docker/internal/test/daemon"
"github.com/go-check/check"
"golang.org/x/net/context"
"golang.org/x/sys/unix"
)
func setPortConfig(portConfig []swarm.PortConfig) testdaemon.ServiceConstructor |
func (s *DockerSwarmSuite) TestAPIServiceUpdatePort(c *check.C) {
d := s.AddDaemon(c, true, true)
// Create a service with a port mapping of 8080:8081.
portConfig := []swarm.PortConfig{{TargetPort: 8081, PublishedPort: 8080}}
serviceID := d.CreateService(c, simpleTestService, setInstances(1), setPortConfig(portConfig))
waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1)
// Update the service: changed the port mapping from 8080:8081 to 8082:8083.
updatedPortConfig := []swarm.PortConfig{{TargetPort: 8083, PublishedPort: 8082}}
remoteService := d.GetService(c, serviceID)
d.UpdateService(c, remoteService, setPortConfig(updatedPortConfig))
// Inspect the service and verify port mapping.
updatedService := d.GetService(c, serviceID)
c.Assert(updatedService.Spec.EndpointSpec, check.NotNil)
c.Assert(len(updatedService.Spec.EndpointSpec.Ports), check.Equals, 1)
c.Assert(updatedService.Spec.EndpointSpec.Ports[0].TargetPort, check.Equals, uint32(8083))
c.Assert(updatedService.Spec.EndpointSpec.Ports[0].PublishedPort, check.Equals, uint32(8082))
}
func (s *DockerSwarmSuite) TestAPISwarmServicesEmptyList(c *check.C) {
d := s.AddDaemon(c, true, true)
services := d.ListServices(c)
c.Assert(services, checker.NotNil)
c.Assert(len(services), checker.Equals, 0, check.Commentf("services: %#v", services))
}
func (s *DockerSwarmSuite) TestAPISwarmServicesCreate(c *check.C) {
d := s.AddDaemon(c, true, true)
instances := 2
id := d.CreateService(c, simpleTestService, setInstances(instances))
waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, instances)
cli, err := d.NewClient()
c.Assert(err, checker.IsNil)
defer cli.Close()
options := types.ServiceInspectOptions{InsertDefaults: true}
// insertDefaults inserts UpdateConfig when service is fetched by ID
resp, _, err := cli.ServiceInspectWithRaw(context.Background(), id, options)
out := fmt.Sprintf("%+v", resp)
c.Assert(err, checker.IsNil)
c.Assert(out, checker.Contains, "UpdateConfig")
// insertDefaults inserts UpdateConfig when service is fetched by ID
resp, _, err = cli.ServiceInspectWithRaw(context.Background(), "top", options)
out = fmt.Sprintf("%+v", resp)
c.Assert(err, checker.IsNil)
c.Assert(string(out), checker.Contains, "UpdateConfig")
service := d.GetService(c, id)
instances = 5
d.UpdateService(c, service, setInstances(instances))
waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, instances)
d.RemoveService(c, service.ID)
waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 0)
}
func (s *DockerSwarmSuite) TestAPISwarmServicesMultipleAgents(c *check.C) {
d1 := s.AddDaemon(c, true, true)
d2 := s.AddDaemon(c, true, false)
d3 := s.AddDaemon(c, true, false)
time.Sleep(1 * time.Second) // make sure all daemons are ready to accept tasks
instances := 9
id := d1.CreateService(c, simpleTestService, setInstances(instances))
waitAndAssert(c, defaultReconciliationTimeout, d1.CheckActiveContainerCount, checker.GreaterThan, 0)
waitAndAssert(c, defaultReconciliationTimeout, d2.CheckActiveContainerCount, checker.GreaterThan, 0)
waitAndAssert(c, defaultReconciliationTimeout, d3.CheckActiveContainerCount, checker.GreaterThan, 0)
waitAndAssert(c, defaultReconciliationTimeout, reducedCheck(sumAsIntegers, d1.CheckActiveContainerCount, d2.CheckActiveContainerCount, d3.CheckActiveContainerCount), checker.Equals, instances)
// reconciliation on d2 node down
d2.Stop(c)
waitAndAssert(c, defaultReconciliationTimeout, reducedCheck(sumAsIntegers, d1.CheckActiveContainerCount, d3.CheckActiveContainerCount), checker.Equals, instances)
// test downscaling
instances = 5
d1.UpdateService(c, d1.GetService(c, id), setInstances(instances))
waitAndAssert(c, defaultReconciliationTimeout, reducedCheck(sumAsIntegers, d1.CheckActiveContainerCount, d3.CheckActiveContainerCount), checker.Equals, instances)
}
func (s *DockerSwarmSuite) TestAPISwarmServicesCreateGlobal(c *check.C) {
d1 := s.AddDaemon(c, true, true)
d2 := s.AddDaemon(c, true, false)
d3 := s.AddDaemon(c, true, false)
d1.CreateService(c, simpleTestService, setGlobalMode)
waitAndAssert(c, defaultReconciliationTimeout, d1.CheckActiveContainerCount, checker.Equals, 1)
waitAndAssert(c, defaultReconciliationTimeout, d2.CheckActiveContainerCount, checker.Equals, 1)
waitAndAssert(c, defaultReconciliationTimeout, d3.CheckActiveContainerCount, checker.Equals, 1)
d4 := s.AddDaemon(c, true, false)
d5 := s.AddDaemon(c, true, false)
waitAndAssert(c, defaultReconciliationTimeout, d4.CheckActiveContainerCount, checker.Equals, 1)
waitAndAssert(c, defaultReconciliationTimeout, d5.CheckActiveContainerCount, checker.Equals, 1)
}
func (s *DockerSwarmSuite) TestAPISwarmServicesUpdate(c *check.C) {
const nodeCount = 3
var daemons [nodeCount]*daemon.Daemon
for i := 0; i < nodeCount; i++ {
daemons[i] = s.AddDaemon(c, true, i == 0)
}
// wait for nodes ready
waitAndAssert(c, 5*time.Second, daemons[0].CheckNodeReadyCount, checker.Equals, nodeCount)
// service image at start
image1 := "busybox:latest"
// target image in update
image2 := "busybox:test"
// create a different tag
for _, d := range daemons {
out, err := d.Cmd("tag", image1, image2)
c.Assert(err, checker.IsNil, check.Commentf(out))
}
// create service
instances := 5
parallelism := 2
rollbackParallelism := 3
id := daemons[0].CreateService(c, serviceForUpdate, setInstances(instances))
// wait for tasks ready
waitAndAssert(c, defaultReconciliationTimeout, daemons[0].CheckRunningTaskImages, checker.DeepEquals,
map[string]int{image1: instances})
// issue service update
service := daemons[0].GetService(c, id)
daemons[0].UpdateService(c, service, setImage(image2))
// first batch
waitAndAssert(c, defaultReconciliationTimeout, daemons[0].CheckRunningTaskImages, checker.DeepEquals,
map[string]int{image1: instances - parallelism, image2: parallelism})
// 2nd batch
waitAndAssert(c, defaultReconciliationTimeout, daemons[0].CheckRunningTaskImages, checker.DeepEquals,
map[string]int{image1: instances - 2*parallelism, image2: 2 * parallelism})
// 3nd batch
waitAndAssert(c, defaultReconciliationTimeout, daemons[0].CheckRunningTaskImages, checker.DeepEquals,
map[string]int{image2: instances})
// Roll back to the previous version. This uses the CLI because
// rollback used to be a client-side operation.
out, err := daemons[0].Cmd("service", "update", "--detach", "--rollback", id)
c.Assert(err, checker.IsNil, check.Commentf(out))
// first batch
waitAndAssert(c, defaultReconciliationTimeout, daemons[0].CheckRunningTaskImages, checker.DeepEquals,
map[string]int{image2: instances - rollbackParallelism, image1: rollbackParallelism})
// 2nd batch
waitAndAssert(c, defaultReconciliationTimeout, daemons[0].CheckRunningTaskImages, checker.DeepEquals,
map[string]int{image1: instances})
}
func (s *DockerSwarmSuite) TestAPISwarmServicesUpdateStartFirst(c *check.C) {
d := s.AddDaemon(c, true, true)
// service image at start
image1 := "busybox:latest"
// target image in update
image2 := "testhealth:latest"
// service started from this image won't pass health check
_, _, err := d.BuildImageWithOut(image2,
`FROM busybox
HEALTHCHECK --interval=1s --timeout=30s --retries=1024 \
CMD cat /status`,
true)
c.Check(err, check.IsNil)
// create service
instances := 5
parallelism := 2
rollbackParallelism := 3
id := d.CreateService(c, serviceForUpdate, setInstances(instances), setUpdateOrder(swarm.UpdateOrderStartFirst), setRollbackOrder(swarm.UpdateOrderStartFirst))
checkStartingTasks := func(expected int) []swarm.Task {
var startingTasks []swarm.Task
waitAndAssert(c, defaultReconciliationTimeout, func(c *check.C) (interface{}, check.CommentInterface) {
tasks := d.GetServiceTasks(c, id)
startingTasks = nil
for _, t := range tasks {
if t.Status.State == swarm.TaskStateStarting {
startingTasks = append(startingTasks, t)
}
}
return startingTasks, nil
}, checker.HasLen, expected)
return startingTasks
}
makeTasksHealthy := func(tasks []swarm.Task) {
for _, t := range tasks {
containerID := t.Status.ContainerStatus.ContainerID
d.Cmd("exec", containerID, "touch", "/status")
}
}
// wait for tasks ready
waitAndAssert(c, defaultReconciliationTimeout, d.CheckRunningTaskImages, checker.DeepEquals,
map[string]int{image1: instances})
// issue service update
service := d.GetService(c, id)
d.UpdateService(c, service, setImage(image2))
// first batch
// The old tasks should be running, and the new ones should be starting.
startingTasks := checkStartingTasks(parallelism)
waitAndAssert(c, defaultReconciliationTimeout, d.CheckRunningTaskImages, checker.DeepEquals,
map[string]int{image1: instances})
// make it healthy
makeTasksHealthy(startingTasks)
waitAndAssert(c, defaultReconciliationTimeout, d.CheckRunningTaskImages, checker.DeepEquals,
map[string]int{image1: instances - parallelism, image2: parallelism})
// 2nd batch
// The old tasks should be running, and the new ones should be starting.
startingTasks = checkStartingTasks(parallelism)
waitAndAssert(c, defaultReconciliationTimeout, d.CheckRunningTaskImages, checker.DeepEquals,
map[string]int{image1: instances - parallelism, image2: parallelism})
// make it healthy
makeTasksHealthy(startingTasks)
waitAndAssert(c, defaultReconciliationTimeout, d.CheckRunningTaskImages, checker.DeepEquals,
map[string]int{image1: instances - 2*parallelism, image2: 2 * parallelism})
// 3nd batch
// The old tasks should be running, and the new ones should be starting.
startingTasks = checkStartingTasks(1)
waitAndAssert(c, defaultReconciliationTimeout, d.CheckRunningTaskImages, checker.DeepEquals,
map[string]int{image1: instances - 2*parallelism, image2: 2 * parallelism})
// make it healthy
makeTasksHealthy(startingTasks)
waitAndAssert(c, defaultReconciliationTimeout, d.CheckRunningTaskImages, checker.DeepEquals,
map[string]int{image2: instances})
// Roll back to the previous version. This uses the CLI because
// rollback is a client-side operation.
out, err := d.Cmd("service", "update", "--detach", "--rollback", id)
c.Assert(err, checker.IsNil, check.Commentf(out))
// first batch
waitAndAssert(c, defaultReconciliationTimeout, d.CheckRunningTaskImages, checker.DeepEquals,
map[string]int{image2: instances - rollbackParallelism, image1: rollbackParallelism})
// 2nd batch
waitAndAssert(c, defaultReconciliationTimeout, d.CheckRunningTaskImages, checker.DeepEquals,
map[string]int{image1: instances})
}
func (s *DockerSwarmSuite) TestAPISwarmServicesFailedUpdate(c *check.C) {
const nodeCount = 3
var daemons [nodeCount]*daemon.Daemon
for i := 0; i < nodeCount; i++ {
daemons[i] = s.AddDaemon(c, true, i == 0)
}
// wait for nodes ready
waitAndAssert(c, 5*time.Second, daemons[0].CheckNodeReadyCount, checker.Equals, nodeCount)
// service image at start
image1 := "busybox:latest"
// target image in update
image2 := "busybox:badtag"
// create service
instances := 5
id := daemons[0].CreateService(c, serviceForUpdate, setInstances(instances))
// wait for tasks ready
waitAndAssert(c, defaultReconciliationTimeout, daemons[0].CheckRunningTaskImages, checker.DeepEquals,
map[string]int{image1: instances})
// issue service update
service := daemons[0].GetService(c, id)
daemons[0].UpdateService(c, service, setImage(image2), setFailureAction(swarm.UpdateFailureActionPause), setMaxFailureRatio(0.25), setParallelism(1))
// should update 2 tasks and then pause
waitAndAssert(c, defaultReconciliationTimeout, daemons[0].CheckServiceUpdateState(id), checker.Equals, swarm.UpdateStatePaused)
v, _ := daemons[0].CheckServiceRunningTasks(id)(c)
c.Assert(v, checker.Equals, instances-2)
// Roll back to the previous version. This uses the CLI because
// rollback used to be a client-side operation.
out, err := daemons[0].Cmd("service", "update", "--detach", "--rollback", id)
c.Assert(err, checker.IsNil, check.Commentf(out))
waitAndAssert(c, defaultReconciliationTimeout, daemons[0].CheckRunningTaskImages, checker.DeepEquals,
map[string]int{image1: instances})
}
func (s *DockerSwarmSuite) TestAPISwarmServiceConstraintRole(c *check.C) {
const nodeCount = 3
var daemons [nodeCount]*daemon.Daemon
for i := 0; i < nodeCount; i++ {
daemons[i] = s.AddDaemon(c, true, i == 0)
}
// wait for nodes ready
waitAndAssert(c, 5*time.Second, daemons[0].CheckNodeReadyCount, checker.Equals, nodeCount)
// create service
constraints := []string{"node.role==worker"}
instances := 3
id := daemons[0].CreateService(c, simpleTestService, setConstraints(constraints), setInstances(instances))
// wait for tasks ready
waitAndAssert(c, defaultReconciliationTimeout, daemons[0].CheckServiceRunningTasks(id), checker.Equals, instances)
// validate tasks are running on worker nodes
tasks := daemons[0].GetServiceTasks(c, id)
for _, task := range tasks {
node := daemons[0].GetNode(c, task.NodeID)
c.Assert(node.Spec.Role, checker.Equals, swarm.NodeRoleWorker)
}
//remove service
daemons[0].RemoveService(c, id)
// create service
constraints = []string{"node.role!=worker"}
id = daemons[0].CreateService(c, simpleTestService, setConstraints(constraints), setInstances(instances))
// wait for tasks ready
waitAndAssert(c, defaultReconciliationTimeout, daemons[0].CheckServiceRunningTasks(id), checker.Equals, instances)
tasks = daemons[0].GetServiceTasks(c, id)
// validate tasks are running on manager nodes
for _, task := range tasks {
node := daemons[0].GetNode(c, task.NodeID)
c.Assert(node.Spec.Role, checker.Equals, swarm.NodeRoleManager)
}
//remove service
daemons[0].RemoveService(c, id)
// create service
constraints = []string{"node.role==nosuchrole"}
id = daemons[0].CreateService(c, simpleTestService, setConstraints(constraints), setInstances(instances))
// wait for tasks created
waitAndAssert(c, defaultReconciliationTimeout, daemons[0].CheckServiceTasks(id), checker.Equals, instances)
// let scheduler try
time.Sleep(250 * time.Millisecond)
// validate tasks are not assigned to any node
tasks = daemons[0].GetServiceTasks(c, id)
for _, task := range tasks {
c.Assert(task.NodeID, checker.Equals, "")
}
}
func (s *DockerSwarmSuite) TestAPISwarmServiceConstraintLabel(c *check.C) {
const nodeCount = 3
var daemons [nodeCount]*daemon.Daemon
for i := 0; i < nodeCount; i++ {
daemons[i] = s.AddDaemon(c, true, i == 0)
}
// wait for nodes ready
waitAndAssert(c, 5*time.Second, daemons[0].CheckNodeReadyCount, checker.Equals, nodeCount)
nodes := daemons[0].ListNodes(c)
c.Assert(len(nodes), checker.Equals, nodeCount)
// add labels to nodes
daemons[0].UpdateNode(c, nodes[0].ID, func(n *swarm.Node) {
n.Spec.Annotations.Labels = map[string]string{
"security": "high",
}
})
for i := 1; i < nodeCount; i++ {
daemons[0].UpdateNode(c, nodes[i].ID, func(n *swarm.Node) {
n.Spec.Annotations.Labels = map[string]string{
"security": "low",
}
})
}
// create service
instances := 3
constraints := []string{"node.labels.security==high"}
id := daemons[0].CreateService(c, simpleTestService, setConstraints(constraints), setInstances(instances))
// wait for tasks ready
waitAndAssert(c, defaultReconciliationTimeout, daemons[0].CheckServiceRunningTasks(id), checker.Equals, instances)
tasks := daemons[0].GetServiceTasks(c, id)
// validate all tasks are running on nodes[0]
for _, task := range tasks {
c.Assert(task.NodeID, checker.Equals, nodes[0].ID)
}
//remove service
daemons[0].RemoveService(c, id)
// create service
constraints = []string{"node.labels.security!=high"}
id = daemons[0].CreateService(c, simpleTestService, setConstraints(constraints), setInstances(instances))
// wait for tasks ready
waitAndAssert(c, defaultReconciliationTimeout, daemons[0].CheckServiceRunningTasks(id), checker.Equals, instances)
tasks = daemons[0].GetServiceTasks(c, id)
// validate all tasks are NOT running on nodes[0]
for _, task := range tasks {
c.Assert(task.NodeID, checker.Not(checker.Equals), nodes[0].ID)
}
//remove service
daemons[0].RemoveService(c, id)
constraints = []string{"node.labels.security==medium"}
id = daemons[0].CreateService(c, simpleTestService, setConstraints(constraints), setInstances(instances))
// wait for tasks created
waitAndAssert(c, defaultReconciliationTimeout, daemons[0].CheckServiceTasks(id), checker.Equals, instances)
// let scheduler try
time.Sleep(250 * time.Millisecond)
tasks = daemons[0].GetServiceTasks(c, id)
// validate tasks are not assigned
for _, task := range tasks {
c.Assert(task.NodeID, checker.Equals, "")
}
//remove service
daemons[0].RemoveService(c, id)
// multiple constraints
constraints = []string{
"node.labels.security==high",
fmt.Sprintf("node.id==%s", nodes[1].ID),
}
id = daemons[0].CreateService(c, simpleTestService, setConstraints(constraints), setInstances(instances))
// wait for tasks created
waitAndAssert(c, defaultReconciliationTimeout, daemons[0].CheckServiceTasks(id), checker.Equals, instances)
// let scheduler try
time.Sleep(250 * time.Millisecond)
tasks = daemons[0].GetServiceTasks(c, id)
// validate tasks are not assigned
for _, task := range tasks {
c.Assert(task.NodeID, checker.Equals, "")
}
// make nodes[1] fulfills the constraints
daemons[0].UpdateNode(c, nodes[1].ID, func(n *swarm.Node) {
n.Spec.Annotations.Labels = map[string]string{
"security": "high",
}
})
// wait for tasks ready
waitAndAssert(c, defaultReconciliationTimeout, daemons[0].CheckServiceRunningTasks(id), checker.Equals, instances)
tasks = daemons[0].GetServiceTasks(c, id)
for _, task := range tasks {
c.Assert(task.NodeID, checker.Equals, nodes[1].ID)
}
}
func (s *DockerSwarmSuite) TestAPISwarmServicePlacementPrefs(c *check.C) {
const nodeCount = 3
var daemons [nodeCount]*daemon.Daemon
for i := 0; i < nodeCount; i++ {
daemons[i] = s.AddDaemon(c, true, i == 0)
}
// wait for nodes ready
waitAndAssert(c, 5*time.Second, daemons[0].CheckNodeReadyCount, checker.Equals, nodeCount)
nodes := daemons[0].ListNodes(c)
c.Assert(len(nodes), checker.Equals, nodeCount)
// add labels to nodes
daemons[0].UpdateNode(c, nodes[0].ID, func(n *swarm.Node) {
n.Spec.Annotations.Labels = map[string]string{
"rack": "a",
}
})
for i := 1; i < nodeCount; i++ {
daemons[0].UpdateNode(c, nodes[i].ID, func(n *swarm.Node) {
n.Spec.Annotations.Labels = map[string]string{
"rack": "b",
}
})
}
// create service
instances := 4
prefs := []swarm.PlacementPreference{{Spread: &swarm.SpreadOver{SpreadDescriptor: "node.labels.rack"}}}
id := daemons[0].CreateService(c, simpleTestService, setPlacementPrefs(prefs), setInstances(instances))
// wait for tasks ready
waitAndAssert(c, defaultReconciliationTimeout, daemons[0].CheckServiceRunningTasks(id), checker.Equals, instances)
tasks := daemons[0].GetServiceTasks(c, id)
// validate all tasks are running on nodes[0]
tasksOnNode := make(map[string]int)
for _, task := range tasks {
tasksOnNode[task.NodeID]++
}
c.Assert(tasksOnNode[nodes[0].ID], checker.Equals, 2)
c.Assert(tasksOnNode[nodes[1].ID], checker.Equals, 1)
c.Assert(tasksOnNode[nodes[2].ID], checker.Equals, 1)
}
func (s *DockerSwarmSuite) TestAPISwarmServicesStateReporting(c *check.C) {
testRequires(c, SameHostDaemon)
testRequires(c, DaemonIsLinux)
d1 := s.AddDaemon(c, true, true)
d2 := s.AddDaemon(c, true, true)
d3 := s.AddDaemon(c, true, false)
time.Sleep(1 * time.Second) // make sure all daemons are ready to accept
instances := 9
d1.CreateService(c, simpleTestService, setInstances(instances))
waitAndAssert(c, defaultReconciliationTimeout, reducedCheck(sumAsIntegers, d1.CheckActiveContainerCount, d2.CheckActiveContainerCount, d3.CheckActiveContainerCount), checker.Equals, instances)
getContainers := func() map[string]*daemon.Daemon {
m := make(map[string]*daemon.Daemon)
for _, d := range []*daemon.Daemon{d1, d2, d3} {
for _, id := range d.ActiveContainers() {
m[id] = d
}
}
return m
}
containers := getContainers()
c.Assert(containers, checker.HasLen, instances)
var toRemove string
for i := range containers {
toRemove = i
}
_, err := containers[toRemove].Cmd("stop", toRemove)
c.Assert(err, checker.IsNil)
waitAndAssert(c, defaultReconciliationTimeout, reducedCheck(sumAsIntegers, d1.CheckActiveContainerCount, d2.CheckActiveContainerCount, d3.CheckActiveContainerCount), checker.Equals, instances)
containers2 := getContainers()
c.Assert(containers2, checker.HasLen, instances)
for i := range containers {
if i == toRemove {
c.Assert(containers2[i], checker.IsNil)
} else {
c.Assert(containers2[i], checker.NotNil)
}
}
containers = containers2
for i := range containers {
toRemove = i
}
// try with killing process outside of docker
pidStr, err := containers[toRemove].Cmd("inspect", "-f", "{{.State.Pid}}", toRemove)
c.Assert(err, checker.IsNil)
pid, err := strconv.Atoi(strings.TrimSpace(pidStr))
c.Assert(err, checker.IsNil)
c.Assert(unix.Kill(pid, unix.SIGKILL), checker.IsNil)
time.Sleep(time.Second) // give some time to handle the signal
waitAndAssert(c, defaultReconciliationTimeout, reducedCheck(sumAsIntegers, d1.CheckActiveContainerCount, d2.CheckActiveContainerCount, d3.CheckActiveContainerCount), checker.Equals, instances)
containers2 = getContainers()
c.Assert(containers2, checker.HasLen, instances)
for i := range containers {
if i == toRemove {
c.Assert(containers2[i], checker.IsNil)
} else {
c.Assert(containers2[i], checker.NotNil)
}
}
}
// Test plugins deployed via swarm services
func (s *DockerSwarmSuite) TestAPISwarmServicesPlugin(c *check.C) {
testRequires(c, ExperimentalDaemon, DaemonIsLinux, IsAmd64)
reg := setupRegistry(c, false, "", "")
defer reg.Close()
repo := path.Join(privateRegistryURL, "swarm", "test:v1")
repo2 := path.Join(privateRegistryURL, "swarm", "test:v2")
name := "test"
err := plugin.CreateInRegistry(context.Background(), repo, nil)
c.Assert(err, checker.IsNil, check.Commentf("failed to create plugin"))
err = plugin.CreateInRegistry(context.Background(), repo2, nil)
c.Assert(err, checker.IsNil, check.Commentf("failed to create plugin"))
d1 := s.AddDaemon(c, true, true)
d2 := s.AddDaemon(c, true, true)
d3 := s.AddDaemon(c, true, false)
makePlugin := func(repo, name string, constraints []string) func(*swarm.Service) {
return func(s *swarm.Service) {
s.Spec.TaskTemplate.Runtime = "plugin"
s.Spec.TaskTemplate.PluginSpec = &runtime.PluginSpec{
Name: name,
Remote: repo,
}
if constraints != nil {
s.Spec.TaskTemplate.Placement = &swarm.Placement{
Constraints: constraints,
}
}
}
}
id := d1.CreateService(c, makePlugin(repo, name, nil))
waitAndAssert(c, defaultReconciliationTimeout, d1.CheckPluginRunning(name), checker.True)
waitAndAssert(c, defaultReconciliationTimeout, d2.CheckPluginRunning(name), checker.True)
waitAndAssert(c, defaultReconciliationTimeout, d3.CheckPluginRunning(name), checker.True)
service := d1.GetService(c, id)
d1.UpdateService(c, service, makePlugin(repo2, name, nil))
waitAndAssert(c, defaultReconciliationTimeout, d1.CheckPluginImage(name), checker.Equals, repo2)
waitAndAssert(c, defaultReconciliationTimeout, d2.CheckPluginImage(name), checker.Equals, repo2)
waitAndAssert(c, defaultReconciliationTimeout, d3.CheckPluginImage(name), checker.Equals, repo2)
waitAndAssert(c, defaultReconciliationTimeout, d1.CheckPluginRunning(name), checker.True)
waitAndAssert(c, defaultReconciliationTimeout, d2.CheckPluginRunning(name), checker.True)
waitAndAssert(c, defaultReconciliationTimeout, d3.CheckPluginRunning(name), checker.True)
d1.RemoveService(c, id)
waitAndAssert(c, defaultReconciliationTimeout, d1.CheckPluginRunning(name), checker.False)
waitAndAssert(c, defaultReconciliationTimeout, d2.CheckPluginRunning(name), checker.False)
waitAndAssert(c, defaultReconciliationTimeout, d3.CheckPluginRunning(name), checker.False)
// constrain to managers only
id = d1.CreateService(c, makePlugin(repo, name, []string{"node.role==manager"}))
waitAndAssert(c, defaultReconciliationTimeout, d1.CheckPluginRunning(name), checker.True)
waitAndAssert(c, defaultReconciliationTimeout, d2.CheckPluginRunning(name), checker.True)
waitAndAssert(c, defaultReconciliationTimeout, d3.CheckPluginRunning(name), checker.False) // Not a manager, not running it
d1.RemoveService(c, id)
waitAndAssert(c, defaultReconciliationTimeout, d1.CheckPluginRunning(name), checker.False)
waitAndAssert(c, defaultReconciliationTimeout, d2.CheckPluginRunning(name), checker.False)
waitAndAssert(c, defaultReconciliationTimeout, d3.CheckPluginRunning(name), checker.False)
// with no name
id = d1.CreateService(c, makePlugin(repo, "", nil))
waitAndAssert(c, defaultReconciliationTimeout, d1.CheckPluginRunning(repo), checker.True)
waitAndAssert(c, defaultReconciliationTimeout, d2.CheckPluginRunning(repo), checker.True)
waitAndAssert(c, defaultReconciliationTimeout, d3.CheckPluginRunning(repo), checker.True)
d1.RemoveService(c, id)
waitAndAssert(c, defaultReconciliationTimeout, d1.CheckPluginRunning(repo), checker.False)
waitAndAssert(c, defaultReconciliationTimeout, d2.CheckPluginRunning(repo), checker.False)
waitAndAssert(c, defaultReconciliationTimeout, d3.CheckPluginRunning(repo), checker.False)
}
| {
return func(s *swarm.Service) {
if s.Spec.EndpointSpec == nil {
s.Spec.EndpointSpec = &swarm.EndpointSpec{}
}
s.Spec.EndpointSpec.Ports = portConfig
}
} |
form-state.test.ts | import { ActionType } from '@/types/core'
import ActionTypes from '@/constants/action-types'
import formStateReducer, { defaultState } from '../form-state'
describe('formStateReducer', () => {
it('should return default state if action not matched', () => {
const newState = formStateReducer(undefined, { type: 'UNKNOWN' as ActionType, data: undefined })
expect(newState).toEqual(defaultState)
}) | type: ActionTypes.SET_INSTALLATIONS_FORM_STATE as ActionType,
data: 'DONE',
})
const expected = {
...defaultState,
state: 'DONE',
}
expect(newState).toEqual(expected)
})
}) | it('should set state to test when FETCH_MEMBER_DETAILS action is called with test', () => {
const newState = formStateReducer(undefined, { |
admin.py | from django.contrib import admin
from .models import Ticket, Review, UserFollows |
admin.site.register(Ticket)
admin.site.register(Review)
admin.site.register(UserFollows) |
|
client.go | package client
import (
"net/rpc"
"HFish/utils/log"
"HFish/utils/conf"
"HFish/utils/ip"
)
// 上报状态结构
type Status struct {
AgentIp string
AgentName string
Web, Deep, Ssh, Redis, Mysql, Http, Telnet, Ftp string
}
// 上报结果结构
type Result struct {
AgentIp string
AgentName string
Type string
ProjectName string
SourceIp string
Info string
Id string // 数据库ID,更新用 0 为新插入数据
}
func createClient() (*rpc.Client, bool) {
rpcAddr := conf.Get("rpc", "addr")
client, err := rpc.Dial("tcp", rpcAddr) | log.Pr("RPC", "127.0.0.1", "连接 RPC Server 失败")
return client, false
}
return client, true
}
func reportStatus(rpcName string, ftpStatus string, telnetStatus string, httpStatus string, mysqlStatus string, redisStatus string, sshStatus string, webStatus string, darkStatus string) {
client, boolStatus := createClient()
if boolStatus {
defer client.Close()
status := Status{
ip.GetLocalIp(),
rpcName,
webStatus,
darkStatus,
sshStatus,
redisStatus,
mysqlStatus,
httpStatus,
telnetStatus,
ftpStatus,
}
var reply string
err := client.Call("HFishRPCService.ReportStatus", status, &reply)
if err != nil {
log.Pr("RPC", "127.0.0.1", "上报服务状态失败", err)
}
}
}
func ReportResult(typex string, projectName string, sourceIp string, info string, id string) string {
// projectName 只有 WEB 才需要传项目名 其他协议空即可
// id 0 为 新插入数据,非 0 都是更新数据
// id 非 0 的时候 sourceIp 为空
client, boolStatus := createClient()
if boolStatus {
defer client.Close()
rpcName := conf.Get("rpc", "name")
result := Result{
ip.GetLocalIp(),
rpcName,
typex,
projectName,
sourceIp,
info,
id,
}
var reply string
err := client.Call("HFishRPCService.ReportResult", result, &reply)
if err != nil {
log.Pr("RPC", "127.0.0.1", "上报上钩结果失败")
}
return reply
}
return ""
}
func Start(rpcName string, ftpStatus string, telnetStatus string, httpStatus string, mysqlStatus string, redisStatus string, sshStatus string, webStatus string, darkStatus string) {
reportStatus(rpcName, ftpStatus, telnetStatus, httpStatus, mysqlStatus, redisStatus, sshStatus, webStatus, darkStatus)
} |
if err != nil { |
cpu.rs | const CARRY_FLAG: u8 = 1 << 0;
const ZERO_FLAG: u8 = 1 << 1;
const INTERRUPT_DISABLE_FLAG: u8 = 1 << 2;
const DECIMAL_FLAG: u8 = 1 << 3;
const OVERFLOW_FLAG: u8 = 1 << 6;
const NEGATIVE_FLAG: u8 = 1 << 7;
pub struct Cpu {
pub program_counter: u16,
pub stack_pointer: u8,
pub accumulator: u8,
pub register_x: u8,
pub processor_status: u8,
}
impl Cpu {
pub fn | () -> Self {
Cpu {
program_counter: 0,
stack_pointer: 0,
accumulator: 0,
register_x: 0,
processor_status: 0,
}
}
fn lda(&mut self, value: u8) {
self.accumulator = value;
self.update_negative_and_zero_flags(self.accumulator);
}
fn tax(&mut self) {
self.register_x = self.accumulator;
self.update_negative_and_zero_flags(self.register_x);
}
fn inx(&mut self) {
self.register_x = self.register_x.wrapping_add(1);
self.update_negative_and_zero_flags(self.register_x);
}
fn update_negative_and_zero_flags(&mut self, result: u8) {
self.udpate_zero_flag(result);
self.update_negative_flag(result);
}
pub fn update_negative_flag(&mut self, last_operation: u8) {
if last_operation & 0x80 == 0x80 {
self.processor_status |= NEGATIVE_FLAG;
} else {
self.processor_status &= 0xFF - NEGATIVE_FLAG;
}
}
pub fn udpate_zero_flag(&mut self, last_operation: u8) {
if last_operation == 0 {
self.processor_status |= ZERO_FLAG;
} else {
self.processor_status &= 0xFF - ZERO_FLAG;
}
}
pub fn run(&mut self, program: Vec<u8>) {
self.program_counter = 0;
loop {
// http://www.obelisk.me.uk/6502/reference.html
let counter = self.program_counter as usize;
let opcode = program[counter];
self.program_counter += 1;
match opcode {
0xa9 => {
let param = opcode;
self.program_counter += 1;
self.lda(param);
}
0xaa => self.tax(),
0xe8 => self.inx(),
0x00 => return,
_ => todo!(),
}
}
}
}
| new |
cli.go | package rdap
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"encoding/pem"
"fmt"
"github.com/Gregory-Ledray/rdap/bootstrap"
"github.com/Gregory-Ledray/rdap/bootstrap/cache"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/Gregory-Ledray/rdap/sandbox"
"golang.org/x/crypto/pkcs12"
kingpin "gopkg.in/alecthomas/kingpin.v2"
)
var (
version = "OpenRDAP v0.0.1"
usageText = version + `
(www.openrdap.org)
Usage: rdap [OPTIONS] DOMAIN|IP|ASN|ENTITY|NAMESERVER|RDAP-URL
e.g. rdap example.cz
rdap 192.0.2.0
rdap 2001:db8::
rdap AS2856
rdap https://rdap.nic.cz/domain/example.cz
rdap -f registrant -f administrative -f billing amazon.com.br
rdap --json https://rdap.nic.cz/domain/example.cz
rdap -s https://rdap.nic.cz -t help
Options:
-h, --help Show help message.
-v, --verbose Print verbose messages on STDERR.
-T, --timeout=SECS Timeout after SECS seconds (default: 30).
-k, --insecure Disable SSL certificate verification.
-e, --experimental Enable some experimental options:
- Use the bootstrap service https://test.rdap.net/rdap
- Enable object tag support
Authentication options:
-P, --p12=cert.p12[:password] Use client certificate & private key (PKCS#12 format)
or:
-C, --cert=cert.pem Use client certificate (PEM format)
-K, --key=cert.key Use client private key (PEM format)
Output Options:
--text Output RDAP, plain text "tree" format (default).
-w, --whois Output WHOIS style (domain queries only).
-j, --json Output JSON, pretty-printed format.
-r, --raw Output the raw server response.
Advanced options (query):
-s --server=URL RDAP server to query.
-t --type=TYPE RDAP query type. Normally auto-detected. The types are:
- ip
- domain
- autnum
- nameserver
- entity
- help
- url
- domain-search
- domain-search-by-nameserver
- domain-search-by-nameserver-ip
- nameserver-search
- nameserver-search-by-ip
- entity-search
- entity-search-by-handle
The servers for domain, ip, autnum, url queries can be
determined automatically. Otherwise, the RDAP server
(--server=URL) must be specified.
Advanced options (bootstrapping):
--cache-dir=DIR Bootstrap cache directory to use. Specify empty string
to disable bootstrap caching. The directory is created
automatically as needed. (default: $HOME/.openrdap).
--bs-url=URL Bootstrap service URL (default: https://data.iana.org/rdap)
--bs-ttl=SECS Bootstrap cache time in seconds (default: 3600)
Advanced options (experiments):
--exp=test_rdap_net Use the bootstrap service https://test.rdap.net/rdap
--exp=object_tag Enable object tag support
(draft-hollenbeck-regext-rdap-object-tag)
`
)
const (
experimentalBootstrapURL = "https://test.rdap.net/rdap"
)
// CLIOptions specifies options for the command line client.
type CLIOptions struct {
// Sandbox mode disables the --cache-dir option, to prevent arbitrary writes to
// the file system.
//
// This is used for https://www.openrdap.org/demo.
Sandbox bool
}
// RunCLI runs the OpenRDAP command line client.
//
// |args| are the command line arguments to use (normally os.Args[1:]).
// |stdout| and |stderr| are the io.Writers for STDOUT/STDERR.
// |options| specifies extra options.
//
// Returns the program exit code.
func RunCLI(args []string, stdout io.Writer, stderr io.Writer, options CLIOptions) int {
// For duration timer (in --verbose output).
start := time.Now()
// Setup command line arguments parser.
app := kingpin.New("rdap", "RDAP command-line client")
app.HelpFlag.Short('h')
app.UsageTemplate(usageText)
app.UsageWriter(stdout)
app.ErrorWriter(stderr)
// Instead of letting kingpin call os.Exit(), flag if it requests to exit
// here.
//
// This lets the function be called in libraries/tests without exiting them.
terminate := false
app.Terminate(func(int) {
terminate = true
})
// Command line options.
verboseFlag := app.Flag("verbose", "").Short('v').Bool()
timeoutFlag := app.Flag("timeout", "").Short('T').Default("30").Uint16()
insecureFlag := app.Flag("insecure", "").Short('k').Bool()
queryType := app.Flag("type", "").Short('t').String()
fetchRolesFlag := app.Flag("fetch", "").Short('f').Strings()
serverFlag := app.Flag("server", "").Short('s').String()
experimentalFlag := app.Flag("experimental", "").Short('e').Bool()
experimentsFlag := app.Flag("exp", "").Strings()
cacheDirFlag := app.Flag("cache-dir", "").Default("default").String()
bootstrapURLFlag := app.Flag("bs-url", "").Default("default").String()
bootstrapTimeoutFlag := app.Flag("bs-ttl", "").Default("3600").Uint32()
clientP12FilenameAndPassword := app.Flag("p12", "").Short('P').String()
clientCertFilename := app.Flag("cert", "").Short('C').String()
clientKeyFilename := app.Flag("key", "").Short('K').String()
outputFormatText := app.Flag("text", "").Bool()
outputFormatWhois := app.Flag("whois", "").Short('w').Bool()
outputFormatJSON := app.Flag("json", "").Short('j').Bool()
outputFormatRaw := app.Flag("raw", "").Short('r').Bool()
// Command line query (any remaining non-option arguments).
queryArgs := app.Arg("", "").Strings()
// Parse command line arguments.
// The help messages for -h/--help are printed directly by app.Parse().
_, err := app.Parse(args)
if err != nil {
printError(stderr, fmt.Sprintf("Error: %s\n\n%s", err, usageText))
return 1
} else if terminate {
// Occurs when kingpin prints the --help message.
return 1
}
var verbose func(text string)
if *verboseFlag {
verbose = func(text string) {
fmt.Fprintf(stderr, "# %s\n", text)
}
} else {
verbose = func(text string) {
}
}
verbose(version)
verbose("")
verbose("rdap: Configuring query...")
// Supported experimental options.
experiments := map[string]bool{
"test_rdap_net": false,
"object_tag": false,
"sandbox": false,
}
// Enable experimental options.
for _, e := range *experimentsFlag {
if _, ok := experiments[e]; ok {
experiments[e] = true
verbose(fmt.Sprintf("rdap: Enabled experiment '%s'", e))
} else {
printError(stderr, fmt.Sprintf("Error: unknown experiment '%s'", e))
return 1
}
}
// Enable the -e selection of experiments?
if *experimentalFlag {
verbose("rdap: Enabled -e/--experiments: test_rdap_net, object_tag")
experiments["test_rdap_net"] = true
experiments["object_tag"] = true
}
// Forced sandbox mode?
if experiments["sandbox"] {
options.Sandbox = true
}
// Exactly one argument is required (i.e. the domain/ip/url/etc), unless
// we're making a help query.
if *queryType != "help" && len(*queryArgs) == 0 {
printError(stderr, fmt.Sprintf("Error: %s\n\n%s", "Query object required, e.g. rdap example.cz", usageText))
return 1
}
// Grab the query text.
queryText := ""
if len(*queryArgs) > 0 {
queryText = (*queryArgs)[0]
}
// Construct the request.
var req *Request
switch *queryType {
case "":
req = NewAutoRequest(queryText)
case "help":
req = NewHelpRequest()
case "domain", "dns":
req = NewDomainRequest(queryText)
case "autnum", "as", "asn":
autnum := strings.ToUpper(queryText)
autnum = strings.TrimPrefix(autnum, "AS")
result, err := strconv.ParseUint(autnum, 10, 32)
if err != nil {
printError(stderr, fmt.Sprintf("Invalid ASN '%s'", queryText))
return 1
}
req = NewAutnumRequest(uint32(result))
case "ip":
ip := net.ParseIP(queryText)
if ip == nil {
printError(stderr, fmt.Sprintf("Invalid IP '%s'", queryText))
return 1
}
req = NewIPRequest(ip)
case "nameserver", "ns":
req = NewNameserverRequest(queryText)
case "entity":
req = NewEntityRequest(queryText)
case "url":
fullURL, err := url.Parse(queryText)
if err != nil |
req = NewRawRequest(fullURL)
case "entity-search":
req = NewRequest(EntitySearchRequest, queryText)
case "entity-search-by-handle":
req = NewRequest(EntitySearchByHandleRequest, queryText)
case "domain-search":
req = NewRequest(DomainSearchRequest, queryText)
case "domain-search-by-nameserver":
req = NewRequest(DomainSearchByNameserverRequest, queryText)
case "domain-search-by-nameserver-ip":
req = NewRequest(DomainSearchByNameserverIPRequest, queryText)
case "nameserver-search":
req = NewRequest(NameserverSearchRequest, queryText)
case "nameserver-search-by-ip":
req = NewRequest(NameserverSearchByNameserverIPRequest, queryText)
default:
printError(stderr, fmt.Sprintf("Unknown query type '%s'", *queryType))
return 1
}
// Determine the server.
if req.Server != nil {
if *serverFlag != "" {
printError(stderr, fmt.Sprintf("--server option cannot be used with query type %s", req.Type))
return 1
}
}
// Server URL specified (--server)?
if *serverFlag != "" {
serverURL, err := url.Parse(*serverFlag)
if err != nil {
printError(stderr, fmt.Sprintf("--server error: %s", err))
return 1
}
if serverURL.Scheme == "" {
serverURL.Scheme = "http"
}
req = req.WithServer(serverURL)
verbose(fmt.Sprintf("rdap: Using server '%s'", serverURL))
}
// Custom TLS config.
tlsConfig := &tls.Config{InsecureSkipVerify: *insecureFlag}
bs := &bootstrap.Client{}
// Custom bootstrap cache type/directory?
if *cacheDirFlag == "" {
// Disk cache disabled, use memory cache.
bs.Cache = cache.NewMemoryCache()
verbose("rdap: Using in-memory cache")
} else {
dc := cache.NewDiskCache()
if *cacheDirFlag != "default" {
if !options.Sandbox {
dc.Dir = *cacheDirFlag
} else {
verbose(fmt.Sprintf("rdap: Ignored --cache-dir option (sandbox mode enabled)"))
}
}
verbose(fmt.Sprintf("rdap: Using disk cache (%s)", dc.Dir))
created, err := dc.InitDir()
if created {
verbose(fmt.Sprintf("rdap: Cache dir %s mkdir'ed", dc.Dir))
} else if err != nil {
printError(stderr, fmt.Sprintf("rdap: Error making cache dir %s", dc.Dir))
return 1
}
bs.Cache = dc
}
// Use experimental bootstrap service URL?
if experiments["test_rdap_net"] && *bootstrapURLFlag == "default" {
*bootstrapURLFlag = experimentalBootstrapURL
verbose("rdap: Using test.rdap.net bootstrap service (test_rdap_net experiment)")
}
// Custom bootstrap service URL?
if *bootstrapURLFlag != "default" {
baseURL, err := url.Parse(*bootstrapURLFlag)
if err != nil {
printError(stderr, fmt.Sprintf("Bootstrap URL error: %s", err))
return 1
}
bs.BaseURL = baseURL
verbose(fmt.Sprintf("rdap: Bootstrap URL set to '%s'", baseURL))
} else {
verbose(fmt.Sprintf("rdap: Bootstrap URL is default '%s'", bootstrap.DefaultBaseURL))
}
// Custom bootstrap cache timeout?
if bootstrapTimeoutFlag != nil {
bs.Cache.SetTimeout(time.Duration(*bootstrapTimeoutFlag) * time.Second)
verbose(fmt.Sprintf("rdap: Bootstrap cache TTL set to %d seconds", *bootstrapTimeoutFlag))
}
var clientCert tls.Certificate
if *clientCertFilename != "" || *clientKeyFilename != "" {
if *clientP12FilenameAndPassword != "" {
printError(stderr, fmt.Sprintf("rdap: Error: Can't use both --cert/--key and --p12 together"))
return 1
} else if *clientCertFilename == "" || *clientKeyFilename == "" {
printError(stderr, fmt.Sprintf("rdap: Error: --cert and --key must be used together"))
return 1
} else if options.Sandbox {
verbose(fmt.Sprintf("rdap: Ignored --cert and --key options (sandbox mode enabled)"))
} else {
var err error
clientCert, err = tls.LoadX509KeyPair(*clientCertFilename, *clientKeyFilename)
if err != nil {
printError(stderr, fmt.Sprintf("rdap: Error: cannot load client certificate/key: %s", err))
return 1
}
verbose(fmt.Sprintf("rdap: Loaded client certificate from '%s'", *clientCertFilename))
tlsConfig.Certificates = append(tlsConfig.Certificates, clientCert)
}
} else if *clientP12FilenameAndPassword != "" {
// Split the filename and optional password.
// [0] is the filename, [1] is the optional password.
var p12FilenameAndPassword []string = strings.SplitAfterN(*clientP12FilenameAndPassword, ":", 2)
p12FilenameAndPassword[0] = strings.TrimSuffix(p12FilenameAndPassword[0], ":")
// Use a blank password if none was specified.
if len(p12FilenameAndPassword) == 1 {
p12FilenameAndPassword = append(p12FilenameAndPassword, "")
}
var p12 []byte
var err error
// Load the file from disk, or the sandbox.
if options.Sandbox {
p12, err = sandbox.LoadFile(p12FilenameAndPassword[0])
} else {
p12, err = ioutil.ReadFile(p12FilenameAndPassword[0])
}
// Check the file was read correctly.
if err != nil {
printError(stderr, fmt.Sprintf("rdap: Error: cannot load client certificate: %s", err))
return 1
}
// Convert P12 to PEM blocks.
var blocks []*pem.Block
blocks, err = pkcs12.ToPEM(p12, p12FilenameAndPassword[1])
if err != nil {
printError(stderr, fmt.Sprintf("rdap: Error: cannot read client certificate: %s", err))
return 1
}
// Build single concatenated PEM block.
var pemData []byte
for _, b := range blocks {
pemData = append(pemData, pem.EncodeToMemory(b)...)
}
clientCert, err = tls.X509KeyPair(pemData, pemData)
if err != nil {
printError(stderr, fmt.Sprintf("rdap: Error: cannot read client certificate: %s", err))
return 1
}
verbose(fmt.Sprintf("rdap: Loaded client certificate from '%s'", p12FilenameAndPassword[0]))
tlsConfig.Certificates = append(tlsConfig.Certificates, clientCert)
}
// Custom HTTP client. Used to disable TLS certificate verification.
transport := &http.Transport{
TLSClientConfig: tlsConfig,
}
// Setup http.RoundTripper for http clients
bs.HTTP = &http.Client{
Transport: transport,
}
httpClient := &http.Client{
Transport: transport,
}
client := &Client{
HTTP: httpClient,
Bootstrap: bs,
Verbose: verbose,
UserAgent: version,
ServiceProviderExperiment: experiments["object_tag"],
}
if *insecureFlag {
verbose(fmt.Sprintf("rdap: SSL certificate validation disabled"))
}
// Set the request timeout.
ctx, cancelFunc := context.WithTimeout(context.Background(), time.Duration(*timeoutFlag)*time.Second)
defer cancelFunc()
req = req.WithContext(ctx)
verbose(fmt.Sprintf("rdap: Timeout is %d seconds", *timeoutFlag))
// Run the request.
var resp *Response
resp, err = client.Do(req)
verbose("")
verbose(fmt.Sprintf("rdap: Finished in %s", time.Since(start)))
if err != nil {
printError(stderr, fmt.Sprintf("Error: %s", err))
return 1
}
// Insert a blank line to seperate verbose messages/proper output.
if *verboseFlag {
fmt.Fprintln(stderr, "")
}
// Output formatting.
if !(*outputFormatText || *outputFormatWhois || *outputFormatJSON || *outputFormatRaw) {
*outputFormatText = true
}
// Print the response out in text format?
if *outputFormatText {
printer := &Printer{
Writer: stdout,
BriefLinks: true,
}
printer.Print(resp.Object)
}
// Print the raw response out?
if *outputFormatRaw {
fmt.Printf("%s", resp.HTTP[0].Body)
}
// Print the response, JSON pretty-printed?
if *outputFormatJSON {
var out bytes.Buffer
json.Indent(&out, resp.HTTP[0].Body, "", " ")
out.WriteTo(os.Stdout)
}
// Print WHOIS style response out?
if *outputFormatWhois {
w := resp.ToWhoisStyleResponse()
for _, key := range w.KeyDisplayOrder {
for _, value := range w.Data[key] {
fmt.Fprintf(stdout, "%s: %s\n", key, safePrint(value))
}
}
}
_ = fetchRolesFlag
return 0
}
func safePrint(v string) string {
removeBadChars := func(r rune) rune {
switch {
case r == '\000':
return -1
case r == '\n':
return ' '
default:
return r
}
}
return strings.Map(removeBadChars, v)
}
func printError(stderr io.Writer, text string) {
fmt.Fprintf(stderr, "# %s\n", text)
}
| {
printError(stderr, fmt.Sprintf("Unable to parse URL '%s': %s", queryText, err))
return 1
} |
create_model_vs_data_txt.py | from __future__ import print_function
import mmtbx.model_vs_data
import libtbx.load_env
from six.moves import cStringIO as StringIO
import os.path as op
import os
import sys
def | ():
html_dir = libtbx.env.find_in_repositories(relative_path="phenix_html")
dest_dir = op.join(html_dir, "rst_files", "reference")
log = StringIO()
print(mmtbx.model_vs_data.msg, file=log)
print("""Default parameters:\n{{phil:mmtbx.model_vs_data}}""", file=log)
ofn = open(op.join(dest_dir, "model_vs_data.txt"), "w")
ofn.write(log.getvalue())
ofn.close()
if (__name__ == "__main__"):
run()
| run |
main.go | package main
import (
"log"
"net/http"
"github.com/yasensim/gameserver/internal/routes"
)
func | () {
r := routes.Handlers()
err := http.ListenAndServe(":8080", r)
if err != nil {
log.Fatal(err)
}
}
| main |
collections_lcds_simple_message.rs | /*
*
*
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 1.0.0
*
* Generated by: https://openapi-generator.tech
*/
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CollectionsLcdsSimpleMessage {
#[serde(rename = "accountId", skip_serializing_if = "Option::is_none")]
pub account_id: Option<i64>,
#[serde(rename = "msgId", skip_serializing_if = "Option::is_none")]
pub msg_id: Option<String>,
#[serde(rename = "params", skip_serializing_if = "Option::is_none")]
pub params: Option<Vec<String>>,
#[serde(rename = "type", skip_serializing_if = "Option::is_none")]
pub _type: Option<String>,
}
impl CollectionsLcdsSimpleMessage {
pub fn | () -> CollectionsLcdsSimpleMessage {
CollectionsLcdsSimpleMessage {
account_id: None,
msg_id: None,
params: None,
_type: None,
}
}
}
| new |
index.tsx | import { Typography } from '@material-ui/core';
import DoneIcon from '@material-ui/icons/Done';
import { ButtonFilled, ButtonOutlined } from 'litmus-ui';
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import useStyles from './styles';
interface AgentDeployModalProps {
handleClose: () => void;
}
const AgentDeployModal: React.FC<AgentDeployModalProps> = ({ handleClose }) => { |
function fallbackCopyTextToClipboard(text: string) {
// eslint-disable-next-line no-alert
window.prompt('Copy to clipboard: Ctrl+C, Enter', text);
}
function copyTextToClipboard(text: string) {
if (!navigator.clipboard) {
fallbackCopyTextToClipboard(text);
return;
}
setCopying(true);
navigator.clipboard
.writeText(text)
.catch((err) => console.error('Async: Could not copy text: ', err));
setTimeout(() => setCopying(false), 3000);
}
return (
<div className={classes.modalContainer}>
<div className={classes.heading}>
<img src="./icons/agentDeployModal.svg" alt="Target Connect" />
<Typography>
{t('homeViews.landingHome.agentDeployModal.heading')}
</Typography>
</div>
<div className={classes.instructionSection}>
<Typography>
{t('homeViews.landingHome.agentDeployModal.firstStep')}
</Typography>
<Typography>
{t('homeViews.landingHome.agentDeployModal.secondStep')}
<a
href="https://github.com/litmuschaos/litmusctl"
target="_blank"
rel="noreferrer noopener"
>
{t('homeViews.landingHome.agentDeployModal.litmusctl')}
</a>
</Typography>
<Typography>
{t('homeViews.landingHome.agentDeployModal.thirdStep')}
</Typography>
</div>
<div className={classes.copyCommandSection}>
<div className={classes.commandRect}>
<Typography>
{t('homeViews.landingHome.agentDeployModal.agentRegister')}
</Typography>
</div>
<ButtonOutlined
className={classes.copyButton}
onClick={() => copyTextToClipboard(`litmusctl agent connect`)}
>
{copying ? (
<DoneIcon />
) : (
<>
<img src="./icons/copy.svg" alt="copy" />
<Typography>
{t('homeViews.landingHome.agentDeployModal.copy')}
</Typography>
</>
)}
</ButtonOutlined>
</div>
<div className={classes.doneButton}>
<ButtonFilled onClick={handleClose}>
<Typography>
{t('homeViews.landingHome.agentDeployModal.done')}
</Typography>
</ButtonFilled>
</div>
</div>
);
};
export { AgentDeployModal }; | const classes = useStyles();
const { t } = useTranslation();
const [copying, setCopying] = useState<boolean>(false); |
reloadConfig.js | /**
* Created by azu on 2014/04/27.
* LICENSE : MIT
*/
"use strict";
function getAutoReloadTime() {
return window.localStorage.getItem("auto-reload-interval") || 60 * 1000;
}
function setAutoReloadTime(timeInterval) {
return window.localStorage.setItem("auto-reload-interval", timeInterval);
}
function | (date) {
window.localStorage.setItem("last-updated", date.toISOString());
}
function getLastUpdated() {
return window.localStorage.getItem("last-updated");
}
function getFilterScriptPath() {
return window.localStorage.getItem("filter-script-path");
}
function setFilterScriptPath(scriptPath) {
window.localStorage.setItem("filter-script-path", scriptPath)
}
module.exports = {
getAutoReloadTime: getAutoReloadTime,
setAutoReloadTime: setAutoReloadTime,
getLastUpdated: getLastUpdated,
setLastUpdated: setLastUpdated,
getFilterScriptPath: getFilterScriptPath,
setFilterScriptPath: setFilterScriptPath
}; | setLastUpdated |
index.js | 'use strict';
const Express = require('express');
const Axios = require('axios');
const NodeCache = require('node-cache');
const LAUNCHER_META_ENDPOINT = 'https://launchermeta.mojang.com';
const VERSION_MANIFEST_URI = `${LAUNCHER_META_ENDPOINT}/mc/game/version_manifest.json`;
const CACHE_MANIFEST = 'versionManifest';
const CACHE_DESCRIPTOR = 'descriptor';
const cache = new NodeCache({
stdTTL: parseInt(process.env.CACHE_TTL || 600)
});
const client = Axios.create();
const app = Express();
async function | () {
const cached = cache.get(CACHE_MANIFEST);
if (cached) {
return cached;
}
const manifest = (await client.get(VERSION_MANIFEST_URI))?.data;
if (!manifest) {
throw new Error('Null manifest!');
}
cache.set(CACHE_MANIFEST, manifest);
return manifest;
}
async function getVersionDescriptor(version) {
const cached = cache.get(`${CACHE_DESCRIPTOR}${version}`);
if (cached) {
return cached;
}
const manifest = await getVersionManifest();
const descriptorUrl = manifest.versions.find(current => current.id === version)?.url;
if (!descriptorUrl) {
throw new Error(`Unknown version ${version}`);
}
const descriptor = (await client.get(descriptorUrl))?.data;
if (!descriptor) {
throw new Error('Null descriptor!');
}
cache.set(`${CACHE_DESCRIPTOR}${version}`, descriptor);
return descriptor;
}
app.get('/minecraft/version/:version', async (request, response) => {
let version;
if (['release', 'snapshot'].includes(request.params.version)) {
const manifest = await getVersionManifest();
if (request.params.version === 'release') {
version = manifest.latest.release;
} else if (request.params.version === 'snapshot') {
version = manifest.latest.release;
}
} else {
version = request.params.version;
}
const descriptor = await getVersionDescriptor(version);
if (!descriptor) {
response.status(404);
response.send(`No such version '${request.params.version}'`);
return;
}
response.json(descriptor);
});
app.get('/minecraft/version/:version/download/:download', async (request, response) => {
const manifest = await getVersionManifest();
let version;
switch (request.params.version) {
case 'release':
version = manifest.latest.release;
break;
case 'snapshot':
version = manifest.latest.release;
break;
default:
version = request.params.version;
}
const descriptor = await getVersionDescriptor(version);
const downloadUrl = descriptor.downloads[request.params.download]?.url;
if (!downloadUrl) {
response.status(404);
response.send(`No such download '${request.params.download}'`);
return;
}
response.redirect(downloadUrl);
});
app.listen(process.env.PORT || 3000);
| getVersionManifest |
spinelist.rs | pub use giftr::refs::functional::Ref as Ref;
use giftr::ispine::*;
use giftr::ispine::contiguous::Contiguous as Spine;
use std::default::Default;
use std::fmt::Debug;
#[derive(Clone, Debug)]
pub struct SpineList<T: Clone> {
spine : Spine<T>,
}
impl <T: Clone+Debug> SpineList<T> {
pub fn new() -> SpineList<T> {
SpineList { spine: Default::default() }
}
pub fn prepend(&mut self, x: T) {
self.spine.add(x);
}
pub fn insert(&mut self, idx: usize, x: T) {
self.spine.at()
.skip(idx).next().unwrap().insert(x);
}
pub fn append(&mut self, x: T) {
if let Some(ref mut l) = self.spine.at().last() {
l.insert(x);
return
}
self.spine.add(x)
}
pub fn pop_front(&mut self) -> Option<T> {
if let Some(x) = self.spine.pop() {
println!("popped {:?}, len was {}", x, self.len());
Some(x)
} else {
None
}
}
pub fn pop_back(&mut self) -> Option<T> {
let len = self.len();
if let Some(x) = self.spine.take_from(len-1).pop() {
Some(x)
} else {
None
}
}
pub fn len(&self) -> usize {
self.spine.iter().count()
}
pub fn iter(&self) -> Iter<T> {
Iter { cur: self.spine.clone() }
}
pub fn to_iter(self) -> Iter<T> {
let SpineList { spine } = self;
Iter { cur: spine }
}
}
pub struct Iter<T: Clone> {
cur: Spine<T>,
}
impl <T: Clone> Iterator for Iter<T> {
type Item = T;
fn | (&mut self) -> Option<Self::Item> {
self.cur.pop()
}
}
mod test {
use giftr::refs::*;
use super::{Ref, SpineList};
#[test]
fn lst_len() {
println!("=== LST_LEN ==============");
let mut lst = Ref::new(SpineList::<i32>::new());
assert_eq!(0, lst.len());
lst.prepend(1);
assert_eq!(1, lst.len());
lst.prepend(2);
assert_eq!(2, lst.len());
lst.prepend(3);
assert_eq!(3, lst.len());
lst.pop_front();
assert_eq!(2, lst.len());
}
#[test]
fn lst_pop_front() {
println!("=== LST_LEN ==============");
let mut lst = Ref::new(SpineList::new());
lst.prepend(3);
lst.prepend(2);
lst.prepend(1);
assert_eq!(Some(1), lst.pop_front());
assert_eq!(Some(2), lst.pop_front());
assert_eq!(Some(3), lst.pop_front());
assert_eq!(None, lst.pop_front());
assert_eq!(None, lst.pop_front());
}
#[test]
fn lst_append() {
let mut lst = SpineList::<i32>::new();
lst.append(1);
lst.append(2);
lst.append(3);
assert_eq!(Some(1), lst.pop_front());
assert_eq!(Some(2), lst.pop_front());
assert_eq!(Some(3), lst.pop_front());
assert_eq!(None, lst.pop_front());
assert_eq!(None, lst.pop_front());
}
#[test]
fn lst_pop_back() {
println!("=== LST_LEN ==============");
let mut lst = Ref::new(SpineList::new());
lst.prepend(3);
lst.prepend(2);
lst.prepend(1);
println!("lst= {:?}", lst);
assert_eq!(Some(3), lst.pop_back());
assert_eq!(Some(2), lst.pop_back());
assert_eq!(Some(1), lst.pop_back());
assert_eq!(None, lst.pop_front());
assert_eq!(None, lst.pop_front());
}
#[test]
fn lst_copy() {
println!("=== LST_COPY ==============");
let mut lst1 = Ref::new(SpineList::new());
lst1.prepend(1);
let lst2 : Ref<SpineList<i32>>;
lst1.prepend(2);
lst2 = lst1.clone();
lst1.prepend(3);
assert!(3 == lst1.len());
assert!(2 == lst2.len());
}
#[test]
fn lst_iter() {
let mut lst1 = Ref::new(SpineList::new());
lst1.prepend(3);
lst1.prepend(2);
lst1.prepend(1);
let mut cnt = 1;
for v in lst1.iter() {
println!("v={}, cnt={}", v, cnt);
assert_eq!(v, cnt);
cnt = cnt+1;
}
}
}
#[cfg(test)]
mod bench {
use test;
use test::Bencher;
use giftr::refs::*;
use super::{Ref, SpineList};
#[bench]
fn lst_append(b: &mut Bencher) {
let mut lst1 : Ref<SpineList<i32>> = Ref::new(SpineList::new());
let size = 10000;
for i in 0..size {
lst1.append(i);
}
b.iter(
|| {
test::black_box(lst1.append(1));
}
);
}
#[bench]
fn lst_prepend(b: &mut Bencher) {
let mut lst1 : SpineList<i32> = SpineList::new();
let size = 10000;
for i in 0..size {
lst1.append(i);
}
b.iter(
|| {
test::black_box(lst1.prepend(1));
}
);
}
#[bench]
fn lst_insert_5000(b: &mut Bencher) {
let mut lst1 : SpineList<i32> = SpineList::new();
let size = 100000;
for i in 0..size {
lst1.append(i);
}
b.iter(
|| {
test::black_box(lst1.insert(50000, 1));
}
);
}
#[bench]
fn lst_len(b: &mut Bencher) {
let mut lst1 : SpineList<i32> = SpineList::new();
let size = 10000;
for i in 0..size {
lst1.append(i);
}
b.iter(
|| {
test::black_box(lst1.len());
}
);
}
}
#[cfg(test)]
mod vecbench {
use test;
use test::Bencher;
#[bench]
fn vec_append(b: &mut Bencher) {
let mut vec1 = Vec::new();
let size = 10000;
for i in 0..size {
vec1.push(i);
}
b.iter(
|| {
test::black_box(vec1.push(1));
}
);
}
#[bench]
fn vec_prepend(b: &mut Bencher) {
let mut vec1 = Vec::new();
let size = 10000;
for i in 0..size {
vec1.push(i);
}
b.iter(
|| {
test::black_box(vec1.insert(0, 1));
}
);
}
#[bench]
fn vec_insert_5000(b: &mut Bencher) {
let mut lst1 = Vec::new();
let size = 100000;
for i in 0..size {
lst1.push(i);
}
b.iter(
|| {
test::black_box(lst1.insert(50000, 1));
}
);
}
#[bench]
fn vec_len(b: &mut Bencher) {
let mut vec1 = Vec::new();
let size = 10000;
for i in 0..size {
vec1.push(i);
}
b.iter(
|| {
test::black_box(vec1.len());
}
);
}
}
| next |
draw.rs | /*! Draw structures - shared between render passes and bundles.
!*/
use crate::{
binding_model::PushConstantUploadError,
error::ErrorFormatter,
id,
track::UseExtendError,
validation::{MissingBufferUsageError, MissingTextureUsageError},
};
use wgt::{BufferAddress, BufferSize, Color};
use std::num::NonZeroU32;
use thiserror::Error;
pub type BufferError = UseExtendError<hal::BufferUses>;
/// Error validating a draw call.
#[derive(Clone, Debug, Error, PartialEq)]
pub enum DrawError {
#[error("blend constant needs to be set")]
MissingBlendConstant,
#[error("render pipeline must be set")]
MissingPipeline,
#[error("vertex buffer {index} must be set")]
MissingVertexBuffer { index: u32 },
#[error("index buffer must be set")]
MissingIndexBuffer,
#[error("current render pipeline has a layout which is incompatible with a currently set bind group, first differing at entry index {index}")]
IncompatibleBindGroup {
index: u32,
//expected: BindGroupLayoutId,
//provided: Option<(BindGroupLayoutId, BindGroupId)>,
},
#[error("vertex {last_vertex} extends beyond limit {vertex_limit} imposed by the buffer in slot {slot}. Did you bind the correct `Vertex` step-rate vertex buffer?")]
VertexBeyondLimit {
last_vertex: u32,
vertex_limit: u32,
slot: u32,
},
#[error("instance {last_instance} extends beyond limit {instance_limit} imposed by the buffer in slot {slot}. Did you bind the correct `Instance` step-rate vertex buffer?")]
InstanceBeyondLimit {
last_instance: u32,
instance_limit: u32,
slot: u32,
},
#[error("index {last_index} extends beyond limit {index_limit}. Did you bind the correct index buffer?")]
IndexBeyondLimit { last_index: u32, index_limit: u32 },
#[error(
"pipeline index format ({pipeline:?}) and buffer index format ({buffer:?}) do not match"
)]
UnmatchedIndexFormats {
pipeline: wgt::IndexFormat,
buffer: wgt::IndexFormat,
},
}
/// Error encountered when encoding a render command.
/// This is the shared error set between render bundles and passes.
#[derive(Clone, Debug, Error)]
pub enum RenderCommandError {
#[error("bind group {0:?} is invalid")]
InvalidBindGroup(id::BindGroupId),
#[error("render bundle {0:?} is invalid")]
InvalidRenderBundle(id::RenderBundleId),
#[error("bind group index {index} is greater than the device's requested `max_bind_group` limit {max}")]
BindGroupIndexOutOfRange { index: u8, max: u32 },
#[error("dynamic buffer offset {0} does not respect device's requested `{1}` limit {2}")]
UnalignedBufferOffset(u64, &'static str, u32),
#[error("number of buffer offsets ({actual}) does not match the number of dynamic bindings ({expected})")]
InvalidDynamicOffsetCount { actual: usize, expected: usize },
#[error("render pipeline {0:?} is invalid")]
InvalidPipeline(id::RenderPipelineId),
#[error("QuerySet {0:?} is invalid")]
InvalidQuerySet(id::QuerySetId),
#[error("Render pipeline targets are incompatible with render pass")]
IncompatiblePipelineTargets(#[from] crate::device::RenderPassCompatibilityError),
#[error("pipeline writes to depth/stencil, while the pass has read-only depth/stencil")]
IncompatiblePipelineRods,
#[error("buffer {0:?} is in error {1:?}")]
Buffer(id::BufferId, BufferError),
#[error("buffer {0:?} is destroyed")]
DestroyedBuffer(id::BufferId),
#[error(transparent)]
MissingBufferUsage(#[from] MissingBufferUsageError),
#[error(transparent)]
MissingTextureUsage(#[from] MissingTextureUsageError),
#[error(transparent)]
PushConstants(#[from] PushConstantUploadError),
#[error("Invalid Viewport parameters")]
InvalidViewport,
#[error("Invalid ScissorRect parameters")]
InvalidScissorRect,
#[error("Support for {0} is not implemented yet")]
Unimplemented(&'static str),
}
impl crate::error::PrettyError for RenderCommandError {
fn fmt_pretty(&self, fmt: &mut ErrorFormatter) {
fmt.error(self);
match *self {
Self::InvalidBindGroup(id) => {
fmt.bind_group_label(&id);
}
Self::InvalidPipeline(id) => {
fmt.render_pipeline_label(&id);
}
Self::Buffer(id, ..) | Self::DestroyedBuffer(id) => {
fmt.buffer_label(&id);
}
_ => {}
};
}
}
#[derive(Clone, Copy, Debug, Default)]
#[cfg_attr(
any(feature = "serial-pass", feature = "trace"),
derive(serde::Serialize)
)]
#[cfg_attr(
any(feature = "serial-pass", feature = "replay"),
derive(serde::Deserialize)
)]
pub struct | <T> {
pub x: T,
pub y: T,
pub w: T,
pub h: T,
}
#[doc(hidden)]
#[derive(Clone, Copy, Debug)]
#[cfg_attr(
any(feature = "serial-pass", feature = "trace"),
derive(serde::Serialize)
)]
#[cfg_attr(
any(feature = "serial-pass", feature = "replay"),
derive(serde::Deserialize)
)]
pub enum RenderCommand {
SetBindGroup {
index: u8,
num_dynamic_offsets: u8,
bind_group_id: id::BindGroupId,
},
SetPipeline(id::RenderPipelineId),
SetIndexBuffer {
buffer_id: id::BufferId,
index_format: wgt::IndexFormat,
offset: BufferAddress,
size: Option<BufferSize>,
},
SetVertexBuffer {
slot: u32,
buffer_id: id::BufferId,
offset: BufferAddress,
size: Option<BufferSize>,
},
SetBlendConstant(Color),
SetStencilReference(u32),
SetViewport {
rect: Rect<f32>,
//TODO: use half-float to reduce the size?
depth_min: f32,
depth_max: f32,
},
SetScissor(Rect<u32>),
SetPushConstant {
stages: wgt::ShaderStages,
offset: u32,
size_bytes: u32,
/// None means there is no data and the data should be an array of zeros.
///
/// Facilitates clears in renderbundles which explicitly do their clears.
values_offset: Option<u32>,
},
Draw {
vertex_count: u32,
instance_count: u32,
first_vertex: u32,
first_instance: u32,
},
DrawIndexed {
index_count: u32,
instance_count: u32,
first_index: u32,
base_vertex: i32,
first_instance: u32,
},
MultiDrawIndirect {
buffer_id: id::BufferId,
offset: BufferAddress,
/// Count of `None` represents a non-multi call.
count: Option<NonZeroU32>,
indexed: bool,
},
MultiDrawIndirectCount {
buffer_id: id::BufferId,
offset: BufferAddress,
count_buffer_id: id::BufferId,
count_buffer_offset: BufferAddress,
max_count: u32,
indexed: bool,
},
PushDebugGroup {
color: u32,
len: usize,
},
PopDebugGroup,
InsertDebugMarker {
color: u32,
len: usize,
},
WriteTimestamp {
query_set_id: id::QuerySetId,
query_index: u32,
},
BeginPipelineStatisticsQuery {
query_set_id: id::QuerySetId,
query_index: u32,
},
EndPipelineStatisticsQuery,
ExecuteBundle(id::RenderBundleId),
}
| Rect |
iteration.go | package sudoku
// iteration is a single iteration of a puzzle.
type iteration struct {
// index is the cell index that this iteration will effect
index int
// minValue is the min value this iteration used when effecting the cell
minValue int
puzzleSize int
sectionSize int
cells group
rows [][]int
columns [][]int
sections [][]int
}
// newIteration returns a new iteration with the given items.
func newIteration(items []int, puzzleSize int, sectionSize int) *iteration |
// items returns all of the items in the iteration.
func (i *iteration) items() []int {
res := make([]int, len(i.cells))
for i, c := range i.cells {
res[i] = c.value
}
return res
}
// iterate returns a iterate of the iteration.
func (i *iteration) iterate() *iteration {
it := &iteration{
puzzleSize: i.puzzleSize,
sectionSize: i.sectionSize,
cells: make(group, len(i.cells)),
rows: i.rows,
columns: i.columns,
sections: i.sections,
minValue: 1,
index: i.index + 1,
}
for i, item := range i.cells {
it.cells[i] = item.copy()
}
return it
}
// finished returns true if there are no zero values left in the iteration.
func (i *iteration) finished() bool {
for _, c := range i.cells {
if c.value == 0 {
return false
}
}
return true
}
// completionRate returns the number of completed non-fixed cells in the iteration.
func (i *iteration) completionRate() *CompletionRate {
res := new(CompletionRate)
res.CellIndex = i.index
res.MinValueAtCell = i.minValue
for _, c := range i.cells {
res.TotalCells++
if c.fixed {
res.FixedCells++
}
if c.value > 0 {
res.FilledCells++
}
}
return res
}
// solve attempts to solve the current iteration.
func (i *iteration) solve() error {
for cellIndex := i.index; ; cellIndex++ {
cell := i.cells[cellIndex]
if cell.fixed {
continue
}
i.index = cellIndex
nextValue, err := i.findNextValue(cell, i.minValue)
if err != nil {
return err
}
i.minValue = nextValue
cell.value = nextValue
return nil
}
}
func (i *iteration) findNextValue(cell *cell, minValue int) (int, error) {
usedMap := map[int]bool{}
for _, cellIndex := range i.rows[getRowFromIndex(cell.index, i.puzzleSize)] {
if usedMap[i.cells[cellIndex].value] || i.cells[cellIndex].value < minValue {
continue
}
usedMap[i.cells[cellIndex].value] = true
}
for _, cellIndex := range i.columns[getColumnFromIndex(cell.index, i.puzzleSize)] {
if usedMap[i.cells[cellIndex].value] || i.cells[cellIndex].value < minValue {
continue
}
usedMap[i.cells[cellIndex].value] = true
}
for _, cellIndex := range i.sections[getSectionFromIndex(cell.index, i.puzzleSize, i.sectionSize)] {
if usedMap[i.cells[cellIndex].value] || i.cells[cellIndex].value < minValue {
continue
}
usedMap[i.cells[cellIndex].value] = true
}
for value := minValue; value <= i.puzzleSize; value++ {
if usedMap[value] {
continue
}
return value, nil
}
return 0, ErrNoMoreMoves
}
| {
rows := make([][]int, puzzleSize)
columns := make([][]int, puzzleSize)
sections := make([][]int, puzzleSize)
it := &iteration{
puzzleSize: puzzleSize,
sectionSize: sectionSize,
cells: make(group, len(items)),
rows: rows,
columns: columns,
sections: sections,
}
for i, item := range items {
c := cell{
fixed: item > 0,
value: item,
index: i,
}
it.cells[i] = &c
rowIndex := getRowFromIndex(c.index, it.puzzleSize)
if it.rows[rowIndex] == nil {
it.rows[rowIndex] = make([]int, 0, it.puzzleSize)
}
it.rows[rowIndex] = append(it.rows[rowIndex], c.index)
columnIndex := getColumnFromIndex(c.index, it.puzzleSize)
if it.columns[columnIndex] == nil {
it.columns[columnIndex] = make([]int, 0, it.puzzleSize)
}
it.columns[columnIndex] = append(it.columns[columnIndex], c.index)
sectionIndex := getSectionFromIndex(c.index, it.puzzleSize, it.sectionSize)
if it.sections[sectionIndex] == nil {
it.sections[sectionIndex] = make([]int, 0, it.puzzleSize)
}
it.sections[sectionIndex] = append(it.sections[sectionIndex], c.index)
}
return it
} |
gulpfile_20180802175929.js | const gulp = require('gulp');
const nodemon = require('gulp-nodemon');
const eslint = require('gulp-eslint');
const ts = require('gulp-typescript');
const merge = require('merge2');
/**
* Gulp task to compile TS to JS
*/
gulp.task('scripts', function() {
var tsResult = gulp.src('lib/**/*.ts')
.pipe(ts({
declaration: true
}));
return merge([
tsResult.dts.pipe(gulp.dest('release/definitions')),
tsResult.js.pipe(gulp.dest('release/js'))
]);
});
/**
* Gulp task to Boot strap server
*/
gulp.task('start', () => {
nodemon({
script: './src/server',
ext: 'js html',
tasks: ['lint'],
});
});
/**
* Gulp config for JS lint
*/
gulp.task('lint', () => (
gulp.src(['src/**/*.js', '!node_modules/**'])
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError())
));
/**
* gulp default
*/ | gulp.task('default', ['start', 'lint']); |
|
api_op_DescribeLifecycleHooks.go | // Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
package autoscaling
import (
"context"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/internal/awsutil"
)
// Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DescribeLifecycleHooksType
type DescribeLifecycleHooksInput struct {
_ struct{} `type:"structure"`
// The name of the Auto Scaling group.
//
// AutoScalingGroupName is a required field
AutoScalingGroupName *string `min:"1" type:"string" required:"true"`
// The names of one or more lifecycle hooks. If you omit this parameter, all
// lifecycle hooks are described.
LifecycleHookNames []string `type:"list"`
}
// String returns the string representation
func (s DescribeLifecycleHooksInput) String() string {
return awsutil.Prettify(s)
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *DescribeLifecycleHooksInput) Validate() error {
invalidParams := aws.ErrInvalidParams{Context: "DescribeLifecycleHooksInput"}
if s.AutoScalingGroupName == nil {
invalidParams.Add(aws.NewErrParamRequired("AutoScalingGroupName"))
}
if s.AutoScalingGroupName != nil && len(*s.AutoScalingGroupName) < 1 {
invalidParams.Add(aws.NewErrParamMinLen("AutoScalingGroupName", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DescribeLifecycleHooksAnswer
type DescribeLifecycleHooksOutput struct {
_ struct{} `type:"structure"` | // The lifecycle hooks for the specified group.
LifecycleHooks []LifecycleHook `type:"list"`
}
// String returns the string representation
func (s DescribeLifecycleHooksOutput) String() string {
return awsutil.Prettify(s)
}
const opDescribeLifecycleHooks = "DescribeLifecycleHooks"
// DescribeLifecycleHooksRequest returns a request value for making API operation for
// Auto Scaling.
//
// Describes the lifecycle hooks for the specified Auto Scaling group.
//
// // Example sending a request using DescribeLifecycleHooksRequest.
// req := client.DescribeLifecycleHooksRequest(params)
// resp, err := req.Send(context.TODO())
// if err == nil {
// fmt.Println(resp)
// }
//
// Please also see https://docs.aws.amazon.com/goto/WebAPI/autoscaling-2011-01-01/DescribeLifecycleHooks
func (c *Client) DescribeLifecycleHooksRequest(input *DescribeLifecycleHooksInput) DescribeLifecycleHooksRequest {
op := &aws.Operation{
Name: opDescribeLifecycleHooks,
HTTPMethod: "POST",
HTTPPath: "/",
}
if input == nil {
input = &DescribeLifecycleHooksInput{}
}
req := c.newRequest(op, input, &DescribeLifecycleHooksOutput{})
return DescribeLifecycleHooksRequest{Request: req, Input: input, Copy: c.DescribeLifecycleHooksRequest}
}
// DescribeLifecycleHooksRequest is the request type for the
// DescribeLifecycleHooks API operation.
type DescribeLifecycleHooksRequest struct {
*aws.Request
Input *DescribeLifecycleHooksInput
Copy func(*DescribeLifecycleHooksInput) DescribeLifecycleHooksRequest
}
// Send marshals and sends the DescribeLifecycleHooks API request.
func (r DescribeLifecycleHooksRequest) Send(ctx context.Context) (*DescribeLifecycleHooksResponse, error) {
r.Request.SetContext(ctx)
err := r.Request.Send()
if err != nil {
return nil, err
}
resp := &DescribeLifecycleHooksResponse{
DescribeLifecycleHooksOutput: r.Request.Data.(*DescribeLifecycleHooksOutput),
response: &aws.Response{Request: r.Request},
}
return resp, nil
}
// DescribeLifecycleHooksResponse is the response type for the
// DescribeLifecycleHooks API operation.
type DescribeLifecycleHooksResponse struct {
*DescribeLifecycleHooksOutput
response *aws.Response
}
// SDKResponseMetdata returns the response metadata for the
// DescribeLifecycleHooks request.
func (r *DescribeLifecycleHooksResponse) SDKResponseMetdata() *aws.Response {
return r.response
} | |
TrajQR.py | ########################################################################
#
# Vision Macro - Python source code - file generated by vision
# Thursday 22 July 2010 11:38:41
#
# The Scripps Research Institute (TSRI)
# Molecular Graphics Lab
# La Jolla, CA 92037, USA
#
# Copyright: Daniel Stoffler, Michel Sanner and TSRI
#
# revision: Guillaume Vareille
#
#########################################################################
#
# $Header: /opt/cvs/python/packages/share1.5/AutoDockTools/VisionInterface/Adt/Macro/TrajQR.py,v 1.1 2010/07/22 18:43:31 jren Exp $
#
# $Id: TrajQR.py,v 1.1 2010/07/22 18:43:31 jren Exp $
#
from NetworkEditor.macros import MacroNode
from NetworkEditor.macros import MacroNode
class TrajQR(MacroNode):
'''
This node runs Traj QR.
Inputs:
port 1: directory containing pdb files
port 2: rmsd
port 3: directory to copy the selected pdb files to
Output:
directory that containst he selected pdb files
'''
def __init__(self, constrkw={}, name='TrajQR', **kw):
kw['name'] = name
apply( MacroNode.__init__, (self,), kw)
def beforeAddingToNetwork(self, net):
MacroNode.beforeAddingToNetwork(self, net)
from WebServices.VisionInterface.WSNodes import wslib
from Vision.StandardNodes import stdlib
net.getEditor().addLibraryInstance(wslib,"WebServices.VisionInterface.WSNodes", "wslib")
from WebServices.VisionInterface.WSNodes import addOpalServerAsCategory
try:
addOpalServerAsCategory("http://kryptonite.nbcr.net/opal2", replace=False)
except:
pass
def | (self):
masterNet = self.macroNetwork
from NetworkEditor.macros import MacroNode
MacroNode.afterAddingToNetwork(self)
from WebServices.VisionInterface.WSNodes import wslib
from Vision.StandardNodes import stdlib
## building macro network ##
TrajQR_0 = self
from traceback import print_exc
from WebServices.VisionInterface.WSNodes import wslib
from Vision.StandardNodes import stdlib
masterNet.getEditor().addLibraryInstance(wslib,"WebServices.VisionInterface.WSNodes", "wslib")
from WebServices.VisionInterface.WSNodes import addOpalServerAsCategory
try:
addOpalServerAsCategory("http://kryptonite.nbcr.net/opal2", replace=False)
except:
pass
try:
## saving node input Ports ##
input_Ports_1 = self.macroNetwork.ipNode
apply(input_Ports_1.configure, (), {'paramPanelImmediate': 1, 'expanded': False})
except:
print "WARNING: failed to restore MacroInputNode named input Ports in network self.macroNetwork"
print_exc()
input_Ports_1=None
try:
## saving node output Ports ##
output_Ports_2 = self.macroNetwork.opNode
apply(output_Ports_2.configure, (), {'paramPanelImmediate': 1, 'expanded': False})
output_Ports_2.move(183, 405)
except:
print "WARNING: failed to restore MacroOutputNode named output Ports in network self.macroNetwork"
print_exc()
output_Ports_2=None
try:
## saving node Make_Zip_File ##
from Vision.StandardNodes import MakeZipFileNE
Make_Zip_File_3 = MakeZipFileNE(constrkw={}, name='Make_Zip_File', library=stdlib)
self.macroNetwork.addNode(Make_Zip_File_3,47,75)
apply(Make_Zip_File_3.inputPortByName['input_directory'].configure, (), {'defaultValue': None})
apply(Make_Zip_File_3.inputPortByName['output_directory'].configure, (), {'defaultValue': None})
apply(Make_Zip_File_3.inputPortByName['output_name'].configure, (), {'defaultValue': None})
apply(Make_Zip_File_3.configure, (), {'paramPanelImmediate': 1, 'expanded': False})
except:
print "WARNING: failed to restore MakeZipFileNE named Make_Zip_File in network self.macroNetwork"
print_exc()
Make_Zip_File_3=None
try:
## saving node TrajQR_kryptonite_nbcr_net ##
from NetworkEditor.items import FunctionNode
TrajQR_kryptonite_nbcr_net_4 = FunctionNode(functionOrString='TrajQR_kryptonite_nbcr_net', host="http://kryptonite.nbcr.net/opal2", namedArgs={'license': False, 'rmsd': '', 'qh_filename': 'qh.tre', 'qr_filename': 'qr.out', 'compressed_pdbs': '', 'localRun': False, 'execPath': ''}, constrkw={'functionOrString': "'TrajQR_kryptonite_nbcr_net'", 'host': '"http://kryptonite.nbcr.net/opal2"', 'namedArgs': {'license': False, 'rmsd': '', 'qh_filename': 'qh.tre', 'qr_filename': 'qr.out', 'compressed_pdbs': '', 'localRun': False, 'execPath': ''}}, name='TrajQR_kryptonite_nbcr_net', library=wslib)
self.macroNetwork.addNode(TrajQR_kryptonite_nbcr_net_4,279,135)
apply(TrajQR_kryptonite_nbcr_net_4.inputPortByName['license'].configure, (), {'defaultValue': None})
apply(TrajQR_kryptonite_nbcr_net_4.inputPortByName['rmsd'].configure, (), {'defaultValue': None, 'required': True})
apply(TrajQR_kryptonite_nbcr_net_4.inputPortByName['qh_filename'].configure, (), {'defaultValue': None})
apply(TrajQR_kryptonite_nbcr_net_4.inputPortByName['qr_filename'].configure, (), {'defaultValue': None})
apply(TrajQR_kryptonite_nbcr_net_4.inputPortByName['compressed_pdbs'].configure, (), {'defaultValue': None, 'required': True})
apply(TrajQR_kryptonite_nbcr_net_4.inputPortByName['localRun'].configure, (), {'defaultValue': None})
apply(TrajQR_kryptonite_nbcr_net_4.inputPortByName['execPath'].configure, (), {'defaultValue': None})
TrajQR_kryptonite_nbcr_net_4.inputPortByName['license'].widget.set(0, run=False)
TrajQR_kryptonite_nbcr_net_4.inputPortByName['rmsd'].rebindWidget()
TrajQR_kryptonite_nbcr_net_4.inputPortByName['rmsd'].widget.set(r"", run=False)
TrajQR_kryptonite_nbcr_net_4.inputPortByName['rmsd'].unbindWidget()
TrajQR_kryptonite_nbcr_net_4.inputPortByName['qh_filename'].widget.set(r"qh.tre", run=False)
TrajQR_kryptonite_nbcr_net_4.inputPortByName['qr_filename'].widget.set(r"qr.out", run=False)
TrajQR_kryptonite_nbcr_net_4.inputPortByName['compressed_pdbs'].rebindWidget()
TrajQR_kryptonite_nbcr_net_4.inputPortByName['compressed_pdbs'].widget.set(r"", run=False)
TrajQR_kryptonite_nbcr_net_4.inputPortByName['compressed_pdbs'].unbindWidget()
TrajQR_kryptonite_nbcr_net_4.inputPortByName['localRun'].widget.set(0, run=False)
TrajQR_kryptonite_nbcr_net_4.inputPortByName['execPath'].widget.set(r"", run=False)
apply(TrajQR_kryptonite_nbcr_net_4.configure, (), {'paramPanelImmediate': 1, 'expanded': False})
except:
print "WARNING: failed to restore FunctionNode named TrajQR_kryptonite_nbcr_net in network self.macroNetwork"
print_exc()
TrajQR_kryptonite_nbcr_net_4=None
try:
## saving node SelectOnExtension ##
from Vision.StandardNodes import SelectOnExtension
SelectOnExtension_5 = SelectOnExtension(constrkw={}, name='SelectOnExtension', library=stdlib)
self.macroNetwork.addNode(SelectOnExtension_5,279,192)
apply(SelectOnExtension_5.inputPortByName['filenames'].configure, (), {'defaultValue': None})
apply(SelectOnExtension_5.inputPortByName['extension'].configure, (), {'defaultValue': None})
SelectOnExtension_5.inputPortByName['extension'].widget.set(r".out", run=False)
apply(SelectOnExtension_5.configure, (), {'paramPanelImmediate': 1})
except:
print "WARNING: failed to restore SelectOnExtension named SelectOnExtension in network self.macroNetwork"
print_exc()
SelectOnExtension_5=None
try:
## saving node Index ##
from Vision.StandardNodes import Index
Index_6 = Index(constrkw={}, name='Index', library=stdlib)
self.macroNetwork.addNode(Index_6,123,281)
apply(Index_6.inputPortByName['data'].configure, (), {'datatype': 'list', 'defaultValue': None, 'originalDatatype': 'None'})
apply(Index_6.inputPortByName['index'].configure, (), {'defaultValue': None})
apply(Index_6.outputPortByName['data'].configure, (), {'datatype': 'string'})
apply(Index_6.inputPortByName['index'].widget.configure, (), {'max': 0, 'min': -1})
Index_6.inputPortByName['index'].widget.set(0, run=False)
apply(Index_6.configure, (), {'paramPanelImmediate': 1, 'expanded': False})
except:
print "WARNING: failed to restore Index named Index in network self.macroNetwork"
print_exc()
Index_6=None
try:
## saving node GetSelectedPDBs ##
from Vision.StandardNodes import Generic
GetSelectedPDBs_7 = Generic(constrkw={}, name='GetSelectedPDBs', library=stdlib)
self.macroNetwork.addNode(GetSelectedPDBs_7,200,346)
apply(GetSelectedPDBs_7.addInputPort, (), {'singleConnection': True, 'name': 'trajqr_url', 'cast': True, 'datatype': 'string', 'defaultValue': None, 'required': True, 'height': 8, 'width': 12, 'shape': 'oval', 'color': 'white', 'originalDatatype': 'None'})
apply(GetSelectedPDBs_7.addInputPort, (), {'singleConnection': True, 'name': 'pdb_in_dir', 'cast': True, 'datatype': 'string', 'defaultValue': None, 'required': True, 'height': 8, 'width': 12, 'shape': 'oval', 'color': 'white', 'originalDatatype': 'None'})
apply(GetSelectedPDBs_7.addInputPort, (), {'singleConnection': True, 'name': 'pdb_out_dir', 'cast': True, 'datatype': 'string', 'defaultValue': None, 'required': True, 'height': 8, 'width': 12, 'shape': 'oval', 'color': 'white', 'originalDatatype': 'None'})
apply(GetSelectedPDBs_7.addOutputPort, (), {'name': 'pdb_out_dir', 'datatype': 'string', 'height': 8, 'width': 12, 'shape': 'oval', 'color': 'white'})
code = """def doit(self, trajqr_url, pdb_in_dir, pdb_out_dir):
pdb_in_dir = os.path.abspath(pdb_in_dir)
pdb_out_dir = os.path.abspath(pdb_out_dir)
import urllib
import shutil
pdb_list = []
f = urllib.urlopen(trajqr_url)
for i in f.readlines():
pdb_file = i.strip('''
''')+'''.pdb'''
infile = pdb_in_dir + os.sep + pdb_file
outfile = pdb_out_dir + os.sep + pdb_file
shutil.copyfile(infile, outfile)
f.close
pass
## to ouput data on port pdb_list use
self.outputData(pdb_out_dir=pdb_out_dir)
"""
GetSelectedPDBs_7.configure(function=code)
apply(GetSelectedPDBs_7.configure, (), {'paramPanelImmediate': 1, 'expanded': False})
except:
print "WARNING: failed to restore Generic named GetSelectedPDBs in network self.macroNetwork"
print_exc()
GetSelectedPDBs_7=None
#self.macroNetwork.run()
self.macroNetwork.freeze()
## saving connections for network TrajQR ##
input_Ports_1 = self.macroNetwork.ipNode
if input_Ports_1 is not None and Make_Zip_File_3 is not None:
try:
self.macroNetwork.connectNodes(
input_Ports_1, Make_Zip_File_3, "new", "input_directory", blocking=True
, splitratio=[0.67469172328672133, 0.50941480178765064])
except:
print "WARNING: failed to restore connection between input_Ports_1 and Make_Zip_File_3 in network self.macroNetwork"
if input_Ports_1 is not None and TrajQR_kryptonite_nbcr_net_4 is not None:
try:
self.macroNetwork.connectNodes(
input_Ports_1, TrajQR_kryptonite_nbcr_net_4, "new", "rmsd", blocking=True
, splitratio=[0.45681934134493246, 0.33803410340720857])
except:
print "WARNING: failed to restore connection between input_Ports_1 and TrajQR_kryptonite_nbcr_net_4 in network self.macroNetwork"
if Make_Zip_File_3 is not None and TrajQR_kryptonite_nbcr_net_4 is not None:
try:
self.macroNetwork.connectNodes(
Make_Zip_File_3, TrajQR_kryptonite_nbcr_net_4, "zipfile", "compressed_pdbs", blocking=True
, splitratio=[0.71081093868178202, 0.43908686250860129])
except:
print "WARNING: failed to restore connection between Make_Zip_File_3 and TrajQR_kryptonite_nbcr_net_4 in network self.macroNetwork"
if TrajQR_kryptonite_nbcr_net_4 is not None and SelectOnExtension_5 is not None:
try:
self.macroNetwork.connectNodes(
TrajQR_kryptonite_nbcr_net_4, SelectOnExtension_5, "result", "filenames", blocking=True
, splitratio=[0.63533198718963335, 0.2560040659014205])
except:
print "WARNING: failed to restore connection between TrajQR_kryptonite_nbcr_net_4 and SelectOnExtension_5 in network self.macroNetwork"
if SelectOnExtension_5 is not None and Index_6 is not None:
try:
self.macroNetwork.connectNodes(
SelectOnExtension_5, Index_6, "matching", "data", blocking=True
, splitratio=[0.65832290589891362, 0.21624347250969889])
except:
print "WARNING: failed to restore connection between SelectOnExtension_5 and Index_6 in network self.macroNetwork"
if Index_6 is not None and GetSelectedPDBs_7 is not None:
try:
self.macroNetwork.connectNodes(
Index_6, GetSelectedPDBs_7, "data", "trajqr_url", blocking=True
, splitratio=[0.51754619993986595, 0.63949220525823236])
except:
print "WARNING: failed to restore connection between Index_6 and GetSelectedPDBs_7 in network self.macroNetwork"
if input_Ports_1 is not None and GetSelectedPDBs_7 is not None:
try:
self.macroNetwork.connectNodes(
input_Ports_1, GetSelectedPDBs_7, "Make_Zip_File_input_directory", "pdb_in_dir", blocking=True
, splitratio=[0.7121964126696847, 0.42697952864467786])
except:
print "WARNING: failed to restore connection between input_Ports_1 and GetSelectedPDBs_7 in network self.macroNetwork"
if input_Ports_1 is not None and GetSelectedPDBs_7 is not None:
try:
self.macroNetwork.connectNodes(
input_Ports_1, GetSelectedPDBs_7, "new", "pdb_out_dir", blocking=True
, splitratio=[0.62460995639428174, 0.60275185701976297])
except:
print "WARNING: failed to restore connection between input_Ports_1 and GetSelectedPDBs_7 in network self.macroNetwork"
output_Ports_2 = self.macroNetwork.opNode
if GetSelectedPDBs_7 is not None and output_Ports_2 is not None:
try:
self.macroNetwork.connectNodes(
GetSelectedPDBs_7, output_Ports_2, "pdb_out_dir", "new", blocking=True
, splitratio=[0.7431176169343523, 0.73697976585137526])
except:
print "WARNING: failed to restore connection between GetSelectedPDBs_7 and output_Ports_2 in network self.macroNetwork"
self.macroNetwork.runOnNewData.value = True
## modifying MacroInputNode dynamic ports
input_Ports_1 = self.macroNetwork.ipNode
input_Ports_1.outputPorts[1].configure(name='Make_Zip_File_input_directory')
input_Ports_1.outputPorts[2].configure(name='TrajQR_kryptonite_nbcr_net_rmsd')
input_Ports_1.outputPorts[3].configure(name='GetSelectedPDBs_pdb_out_dir')
## modifying MacroOutputNode dynamic ports
output_Ports_2 = self.macroNetwork.opNode
output_Ports_2.inputPorts[1].configure(singleConnection='auto')
output_Ports_2.inputPorts[1].configure(name='GetSelectedPDBs_pdb_out_dir')
## configure MacroNode input ports
TrajQR_0.inputPorts[0].configure(name='Make_Zip_File_input_directory')
TrajQR_0.inputPorts[0].configure(datatype='string')
TrajQR_0.inputPorts[1].configure(name='TrajQR_kryptonite_nbcr_net_rmsd')
TrajQR_0.inputPorts[1].configure(datatype='string')
TrajQR_0.inputPorts[2].configure(name='GetSelectedPDBs_pdb_out_dir')
TrajQR_0.inputPorts[2].configure(datatype='string')
## configure MacroNode output ports
TrajQR_0.outputPorts[0].configure(name='GetSelectedPDBs_pdb_out_dir')
TrajQR_0.outputPorts[0].configure(datatype='string')
TrajQR_0.shrink()
## reset modifications ##
TrajQR_0.resetTags()
TrajQR_0.buildOriginalList()
| afterAddingToNetwork |
app.py | import falcon
from falcon_pagination_processor import PaginationProcessor
from tests.falcon.resources import TestResourceCollection
api = falcon.API(middleware=[PaginationProcessor()]) | api.add_route(TestResourceCollection.route, TestResourceCollection()) | |
categories.py | """
Category queries application file.
"""
from lib import database as db
def printAvailableCategories():
"""
Iterate through Categories in db to print out name and Profile count
for each.
:return: None
"""
print(" Category | Profiles")
print("-------------------------------+---------")
categoryResult = db.Category.select()
for i, v in enumerate(categoryResult):
print(
"{index:3d}. {category:25s} | {profCnt:7,d}".format(
index=i + 1, category=v.name, profCnt=v.profiles.count()
)
)
print()
def printCategoriesAndProfiles():
|
def printUnassignedProfiles():
"""
Iterate through Profiles in db to print out those in no Categories.
Output may be very long for large datasets of Profiles.
TODO: Add filters such as top N recently created profiles or most
followers. And find a way to make this more useful, considering that
the influencer category and a specific influencer category could be assigned
on fetch_profiles.py running, but it has to be clear that industry is
assigned yet.
:return: None
"""
for profileRec in db.Profile.select(orderBy="screen_name"):
if not profileRec.categories.count():
print(
"@{screenName} | {name} | {followers:,d} followers".format(
screenName=profileRec.screenName,
name=profileRec.name,
followers=profileRec.followersCount,
)
)
print(profileRec.getFlatDescription())
print()
if __name__ == "__main__":
print("Available cateogries")
print("====================")
printAvailableCategories()
print()
print("Profiles")
print("========")
printCategoriesAndProfiles()
| """
Iterate through Categories in db to print out the name and list of
the Profiles in each.
:return: None
"""
for i, cat in enumerate(db.Category.select()):
profiles = list(cat.profiles.orderBy("screen_name"))
print(
"{index:d}. {name:15s} {profCnt:,d} profiles".format(
index=i + 1, name=cat.name, profCnt=len(profiles)
)
)
for p in profiles:
print(
" - @{screenName:20} | {name}".format(
screenName=p.screenName, name=p.name
)
)
print() |
dates_time.rs | //! This module exists to reduce compilation times.
//! All the data types are backed by a physical type in memory e.g. Date -> i32, Datetime-> i64.
//!
//! Series lead to code implementations of all traits. Whereas there are a lot of duplicates due to
//! data types being backed by the same physical type. In this module we reduce compile times by
//! opting for a little more run time cost. We cast to the physical type -> apply the operation and
//! (depending on the result) cast back to the original type
//!
use super::private;
use super::IntoSeries;
use super::SeriesTrait;
use super::SeriesWrap;
use crate::chunked_array::{
comparison::*,
ops::{explode::ExplodeByOffsets, ToBitRepr},
AsSinglePtr, ChunkIdIter,
};
use crate::fmt::FmtList;
use crate::frame::{groupby::*, hash_join::*};
use crate::prelude::*;
use ahash::RandomState;
use polars_arrow::prelude::QuantileInterpolOptions;
use std::borrow::Cow;
use std::ops::{Deref, DerefMut};
macro_rules! impl_dyn_series {
($ca: ident, $into_logical: ident) => {
impl IntoSeries for $ca {
fn into_series(self) -> Series {
Series(Arc::new(SeriesWrap(self)))
}
}
impl private::PrivateSeries for SeriesWrap<$ca> {
fn _field(&self) -> Cow<Field> {
Cow::Owned(self.0.field())
}
fn _dtype(&self) -> &DataType {
self.0.dtype()
}
fn explode_by_offsets(&self, offsets: &[i64]) -> Series {
self.0
.explode_by_offsets(offsets)
.$into_logical()
.into_series()
}
#[cfg(feature = "cum_agg")]
fn _cummax(&self, reverse: bool) -> Series {
self.0.cummax(reverse).$into_logical().into_series()
}
#[cfg(feature = "cum_agg")]
fn _cummin(&self, reverse: bool) -> Series {
self.0.cummin(reverse).$into_logical().into_series()
}
#[cfg(feature = "asof_join")]
fn join_asof(&self, other: &Series) -> Result<Vec<Option<u32>>> {
let other = other.to_physical_repr();
self.0.deref().join_asof(&other)
}
fn set_sorted(&mut self, reverse: bool) {
self.0.deref_mut().set_sorted(reverse)
}
unsafe fn equal_element(
&self,
idx_self: usize,
idx_other: usize,
other: &Series,
) -> bool {
self.0.equal_element(idx_self, idx_other, other)
}
#[cfg(feature = "zip_with")]
fn zip_with_same_type(&self, mask: &BooleanChunked, other: &Series) -> Result<Series> {
let other = other.to_physical_repr().into_owned();
self.0
.zip_with(mask, &other.as_ref().as_ref())
.map(|ca| ca.$into_logical().into_series())
}
fn vec_hash(&self, random_state: RandomState) -> Vec<u64> {
self.0.vec_hash(random_state)
}
fn vec_hash_combine(&self, build_hasher: RandomState, hashes: &mut [u64]) {
self.0.vec_hash_combine(build_hasher, hashes)
}
fn agg_mean(&self, _groups: &GroupsProxy) -> Option<Series> {
// does not make sense on logical
None
}
fn agg_min(&self, groups: &GroupsProxy) -> Option<Series> {
self.0
.agg_min(groups)
.map(|ca| ca.$into_logical().into_series())
}
fn agg_max(&self, groups: &GroupsProxy) -> Option<Series> {
self.0
.agg_max(groups)
.map(|ca| ca.$into_logical().into_series())
}
fn agg_sum(&self, _groups: &GroupsProxy) -> Option<Series> {
// does not make sense on logical
None
}
fn agg_std(&self, _groups: &GroupsProxy) -> Option<Series> {
// does not make sense on logical
None
}
fn agg_var(&self, _groups: &GroupsProxy) -> Option<Series> {
// does not make sense on logical
None
}
fn agg_list(&self, groups: &GroupsProxy) -> Option<Series> {
// we cannot cast and dispatch as the inner type of the list would be incorrect
self.0.agg_list(groups).map(|s| {
s.cast(&DataType::List(Box::new(self.dtype().clone())))
.unwrap()
})
}
fn agg_quantile(
&self,
groups: &GroupsProxy,
quantile: f64,
interpol: QuantileInterpolOptions,
) -> Option<Series> {
self.0
.agg_quantile(groups, quantile, interpol)
.map(|s| s.$into_logical().into_series())
}
fn agg_median(&self, groups: &GroupsProxy) -> Option<Series> {
self.0
.agg_median(groups)
.map(|s| s.$into_logical().into_series())
}
fn hash_join_inner(&self, other: &Series) -> Vec<(u32, u32)> {
let other = other.to_physical_repr().into_owned();
self.0.hash_join_inner(&other.as_ref().as_ref())
}
fn hash_join_left(&self, other: &Series) -> Vec<(u32, Option<u32>)> {
let other = other.to_physical_repr().into_owned();
self.0.hash_join_left(&other.as_ref().as_ref())
}
fn hash_join_outer(&self, other: &Series) -> Vec<(Option<u32>, Option<u32>)> {
let other = other.to_physical_repr().into_owned();
self.0.hash_join_outer(&other.as_ref().as_ref())
}
fn zip_outer_join_column(
&self,
right_column: &Series,
opt_join_tuples: &[(Option<u32>, Option<u32>)],
) -> Series {
let right_column = right_column.to_physical_repr().into_owned();
self.0
.zip_outer_join_column(&right_column, opt_join_tuples)
.$into_logical()
.into_series()
}
fn subtract(&self, rhs: &Series) -> Result<Series> {
match (self.dtype(), rhs.dtype()) {
(DataType::Date, DataType::Date) => {
let dt = DataType::Datetime(TimeUnit::Milliseconds, None);
let lhs = self.cast(&dt)?;
let rhs = rhs.cast(&dt)?;
lhs.subtract(&rhs)
}
(dtl, dtr) => Err(PolarsError::ComputeError(
format!(
"cannot do subtraction on these date types: {:?}, {:?}",
dtl, dtr
)
.into(),
)),
}
}
fn add_to(&self, rhs: &Series) -> Result<Series> {
match (self.dtype(), rhs.dtype()) {
(dtl, dtr) => Err(PolarsError::ComputeError(
format!(
"cannot do addition on these date types: {:?}, {:?}",
dtl, dtr
)
.into(),
)),
}
}
fn multiply(&self, _rhs: &Series) -> Result<Series> {
Err(PolarsError::ComputeError(
"cannot do multiplication on logical".into(),
))
}
fn divide(&self, _rhs: &Series) -> Result<Series> {
Err(PolarsError::ComputeError(
"cannot do division on logical".into(),
))
}
fn remainder(&self, _rhs: &Series) -> Result<Series> {
Err(PolarsError::ComputeError(
"cannot do remainder operation on logical".into(),
))
}
fn group_tuples(&self, multithreaded: bool) -> GroupsProxy {
self.0.group_tuples(multithreaded)
}
#[cfg(feature = "sort_multiple")]
fn argsort_multiple(&self, by: &[Series], reverse: &[bool]) -> Result<UInt32Chunked> {
self.0.deref().argsort_multiple(by, reverse)
}
}
impl SeriesTrait for SeriesWrap<$ca> {
#[cfg(feature = "interpolate")]
fn interpolate(&self) -> Series {
self.0.interpolate().$into_logical().into_series()
}
fn rename(&mut self, name: &str) {
self.0.rename(name);
}
fn chunk_lengths(&self) -> ChunkIdIter {
self.0.chunk_id()
}
fn name(&self) -> &str {
self.0.name()
}
fn chunks(&self) -> &Vec<ArrayRef> {
self.0.chunks()
}
fn shrink_to_fit(&mut self) {
self.0.shrink_to_fit()
}
fn time(&self) -> Result<&TimeChunked> {
if matches!(self.0.dtype(), DataType::Time) {
unsafe { Ok(&*(self as *const dyn SeriesTrait as *const TimeChunked)) }
} else {
Err(PolarsError::SchemaMisMatch(
format!(
"cannot unpack Series: {:?} of type {:?} into Time",
self.name(),
self.dtype(),
)
.into(),
))
}
}
fn date(&self) -> Result<&DateChunked> {
if matches!(self.0.dtype(), DataType::Date) {
unsafe { Ok(&*(self as *const dyn SeriesTrait as *const DateChunked)) }
} else {
Err(PolarsError::SchemaMisMatch(
format!(
"cannot unpack Series: {:?} of type {:?} into Date",
self.name(),
self.dtype(),
)
.into(),
))
}
}
fn append_array(&mut self, other: ArrayRef) -> Result<()> {
self.0.append_array(other)
}
fn slice(&self, offset: i64, length: usize) -> Series {
self.0.slice(offset, length).$into_logical().into_series()
}
fn mean(&self) -> Option<f64> {
self.0.mean()
}
fn median(&self) -> Option<f64> {
self.0.median()
}
fn append(&mut self, other: &Series) -> Result<()> {
if self.0.dtype() == other.dtype() {
let other = other.to_physical_repr().into_owned();
self.0.append(other.as_ref().as_ref());
Ok(())
} else {
Err(PolarsError::SchemaMisMatch(
"cannot append Series; data types don't match".into(),
))
}
}
fn filter(&self, filter: &BooleanChunked) -> Result<Series> {
self.0
.filter(filter)
.map(|ca| ca.$into_logical().into_series())
}
fn take(&self, indices: &UInt32Chunked) -> Result<Series> {
ChunkTake::take(self.0.deref(), indices.into())
.map(|ca| ca.$into_logical().into_series())
}
fn take_iter(&self, iter: &mut dyn TakeIterator) -> Result<Series> {
ChunkTake::take(self.0.deref(), iter.into())
.map(|ca| ca.$into_logical().into_series())
}
fn take_every(&self, n: usize) -> Series {
self.0.take_every(n).$into_logical().into_series()
}
unsafe fn take_iter_unchecked(&self, iter: &mut dyn TakeIterator) -> Series {
ChunkTake::take_unchecked(self.0.deref(), iter.into())
.$into_logical()
.into_series()
}
unsafe fn take_unchecked(&self, idx: &UInt32Chunked) -> Result<Series> {
Ok(ChunkTake::take_unchecked(self.0.deref(), idx.into())
.$into_logical()
.into_series())
}
unsafe fn take_opt_iter_unchecked(&self, iter: &mut dyn TakeIteratorNulls) -> Series {
ChunkTake::take_unchecked(self.0.deref(), iter.into())
.$into_logical()
.into_series()
}
#[cfg(feature = "take_opt_iter")]
fn take_opt_iter(&self, iter: &mut dyn TakeIteratorNulls) -> Result<Series> {
ChunkTake::take(self.0.deref(), iter.into())
.map(|ca| ca.$into_logical().into_series())
}
fn len(&self) -> usize {
self.0.len()
}
fn rechunk(&self) -> Series {
self.0.rechunk().$into_logical().into_series()
}
fn expand_at_index(&self, index: usize, length: usize) -> Series {
self.0
.expand_at_index(index, length)
.$into_logical()
.into_series()
}
fn cast(&self, data_type: &DataType) -> Result<Series> {
const NS_IN_DAY: i64 = 86400000_000_000;
const MS_IN_DAY: i64 = 86400000;
use DataType::*;
let ca = match (self.dtype(), data_type) {
#[cfg(feature = "dtype-datetime")]
(Date, Datetime(tu, tz)) => {
let casted = self.0.cast(data_type)?;
let casted = casted.datetime().unwrap();
match tu {
TimeUnit::Nanoseconds => {
return Ok((casted.deref() * NS_IN_DAY)
.into_datetime(*tu, tz.clone())
.into_series());
}
TimeUnit::Milliseconds => {
return Ok((casted.deref() * MS_IN_DAY)
.into_datetime(*tu, tz.clone())
.into_series());
}
}
}
_ => Cow::Borrowed(self.0.deref()),
};
ca.cast(data_type)
}
fn to_dummies(&self) -> Result<DataFrame> {
self.0.to_dummies()
}
fn value_counts(&self) -> Result<DataFrame> {
self.0.value_counts()
}
fn get(&self, index: usize) -> AnyValue {
self.0.get_any_value(index)
}
#[inline]
unsafe fn get_unchecked(&self, index: usize) -> AnyValue {
self.0.get_any_value_unchecked(index).$into_logical()
}
fn sort_with(&self, options: SortOptions) -> Series {
self.0.sort_with(options).$into_logical().into_series()
}
fn argsort(&self, reverse: bool) -> UInt32Chunked {
self.0.argsort(reverse)
}
fn null_count(&self) -> usize {
self.0.null_count()
}
fn has_validity(&self) -> bool {
self.0.has_validity()
}
fn unique(&self) -> Result<Series> {
self.0.unique().map(|ca| ca.$into_logical().into_series())
}
fn n_unique(&self) -> Result<usize> {
self.0.n_unique()
}
fn arg_unique(&self) -> Result<UInt32Chunked> {
self.0.arg_unique()
}
fn arg_min(&self) -> Option<usize> {
self.0.arg_min()
}
fn arg_max(&self) -> Option<usize> {
self.0.arg_max()
}
fn is_null(&self) -> BooleanChunked {
self.0.is_null()
}
fn is_not_null(&self) -> BooleanChunked {
self.0.is_not_null()
}
fn is_unique(&self) -> Result<BooleanChunked> {
self.0.is_unique()
}
fn is_duplicated(&self) -> Result<BooleanChunked> {
self.0.is_duplicated()
}
fn reverse(&self) -> Series {
self.0.reverse().$into_logical().into_series()
}
fn as_single_ptr(&mut self) -> Result<usize> {
self.0.as_single_ptr()
}
fn shift(&self, periods: i64) -> Series {
self.0.shift(periods).$into_logical().into_series()
}
fn fill_null(&self, strategy: FillNullStrategy) -> Result<Series> {
self.0
.fill_null(strategy)
.map(|ca| ca.$into_logical().into_series())
}
fn _sum_as_series(&self) -> Series {
Int32Chunked::full_null(self.name(), 1)
.cast(self.dtype())
.unwrap()
.into()
}
fn max_as_series(&self) -> Series {
self.0.max_as_series().$into_logical()
}
fn min_as_series(&self) -> Series {
self.0.min_as_series().$into_logical()
}
fn mean_as_series(&self) -> Series {
Int32Chunked::full_null(self.name(), 1)
.cast(self.dtype())
.unwrap()
.into()
}
fn median_as_series(&self) -> Series {
Int32Chunked::full_null(self.name(), 1)
.cast(self.dtype())
.unwrap()
.into()
}
fn var_as_series(&self) -> Series {
Int32Chunked::full_null(self.name(), 1)
.cast(self.dtype())
.unwrap()
.into()
}
fn std_as_series(&self) -> Series {
Int32Chunked::full_null(self.name(), 1)
.cast(self.dtype())
.unwrap()
.into()
}
fn quantile_as_series(
&self,
_quantile: f64,
_interpol: QuantileInterpolOptions,
) -> Result<Series> {
Ok(Int32Chunked::full_null(self.name(), 1)
.cast(self.dtype())
.unwrap()
.into())
}
fn fmt_list(&self) -> String {
FmtList::fmt_list(&self.0)
}
fn clone_inner(&self) -> Arc<dyn SeriesTrait> {
Arc::new(SeriesWrap(Clone::clone(&self.0)))
}
fn pow(&self, _exponent: f64) -> Result<Series> {
Err(PolarsError::ComputeError(
"cannot compute power of logical".into(),
))
}
fn peak_max(&self) -> BooleanChunked {
self.0.peak_max()
}
fn peak_min(&self) -> BooleanChunked {
self.0.peak_min()
}
#[cfg(feature = "is_in")]
fn is_in(&self, other: &Series) -> Result<BooleanChunked> {
self.0.is_in(other)
}
#[cfg(feature = "repeat_by")]
fn repeat_by(&self, by: &UInt32Chunked) -> ListChunked {
match self.0.dtype() {
DataType::Date => self
.0
.repeat_by(by)
.cast(&DataType::List(Box::new(DataType::Date)))
.unwrap()
.list()
.unwrap()
.clone(),
DataType::Time => self
.0
.repeat_by(by)
.cast(&DataType::List(Box::new(DataType::Time)))
.unwrap()
.list()
.unwrap()
.clone(),
_ => unreachable!(),
}
}
#[cfg(feature = "is_first")]
fn is_first(&self) -> Result<BooleanChunked> {
self.0.is_first()
}
#[cfg(feature = "mode")]
fn mode(&self) -> Result<Series> {
self.0.mode().map(|ca| ca.$into_logical().into_series())
}
}
};
}
#[cfg(feature = "dtype-date")]
impl_dyn_series!(DateChunked, into_date);
#[cfg(feature = "dtype-time")]
impl_dyn_series!(TimeChunked, into_time);
macro_rules! impl_dyn_series_numeric {
($ca: ident) => {
impl private::PrivateSeriesNumeric for SeriesWrap<$ca> {
fn bit_repr_is_large(&self) -> bool {
if let DataType::Time = self.dtype() {
true
} else {
false
}
}
fn bit_repr_large(&self) -> UInt64Chunked {
self.0.bit_repr_large()
}
fn bit_repr_small(&self) -> UInt32Chunked {
self.0.bit_repr_small()
}
}
};
}
#[cfg(feature = "dtype-date")]
impl_dyn_series_numeric!(DateChunked);
#[cfg(feature = "dtype-time")]
impl_dyn_series_numeric!(TimeChunked);
#[cfg(test)]
mod test {
use super::*;
#[test]
#[cfg(feature = "dtype-datetime")]
fn test_agg_list_type() -> Result<()> {
let s = Series::new("foo", &[1, 2, 3]);
let s = s.cast(&DataType::Datetime(TimeUnit::Nanoseconds, None))?;
let l = s
.agg_list(&GroupsProxy::Idx(vec![(0, vec![0, 1, 2])]))
.unwrap();
match l.dtype() {
DataType::List(inner) => {
assert!(matches!(
&**inner,
DataType::Datetime(TimeUnit::Nanoseconds, None)
))
}
_ => assert!(false),
}
Ok(())
}
#[test]
#[cfg(feature = "dtype-datetime")]
#[cfg_attr(miri, ignore)]
fn | () -> Result<()> {
let s = Series::new("foo", &[1, 2, 3]);
let mut s1 = s.cast(&DataType::Datetime(TimeUnit::Nanoseconds, None))?;
s1.rename("bar");
let df = DataFrame::new(vec![s, s1])?;
let out = df.left_join(&df.clone(), ["bar"], ["bar"])?;
assert!(matches!(
out.column("bar")?.dtype(),
DataType::Datetime(TimeUnit::Nanoseconds, None)
));
let out = df.inner_join(&df.clone(), ["bar"], ["bar"])?;
assert!(matches!(
out.column("bar")?.dtype(),
DataType::Datetime(TimeUnit::Nanoseconds, None)
));
let out = df.outer_join(&df.clone(), ["bar"], ["bar"])?;
assert!(matches!(
out.column("bar")?.dtype(),
DataType::Datetime(TimeUnit::Nanoseconds, None)
));
Ok(())
}
#[test]
#[cfg(feature = "dtype-datetime")]
fn test_datelike_methods() -> Result<()> {
let s = Series::new("foo", &[1, 2, 3]);
let s = s.cast(&DataType::Datetime(TimeUnit::Nanoseconds, None))?;
let out = s.subtract(&s)?;
assert!(matches!(
out.dtype(),
DataType::Duration(TimeUnit::Nanoseconds)
));
let mut a = s.clone();
a.append(&s).unwrap();
assert_eq!(a.len(), 6);
Ok(())
}
#[test]
#[cfg(feature = "dtype-datetime")]
fn test_arithmetic_dispatch() {
let s = Int64Chunked::new("", &[1, 2, 3])
.into_datetime(TimeUnit::Nanoseconds, None)
.into_series();
// check if we don't panic.
let out = &s * 100;
assert_eq!(
out.dtype(),
&DataType::Datetime(TimeUnit::Nanoseconds, None)
);
let out = &s / 100;
assert_eq!(
out.dtype(),
&DataType::Datetime(TimeUnit::Nanoseconds, None)
);
let out = &s + 100;
assert_eq!(
out.dtype(),
&DataType::Datetime(TimeUnit::Nanoseconds, None)
);
let out = &s - 100;
assert_eq!(
out.dtype(),
&DataType::Datetime(TimeUnit::Nanoseconds, None)
);
let out = &s % 100;
assert_eq!(
out.dtype(),
&DataType::Datetime(TimeUnit::Nanoseconds, None)
);
let out = 100.mul(&s);
assert_eq!(
out.dtype(),
&DataType::Datetime(TimeUnit::Nanoseconds, None)
);
let out = 100.div(&s);
assert_eq!(
out.dtype(),
&DataType::Datetime(TimeUnit::Nanoseconds, None)
);
let out = 100.sub(&s);
assert_eq!(
out.dtype(),
&DataType::Datetime(TimeUnit::Nanoseconds, None)
);
let out = 100.add(&s);
assert_eq!(
out.dtype(),
&DataType::Datetime(TimeUnit::Nanoseconds, None)
);
let out = 100.rem(&s);
assert_eq!(
out.dtype(),
&DataType::Datetime(TimeUnit::Nanoseconds, None)
);
}
#[test]
#[cfg(feature = "dtype-duration")]
fn test_duration() -> Result<()> {
let a = Int64Chunked::new("", &[1, 2, 3])
.into_datetime(TimeUnit::Nanoseconds, None)
.into_series();
let b = Int64Chunked::new("", &[2, 3, 4])
.into_datetime(TimeUnit::Nanoseconds, None)
.into_series();
let c = Int64Chunked::new("", &[1, 1, 1])
.into_duration(TimeUnit::Nanoseconds)
.into_series();
assert_eq!(
*b.subtract(&a)?.dtype(),
DataType::Duration(TimeUnit::Nanoseconds)
);
assert_eq!(
*a.add_to(&c)?.dtype(),
DataType::Datetime(TimeUnit::Nanoseconds, None)
);
assert_eq!(
b.subtract(&a)?,
Int64Chunked::full("", 1, a.len())
.into_duration(TimeUnit::Nanoseconds)
.into_series()
);
Ok(())
}
}
| test_datelike_join |
infer_ros_melodic_pretained_same_frame.py | #!/usr/bin/env python
# ROS node libs
import time
import numpy as np
import rospy
import torch
# from geometry_msgs.msg import Quaternion, Pose, Point, Vector3
from pyquaternion import Quaternion
from google.protobuf import text_format
from sensor_msgs.msg import PointCloud2
from std_msgs.msg import Header, ColorRGBA
# from cv_bridge import CvBridge, CvBridgeError
from visualization_msgs.msg import Marker, MarkerArray
from second.protos import pipeline_pb2
# from second.utils import simplevis
from second.pytorch.train import build_network
from second.utils import config_tool
from std_msgs.msg import Int16, Float32MultiArray
from jsk_recognition_msgs.msg import BoundingBox, BoundingBoxArray
# import ros_numpy
# GPU settings: Select GPUs to use. Coment it to let the system decide
# os.environ["CUDA_VISIBLE_DEVICES"]="0"
class ros_tensorflow_obj():
def | (self):
# ## Initial msg
rospy.loginfo(' ## Starting ROS interface ##')
# ## Load a (frozen) Tensorflow model into memory.
print("ready to process----------------------------------------------------------")
####################################################################################333
# config_path = "../configs/nuscenes/all.pp.largea.config"
# config_path = "/home/mayank_sati/codebase/python/lidar/second.pytorch/second/configs/pointpillars/car/xyres_28.config"
config_path = "/home/mayank_sati/codebase/python/lidar/second.pytorch/second/configs/pointpillars/car/xyres_24.config"
config = pipeline_pb2.TrainEvalPipelineConfig()
with open(config_path, "r") as f:
proto_str = f.read()
text_format.Merge(proto_str, config)
input_cfg = config.eval_input_reader
model_cfg = config.model.second
# config_tool.change_detection_range(model_cfg, [-50, -50, 50, 50])
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# ckpt_path = "../checkpoint/voxelnet-140670.tckpt"
ckpt_path="/home/mayank_sati/Downloads/pretrained_models_v1.5/pp_model_for_nuscenes_pretrain/voxelnet-296960.tckpt"
net = build_network(model_cfg).to(device).eval()
net.load_state_dict(torch.load(ckpt_path))
target_assigner = net.target_assigner
self.voxel_generator = net.voxel_generator
class_names = target_assigner.classes
grid_size = self.voxel_generator.grid_size
feature_map_size = grid_size[:2] // config_tool.get_downsample_factor(model_cfg)
feature_map_size = [*feature_map_size, 1][::-1]
anchors = target_assigner.generate_anchors(feature_map_size)["anchors"]
anchors = torch.tensor(anchors, dtype=torch.float32, device=device)
anchors = anchors.view(1, -1, 7)
# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
feature_map_size = [1, 50, 50]
ret = target_assigner.generate_anchors(feature_map_size)
class_names = target_assigner.classes
anchors_dict = target_assigner.generate_anchors_dict(feature_map_size)
anchors_list = []
for k, v in anchors_dict.items():
anchors_list.append(v["anchors"])
# anchors = ret["anchors"]
anchors = np.concatenate(anchors_list, axis=0)
anchors = anchors.reshape([-1, target_assigner.box_ndim])
assert np.allclose(anchors, ret["anchors"].reshape(-1, target_assigner.box_ndim))
matched_thresholds = ret["matched_thresholds"]
unmatched_thresholds = ret["unmatched_thresholds"]
# anchors_bv = box_np_ops.rbbox2d_to_near_bbox(anchors[:, [0, 1, 3, 4, 6]])
anchors_bv = 2
anchor_cache = {
"anchors": anchors,
"anchors_bv": anchors_bv,
"matched_thresholds": matched_thresholds,
"unmatched_thresholds": unmatched_thresholds,
"anchors_dict": anchors_dict,
}
anchors = torch.tensor(anchors, dtype=torch.float32, device=device)
self.anchors = anchors.view(1, -1, 7)
self.net = net
self.device = device
##########################################################################################
# self.marker_publisher = rospy.Publisher('visualization_marker', MarkerArray, queue_size=5)
self.pcl_publisher = rospy.Publisher('result_pcl', PointCloud2, queue_size=1)
############
# [print(n.name) for n in tf.get_default_graph().as_graph_def().node]
# ROS environment setup
# ## Define subscribers
self.subscribers_def()
# ## Define publishers
self.publishers_def()
self.now = rospy.Time.now()
# Define subscribers
def subscribers_def(self):
# subs_topic = '/kitti/velo/pointcloud'
#subs_topic = '/apollo/sensor/velodyne64/compensator/PointCloud2'
# subs_topic = '/velodyne64_points'
# subs_topic = '/apollo/sensor/velodyne64/PointCloud2'
# subs_topic = '/points_raw'
# subs_topic = '/livox/lidar'
# subs_topic = '/apollo/sensor/velodyne32C/compensator/PointCloud2'
subs_topic = '/lidar_top'
self._sub = rospy.Subscriber(subs_topic, PointCloud2, self.lidar_callback, queue_size=10, buff_size=2 ** 24)
# mydata = rospy.Subscriber( subs_topic , PointCloud2, self.lidar_callback, queue_size=1, buff_size=2**24)
# print(mydata)
# self._sub = rospy.Subscriber( subs_topic , Image, self.lidar_callback, queue_size=1, buff_size=100)
# Define publishers
def publishers_def(self):
self._pub = rospy.Publisher('pc_bbox_topic', Float32MultiArray, queue_size=1)
self.pub_arr_bbox = rospy.Publisher("Detections", BoundingBoxArray, queue_size=1)
# Camera image callback
def lidar_callback(self, point_cl_msg):
arr_bbox = BoundingBoxArray()
############################################################################3
# lidar = np.fromstring(point_cl_msg.data, dtype=np.float32)
# points = lidar.reshape(-1, 4)
# print('gotit"')
# pc = ros_numpy.numpify(point_cl_msg)
# points = np.zeros((pc.shape[0], 4))
# points[:, 0] = pc['x']
# points[:, 1] = pc['y']
# points[:, 2] = pc['z']
# points[:, 3] = pc['intensity']
# points[:, 3] /= 255
#########################################################333
lidar = np.fromstring(point_cl_msg.data, dtype=np.float32)
points = lidar.reshape(-1, 4)
points[:, 3] /= 255
#######################################################################
res = self.voxel_generator.generate(points, max_voxels=30000)
voxels = res["voxels"]
coords = res["coordinates"]
num_points = res["num_points_per_voxel"]
num_voxels = np.array([voxels.shape[0]], dtype=np.int64)
# print("voxel_generator_time",(time.time() - t)*1000)
###############################################################
# print(voxels.shape)
# add batch idx to coords
coords = np.pad(coords, ((0, 0), (1, 0)), mode='constant', constant_values=0)
voxels = torch.tensor(voxels, dtype=torch.float32, device=self.device)
coords = torch.tensor(coords, dtype=torch.int32, device=self.device)
num_points = torch.tensor(num_points, dtype=torch.int32, device=self.device)
# print("conversion time",(time.time() - t)*1000)
example = {"anchors": self.anchors, "voxels": voxels, "num_points": num_points, "coordinates": coords, }
t2 = time.time()
pred = self.net(example)[0]
# print(pred)
# print("prediction",(time.time() - t2)*1000)
# print("total_time",(time.time() - t)*1000)
boxes_lidar = pred["box3d_lidar"].detach().cpu().numpy()
scores_lidar = pred["scores"].detach().cpu().numpy()
labels_lidar = pred["label_preds"].detach().cpu().numpy()
##############################3333
threshold = 0.2
keep = np.where((scores_lidar >= threshold))[0]
scores_lidar = scores_lidar[keep]
print(scores_lidar)
boxes_lidar = boxes_lidar[keep]
labels_lidar = labels_lidar[keep]
# sco
# print(scores_lidar)
################################################################################
# self.show_text_in_rviz_mullti_cube(boxes_lidar,point_cl_msg)
# self.show_text_in_rviz_mullti_sphere(boxes_lidar,point_cl_msg)
##################################################################################
# apollo integration
# numboxes = np.squeeze(scores_lidar)
numboxes = len(scores_lidar)
tl_bbox = Float32MultiArray()
iLen = boxes_lidar.shape[0]
lidar_bbox = Float32MultiArray()
print('Processing no of object:', iLen)
if (numboxes) >= 1:
tmp = -np.ones(10 * (numboxes) + 1)
for i in range(0, int(numboxes)):
try:
score = float((scores_lidar)[i])
if (boxes_lidar.shape[0]) == 1:
bboxes = [float(v) for v in (boxes_lidar)[i]]
else:
bboxes = [float(v) for v in np.squeeze(boxes_lidar)[i]]
tmp[0] = numboxes
tmp[10 * i + 1] = score
tmp[10 * i + 2] = bboxes[0]
tmp[10 * i + 3] = bboxes[1]
tmp[10 * i + 4] = bboxes[2]
tmp[10 * i + 5] = bboxes[3]
tmp[10 * i + 6] = bboxes[4]
tmp[10 * i + 7] = bboxes[5]
tmp[10 * i + 8] = bboxes[6]
tmp[10 * i + 9] = 0
tmp[10 * i + 10] = 0
bbox = BoundingBox()
# bbox.header.frame_id = point_cl_msg.header.frame_id
# bbox.header.frame_id = 'livox_frame'
bbox.header.frame_id = 'lidar_top'
q = Quaternion(axis=(0, 0, 1), radians=-1.0 * float(boxes_lidar[i][6]))
bbox.pose.orientation.x = q.x
bbox.pose.orientation.y = q.y
bbox.pose.orientation.z = q.z
bbox.pose.orientation.w = q.w
bbox.pose.position.x = float(boxes_lidar[i][0])
bbox.pose.position.y = float(boxes_lidar[i][1])
bbox.pose.position.z = float(boxes_lidar[i][2])
bbox.dimensions.x = float(boxes_lidar[i][3])
bbox.dimensions.y = float(boxes_lidar[i][4])
bbox.dimensions.z = float(boxes_lidar[i][5])
arr_bbox.boxes.append(bbox)
except:
print("I am here")
# here data for publishing
tl_bbox.data = tmp
self._pub.publish(tl_bbox)
arr_bbox.header.frame_id = point_cl_msg.header.frame_id
self.pub_arr_bbox.publish(arr_bbox)
point_cl_msg.header.frame_id = point_cl_msg.header.frame_id
self.pcl_publisher.publish(point_cl_msg)
arr_bbox.boxes.clear()
def spin(self):
rospy.spin()
def main():
rospy.init_node('LIDAR_NODE', anonymous=True)
tf_ob = ros_tensorflow_obj()
# tf_ob.subscribers_def
try:
rospy.spin()
except KeyboardInterrupt:
print("Shutting down")
if __name__ == '__main__':
main()
| __init__ |
Microsoft_Windows_Direct3D10_1.py | # -*- coding: utf-8 -*-
"""
Microsoft-Windows-Direct3D10_1
GUID : 9b7e4c8f-342c-4106-a19f-4f2704f689f0
"""
from construct import Int8sl, Int8ul, Int16ul, Int16sl, Int32sl, Int32ul, Int64sl, Int64ul, Bytes, Double, Float32l, Struct
from etl.utils import WString, CString, SystemTime, Guid
from etl.dtyp import Sid
from etl.parsers.etw.core import Etw, declare, guid
@declare(guid=guid("9b7e4c8f-342c-4106-a19f-4f2704f689f0"), event_id=1, version=0)
class Microsoft_Windows_Direct3D10_1_1_0(Etw):
pattern = Struct(
"pObject" / Int64ul,
"CchOldDebugObjectName" / Int32ul,
"OldDebugObjectName" / Bytes(lambda this: this.CchOldDebugObjectName),
"CchNewDebugObjectName" / Int32ul,
"NewDebugObjectName" / Bytes(lambda this: this.CchNewDebugObjectName)
)
@declare(guid=guid("9b7e4c8f-342c-4106-a19f-4f2704f689f0"), event_id=2, version=0)
class Microsoft_Windows_Direct3D10_1_2_0(Etw):
pattern = Struct(
"pObject" / Int64ul,
"CchDebugObjectName" / Int32ul,
"DebugObjectName" / Bytes(lambda this: this.CchDebugObjectName)
)
@declare(guid=guid("9b7e4c8f-342c-4106-a19f-4f2704f689f0"), event_id=3, version=0)
class Microsoft_Windows_Direct3D10_1_3_0(Etw):
pattern = Struct(
"pID3D10_1Device" / Int64ul,
"pIDXGIDevice" / Int64ul,
"pIDXGIAdapter" / Int64ul,
"CreationFlags" / Int32ul,
"FeatureLevel" / Int32ul,
"hKMAdapter" / Int32ul,
"hUMAdapter" / Int64ul,
"UMAdapterVersion" / Int64ul,
"hKMDevice" / Int32ul,
"hUMDevice" / Int64ul,
"UMDeviceVersion" / Int64ul,
"UMDeviceFlags" / Int32ul
)
@declare(guid=guid("9b7e4c8f-342c-4106-a19f-4f2704f689f0"), event_id=4, version=0)
class Microsoft_Windows_Direct3D10_1_4_0(Etw):
pattern = Struct(
"pID3D10_1Device" / Int64ul,
"pIDXGIDevice" / Int64ul,
"pIDXGIAdapter" / Int64ul,
"CreationFlags" / Int32ul,
"FeatureLevel" / Int32ul,
"hKMAdapter" / Int32ul,
"hUMAdapter" / Int64ul,
"UMAdapterVersion" / Int64ul,
"hKMDevice" / Int32ul,
"hUMDevice" / Int64ul,
"UMDeviceVersion" / Int64ul,
"UMDeviceFlags" / Int32ul
)
@declare(guid=guid("9b7e4c8f-342c-4106-a19f-4f2704f689f0"), event_id=5, version=0)
class Microsoft_Windows_Direct3D10_1_5_0(Etw):
pattern = Struct(
"pID3D10_1Device" / Int64ul,
"pIDXGIDevice" / Int64ul,
"pIDXGIAdapter" / Int64ul,
"CreationFlags" / Int32ul,
"FeatureLevel" / Int32ul,
"hKMAdapter" / Int32ul,
"hUMAdapter" / Int64ul,
"UMAdapterVersion" / Int64ul,
"hKMDevice" / Int32ul,
"hUMDevice" / Int64ul,
"UMDeviceVersion" / Int64ul,
"UMDeviceFlags" / Int32ul
)
@declare(guid=guid("9b7e4c8f-342c-4106-a19f-4f2704f689f0"), event_id=6, version=0)
class Microsoft_Windows_Direct3D10_1_6_0(Etw):
pattern = Struct(
"pID3D10Resource" / Int64ul,
"pIDXGISurface" / Int64ul,
"pID3D10_1Device" / Int64ul,
"Dimension" / Int32ul,
"Usage" / Int32ul, | "ArraySize" / Int32ul,
"Format" / Int32ul,
"SampleCount" / Int32ul,
"SampleQuality" / Int32ul,
"BindFlags" / Int32ul,
"CPUAccessFlags" / Int32ul,
"MiscFlags" / Int32ul,
"hKMResource" / Int32ul,
"hUMResource" / Int64ul,
"UMResourceMiscFlags" / Int32ul
)
@declare(guid=guid("9b7e4c8f-342c-4106-a19f-4f2704f689f0"), event_id=7, version=0)
class Microsoft_Windows_Direct3D10_1_7_0(Etw):
pattern = Struct(
"pID3D10Resource" / Int64ul,
"pIDXGISurface" / Int64ul,
"pID3D10_1Device" / Int64ul,
"Dimension" / Int32ul,
"Usage" / Int32ul,
"Width" / Int32ul,
"Height" / Int32ul,
"Depth" / Int32ul,
"MipLevels" / Int32ul,
"ArraySize" / Int32ul,
"Format" / Int32ul,
"SampleCount" / Int32ul,
"SampleQuality" / Int32ul,
"BindFlags" / Int32ul,
"CPUAccessFlags" / Int32ul,
"MiscFlags" / Int32ul,
"hKMResource" / Int32ul,
"hUMResource" / Int64ul,
"UMResourceMiscFlags" / Int32ul
)
@declare(guid=guid("9b7e4c8f-342c-4106-a19f-4f2704f689f0"), event_id=8, version=0)
class Microsoft_Windows_Direct3D10_1_8_0(Etw):
pattern = Struct(
"pID3D10Resource" / Int64ul,
"pIDXGISurface" / Int64ul,
"pID3D10_1Device" / Int64ul,
"Dimension" / Int32ul,
"Usage" / Int32ul,
"Width" / Int32ul,
"Height" / Int32ul,
"Depth" / Int32ul,
"MipLevels" / Int32ul,
"ArraySize" / Int32ul,
"Format" / Int32ul,
"SampleCount" / Int32ul,
"SampleQuality" / Int32ul,
"BindFlags" / Int32ul,
"CPUAccessFlags" / Int32ul,
"MiscFlags" / Int32ul,
"hKMResource" / Int32ul,
"hUMResource" / Int64ul,
"UMResourceMiscFlags" / Int32ul
)
@declare(guid=guid("9b7e4c8f-342c-4106-a19f-4f2704f689f0"), event_id=9, version=0)
class Microsoft_Windows_Direct3D10_1_9_0(Etw):
pattern = Struct(
"pID3D10Resource" / Int64ul,
"pIDXGISurface" / Int64ul,
"pID3D10_1Device" / Int64ul,
"Dimension" / Int32ul,
"Usage" / Int32ul,
"Width" / Int32ul,
"Height" / Int32ul,
"Depth" / Int32ul,
"MipLevels" / Int32ul,
"ArraySize" / Int32ul,
"Format" / Int32ul,
"SampleCount" / Int32ul,
"SampleQuality" / Int32ul,
"BindFlags" / Int32ul,
"CPUAccessFlags" / Int32ul,
"MiscFlags" / Int32ul,
"hKMResource" / Int32ul,
"hUMResource" / Int64ul,
"UMResourceMiscFlags" / Int32ul
)
@declare(guid=guid("9b7e4c8f-342c-4106-a19f-4f2704f689f0"), event_id=10, version=0)
class Microsoft_Windows_Direct3D10_1_10_0(Etw):
pattern = Struct(
"pID3D10Resource" / Int64ul,
"pIDXGISurface" / Int64ul,
"pID3D10_1Device" / Int64ul,
"Dimension" / Int32ul,
"Usage" / Int32ul,
"Width" / Int32ul,
"Height" / Int32ul,
"Depth" / Int32ul,
"MipLevels" / Int32ul,
"ArraySize" / Int32ul,
"Format" / Int32ul,
"SampleCount" / Int32ul,
"SampleQuality" / Int32ul,
"BindFlags" / Int32ul,
"CPUAccessFlags" / Int32ul,
"MiscFlags" / Int32ul,
"hKMResource" / Int32ul,
"hUMResource" / Int64ul,
"UMResourceMiscFlags" / Int32ul
)
@declare(guid=guid("9b7e4c8f-342c-4106-a19f-4f2704f689f0"), event_id=11, version=0)
class Microsoft_Windows_Direct3D10_1_11_0(Etw):
pattern = Struct(
"pID3D10Resource" / Int64ul,
"pIDXGISurface" / Int64ul,
"pID3D10_1Device" / Int64ul,
"Dimension" / Int32ul,
"Usage" / Int32ul,
"Width" / Int32ul,
"Height" / Int32ul,
"Depth" / Int32ul,
"MipLevels" / Int32ul,
"ArraySize" / Int32ul,
"Format" / Int32ul,
"SampleCount" / Int32ul,
"SampleQuality" / Int32ul,
"BindFlags" / Int32ul,
"CPUAccessFlags" / Int32ul,
"MiscFlags" / Int32ul,
"hKMResource" / Int32ul,
"hUMResource" / Int64ul,
"UMResourceMiscFlags" / Int32ul
)
@declare(guid=guid("9b7e4c8f-342c-4106-a19f-4f2704f689f0"), event_id=12, version=0)
class Microsoft_Windows_Direct3D10_1_12_0(Etw):
pattern = Struct(
"pID3D10Resource" / Int64ul,
"pIDXGISurface" / Int64ul,
"pID3D10_1Device" / Int64ul,
"Dimension" / Int32ul,
"Usage" / Int32ul,
"Width" / Int32ul,
"Height" / Int32ul,
"Depth" / Int32ul,
"MipLevels" / Int32ul,
"ArraySize" / Int32ul,
"Format" / Int32ul,
"SampleCount" / Int32ul,
"SampleQuality" / Int32ul,
"BindFlags" / Int32ul,
"CPUAccessFlags" / Int32ul,
"MiscFlags" / Int32ul,
"hKMResource" / Int32ul,
"hUMResource" / Int64ul,
"UMResourceMiscFlags" / Int32ul
)
@declare(guid=guid("9b7e4c8f-342c-4106-a19f-4f2704f689f0"), event_id=13, version=0)
class Microsoft_Windows_Direct3D10_1_13_0(Etw):
pattern = Struct(
"pID3D10Resource" / Int64ul,
"pIDXGISurface" / Int64ul,
"pID3D10_1Device" / Int64ul,
"Dimension" / Int32ul,
"Usage" / Int32ul,
"Width" / Int32ul,
"Height" / Int32ul,
"Depth" / Int32ul,
"MipLevels" / Int32ul,
"ArraySize" / Int32ul,
"Format" / Int32ul,
"SampleCount" / Int32ul,
"SampleQuality" / Int32ul,
"BindFlags" / Int32ul,
"CPUAccessFlags" / Int32ul,
"MiscFlags" / Int32ul,
"hKMResource" / Int32ul,
"hUMResource" / Int64ul,
"UMResourceMiscFlags" / Int32ul
)
@declare(guid=guid("9b7e4c8f-342c-4106-a19f-4f2704f689f0"), event_id=14, version=0)
class Microsoft_Windows_Direct3D10_1_14_0(Etw):
pattern = Struct(
"pID3D10Resource" / Int64ul,
"pIDXGISurface" / Int64ul,
"pID3D10_1Device" / Int64ul,
"Dimension" / Int32ul,
"Usage" / Int32ul,
"Width" / Int32ul,
"Height" / Int32ul,
"Depth" / Int32ul,
"MipLevels" / Int32ul,
"ArraySize" / Int32ul,
"Format" / Int32ul,
"SampleCount" / Int32ul,
"SampleQuality" / Int32ul,
"BindFlags" / Int32ul,
"CPUAccessFlags" / Int32ul,
"MiscFlags" / Int32ul,
"hKMResource" / Int32ul,
"hUMResource" / Int64ul,
"UMResourceMiscFlags" / Int32ul
)
@declare(guid=guid("9b7e4c8f-342c-4106-a19f-4f2704f689f0"), event_id=15, version=0)
class Microsoft_Windows_Direct3D10_1_15_0(Etw):
pattern = Struct(
"pID3D10Resource" / Int64ul,
"pIDXGISurface" / Int64ul,
"pID3D10_1Device" / Int64ul,
"Dimension" / Int32ul,
"Usage" / Int32ul,
"Width" / Int32ul,
"Height" / Int32ul,
"Depth" / Int32ul,
"MipLevels" / Int32ul,
"ArraySize" / Int32ul,
"Format" / Int32ul,
"SampleCount" / Int32ul,
"SampleQuality" / Int32ul,
"BindFlags" / Int32ul,
"CPUAccessFlags" / Int32ul,
"MiscFlags" / Int32ul,
"hKMResource" / Int32ul,
"hUMResource" / Int64ul,
"UMResourceMiscFlags" / Int32ul
)
@declare(guid=guid("9b7e4c8f-342c-4106-a19f-4f2704f689f0"), event_id=16, version=0)
class Microsoft_Windows_Direct3D10_1_16_0(Etw):
pattern = Struct(
"pID3D10Resource" / Int64ul,
"pIDXGISurface" / Int64ul,
"pID3D10_1Device" / Int64ul,
"Dimension" / Int32ul,
"Usage" / Int32ul,
"Width" / Int32ul,
"Height" / Int32ul,
"Depth" / Int32ul,
"MipLevels" / Int32ul,
"ArraySize" / Int32ul,
"Format" / Int32ul,
"SampleCount" / Int32ul,
"SampleQuality" / Int32ul,
"BindFlags" / Int32ul,
"CPUAccessFlags" / Int32ul,
"MiscFlags" / Int32ul,
"hKMResource" / Int32ul,
"hUMResource" / Int64ul,
"UMResourceMiscFlags" / Int32ul
)
@declare(guid=guid("9b7e4c8f-342c-4106-a19f-4f2704f689f0"), event_id=17, version=0)
class Microsoft_Windows_Direct3D10_1_17_0(Etw):
pattern = Struct(
"pID3D10Resource" / Int64ul,
"pIDXGISurface" / Int64ul,
"pID3D10_1Device" / Int64ul,
"Dimension" / Int32ul,
"Usage" / Int32ul,
"Width" / Int32ul,
"Height" / Int32ul,
"Depth" / Int32ul,
"MipLevels" / Int32ul,
"ArraySize" / Int32ul,
"Format" / Int32ul,
"SampleCount" / Int32ul,
"SampleQuality" / Int32ul,
"BindFlags" / Int32ul,
"CPUAccessFlags" / Int32ul,
"MiscFlags" / Int32ul,
"hKMResource" / Int32ul,
"hUMResource" / Int64ul,
"UMResourceMiscFlags" / Int32ul
)
@declare(guid=guid("9b7e4c8f-342c-4106-a19f-4f2704f689f0"), event_id=18, version=0)
class Microsoft_Windows_Direct3D10_1_18_0(Etw):
pattern = Struct(
"Resources" / Int32ul,
"pIDXGISurfaces" / Int64ul,
"hNewKMResources" / Int32ul
) | "Width" / Int32ul,
"Height" / Int32ul,
"Depth" / Int32ul,
"MipLevels" / Int32ul, |
errors.go | // Code generated by smithy-go-codegen DO NOT EDIT.
package types
import (
"fmt"
smithy "github.com/aws/smithy-go"
)
// Access is denied.
type AccessDeniedException struct {
Message *string
noSmithyDocumentSerde
}
func (e *AccessDeniedException) Error() string {
return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage())
}
func (e *AccessDeniedException) ErrorMessage() string {
if e.Message == nil {
return ""
}
return *e.Message
}
func (e *AccessDeniedException) ErrorCode() string { return "AccessDeniedException" }
func (e *AccessDeniedException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient }
// There was an internal service exception.
type InternalServiceException struct {
Message *string
noSmithyDocumentSerde
}
func (e *InternalServiceException) Error() string {
return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage())
}
func (e *InternalServiceException) ErrorMessage() string {
if e.Message == nil |
return *e.Message
}
func (e *InternalServiceException) ErrorCode() string { return "InternalServiceException" }
func (e *InternalServiceException) ErrorFault() smithy.ErrorFault { return smithy.FaultServer }
// The resource is currently in use.
type ResourceInUseException struct {
Message *string
noSmithyDocumentSerde
}
func (e *ResourceInUseException) Error() string {
return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage())
}
func (e *ResourceInUseException) ErrorMessage() string {
if e.Message == nil {
return ""
}
return *e.Message
}
func (e *ResourceInUseException) ErrorCode() string { return "ResourceInUseException" }
func (e *ResourceInUseException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient }
// The specified resource wasn't found.
type ResourceNotFoundException struct {
Message *string
noSmithyDocumentSerde
}
func (e *ResourceNotFoundException) Error() string {
return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage())
}
func (e *ResourceNotFoundException) ErrorMessage() string {
if e.Message == nil {
return ""
}
return *e.Message
}
func (e *ResourceNotFoundException) ErrorCode() string { return "ResourceNotFoundException" }
func (e *ResourceNotFoundException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient }
// Currently, the specified resource is not supported.
type ResourceNotSupportedException struct {
Message *string
noSmithyDocumentSerde
}
func (e *ResourceNotSupportedException) Error() string {
return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage())
}
func (e *ResourceNotSupportedException) ErrorMessage() string {
if e.Message == nil {
return ""
}
return *e.Message
}
func (e *ResourceNotSupportedException) ErrorCode() string { return "ResourceNotSupportedException" }
func (e *ResourceNotSupportedException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient }
// The maximum number of open requests per account has been exceeded.
type ServiceQuotaExceededException struct {
Message *string
noSmithyDocumentSerde
}
func (e *ServiceQuotaExceededException) Error() string {
return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage())
}
func (e *ServiceQuotaExceededException) ErrorMessage() string {
if e.Message == nil {
return ""
}
return *e.Message
}
func (e *ServiceQuotaExceededException) ErrorCode() string { return "ServiceQuotaExceededException" }
func (e *ServiceQuotaExceededException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient }
// Too many requests.
type ThrottlingException struct {
Message *string
noSmithyDocumentSerde
}
func (e *ThrottlingException) Error() string {
return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage())
}
func (e *ThrottlingException) ErrorMessage() string {
if e.Message == nil {
return ""
}
return *e.Message
}
func (e *ThrottlingException) ErrorCode() string { return "ThrottlingException" }
func (e *ThrottlingException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient }
// An error occurred during validation.
type ValidationException struct {
Message *string
noSmithyDocumentSerde
}
func (e *ValidationException) Error() string {
return fmt.Sprintf("%s: %s", e.ErrorCode(), e.ErrorMessage())
}
func (e *ValidationException) ErrorMessage() string {
if e.Message == nil {
return ""
}
return *e.Message
}
func (e *ValidationException) ErrorCode() string { return "ValidationException" }
func (e *ValidationException) ErrorFault() smithy.ErrorFault { return smithy.FaultClient }
| {
return ""
} |
buffer.go | // Go MySQL Driver - A MySQL-Driver for Go's database/sql package
//
// Copyright 2013 The Go-MySQL-Driver Authors. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.
package mysql
import "io"
const defaultBufSize = 4096
// A buffer which is used for both reading and writing.
// This is possible since communication on each connection is synchronous.
// In other words, we can't write and read simultaneously on the same connection.
// The buffer is similar to bufio.Reader / Writer but zero-copy-ish
// Also highly optimized for this particular use case.
type buffer struct {
buf []byte
rd io.Reader
idx int
length int
}
func newBuffer(rd io.Reader) *buffer |
// fill reads into the buffer until at least _need_ bytes are in it
func (b *buffer) fill(need int) error {
// move existing data to the beginning
if b.length > 0 && b.idx > 0 {
copy(b.buf[0:b.length], b.buf[b.idx:])
}
// grow buffer if necessary
// TODO: let the buffer shrink again at some point
// Maybe keep the org buf slice and swap back?
if need > len(b.buf) {
// Round up to the next multiple of the default size
newBuf := make([]byte, ((need/defaultBufSize)+1)*defaultBufSize)
copy(newBuf, b.buf)
b.buf = newBuf
}
b.idx = 0
for {
n, err := b.rd.Read(b.buf[b.length:])
b.length += n
if err == nil {
if b.length < need {
continue
}
return nil
}
if b.length >= need && err == io.EOF {
return nil
}
return err
}
}
// returns next N bytes from buffer.
// The returned slice is only guaranteed to be valid until the next read
func (b *buffer) readNext(need int) ([]byte, error) {
if b.length < need {
// refill
if err := b.fill(need); err != nil {
return nil, err
}
}
offset := b.idx
b.idx += need
b.length -= need
return b.buf[offset:b.idx], nil
}
// returns a buffer with the requested size.
// If possible, a slice from the existing buffer is returned.
// Otherwise a bigger buffer is made.
// Only one buffer (total) can be used at a time.
func (b *buffer) takeBuffer(length int) []byte {
if b.length > 0 {
return nil
}
// test (cheap) general case first
if length <= defaultBufSize || length <= cap(b.buf) {
return b.buf[:length]
}
if length < maxPacketSize {
b.buf = make([]byte, length)
return b.buf
}
return make([]byte, length)
}
// shortcut which can be used if the requested buffer is guaranteed to be
// smaller than defaultBufSize
// Only one buffer (total) can be used at a time.
func (b *buffer) takeSmallBuffer(length int) []byte {
if b.length == 0 {
return b.buf[:length]
}
return nil
}
// takeCompleteBuffer returns the complete existing buffer.
// This can be used if the necessary buffer size is unknown.
// Only one buffer (total) can be used at a time.
func (b *buffer) takeCompleteBuffer() []byte {
if b.length == 0 {
return b.buf
}
return nil
}
| {
var b [defaultBufSize]byte
return &buffer{
buf: b[:],
rd: rd,
}
} |
block_demo_policy.py | import numpy as np
from collections import deque
import copy
from spirl.utils.general_utils import AttrDict, split_along_axis
from spirl.data.block_stacking.src.utils.utils import quat2euler
from spirl.data.block_stacking.src.block_stacking_env import BlockStackEnv
class BlockStackDemoPolicy:
"""Follows plan on given env."""
GRASP_OFFSET = 0.08 # offset between robot pos and block pos for grasping
PICK_OFFSET = 0.14 # additional vertical offset btw robot and block for placing
PLACE_OFFSET = 0.17 # additional vertical offset btw robot and block for placing
ACT_RANGE = [0.05, 0.05, 0.05, np.pi/10, 0.5] # maximum action scale for each action dimension
GRAVITY_SUPPORT = 0.01 # z dimension action when noop to prevent robot from falling
GRIPPER_OPEN = 1.
GRIPPER_CLOSED = 0.
MULTIPLIER = 20.
EPS = 0.01
def __init__(self, env_params):
"""
:param hl_plan: list of HL index tuples indicating which block should get stacked (e.g. [(1,2), (3,5)])
"""
# TODO consider whether to make task/hl_plan a proper class with transition subclass (to make reuse for kitchen easier)
self.env_params = env_params
self.lift_height = env_params.table_size[-1] + env_params.block_size * 2 * env_params.max_tower_height + 0.2
self.block_height = env_params.block_size * 2
self._hl_plan = None
self._hl_plan_to_run = deque()
self._action_plan = None
self._u_obs = None # this stores env state when planning action sequence
self._update_robot_state = True
def reset(self):
self._hl_plan = self.env_params.get_task()
self._action_plan = None
self._hl_plan_to_run = deque(self._hl_plan)
self._u_obs = None
def act(self, obs):
if self.execution_finished: # should not call 'act' if execution is already finished
return None
self._u_obs = BlockUnflattenWrapper(BlockStackEnv.unflatten_block_obs(copy.deepcopy(obs),
include_quat=self.env_params.include_quat,
include_vel=self.env_params.include_vel))
while True:
if self._action_plan is None:
if not self._hl_plan_to_run:
self._action_plan = None
ac = np.zeros(5,)
break
# generate new action plan
self._action_plan = self._plan_actions()
try:
ac = next(self._action_plan)
break
except (StopIteration, IndexError): # generator exhausted
self._action_plan = None
ac = self._post_process(ac)
return ac
@property
def execution_finished(self):
"""Checks whether the plan execution has been finished."""
return self._action_plan is None and not self._hl_plan_to_run
def _plan_actions(self):
"""Plans LL actions given HL action plan and current env state."""
# generate pick-place plan for one stacking subtask
bottom_block, top_block = self._hl_plan_to_run.popleft()
raw_plan = self._pick_place(bottom_block, top_block)
for ac in split_along_axis(raw_plan, axis=0):
yield ac
def _pick_place(self, bottom_block, top_block):
"""Plans action sequence for pick&place of single block."""
action_plan = []
# pick up block
pick_target_pos = self._get_pick_target(top_block)
top_block_quat = self._u_obs.block_quat(top_block)
action_plan.append(self._move_to(pick_target_pos, top_block_quat, self.GRIPPER_OPEN)[0])
action_plan.append(self._grasp())
# place block
place_target_pos = self._get_place_target(bottom_block)
bottom_block_quat = self._u_obs.block_quat(bottom_block)
action_plan.append(self._move_to(place_target_pos, bottom_block_quat, self.GRIPPER_CLOSED)[0])
action_plan.append(self._place())
return np.concatenate(action_plan)
def _get_pick_target(self, block):
block_pos = self._u_obs.block_pos(block)
block_pos[2] += self.PICK_OFFSET
return block_pos
def _get_place_target(self, block):
block_pos = self._u_obs.block_pos(block)
block_pos[2] += self.PLACE_OFFSET
return block_pos
def _move_to(self, target_block_pos, target_block_quat, gripper, waypoints=None):
"""
Plans action sequence for moving robot arm to block.
:param gripper: indicates whether gripper should be ['open', 'closed'] during execution
:param waypoints: (optional) list of precomputed waypoints
"""
block_angle = quat2euler(*target_block_quat)[0] # assume single-axis rotation
robot_pos, robot_angle = self._u_obs.gripper_pos, self._u_obs.gripper_angle
if waypoints is None:
waypoints = [
[robot_pos[0], robot_pos[1], robot_pos[2], robot_angle, self._u_obs.gripper_finger_pos],
[robot_pos[0], robot_pos[1], self.lift_height, robot_angle, gripper],
[target_block_pos[0], target_block_pos[1], self.lift_height, robot_angle, gripper],
[target_block_pos[0], target_block_pos[1], target_block_pos[2] + self.GRASP_OFFSET, block_angle, gripper],
]
# add disturbed subgoals in between waypoints for better state coverage
subgoals = [
self._sample_disturbed_subgoal(robot_pos,
[robot_pos[0], robot_pos[1], self.lift_height])
+ [robot_angle, gripper],
self._sample_disturbed_subgoal([robot_pos[0], robot_pos[1], self.lift_height],
[target_block_pos[0], target_block_pos[1], self.lift_height])
+ [robot_angle, gripper],
self._sample_disturbed_subgoal([target_block_pos[0], target_block_pos[1], self.lift_height],
[target_block_pos[0], target_block_pos[1], target_block_pos[2] + self.GRASP_OFFSET])
+ [block_angle, gripper],
]
# assemble final waypoint list
waypoints = [waypoints[0], subgoals[0], waypoints[1], subgoals[1], waypoints[2], subgoals[2], waypoints[3]]
else:
waypoints = [[robot_pos[0], robot_pos[1], robot_pos[2], robot_angle, self._u_obs.gripper_finger_pos]] \
+ waypoints
if self._update_robot_state:
self._u_obs.gripper_pos, self._u_obs.gripper_angle, self._u_obs.gripper_finger_pos = \
np.array(waypoints[-1][:3]), waypoints[-1][3], gripper # update robot state
return self._waypoints2plan(waypoints, absolute_dims=[-1]), waypoints[1:]
def _grasp(self):
"""Moves robot GRASP-offset down, closes gripper, moves GRASP-offset up."""
robot_pos, robot_angle = self._u_obs.gripper_pos, self._u_obs.gripper_angle
waypoints = [
[robot_pos[0], robot_pos[1], robot_pos[2], robot_angle, self.GRIPPER_OPEN],
[robot_pos[0], robot_pos[1], robot_pos[2] - self.GRASP_OFFSET, robot_angle, self.GRIPPER_OPEN],
[robot_pos[0], robot_pos[1], robot_pos[2] - self.GRASP_OFFSET, robot_angle, self.GRIPPER_CLOSED]]
waypoints += [waypoints[-1]] * 3 # noop
waypoints += [[robot_pos[0], robot_pos[1], robot_pos[2], robot_angle, self.GRIPPER_CLOSED]]
if self._update_robot_state:
self._u_obs.gripper_finger_pos = self.GRIPPER_CLOSED # update robot state
return self._waypoints2plan(waypoints, absolute_dims=[-1])
def _place(self):
"""Moves robot GRASP-offset down, opens gripper, moves GRASP-offset up."""
robot_pos, robot_angle = self._u_obs.gripper_pos, self._u_obs.gripper_angle
waypoints = [
[robot_pos[0], robot_pos[1], robot_pos[2], robot_angle, self.GRIPPER_CLOSED],
[robot_pos[0], robot_pos[1], robot_pos[2] - self.GRASP_OFFSET, robot_angle, self.GRIPPER_CLOSED],
[robot_pos[0], robot_pos[1], robot_pos[2] - self.GRASP_OFFSET, robot_angle, self.GRIPPER_OPEN],
[robot_pos[0], robot_pos[1], robot_pos[2], robot_angle, self.GRIPPER_OPEN],
[robot_pos[0], robot_pos[1], self.lift_height, robot_angle, self.GRIPPER_OPEN]
]
if self._update_robot_state:
self._u_obs.gripper_finger_pos = self.GRIPPER_OPEN # update robot state
return self._waypoints2plan(waypoints, absolute_dims=[-1])
def _waypoints2plan(self, waypoints, absolute_dims=None):
plan = np.concatenate([self._interpolate(waypoints[i], waypoints[i+1], absolute_dims)
for i in range(len(waypoints) - 1)])
return plan
def _interpolate(self, start, goal, absolute_dims=None):
"""
Interpolates between start and goal linearly while taking max_actions into account.
Since action effect is smaller than actual action scale we need a multiplier to treat the distance farther than the actual one.
:param absolute_dims: list of dimensions for which action will be set to goal state.
"""
diff = np.array(goal) - np.array(start)
n_steps = int(np.max(np.ceil(np.divide(np.abs(diff), np.array(self.ACT_RANGE)))))
for dim in absolute_dims if absolute_dims is not None else []:
diff[dim] = goal[dim] * n_steps # hack to make dims action values absolute
if n_steps > 0:
actions = [diff / n_steps for _ in range(n_steps)]
return actions
else:
return np.zeros([0, diff.shape[-1]])
def _post_process(self, ac):
# scale action
ac[:3] *= self.MULTIPLIER # scale lateral actions to make them reach the target states
# add gravity support for noop
if np.sum(ac[:-1]) == 0:
ac[2] += self.GRAVITY_SUPPORT
# crop action dimensions according to env params
if not self.env_params.allow_rotate:
ac = np.concatenate([ac[:3], ac[4:]])
if self.env_params.dimension == 2:
ac = ac[1:]
return ac
def _sample_disturbed_subgoal(self, start_pos, goal_pos, max_displacement_ratio=0.2):
"""Samples a subgoal with some offset to the direct connection line."""
start_pos, goal_pos = np.array(start_pos), np.array(goal_pos)
diff = goal_pos - start_pos
# generate unit vector that's orthogonal to diff
noise = np.asarray([diff[0], diff[2], -diff[1]])
noise /= np.linalg.norm(noise) # normalize it
# sample random offset along connection line + random length
length = (np.random.rand() * 2 * max_displacement_ratio - max_displacement_ratio) * np.linalg.norm(diff)
offset = (np.random.rand() * 0.6 + 0.2) * diff
# compute subgoal position
subgoal_pos = start_pos + offset + length * noise
return [coord for coord in subgoal_pos]
class ClosedLoopBlockStackDemoPolicy(BlockStackDemoPolicy):
PICK_OFFSET = 0.11
def __init__(self, env_params):
super().__init__(env_params)
self._update_robot_state = False
def _plan_actions(self):
# generate pick-place plan for one stacking subtask
bottom_block, top_block = self._hl_plan_to_run.popleft()
top_block_init_pos = self._u_obs.block_pos(top_block)
waypoints = None
while not self._lifted(top_block):
while not self._reached(self._get_pick_target(top_block)):
pick_target_pos = self._get_pick_target(top_block)
top_block_quat = self._u_obs.block_quat(top_block)
actions, waypoints = self._move_to(pick_target_pos, top_block_quat, self.GRIPPER_OPEN, waypoints)
if self._reached_waypoint(waypoints[0]) and len(waypoints) > 1:
waypoints = waypoints[1:]
if len(actions) > 0:
yield actions[0]
else:
break
grasp_plan = split_along_axis(self._grasp(), axis=0)
for i, action in enumerate(grasp_plan):
yield action
waypoints = None
while not self._reached(self._get_place_target(bottom_block)):
place_target_pos = self._get_place_target(bottom_block)
bottom_block_quat = self._u_obs.block_quat(bottom_block)
actions, waypoints = self._move_to(place_target_pos, bottom_block_quat, self.GRIPPER_CLOSED, waypoints)
if self._reached_waypoint(waypoints[0]) and len(waypoints) > 1:
waypoints = waypoints[1:]
if len(actions) > 0:
yield actions[0]
else:
break
while not self._stacked(top_block, bottom_block):
for action in split_along_axis(self._place(), axis=0):
yield action
def _lifted(self, top_block):
top_block_pos = self._u_obs.block_pos(top_block)
gripper_pos = self._u_obs.gripper_pos
lifted = True
x_dist = np.abs(gripper_pos[0] - top_block_pos[0])
lifted &= x_dist < self.env_params.block_size
y_dist = np.abs(gripper_pos[1] - top_block_pos[1])
lifted &= y_dist < self.env_params.block_size
z_vec = gripper_pos[-1] - top_block_pos[-1]
lifted &= z_vec < 0.14
lifted &= z_vec > 0.08
return lifted
def | (self, top_block, bottom_block):
top_pos = self._u_obs.block_pos(top_block)
bottom_pos = self._u_obs.block_pos(bottom_block)
x_dist = np.linalg.norm(top_pos[0] - bottom_pos[0])
y_dist = np.linalg.norm(top_pos[0] - bottom_pos[0])
x_dist_correct = x_dist < self.env_params.block_size
y_dist_correct = y_dist < self.env_params.block_size
z_vec = top_pos[2] - bottom_pos[2]
z_vec_correct = np.abs(z_vec - 2 * self.env_params.block_size) < 0.005
return x_dist_correct and y_dist_correct and z_vec_correct
def _reached(self, pos):
target_pos = pos
target_pos[2] += self.GRASP_OFFSET
return np.linalg.norm(pos - self._u_obs.gripper_pos) < self.EPS
def _reached_waypoint(self, waypoint):
return np.linalg.norm(np.array(waypoint[:3]) - self._u_obs.gripper_pos) < self.EPS
class BlockUnflattenWrapper(AttrDict):
def block_pos(self, idx):
return list(self['block_pos'][idx])
def block_quat(self, idx):
return list(self['block_quat'][idx])
def set_block_pos(self, idx, val):
self['block_pos'][idx] = val
def set_block_quat(self, idx, val):
self['block_quat'][idx] = val
if __name__ == "__main__":
from spirl.data.block_stacking.src.block_task_generator import SingleTowerBlockTaskGenerator
obs = AttrDict(
block_pos=np.random.rand(4*3),
block_quat=np.random.rand(4*4),
gripper_pos=np.random.rand(3),
gripper_angle=np.random.rand(),
gripper_finger_pos=np.random.rand(),
)
task_gen = SingleTowerBlockTaskGenerator({}, 4)
task = task_gen.sample()
policy = BlockStackDemoPolicy(task)
print(policy.act(obs))
# print(policy._plan_actions(obs))
| _stacked |
GogsFactory.py | from .GogsClient import GogsClient
from js9 import j |
JSConfigBaseFactory = j.tools.configmanager.base_class_configs
class GogsFactory(JSConfigBaseFactory):
def __init__(self):
self.__jslocation__ = "j.clients.gogs"
self.__imports__ = "requests,psycopg2"
JSConfigBaseFactory.__init__(self, GogsClient) | |
Strip.py | # strip puncuation custom module
# 12 / 03 / 2015
# Brandon
# https://www.facebook.com/AiiYourBaseRBel0ngToUs
"""
This program was designed to strip puncuation
from a string
This program was made by Brandon in February 2015
and was finished in February 2015
If you have any suggestions or want to help
contact me at
https://www.facebook.com/AiiYourBaseRBel0ngToUs
This program abides by the rules of presentation for
PEP-8
shown here on
https://www.python.org/dev/peps/pep-0008/
You may use this code, or any features of this code
in your own work, as long as you link my page
and the BSD licensing, which can be copied directly
below.
https://www.facebook.com/AiiYourBaseRBel0ngToUs
*BSD licensed*
More info can be read here
http://opensource.org/licenses/BSD-3-Clause
"""
import sys
# Sys is required for Sys.exit() in close() function
def main():
# runs through every function and strips everything
message = str(input("enter message here to strip "))
message1 = strip(message)
message2 = stripWithSpace(message)
message3 = stripSpaceOnly(message)
print(message1)
print(message2)
print(message3)
close()
def strip(message):
# strips all basic puncuation
# defines puncuations
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
# creates empty variable
no_punct = ""
# for every charecter in MESSAGE
for char in message:
# if charecter is not in puncuations
if char not in punctuations:
no_punct = no_punct + char
# replaces puncuation with nothing
return no_punct
# returns non-puncuated string
def stripWithSpace(message):
# strips all puncuation with Space
# defines puncuations
punctuations = ''' !()-[]{};:'"\,<>./?@#$%^&*_~'''
# creates empty variable
no_punct = ""
for char in message:
if char not in punctuations:
no_punct = no_punct + char
# replaces puncuation with nothing
return no_punct
def stripSpaceOnly(message):
# Strips Space only
# defines puncuations
punctuations = ''' '''
# creates empty variable
no_punct = ""
for char in message:
if char not in punctuations:
no_punct = no_punct + char
# replaces puncuation with nothing
return no_punct
def stripLetters(message):
| # Strips only alphabetical letters
# defines puncuations
message = message.upper()
# converts message to upper case, makes it easier to strip
punctuations = '''ABCDEFGHIJKLMNOPQRSTUVWXYZ'''
# creates empty variable
no_punct = ""
for char in message:
if char not in punctuations:
no_punct = no_punct + char
# replaces puncuation with nothing
return no_punct
def Reverse(message):
# reverse a string
# may be useful
reverseTranslated = ''
i = len(message) - 1
while i >= 0:
reverseTranslated = reverseTranslated + message[i]
i = i - 1
def close():
input("Any key to exit! ")
sys.exit()
if __name__ == '__main__':
main() | |
network.py | import numpy as np
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
# ----------------------------------------------------------------------------------
# Commonly used layers and operations based on ethereon's implementation
# https://github.com/ethereon/caffe-tensorflow
# Slight modifications may apply. FCRN-specific operations have also been appended.
# ----------------------------------------------------------------------------------
# Thanks to *Helisa Dhamo* for the model conversion and integration into TensorFlow.
# ----------------------------------------------------------------------------------
DEFAULT_PADDING = 'SAME'
def get_incoming_shape(incoming):
""" Returns the incoming data shape """
if isinstance(incoming, tf.Tensor):
return incoming.get_shape().as_list()
elif type(incoming) in [np.array, list, tuple]:
return np.shape(incoming)
else:
raise Exception("Invalid incoming layer.")
def interleave(tensors, axis):
old_shape = get_incoming_shape(tensors[0])[1:]
new_shape = [-1] + old_shape
new_shape[axis] *= len(tensors)
return tf.reshape(tf.stack(tensors, axis + 1), new_shape)
def layer(op):
'''Decorator for composable network layers.'''
def layer_decorated(self, *args, **kwargs):
# Automatically set a name if not provided.
name = kwargs.setdefault('name', self.get_unique_name(op.__name__))
# Figure out the layer inputs.
if len(self.terminals) == 0:
raise RuntimeError('No input variables found for layer %s.' % name)
elif len(self.terminals) == 1:
layer_input = self.terminals[0]
else:
layer_input = list(self.terminals)
# Perform the operation and get the output.
layer_output = op(self, layer_input, *args, **kwargs)
# Add to layer LUT.
self.layers[name] = layer_output
# This output is now the input for the next layer.
self.feed(layer_output)
# Return self for chained calls.
return self
return layer_decorated
class Network(object):
def __init__(self, inputs, batch, keep_prob, is_training, trainable = True):
# The input nodes for this network
self.inputs = inputs
# The current list of terminal nodes
self.terminals = []
# Mapping from layer names to layers
self.layers = dict(inputs)
# If true, the resulting variables are set as trainable
self.trainable = trainable
self.batch_size = batch
self.keep_prob = keep_prob
self.is_training = is_training
self.setup()
def setup(self):
'''Construct the network. '''
raise NotImplementedError('Must be implemented by the subclass.')
def load(self, data_path, session, ignore_missing=False):
'''Load network weights.
data_path: The path to the numpy-serialized network weights
session: The current TensorFlow session
ignore_missing: If true, serialized weights for missing layers are ignored.
'''
data_dict = np.load(data_path, encoding='latin1').item()
for op_name in data_dict:
with tf.variable_scope(op_name, reuse=True):
for param_name, data in iter(data_dict[op_name].items()):
try:
var = tf.get_variable(param_name)
session.run(var.assign(data))
except ValueError:
if not ignore_missing:
raise
def feed(self, *args):
'''Set the input(s) for the next operation by replacing the terminal nodes.
The arguments can be either layer names or the actual layers.
'''
assert len(args) != 0
self.terminals = []
for fed_layer in args:
if isinstance(fed_layer, str):
try:
fed_layer = self.layers[fed_layer]
except KeyError:
raise KeyError('Unknown layer name fed: %s' % fed_layer)
self.terminals.append(fed_layer)
return self
def get_output(self):
'''Returns the current network output.'''
return self.terminals[-1]
def get_layer_output(self, name):
return self.layers[name]
def get_unique_name(self, prefix):
'''Returns an index-suffixed unique name for the given prefix.
This is used for auto-generating layer names based on the type-prefix.
'''
ident = sum(t.startswith(prefix) for t, _ in self.layers.items()) + 1
return '%s_%d' % (prefix, ident)
def make_var(self, name, shape):
'''Creates a new TensorFlow variable.'''
return tf.get_variable(name, shape, dtype = 'float32', trainable=self.trainable)
def validate_padding(self, padding):
'''Verifies that the padding is one of the supported ones.'''
assert padding in ('SAME', 'VALID')
@layer
def conv(self,
input_data,
k_h,
k_w,
c_o,
s_h,
s_w,
name,
relu=True,
padding=DEFAULT_PADDING,
group=1,
biased=True):
# Verify that the padding is acceptable
self.validate_padding(padding)
# Get the number of channels in the input
c_i = input_data.get_shape()[-1]
if (padding == 'SAME'):
input_data = tf.pad(input_data, [[0, 0], [(k_h - 1)//2, (k_h - 1)//2], [(k_w - 1)//2, (k_w - 1)//2], [0, 0]], "CONSTANT")
# Verify that the grouping parameter is valid
assert c_i % group == 0
assert c_o % group == 0
# Convolution for a given input and kernel
convolve = lambda i, k: tf.nn.conv2d(i, k, [1, s_h, s_w, 1], padding='VALID')
with tf.variable_scope(name) as scope:
kernel = self.make_var('weights', shape=[k_h, k_w, c_i // group, c_o])
if group == 1:
# This is the common-case. Convolve the input without any further complications.
output = convolve(input_data, kernel)
else:
# Split the input into groups and then convolve each of them independently
input_groups = tf.split(3, group, input_data)
kernel_groups = tf.split(3, group, kernel)
output_groups = [convolve(i, k) for i, k in zip(input_groups, kernel_groups)]
# Concatenate the groups
output = tf.concat(3, output_groups)
# Add the biases
if biased:
biases = self.make_var('biases', [c_o])
output = tf.nn.bias_add(output, biases)
if relu:
# ReLU non-linearity
output = tf.nn.relu(output, name=scope.name)
return output
@layer
def relu(self, input_data, name):
return tf.nn.relu(input_data, name=name)
@layer
def max_pool(self, input_data, k_h, k_w, s_h, s_w, name, padding=DEFAULT_PADDING):
self.validate_padding(padding)
return tf.nn.max_pool(input_data,
ksize=[1, k_h, k_w, 1],
strides=[1, s_h, s_w, 1],
padding=padding,
name=name)
@layer
def avg_pool(self, input_data, k_h, k_w, s_h, s_w, name, padding=DEFAULT_PADDING):
self.validate_padding(padding)
return tf.nn.avg_pool(input_data,
ksize=[1, k_h, k_w, 1],
strides=[1, s_h, s_w, 1],
padding=padding,
name=name)
@layer
def lrn(self, input_data, radius, alpha, beta, name, bias=1.0):
return tf.nn.local_response_normalization(input_data,
depth_radius=radius,
alpha=alpha,
beta=beta,
bias=bias,
name=name)
@layer
def concat(self, inputs, axis, name):
return tf.concat(concat_dim=axis, values=inputs, name=name)
@layer
def add(self, inputs, name):
return tf.add_n(inputs, name=name)
@layer
def fc(self, input_data, num_out, name, relu=True):
with tf.variable_scope(name) as scope:
input_shape = input_data.get_shape()
if input_shape.ndims == 4:
# The input is spatial. Vectorize it first.
dim = 1
for d in input_shape[1:].as_list():
dim *= d
feed_in = tf.reshape(input_data, [-1, dim])
else:
feed_in, dim = (input_data, input_shape[-1].value)
weights = self.make_var('weights', shape=[dim, num_out])
biases = self.make_var('biases', [num_out])
op = tf.nn.relu_layer if relu else tf.nn.xw_plus_b
fc = op(feed_in, weights, biases, name=scope.name)
return fc
@layer
def softmax(self, input_data, name):
input_shape = map(lambda v: v.value, input_data.get_shape())
if len(input_shape) > 2:
# For certain models (like NiN), the singleton spatial dimensions
# need to be explicitly squeezed, since they're not broadcast-able
# in TensorFlow's NHWC ordering (unlike Caffe's NCHW).
if input_shape[1] == 1 and input_shape[2] == 1:
input_data = tf.squeeze(input_data, squeeze_dims=[1, 2])
else:
raise ValueError('Rank 2 tensor input expected for softmax!')
return tf.nn.softmax(input_data, name)
@layer
def batch_normalization(self, input_data, name, scale_offset=True, relu=False):
|
@layer
def dropout(self, input_data, keep_prob, name):
return tf.nn.dropout(input_data, keep_prob, name=name)
def unpool_as_conv(self, size, input_data, id, stride = 1, ReLU = False, BN = True):
# Model upconvolutions (unpooling + convolution) as interleaving feature
# maps of four convolutions (A,B,C,D). Building block for up-projections.
# Convolution A (3x3)
# --------------------------------------------------
layerName = "layer%s_ConvA" % (id)
self.feed(input_data)
self.conv( 3, 3, size[3], stride, stride, name = layerName, padding = 'SAME', relu = False)
outputA = self.get_output()
# Convolution B (2x3)
# --------------------------------------------------
layerName = "layer%s_ConvB" % (id)
padded_input_B = tf.pad(input_data, [[0, 0], [1, 0], [1, 1], [0, 0]], "CONSTANT")
self.feed(padded_input_B)
self.conv(2, 3, size[3], stride, stride, name = layerName, padding = 'VALID', relu = False)
outputB = self.get_output()
# Convolution C (3x2)
# --------------------------------------------------
layerName = "layer%s_ConvC" % (id)
padded_input_C = tf.pad(input_data, [[0, 0], [1, 1], [1, 0], [0, 0]], "CONSTANT")
self.feed(padded_input_C)
self.conv(3, 2, size[3], stride, stride, name = layerName, padding = 'VALID', relu = False)
outputC = self.get_output()
# Convolution D (2x2)
# --------------------------------------------------
layerName = "layer%s_ConvD" % (id)
padded_input_D = tf.pad(input_data, [[0, 0], [1, 0], [1, 0], [0, 0]], "CONSTANT")
self.feed(padded_input_D)
self.conv(2, 2, size[3], stride, stride, name = layerName, padding = 'VALID', relu = False)
outputD = self.get_output()
# Interleaving elements of the four feature maps
# --------------------------------------------------
left = interleave([outputA, outputB], axis=1) # columns
right = interleave([outputC, outputD], axis=1) # columns
Y = interleave([left, right], axis=2) # rows
if BN:
layerName = "layer%s_BN" % (id)
self.feed(Y)
self.batch_normalization(name = layerName, scale_offset = True, relu = False)
Y = self.get_output()
if ReLU:
Y = tf.nn.relu(Y, name = layerName)
return Y
def up_project(self, size, id, stride = 1, BN = True):
# Create residual upsampling layer (UpProjection)
input_data = self.get_output()
# Branch 1
id_br1 = "%s_br1" % (id)
# Interleaving Convs of 1st branch
out = self.unpool_as_conv(size, input_data, id_br1, stride, ReLU=True, BN=True)
# Convolution following the upProjection on the 1st branch
layerName = "layer%s_Conv" % (id)
self.feed(out)
self.conv(size[0], size[1], size[3], stride, stride, name = layerName, relu = False)
if BN:
layerName = "layer%s_BN" % (id)
self.batch_normalization(name = layerName, scale_offset=True, relu = False)
# Output of 1st branch
branch1_output = self.get_output()
# Branch 2
id_br2 = "%s_br2" % (id)
# Interleaving convolutions and output of 2nd branch
branch2_output = self.unpool_as_conv(size, input_data, id_br2, stride, ReLU=False)
# sum branches
layerName = "layer%s_Sum" % (id)
output = tf.add_n([branch1_output, branch2_output], name = layerName)
# ReLU
layerName = "layer%s_ReLU" % (id)
output = tf.nn.relu(output, name=layerName)
self.feed(output)
return self
| with tf.variable_scope(name) as scope:
shape = [input_data.get_shape()[-1]]
pop_mean = tf.get_variable("mean", shape, initializer = tf.constant_initializer(0.0), trainable=False)
pop_var = tf.get_variable("variance", shape, initializer = tf.constant_initializer(1.0), trainable=False)
epsilon = 1e-4
decay = 0.999
if scale_offset:
scale = tf.get_variable("scale", shape, initializer = tf.constant_initializer(1.0))
offset = tf.get_variable("offset", shape, initializer = tf.constant_initializer(0.0))
else:
scale, offset = (None, None)
if self.is_training:
batch_mean, batch_var = tf.nn.moments(input_data, [0, 1, 2])
train_mean = tf.assign(pop_mean,
pop_mean * decay + batch_mean * (1 - decay))
train_var = tf.assign(pop_var,
pop_var * decay + batch_var * (1 - decay))
with tf.control_dependencies([train_mean, train_var]):
output = tf.nn.batch_normalization(input_data,
batch_mean, batch_var, offset, scale, epsilon, name = name)
else:
output = tf.nn.batch_normalization(input_data,
pop_mean, pop_var, offset, scale, epsilon, name = name)
if relu:
output = tf.nn.relu(output)
return output |
sync_listener_test.rs | use hey_listen::{
sync::{Dispatcher, Listener, SyncDispatcherRequest},
RwLock,
};
use std::{ops::Deref, sync::Arc};
#[derive(Clone, Eq, Hash, PartialEq)]
enum Event {
VariantA,
VariantB,
}
struct EventListener {
received_variant_a: bool,
received_variant_b: bool,
}
impl Listener<Event> for EventListener {
fn on_event(&mut self, event: &Event) -> Option<SyncDispatcherRequest> {
match *event {
Event::VariantA => self.received_variant_a = true,
Event::VariantB => self.received_variant_b = true,
}
None
}
}
enum EnumListener {
SomeVariant(bool),
}
impl Listener<Event> for EnumListener {
fn on_event(&mut self, event: &Event) -> Option<SyncDispatcherRequest> {
if let Event::VariantA = *event {
match *self {
EnumListener::SomeVariant(ref mut x) => *x = true,
}
}
None
}
}
#[test]
fn dispatch_enum_variant_with_field() {
let listener = Arc::new(RwLock::new(EnumListener::SomeVariant(false)));
let mut dispatcher = Dispatcher::<Event>::default();
dispatcher.add_listener(Event::VariantA, &listener);
dispatcher.dispatch_event(&Event::VariantA);
let enum_field = match *listener.write().deref() {
EnumListener::SomeVariant(x) => x,
};
assert!(enum_field);
}
#[test]
fn register_one_enum_listener_for_one_event_variant_but_dispatch_two_variants() {
let listener = Arc::new(RwLock::new(EventListener {
received_variant_a: false,
received_variant_b: false,
}));
let mut dispatcher = Dispatcher::<Event>::default();
dispatcher.add_listener(Event::VariantA, &listener);
dispatcher.dispatch_event(&Event::VariantA);
let a_has_been_received = listener.try_write().unwrap().received_variant_a;
let b_has_been_received = listener.try_write().unwrap().received_variant_b;
assert!(a_has_been_received);
assert!(!b_has_been_received);
dispatcher.dispatch_event(&Event::VariantB);
let a_has_been_received = listener.try_write().unwrap().received_variant_a;
let b_has_been_received = listener.try_write().unwrap().received_variant_b;
assert!(a_has_been_received);
assert!(!b_has_been_received);
}
#[test]
fn register_one_listener_for_two_event_variants_and_dispatch_two_variants() {
let listener = Arc::new(RwLock::new(EventListener {
received_variant_a: false,
received_variant_b: false,
}));
let mut dispatcher = Dispatcher::<Event>::default();
dispatcher.add_listener(Event::VariantA, &listener);
dispatcher.add_listener(Event::VariantB, &listener);
dispatcher.dispatch_event(&Event::VariantA);
let a_has_been_received = listener.write().received_variant_a;
let b_has_been_received = listener.write().received_variant_b;
assert!(a_has_been_received);
assert!(!b_has_been_received);
dispatcher.dispatch_event(&Event::VariantB);
let a_has_been_received = listener.write().received_variant_a;
let b_has_been_received = listener.write().received_variant_b;
assert!(a_has_been_received);
assert!(b_has_been_received);
}
#[test]
fn dispatch_to_function() {
struct EventListener {
used_method: bool,
}
impl EventListener {
fn test_method(&mut self, _event: &Event) {
self.used_method = true;
}
}
let listener = Arc::new(RwLock::new(EventListener { used_method: false }));
let weak_listener_ref = Arc::downgrade(&Arc::clone(&listener));
let closure = Box::new(move |event: &Event| {
let listener = weak_listener_ref.upgrade().unwrap();
listener.write().test_method(event);
None
});
let mut dispatcher: Dispatcher<Event> = Dispatcher::default();
dispatcher.add_fn(Event::VariantA, closure);
dispatcher.dispatch_event(&Event::VariantA);
let listener = listener.write();
assert!(listener.used_method);
}
#[test]
fn register_and_request_stop_listening() {
#[derive(Clone, Eq, Hash, PartialEq)]
enum Event {
EventType,
}
struct ListenerStruct {
dispatched_events: usize,
}
impl Listener<Event> for ListenerStruct {
fn on_event(&mut self, _: &Event) -> Option<SyncDispatcherRequest> {
self.dispatched_events += 1;
Some(SyncDispatcherRequest::StopListening)
}
}
let listener = Arc::new(RwLock::new(ListenerStruct {
dispatched_events: 0,
}));
let mut dispatcher: Dispatcher<Event> = Dispatcher::default();
dispatcher.add_listener(Event::EventType, &listener);
dispatcher.dispatch_event(&Event::EventType);
dispatcher.dispatch_event(&Event::EventType);
assert_eq!(listener.write().dispatched_events, 1);
}
#[test]
fn register_one_listener_for_one_event_variant_but_dispatch_two_variants() {
use std::hash::{Hash, Hasher};
use std::mem::discriminant;
#[derive(Clone, Eq)]
enum Event {
VariantA(i32),
VariantB(i32),
}
impl Hash for Event {
fn hash<H: Hasher>(&self, _state: &mut H) {}
}
impl PartialEq for Event {
fn eq(&self, other: &Event) -> bool {
discriminant(self) == discriminant(other)
}
}
struct EventListener {
received_variant_a: bool,
received_variant_b: bool,
}
impl Listener<Event> for EventListener {
fn on_event(&mut self, event: &Event) -> Option<SyncDispatcherRequest> {
match *event {
Event::VariantA(_) => self.received_variant_a = true,
Event::VariantB(_) => self.received_variant_b = true,
}
None
}
}
let listener = Arc::new(RwLock::new(EventListener {
received_variant_a: false,
received_variant_b: false,
}));
let mut dispatcher = Dispatcher::<Event>::default();
dispatcher.add_listener(Event::VariantA(5), &listener);
dispatcher.add_listener(Event::VariantB(0), &listener);
dispatcher.dispatch_event(&Event::VariantA(10));
let a_has_been_received = listener.write().received_variant_a;
let b_has_been_received = listener.write().received_variant_b;
assert!(a_has_been_received);
assert!(!b_has_been_received);
dispatcher.dispatch_event(&Event::VariantB(10));
let b_has_been_received = listener.write().received_variant_b;
assert!(b_has_been_received);
}
#[test]
fn stop_propagation_on_sync_dispatcher() {
struct EventListener {
has_been_dispatched: bool,
}
impl Listener<Event> for EventListener {
fn on_event(&mut self, _: &Event) -> Option<SyncDispatcherRequest> {
self.has_been_dispatched = true;
Some(SyncDispatcherRequest::StopPropagation)
}
}
let listener_a = Arc::new(RwLock::new(EventListener {
has_been_dispatched: false,
}));
let listener_b = Arc::new(RwLock::new(EventListener {
has_been_dispatched: false,
}));
let mut dispatcher = Dispatcher::<Event>::default();
dispatcher.add_listener(Event::VariantA, &listener_a);
dispatcher.add_listener(Event::VariantA, &listener_b);
dispatcher.dispatch_event(&Event::VariantA);
let a_has_been_dispatched = listener_a.try_write().unwrap().has_been_dispatched;
let b_has_been_dispatched = listener_b.try_write().unwrap().has_been_dispatched;
assert!(a_has_been_dispatched);
assert!(!b_has_been_dispatched);
}
#[test]
fn stop_listening_and_propagation_on_sync_dispatcher() {
struct EventListener {
dispatch_counter: usize,
}
impl Listener<Event> for EventListener {
fn on_event(&mut self, _: &Event) -> Option<SyncDispatcherRequest> {
self.dispatch_counter += 1;
Some(SyncDispatcherRequest::StopListeningAndPropagation)
}
}
let listener_a = Arc::new(RwLock::new(EventListener {
dispatch_counter: 0,
}));
let listener_b = Arc::new(RwLock::new(EventListener {
dispatch_counter: 0,
}));
let mut dispatcher = Dispatcher::<Event>::default();
dispatcher.add_listener(Event::VariantA, &listener_a);
dispatcher.add_listener(Event::VariantA, &listener_b);
let counter_a = listener_a.try_write().unwrap().dispatch_counter;
let counter_b = listener_b.try_write().unwrap().dispatch_counter;
assert_eq!(counter_a, 0);
assert_eq!(counter_b, 0);
dispatcher.dispatch_event(&Event::VariantA);
let counter_a = listener_a.try_write().unwrap().dispatch_counter;
let counter_b = listener_b.try_write().unwrap().dispatch_counter;
assert_eq!(counter_a, 1);
assert_eq!(counter_b, 0);
dispatcher.dispatch_event(&Event::VariantA);
let counter_a = listener_a.try_write().unwrap().dispatch_counter;
let counter_b = listener_b.try_write().unwrap().dispatch_counter;
assert_eq!(counter_a, 1);
assert_eq!(counter_b, 1);
dispatcher.dispatch_event(&Event::VariantA);
let counter_a = listener_a.try_write().unwrap().dispatch_counter;
let counter_b = listener_b.try_write().unwrap().dispatch_counter;
assert_eq!(counter_a, 1);
assert_eq!(counter_b, 1);
}
#[test]
fn stop_listening_on_sync_dispatcher_of_fns() {
struct EventListener {
use_counter: usize,
};
let listener = Arc::new(RwLock::new(EventListener { use_counter: 0 }));
let weak_listener_ref = Arc::downgrade(&Arc::clone(&listener));
let closure_a = Box::new(move |_event: &Event| {
let listener = &weak_listener_ref.upgrade().unwrap();
listener.write().use_counter += 1;
Some(SyncDispatcherRequest::StopListening)
});
let weak_listener_ref = Arc::downgrade(&Arc::clone(&listener));
let closure_b = Box::new(move |_event: &Event| {
let listener = &weak_listener_ref.upgrade().unwrap();
listener.write().use_counter += 1;
Some(SyncDispatcherRequest::StopListening)
});
let counter = listener.try_write().unwrap().use_counter;
assert_eq!(counter, 0);
let mut dispatcher: Dispatcher<Event> = Dispatcher::default();
dispatcher.add_fn(Event::VariantA, closure_a);
dispatcher.add_fn(Event::VariantA, closure_b);
dispatcher.dispatch_event(&Event::VariantA);
let counter = listener.try_write().unwrap().use_counter;
assert_eq!(counter, 2);
dispatcher.dispatch_event(&Event::VariantA);
let counter = listener.try_write().unwrap().use_counter;
assert_eq!(counter, 2);
}
#[test]
fn | () {
struct EventListener {
use_counter: usize,
};
let listener = Arc::new(RwLock::new(EventListener { use_counter: 0 }));
let weak_listener_ref = Arc::downgrade(&Arc::clone(&listener));
let closure_a = Box::new(move |_event: &Event| {
let listener = &weak_listener_ref.upgrade().unwrap();
listener.write().use_counter += 1;
Some(SyncDispatcherRequest::StopPropagation)
});
let weak_listener_ref = Arc::downgrade(&Arc::clone(&listener));
let closure_b = Box::new(move |_event: &Event| {
let listener = &weak_listener_ref.upgrade().unwrap();
listener.write().use_counter += 1;
Some(SyncDispatcherRequest::StopPropagation)
});
let counter = listener.try_write().unwrap().use_counter;
assert_eq!(counter, 0);
let mut dispatcher: Dispatcher<Event> = Dispatcher::default();
dispatcher.add_fn(Event::VariantA, closure_a);
dispatcher.add_fn(Event::VariantA, closure_b);
dispatcher.dispatch_event(&Event::VariantA);
let counter = listener.try_write().unwrap().use_counter;
assert_eq!(counter, 1);
dispatcher.dispatch_event(&Event::VariantA);
let counter = listener.try_write().unwrap().use_counter;
assert_eq!(counter, 2);
}
#[test]
fn stop_propagation_and_listening_on_sync_dispatcher_of_fns() {
struct EventListener {
use_counter: usize,
};
let listener = Arc::new(RwLock::new(EventListener { use_counter: 0 }));
let weak_listener_ref = Arc::downgrade(&Arc::clone(&listener));
let closure_a = Box::new(move |_event: &Event| {
let listener = &weak_listener_ref.upgrade().unwrap();
listener.write().use_counter += 1;
Some(SyncDispatcherRequest::StopListeningAndPropagation)
});
let weak_listener_ref = Arc::downgrade(&Arc::clone(&listener));
let closure_b = Box::new(move |_event: &Event| {
let listener = &weak_listener_ref.upgrade().unwrap();
listener.write().use_counter += 1;
Some(SyncDispatcherRequest::StopListeningAndPropagation)
});
let counter = listener.try_write().unwrap().use_counter;
assert_eq!(counter, 0);
let mut dispatcher: Dispatcher<Event> = Dispatcher::default();
dispatcher.add_fn(Event::VariantA, closure_a);
dispatcher.add_fn(Event::VariantA, closure_b);
dispatcher.dispatch_event(&Event::VariantA);
let counter = listener.try_write().unwrap().use_counter;
assert_eq!(counter, 1);
dispatcher.dispatch_event(&Event::VariantA);
let counter = listener.try_write().unwrap().use_counter;
assert_eq!(counter, 2);
dispatcher.dispatch_event(&Event::VariantA);
let counter = listener.try_write().unwrap().use_counter;
assert_eq!(counter, 2);
}
#[test]
fn is_send_and_sync() {
fn assert_send<T: Send + Sync>(_: &T) {};
assert_send(&Dispatcher::<Event>::default());
}
| stop_propagation_on_sync_dispatcher_of_fns |
paper_material.py | #! /usr/bin/env python
import os
import subprocess
import svgwrite
import math
import shutil
########################################################################################################################
def ensure_requisite_folders(path):
folder = os.path.split(path)[0]
if len(folder) and not os.path.exists(folder):
os.makedirs(folder)
def _png_name(p):
return p.split(".svg")[0]+".png"
def to_png(from_path, to_path):
ensure_requisite_folders(to_path)
cmd = \
"""
convert {} {}
""".format(from_path, to_path)
subprocess.call(cmd.split())
def _advance_cursor(c, x, y):
return (c[0]+x, c[1]+y)
def _kot(dwg, _c, text, ox=-40, oy=50, style="font-size:40;font-family:Arial;font-weight:bold;stroke:black;stroke-width:1;fill:black"):
dwg.add(dwg.text(text, insert=(_c[0]+ox, _c[1]+oy), fill='black', style=style))
def figure_1(args):
_p = "_fig1.svg"#os.path.join(args.output_folder, "fig1.svg")
# diagram is (341,972); plots are 600,600
_1_size = (467, 986)
_2_size = (341, 972)
_size = (_1_size[0]+140+_2_size[0], _1_size[1])
dwg = svgwrite.Drawing(_p, size=_size)
dwg.add(dwg.rect(insert=(0, 0), size=_size, fill="rgb(255,255,255)"))
_c = (40,0) # conceptual cursor
dwg.add(dwg.image(os.path.join(args.input_folder_2, "multixcan_illustration.png"), _c, _1_size))
_kot(dwg, _c, "a", ox=-20, oy=30)
_c = _advance_cursor(_c, _1_size[0] + 90 , 0)
dwg.add(dwg.image(os.path.join(args.input_folder_2, "S-Predixcan-MT-diagram_2.png"), _c, _1_size))
_kot(dwg, _c, "b", ox=-20, oy=30)
dwg.save()
t = os.path.join(args.output_folder, "fig-multi-tissue-presentation.png")
to_png(_p, t)
os.remove(_p)
def figure_2(args):
_p = "_fig2.svg"#os.path.join(args.output_folder, "fig1.svg")
# diagram is (341,972); plots are 600,600
_1_size = (600, 600)
_size = (_1_size[0]*3+140, _1_size[1])
dwg = svgwrite.Drawing(_p, size=_size)
dwg.add(dwg.rect(insert=(0, 0), size=_size, fill="rgb(255,255,255)"))
_c = (20,0) # conceptual cursor
dwg.add(dwg.image(os.path.join(args.plots_folder, "ukb", "ukb_mt_vs_p_number_significant.png"), _c, _1_size))
_kot(dwg, _c, "a", ox=0, oy=30)
_c = _advance_cursor(_c, _1_size[0] + 50, 0)
dwg.add(dwg.image(os.path.join(args.plots_folder, "ukb", "UKB_Cholesterol_significant_bars.png"), _c, _1_size))
_kot(dwg, _c, "b", ox=0, oy=30)
_c =_advance_cursor (_c, _1_size[0]+50, 0)
dwg.add(dwg.image(os.path.join(args.plots_folder, "ukb", "UKB_Cholesterol_qq.png"), _c, _1_size))
_kot(dwg, _c, "c", ox=0, oy=30)
dwg.save()
t = os.path.join(args.output_folder, "fig-multi-tissue-ukb-cholesterol.png")
to_png(_p, t)
os.remove(_p)
def figure_3(args):
_p = "_fig3.svg"#os.path.join(args.output_folder, "fig1.svg")
# diagram is (341,972); plots are 600,600; illustration is 455,571
_1_size = (600, 600)
_2_size = (526*600.0/552, 600)
_size = (_1_size[0]*2+80, _1_size[1]*2+40)
dwg = svgwrite.Drawing(_p, size=_size)
dwg.add(dwg.rect(insert=(0, 0), size=_size, fill="rgb(255,255,255)"))
_c = (40+math.ceil(_1_size[0]-_2_size[0])/2.0, 0) # conceptual cursor
dwg.add(dwg.image(os.path.join(args.input_folder_2, "smultixcan_illustration.png"), _c, _1_size))
_kot(dwg, _c, "a", ox=-20, oy=30)
_c =_advance_cursor (_c, _2_size[0]+40, 0)
dwg.add(dwg.image(os.path.join(args.plots_folder, "gwas", "smt_vs_sp_number_significant.png"), _c, _1_size))
_kot(dwg, _c, "b", ox=-20, oy=30)
_c = (40, _1_size[1]+40) # conceptual cursor
dwg.add(dwg.image(os.path.join(args.plots_folder, "gwas", "PGC_scz2_qq.png"), _c, _1_size))
_kot(dwg, _c, "c", ox=-20, oy=30)
_c =_advance_cursor (_c, _1_size[1]+40, 0)
dwg.add(dwg.image(os.path.join(args.plots_folder, "gwas", "PGC_scz2_significant_bars.png"), _c, _1_size))
_kot(dwg, _c, "d", ox=-20, oy=30)
dwg.save()
t = os.path.join(args.output_folder, "fig-s-multi-tissue-presentation.png")
to_png(_p, t)
os.remove(_p)
def figure_5(args):
_p = "_fig5.svg"#os.path.join(args.output_folder, "fig1.svg")
_1_size = (800, 800)
_size = (_1_size[0]*2+80, _1_size[1]+40)
dwg = svgwrite.Drawing(_p, size=_size)
dwg.add(dwg.rect(insert=(0, 0), size=_size, fill="rgb(255,255,255)"))
_c = (40, 0) # conceptual cursor
dwg.add(dwg.image(os.path.join(args.plots_folder, "simulations", "null_30_qq.png"), _c, _1_size))
_kot(dwg, _c, "a", ox=-20, oy=30)
_c =_advance_cursor (_c, _1_size[0]+40, 0)
dwg.add(dwg.image(os.path.join(args.plots_folder, "simulations", "null_0_qq.png"), _c, _1_size))
_kot(dwg, _c, "b", ox=-20, oy=30)
dwg.save()
t = os.path.join(args.output_folder, "supp-fig-simulations-null.png")
to_png(_p, t)
os.remove(_p)
def figure_6_d(args):
_p = "_fig6.svg" # os.path.join(args.output_folder, "fig1.svg")
_1_size = (800, 800)
_size = (_1_size[0] * 2 + 80, _1_size[1] *2 + 80)
dwg = svgwrite.Drawing(_p, size=_size)
dwg.add(dwg.rect(insert=(0, 0), size=_size, fill="rgb(255,255,255)"))
_c = (40.0, 40) # conceptual cursor
dwg.add(dwg.image(os.path.join(args.plots_folder, "simulations", "single_tissue_bp.png"), _c, _1_size))
_kot(dwg, _c, "a", ox=-20, oy=30)
_c =_advance_cursor (_c, _1_size[0]+40, 0)
dwg.add(dwg.image(os.path.join(args.plots_folder, "simulations", "correlated_tissues_bp.png"), _c, _1_size))
_kot(dwg, _c, "b", ox=-20, oy=30)
_c = (40, _1_size[1]*1+80)
dwg.add(dwg.image(os.path.join(args.plots_folder, "simulations", "combination_brain_bp.png"), _c, _1_size))
_kot(dwg, _c, "c", ox=-20, oy=30)
_c =_advance_cursor (_c, _1_size[0]+40, 0)
dwg.add(dwg.image(os.path.join(args.plots_folder, "simulations", "combination_all_bp.png"), _c, _1_size))
_kot(dwg, _c, "d", ox=-20, oy=30)
dwg.save()
t = os.path.join(args.output_folder, "supp-fig-simulations-misc.png")
to_png(_p, t)
os.remove(_p)
def figure_6(args):
_p = "_fig6.svg" # os.path.join(args.output_folder, "fig1.svg")
_1_size = (800, 800)
_size = (_1_size[0] * 3 + 80, _1_size[1])
dwg = svgwrite.Drawing(_p, size=_size)
dwg.add(dwg.rect(insert=(0, 0), size=_size, fill="rgb(255,255,255)"))
_c = (40.0, 0) # conceptual cursor
dwg.add(dwg.image(os.path.join(args.plots_folder, "simulations", "single_tissue_bp.png"), _c, _1_size))
_kot(dwg, _c, "a", ox=-20, oy=30)
_c = _advance_cursor(_c, _1_size[0] + 40, 0)
dwg.add(dwg.image(os.path.join(args.plots_folder, "simulations", "combination_brain_bp.png"), _c, _1_size))
_kot(dwg, _c, "b", ox=-20, oy=30)
_c =_advance_cursor (_c, _1_size[0]+40, 0)
dwg.add(dwg.image(os.path.join(args.plots_folder, "simulations", "combination_all_bp.png"), _c, _1_size))
_kot(dwg, _c, "c", ox=-20, oy=30)
dwg.save()
t = os.path.join(args.output_folder, "supp-fig-simulations-misc.png")
to_png(_p, t)
os.remove(_p)
def | (args):
def _shove(input_folder, output_folder, files, file_prefix=""):
for sf in files:
shutil.copy(os.path.join(input_folder, *sf),
os.path.join(output_folder, file_prefix + sf[len(sf) - 1].replace("_", "-")))
figures = [("ukb","smt_vs_mt_ukb.png",)]
_shove(args.plots_folder, args.output_folder, figures, file_prefix="fig-")
supp_figures = [("ukb", "smt_vs_mt_ukb_supp.png",),
("ukb", "proportion_underestimated_ukb.png",),
("ukb", "UKB_Cholesterol_significant_bars_fdr.png",),
("simulations", "combination_all_tendency.png",),
("simulations", "pc.png"),
("wtccc", "t1d_snp_intersection.png")]
_shove(args.plots_folder, args.output_folder, supp_figures, "supp-fig-")
supp_data =[("gwas_traits.txt",),
("gwas_smultixcan_stats.txt",),
("gwas_smultixcan_significant.txt",),
("gwas_sp_significant.txt",),
("ukb_multixcan_stats.txt",),
("ukb_p_significant.txt",),
("ukb_multixcan_significant.txt",),
("ukb_individual_pm.txt",),
("wtccc_t1d.txt",)]
_shove(args.input_folder, args.output_folder, supp_data, "supp-data-")
images = [("corrplot_pearson_SLC5A6.png",)]
_shove(args.input_folder_2, args.output_folder, images, "supp-fig-")
########################################################################################################################
def run(args):
if not os.path.exists(args.output_folder):
os.makedirs(args.output_folder)
shove(args)
figure_1(args)
figure_2(args)
figure_3(args)
#figure_4(args)
figure_5(args)
figure_6(args)
if __name__ == "__main__":
class Dummy(object):
def __init__(self):
self.output_folder = "results/paper_material"
self.plots_folder = "results/plots"
self.input_folder = "results"
self.input_folder_2 = "images"
self.input_folder_3 = "external_data"
args = Dummy()
run(args)
| shove |
test-basic-boot.rs | #![cfg_attr(not(test), no_std)]
#![cfg_attr(not(test), no_main)] // disable all Rust-level entry points
#![cfg_attr(test, allow(unused_imports))]
use blog_os::{exit_qemu, serial_println};
use core::panic::PanicInfo;
/// This function is the entry point, since the linker looks for a function
/// named `_start` by default.
#[cfg(not(test))]
#[no_mangle] // don't mangle the name of this function
pub extern "C" fn _start() -> ! |
/// This function is called on panic.
#[cfg(not(test))]
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
serial_println!("failed");
serial_println!("{}", info);
unsafe {
exit_qemu();
}
loop {}
}
| {
serial_println!("ok");
unsafe {
exit_qemu();
}
loop {}
} |
main.rs | use std::env;
use std::process;
fn main() -> Result<(), Box<dyn std::error::Error>> | {
let input = day8::Input::new(env::args()).unwrap_or_else(|err| {
eprintln!("Problem parsing args: {}", err);
process::exit(1);
});
day8::run(input)
} |
|
fan.py | """Support for MQTT fans."""
from __future__ import annotations
import asyncio
import functools
import logging
import math
import voluptuous as vol
from homeassistant.components import fan
from homeassistant.components.fan import (
ATTR_OSCILLATING,
ATTR_PERCENTAGE,
ATTR_PRESET_MODE,
FanEntity,
FanEntityFeature,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONF_NAME,
CONF_OPTIMISTIC,
CONF_PAYLOAD_OFF,
CONF_PAYLOAD_ON,
CONF_STATE,
)
from homeassistant.core import HomeAssistant, callback
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from homeassistant.util.percentage import (
int_states_in_range,
percentage_to_ranged_value,
ranged_value_to_percentage,
)
from . import subscription
from .config import MQTT_RW_SCHEMA
from .const import (
CONF_COMMAND_TEMPLATE,
CONF_COMMAND_TOPIC,
CONF_ENCODING,
CONF_QOS,
CONF_RETAIN,
CONF_STATE_TOPIC,
CONF_STATE_VALUE_TEMPLATE,
PAYLOAD_NONE,
)
from .debug_info import log_messages
from .mixins import (
MQTT_ENTITY_COMMON_SCHEMA,
MqttEntity,
async_get_platform_config_from_yaml,
async_setup_entry_helper,
async_setup_platform_helper,
warn_for_legacy_schema,
)
from .models import MqttCommandTemplate, MqttValueTemplate
from .util import valid_publish_topic, valid_subscribe_topic
CONF_PERCENTAGE_STATE_TOPIC = "percentage_state_topic"
CONF_PERCENTAGE_COMMAND_TOPIC = "percentage_command_topic"
CONF_PERCENTAGE_VALUE_TEMPLATE = "percentage_value_template"
CONF_PERCENTAGE_COMMAND_TEMPLATE = "percentage_command_template"
CONF_PAYLOAD_RESET_PERCENTAGE = "payload_reset_percentage"
CONF_SPEED_RANGE_MIN = "speed_range_min"
CONF_SPEED_RANGE_MAX = "speed_range_max"
CONF_PRESET_MODE_STATE_TOPIC = "preset_mode_state_topic"
CONF_PRESET_MODE_COMMAND_TOPIC = "preset_mode_command_topic"
CONF_PRESET_MODE_VALUE_TEMPLATE = "preset_mode_value_template"
CONF_PRESET_MODE_COMMAND_TEMPLATE = "preset_mode_command_template"
CONF_PRESET_MODES_LIST = "preset_modes"
CONF_PAYLOAD_RESET_PRESET_MODE = "payload_reset_preset_mode"
CONF_SPEED_STATE_TOPIC = "speed_state_topic"
CONF_SPEED_COMMAND_TOPIC = "speed_command_topic"
CONF_SPEED_VALUE_TEMPLATE = "speed_value_template"
CONF_OSCILLATION_STATE_TOPIC = "oscillation_state_topic"
CONF_OSCILLATION_COMMAND_TOPIC = "oscillation_command_topic"
CONF_OSCILLATION_VALUE_TEMPLATE = "oscillation_value_template"
CONF_OSCILLATION_COMMAND_TEMPLATE = "oscillation_command_template"
CONF_PAYLOAD_OSCILLATION_ON = "payload_oscillation_on"
CONF_PAYLOAD_OSCILLATION_OFF = "payload_oscillation_off"
CONF_PAYLOAD_OFF_SPEED = "payload_off_speed"
CONF_PAYLOAD_LOW_SPEED = "payload_low_speed"
CONF_PAYLOAD_MEDIUM_SPEED = "payload_medium_speed"
CONF_PAYLOAD_HIGH_SPEED = "payload_high_speed"
CONF_SPEED_LIST = "speeds"
DEFAULT_NAME = "MQTT Fan"
DEFAULT_PAYLOAD_ON = "ON"
DEFAULT_PAYLOAD_OFF = "OFF"
DEFAULT_PAYLOAD_RESET = "None"
DEFAULT_OPTIMISTIC = False
DEFAULT_SPEED_RANGE_MIN = 1
DEFAULT_SPEED_RANGE_MAX = 100
OSCILLATE_ON_PAYLOAD = "oscillate_on"
OSCILLATE_OFF_PAYLOAD = "oscillate_off"
MQTT_FAN_ATTRIBUTES_BLOCKED = frozenset(
{
fan.ATTR_DIRECTION,
fan.ATTR_OSCILLATING,
fan.ATTR_PERCENTAGE_STEP,
fan.ATTR_PERCENTAGE,
fan.ATTR_PRESET_MODE,
fan.ATTR_PRESET_MODES,
}
)
_LOGGER = logging.getLogger(__name__)
def valid_speed_range_configuration(config):
"""Validate that the fan speed_range configuration is valid, throws if it isn't."""
if config.get(CONF_SPEED_RANGE_MIN) == 0:
raise ValueError("speed_range_min must be > 0")
if config.get(CONF_SPEED_RANGE_MIN) >= config.get(CONF_SPEED_RANGE_MAX):
raise ValueError("speed_range_max must be > speed_range_min")
return config
def valid_preset_mode_configuration(config):
"""Validate that the preset mode reset payload is not one of the preset modes."""
if config.get(CONF_PAYLOAD_RESET_PRESET_MODE) in config.get(CONF_PRESET_MODES_LIST):
raise ValueError("preset_modes must not contain payload_reset_preset_mode")
return config
_PLATFORM_SCHEMA_BASE = MQTT_RW_SCHEMA.extend(
{
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_OPTIMISTIC, default=DEFAULT_OPTIMISTIC): cv.boolean,
vol.Optional(CONF_COMMAND_TEMPLATE): cv.template,
vol.Optional(CONF_OSCILLATION_COMMAND_TOPIC): valid_publish_topic,
vol.Optional(CONF_OSCILLATION_COMMAND_TEMPLATE): cv.template,
vol.Optional(CONF_OSCILLATION_STATE_TOPIC): valid_subscribe_topic,
vol.Optional(CONF_OSCILLATION_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_PERCENTAGE_COMMAND_TOPIC): valid_publish_topic,
vol.Optional(CONF_PERCENTAGE_COMMAND_TEMPLATE): cv.template,
vol.Optional(CONF_PERCENTAGE_STATE_TOPIC): valid_subscribe_topic,
vol.Optional(CONF_PERCENTAGE_VALUE_TEMPLATE): cv.template,
# CONF_PRESET_MODE_COMMAND_TOPIC and CONF_PRESET_MODES_LIST must be used together
vol.Inclusive(
CONF_PRESET_MODE_COMMAND_TOPIC, "preset_modes"
): valid_publish_topic,
vol.Inclusive(
CONF_PRESET_MODES_LIST, "preset_modes", default=[]
): cv.ensure_list,
vol.Optional(CONF_PRESET_MODE_COMMAND_TEMPLATE): cv.template,
vol.Optional(CONF_PRESET_MODE_STATE_TOPIC): valid_subscribe_topic,
vol.Optional(CONF_PRESET_MODE_VALUE_TEMPLATE): cv.template,
vol.Optional(
CONF_SPEED_RANGE_MIN, default=DEFAULT_SPEED_RANGE_MIN
): cv.positive_int,
vol.Optional(
CONF_SPEED_RANGE_MAX, default=DEFAULT_SPEED_RANGE_MAX
): cv.positive_int,
vol.Optional(
CONF_PAYLOAD_RESET_PERCENTAGE, default=DEFAULT_PAYLOAD_RESET
): cv.string,
vol.Optional(
CONF_PAYLOAD_RESET_PRESET_MODE, default=DEFAULT_PAYLOAD_RESET
): cv.string,
vol.Optional(CONF_PAYLOAD_OFF, default=DEFAULT_PAYLOAD_OFF): cv.string,
vol.Optional(CONF_PAYLOAD_ON, default=DEFAULT_PAYLOAD_ON): cv.string,
vol.Optional(
CONF_PAYLOAD_OSCILLATION_OFF, default=OSCILLATE_OFF_PAYLOAD
): cv.string,
vol.Optional(
CONF_PAYLOAD_OSCILLATION_ON, default=OSCILLATE_ON_PAYLOAD
): cv.string,
vol.Optional(CONF_SPEED_COMMAND_TOPIC): valid_publish_topic,
vol.Optional(CONF_SPEED_STATE_TOPIC): valid_subscribe_topic,
vol.Optional(CONF_SPEED_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_STATE_VALUE_TEMPLATE): cv.template,
}
).extend(MQTT_ENTITY_COMMON_SCHEMA.schema)
# Configuring MQTT Fans under the fan platform key is deprecated in HA Core 2022.6
PLATFORM_SCHEMA = vol.All(
cv.PLATFORM_SCHEMA.extend(_PLATFORM_SCHEMA_BASE.schema),
valid_speed_range_configuration,
valid_preset_mode_configuration,
warn_for_legacy_schema(fan.DOMAIN),
)
PLATFORM_SCHEMA_MODERN = vol.All(
_PLATFORM_SCHEMA_BASE,
valid_speed_range_configuration,
valid_preset_mode_configuration,
)
DISCOVERY_SCHEMA = vol.All(
# CONF_SPEED_COMMAND_TOPIC, CONF_SPEED_LIST, CONF_SPEED_STATE_TOPIC, CONF_SPEED_VALUE_TEMPLATE and
# Speeds SPEED_LOW, SPEED_MEDIUM, SPEED_HIGH SPEED_OFF,
# are no longer supported, support was removed in release 2021.12
cv.removed(CONF_PAYLOAD_HIGH_SPEED),
cv.removed(CONF_PAYLOAD_LOW_SPEED),
cv.removed(CONF_PAYLOAD_MEDIUM_SPEED),
cv.removed(CONF_SPEED_COMMAND_TOPIC),
cv.removed(CONF_SPEED_LIST),
cv.removed(CONF_SPEED_STATE_TOPIC),
cv.removed(CONF_SPEED_VALUE_TEMPLATE),
_PLATFORM_SCHEMA_BASE.extend({}, extra=vol.REMOVE_EXTRA),
valid_speed_range_configuration,
valid_preset_mode_configuration,
)
async def async_setup_platform(
hass: HomeAssistant,
config: ConfigType,
async_add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up MQTT fans configured under the fan platform key (deprecated)."""
# Deprecated in HA Core 2022.6
await async_setup_platform_helper(
hass, fan.DOMAIN, config, async_add_entities, _async_setup_entity
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up MQTT fan through configuration.yaml and dynamically through MQTT discovery."""
# load and initialize platform config from configuration.yaml
await asyncio.gather(
*(
_async_setup_entity(hass, async_add_entities, config, config_entry)
for config in await async_get_platform_config_from_yaml(
hass, fan.DOMAIN, PLATFORM_SCHEMA_MODERN
)
)
)
# setup for discovery
setup = functools.partial(
_async_setup_entity, hass, async_add_entities, config_entry=config_entry
)
await async_setup_entry_helper(hass, fan.DOMAIN, setup, DISCOVERY_SCHEMA)
async def _async_setup_entity(
hass, async_add_entities, config, config_entry=None, discovery_data=None
):
"""Set up the MQTT fan."""
async_add_entities([MqttFan(hass, config, config_entry, discovery_data)])
class MqttFan(MqttEntity, FanEntity):
"""A MQTT fan component."""
_entity_id_format = fan.ENTITY_ID_FORMAT
_attributes_extra_blocked = MQTT_FAN_ATTRIBUTES_BLOCKED
def __init__(self, hass, config, config_entry, discovery_data):
"""Initialize the MQTT fan."""
self._state = None
self._percentage = None
self._preset_mode = None
self._oscillation = None
self._supported_features = 0
self._topic = None
self._payload = None
self._value_templates = None
self._command_templates = None
self._optimistic = None
self._optimistic_oscillation = None
self._optimistic_percentage = None
self._optimistic_preset_mode = None
MqttEntity.__init__(self, hass, config, config_entry, discovery_data)
@staticmethod
def config_schema():
"""Return the config schema."""
return DISCOVERY_SCHEMA
def _setup_from_config(self, config):
"""(Re)Setup the entity."""
self._speed_range = (
config.get(CONF_SPEED_RANGE_MIN),
config.get(CONF_SPEED_RANGE_MAX),
)
self._topic = {
key: config.get(key)
for key in (
CONF_STATE_TOPIC,
CONF_COMMAND_TOPIC,
CONF_PERCENTAGE_STATE_TOPIC,
CONF_PERCENTAGE_COMMAND_TOPIC,
CONF_PRESET_MODE_STATE_TOPIC,
CONF_PRESET_MODE_COMMAND_TOPIC,
CONF_OSCILLATION_STATE_TOPIC,
CONF_OSCILLATION_COMMAND_TOPIC,
)
}
self._value_templates = {
CONF_STATE: config.get(CONF_STATE_VALUE_TEMPLATE),
ATTR_PERCENTAGE: config.get(CONF_PERCENTAGE_VALUE_TEMPLATE),
ATTR_PRESET_MODE: config.get(CONF_PRESET_MODE_VALUE_TEMPLATE),
ATTR_OSCILLATING: config.get(CONF_OSCILLATION_VALUE_TEMPLATE),
}
self._command_templates = {
CONF_STATE: config.get(CONF_COMMAND_TEMPLATE),
ATTR_PERCENTAGE: config.get(CONF_PERCENTAGE_COMMAND_TEMPLATE),
ATTR_PRESET_MODE: config.get(CONF_PRESET_MODE_COMMAND_TEMPLATE),
ATTR_OSCILLATING: config.get(CONF_OSCILLATION_COMMAND_TEMPLATE),
}
self._payload = {
"STATE_ON": config[CONF_PAYLOAD_ON],
"STATE_OFF": config[CONF_PAYLOAD_OFF],
"OSCILLATE_ON_PAYLOAD": config[CONF_PAYLOAD_OSCILLATION_ON],
"OSCILLATE_OFF_PAYLOAD": config[CONF_PAYLOAD_OSCILLATION_OFF],
"PERCENTAGE_RESET": config[CONF_PAYLOAD_RESET_PERCENTAGE],
"PRESET_MODE_RESET": config[CONF_PAYLOAD_RESET_PRESET_MODE],
}
self._feature_percentage = CONF_PERCENTAGE_COMMAND_TOPIC in config
self._feature_preset_mode = CONF_PRESET_MODE_COMMAND_TOPIC in config
if self._feature_preset_mode:
self._preset_modes = config[CONF_PRESET_MODES_LIST]
else:
self._preset_modes = []
self._speed_count = (
min(int_states_in_range(self._speed_range), 100)
if self._feature_percentage
else 100
)
optimistic = config[CONF_OPTIMISTIC]
self._optimistic = optimistic or self._topic[CONF_STATE_TOPIC] is None
self._optimistic_oscillation = (
optimistic or self._topic[CONF_OSCILLATION_STATE_TOPIC] is None
)
self._optimistic_percentage = (
optimistic or self._topic[CONF_PERCENTAGE_STATE_TOPIC] is None
)
self._optimistic_preset_mode = (
optimistic or self._topic[CONF_PRESET_MODE_STATE_TOPIC] is None
)
self._supported_features = 0
self._supported_features |= (
self._topic[CONF_OSCILLATION_COMMAND_TOPIC] is not None
and FanEntityFeature.OSCILLATE
)
if self._feature_percentage:
self._supported_features |= FanEntityFeature.SET_SPEED
if self._feature_preset_mode:
self._supported_features |= FanEntityFeature.PRESET_MODE
for key, tpl in self._command_templates.items():
self._command_templates[key] = MqttCommandTemplate(
tpl, entity=self
).async_render
for key, tpl in self._value_templates.items():
self._value_templates[key] = MqttValueTemplate(
tpl,
entity=self,
).async_render_with_possible_json_value
def _prepare_subscribe_topics(self):
"""(Re)Subscribe to topics."""
topics = {}
@callback
@log_messages(self.hass, self.entity_id)
def state_received(msg):
"""Handle new received MQTT message."""
payload = self._value_templates[CONF_STATE](msg.payload)
if not payload:
_LOGGER.debug("Ignoring empty state from '%s'", msg.topic)
return
if payload == self._payload["STATE_ON"]:
self._state = True
elif payload == self._payload["STATE_OFF"]:
self._state = False
elif payload == PAYLOAD_NONE:
self._state = None
self.async_write_ha_state()
if self._topic[CONF_STATE_TOPIC] is not None:
topics[CONF_STATE_TOPIC] = {
"topic": self._topic[CONF_STATE_TOPIC],
"msg_callback": state_received,
"qos": self._config[CONF_QOS],
"encoding": self._config[CONF_ENCODING] or None,
}
@callback
@log_messages(self.hass, self.entity_id)
def percentage_received(msg):
"""Handle new received MQTT message for the percentage."""
rendered_percentage_payload = self._value_templates[ATTR_PERCENTAGE](
msg.payload
)
if not rendered_percentage_payload:
_LOGGER.debug("Ignoring empty speed from '%s'", msg.topic)
return
if rendered_percentage_payload == self._payload["PERCENTAGE_RESET"]:
self._percentage = None
self.async_write_ha_state()
return
try:
percentage = ranged_value_to_percentage(
self._speed_range, int(rendered_percentage_payload)
)
except ValueError:
_LOGGER.warning(
"'%s' received on topic %s. '%s' is not a valid speed within the speed range",
msg.payload,
msg.topic,
rendered_percentage_payload,
)
return
if percentage < 0 or percentage > 100:
_LOGGER.warning(
"'%s' received on topic %s. '%s' is not a valid speed within the speed range",
msg.payload,
msg.topic,
rendered_percentage_payload,
)
return
self._percentage = percentage
self.async_write_ha_state()
if self._topic[CONF_PERCENTAGE_STATE_TOPIC] is not None:
topics[CONF_PERCENTAGE_STATE_TOPIC] = {
"topic": self._topic[CONF_PERCENTAGE_STATE_TOPIC],
"msg_callback": percentage_received,
"qos": self._config[CONF_QOS],
"encoding": self._config[CONF_ENCODING] or None,
}
self._percentage = None
@callback
@log_messages(self.hass, self.entity_id)
def preset_mode_received(msg):
"""Handle new received MQTT message for preset mode."""
preset_mode = self._value_templates[ATTR_PRESET_MODE](msg.payload)
if preset_mode == self._payload["PRESET_MODE_RESET"]:
self._preset_mode = None
self.async_write_ha_state()
return
if not preset_mode:
_LOGGER.debug("Ignoring empty preset_mode from '%s'", msg.topic)
return
if preset_mode not in self.preset_modes:
_LOGGER.warning(
"'%s' received on topic %s. '%s' is not a valid preset mode",
msg.payload,
msg.topic,
preset_mode,
)
return
self._preset_mode = preset_mode
self.async_write_ha_state()
if self._topic[CONF_PRESET_MODE_STATE_TOPIC] is not None:
topics[CONF_PRESET_MODE_STATE_TOPIC] = {
"topic": self._topic[CONF_PRESET_MODE_STATE_TOPIC],
"msg_callback": preset_mode_received,
"qos": self._config[CONF_QOS],
"encoding": self._config[CONF_ENCODING] or None,
}
self._preset_mode = None
@callback
@log_messages(self.hass, self.entity_id)
def oscillation_received(msg):
"""Handle new received MQTT message for the oscillation."""
payload = self._value_templates[ATTR_OSCILLATING](msg.payload)
if not payload:
_LOGGER.debug("Ignoring empty oscillation from '%s'", msg.topic)
return
if payload == self._payload["OSCILLATE_ON_PAYLOAD"]:
self._oscillation = True
elif payload == self._payload["OSCILLATE_OFF_PAYLOAD"]:
self._oscillation = False
self.async_write_ha_state()
if self._topic[CONF_OSCILLATION_STATE_TOPIC] is not None:
topics[CONF_OSCILLATION_STATE_TOPIC] = {
"topic": self._topic[CONF_OSCILLATION_STATE_TOPIC],
"msg_callback": oscillation_received,
"qos": self._config[CONF_QOS],
"encoding": self._config[CONF_ENCODING] or None,
}
self._oscillation = False
self._sub_state = subscription.async_prepare_subscribe_topics(
self.hass, self._sub_state, topics
)
async def _subscribe_topics(self):
"""(Re)Subscribe to topics."""
await subscription.async_subscribe_topics(self.hass, self._sub_state)
@property
def assumed_state(self):
"""Return true if we do optimistic updates."""
return self._optimistic
@property
def is_on(self) -> bool | None:
"""Return true if device is on."""
return self._state
@property
def percentage(self):
"""Return the current percentage."""
return self._percentage
@property
def preset_mode(self):
"""Return the current preset _mode."""
return self._preset_mode
@property
def preset_modes(self) -> list:
"""Get the list of available preset modes."""
return self._preset_modes
@property
def supported_features(self) -> int:
"""Flag supported features."""
return self._supported_features
@property
def speed_count(self) -> int:
|
@property
def oscillating(self):
"""Return the oscillation state."""
return self._oscillation
# The speed attribute deprecated in the schema, support will be removed after a quarter (2021.7)
async def async_turn_on(
self,
percentage: int = None,
preset_mode: str = None,
**kwargs,
) -> None:
"""Turn on the entity.
This method is a coroutine.
"""
mqtt_payload = self._command_templates[CONF_STATE](self._payload["STATE_ON"])
await self.async_publish(
self._topic[CONF_COMMAND_TOPIC],
mqtt_payload,
self._config[CONF_QOS],
self._config[CONF_RETAIN],
self._config[CONF_ENCODING],
)
if percentage:
await self.async_set_percentage(percentage)
if preset_mode:
await self.async_set_preset_mode(preset_mode)
if self._optimistic:
self._state = True
self.async_write_ha_state()
async def async_turn_off(self, **kwargs) -> None:
"""Turn off the entity.
This method is a coroutine.
"""
mqtt_payload = self._command_templates[CONF_STATE](self._payload["STATE_OFF"])
await self.async_publish(
self._topic[CONF_COMMAND_TOPIC],
mqtt_payload,
self._config[CONF_QOS],
self._config[CONF_RETAIN],
self._config[CONF_ENCODING],
)
if self._optimistic:
self._state = False
self.async_write_ha_state()
async def async_set_percentage(self, percentage: int) -> None:
"""Set the percentage of the fan.
This method is a coroutine.
"""
percentage_payload = math.ceil(
percentage_to_ranged_value(self._speed_range, percentage)
)
mqtt_payload = self._command_templates[ATTR_PERCENTAGE](percentage_payload)
await self.async_publish(
self._topic[CONF_PERCENTAGE_COMMAND_TOPIC],
mqtt_payload,
self._config[CONF_QOS],
self._config[CONF_RETAIN],
self._config[CONF_ENCODING],
)
if self._optimistic_percentage:
self._percentage = percentage
self.async_write_ha_state()
async def async_set_preset_mode(self, preset_mode: str) -> None:
"""Set the preset mode of the fan.
This method is a coroutine.
"""
self._valid_preset_mode_or_raise(preset_mode)
mqtt_payload = self._command_templates[ATTR_PRESET_MODE](preset_mode)
await self.async_publish(
self._topic[CONF_PRESET_MODE_COMMAND_TOPIC],
mqtt_payload,
self._config[CONF_QOS],
self._config[CONF_RETAIN],
self._config[CONF_ENCODING],
)
if self._optimistic_preset_mode:
self._preset_mode = preset_mode
self.async_write_ha_state()
async def async_oscillate(self, oscillating: bool) -> None:
"""Set oscillation.
This method is a coroutine.
"""
if oscillating:
mqtt_payload = self._command_templates[ATTR_OSCILLATING](
self._payload["OSCILLATE_ON_PAYLOAD"]
)
else:
mqtt_payload = self._command_templates[ATTR_OSCILLATING](
self._payload["OSCILLATE_OFF_PAYLOAD"]
)
await self.async_publish(
self._topic[CONF_OSCILLATION_COMMAND_TOPIC],
mqtt_payload,
self._config[CONF_QOS],
self._config[CONF_RETAIN],
self._config[CONF_ENCODING],
)
if self._optimistic_oscillation:
self._oscillation = oscillating
self.async_write_ha_state()
| """Return the number of speeds the fan supports."""
return self._speed_count |
core.py | from bz2 import BZ2File
from collections import Counter, Sequence, Iterable, \
Mapping
from functools import partial
import gc
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email import encoders
from inspect import signature, getattr_static, ismethod, getmembers, getmodule
from itertools import chain
import json
from multiprocessing import Pool
import os
from pathlib import Path
import pickle
from random import choice
import re
import smtplib
from subprocess import run, check_output
import sys
import time
from tqdm.auto import tqdm
import wordninja as wn
from htools.config import get_credentials, get_default_user
class InvalidArgumentError(Exception):
pass
def hdir(obj, magics=False, internals=False):
"""Print object methods and attributes, by default excluding magic methods.
Parameters
-----------
obj: any type
The object to print methods and attributes for.
magics: bool
Specifies whether to include magic methods (e.g. __name__, __hash__).
Default False.
internals: bool
Specifies whether to include internal methods (e.g. _dfs, _name).
Default False.
Returns
--------
dict
Keys are method/attribute names, values are strings specifying whether
the corresponding key is a 'method' or an 'attr'.
"""
output = dict()
for attr in dir(obj):
# Exclude magics or internals if specified.
if (not magics and attr.startswith('__')) or \
(not internals and re.match('_[^_]', attr)):
continue
# Handle rare case where attr can't be invoked (e.g. df.sparse on a
# non-sparse Pandas dataframe).
try:
is_method = callable(getattr(obj, attr))
except Exception:
continue
# Update output to specify whether attr is callable.
if is_method:
output[attr] = 'method'
else:
output[attr] = 'attribute'
return output
def tdir(obj, **kwargs):
"""A variation of the built in `dir` function that shows the
attribute names as well as their types. Methods are excluded as they can
change the object's state.
Parameters
----------
obj: any type
The object to examine.
kwargs: bool
Additional arguments to be passed to hdir. Options are `magics` and
`internals`. See hdir documentation for more information.
Returns
-------
dict[str, type]: Dictionary mapping the name of the object's attributes to
the corresponding types of those attributes.
"""
return {k: type(getattr(obj, k))
for k, v in hdir(obj, **kwargs).items() if v == 'attribute'}
def hasarg(func, arg):
"""Checks if a function has a given argument. Works with args and kwargs as
well if you exclude the stars. See example below.
Parameters
----------
func: function
arg: str
Name of argument to look for.
Returns
-------
bool
Example
-------
def foo(a, b=6, *args):
return
>>> hasarg(foo, 'b')
True
>>> hasarg(foo, 'args')
True
>>> hasarg(foo, 'c')
False
"""
return arg in signature(func).parameters
def quickmail(subject, message, to_email, from_email=None, img_path=None,
img_name=None, verbose=True, password=None):
"""Send an email.
Parameters
-----------
from_email: str
Gmail address being used to send email.
to_email: str
Recipient's email.
subject: str
Subject line of email.
message: str
Body of email.
Returns
--------
None
"""
# Load email username. Error handling takes place in config functions.
from_email = from_email or get_default_user()
if not from_email: return None
# Load email password.
password = password or get_credentials(from_email)
if not password: return None
# Create message and add text if specified.
msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = from_email
msg['To'] = to_email
if message: msg.attach(MIMEText(message))
# Load and attach image.
if img_path:
with open(img_path, 'rb') as f:
img = MIMEImage(f.read(),
name=img_name or os.path.basename(img_path))
encoders.encode_base64(img)
msg.attach(img)
# Access server and send email.
server = smtplib.SMTP(host='smtp.gmail.com', port=587)
server.starttls()
server.login(user=from_email, password=password)
server.sendmail(from_email, to_email, msg.as_string())
if verbose: print(f'Email sent to {to_email}.')
def hsplit(text, sep, group=True, attach=True):
"""Flexible string splitting that retains the delimiter rather, unlike
the built-in str.split() method.
NOTE: I recently observed behavior suggesting separators with special
characters (e.g. "\n") may not work as expected for some settings. It
should work when group=True and attach=True though since I rewrote that
with new logic without the re module.
Parameters
-----------
text: str
The input text to be split.
sep: str
The delimiter to be split on.
group: bool
Specifies whether to group consecutive delimiters together (True),
or to separate them (False).
attach: bool
Specifies whether to attach the delimiter to the string that preceeds
it (True), or to detach it so it appears in the output list as its own
item (False).
Returns
--------
list[str]
Examples
---------
text = "Score -- Giants win 6-5"
sep = '-'
# Case 0.1: Delimiters are grouped together and attached to the preceding
word.
>> hsplit(text, sep, group=True, attach=True)
>> ['Score --', ' Giants win 6-', '5']
# Case 0.2: Delimiters are grouped together but are detached from the
preceding word, instead appearing as their own item in the output list.
>> hsplit(text, sep, group=True, attach=False)
>> ['Score ', '--', ' Giants win 6', '-', '5']
Case 1.1: Delimiters are retained and attached to the preceding string.
If the delimiter occurs multiple times consecutively, only the first
occurrence is attached, and the rest appear as individual items in the
output list.
>> hsplit(text, sep, group=False, attach=True)
>> ['Score -', '-', ' Giants win 6-', '5']
# Case 1.2: Delimiters are retained but are detached from the preceding
string. Each instance appears as its own item in the output list.
>> hsplit(text, sep, group=False, attach=False)
>> ['Score ', '-', '-', ' Giants win 6', '-', '5']
"""
sep_re = re.escape(sep)
regex = f'[^{sep_re}]*{sep_re}*'
##########################################################################
# Case 0: Consecutive delimiters are grouped together.
##########################################################################
if group:
# Subcase 0.1
if attach:
return _grouped_split(text, sep)
# Subcase 0.2
else:
return [word for word in re.split(f'({sep_re}+)', text) if word]
##########################################################################
# Case 1: Consecutive delimiters are NOT grouped together.
##########################################################################
words = text.split(sep)
# Subcase 1.1
if attach:
return [word for word in re.findall(regex[:-1]+'?', text) if word]
# Subcase 1.2
return [word for word in chain(*zip(words, [sep]*len(words))) if word][:-1]
def _grouped_split(text, sep):
"""Hsplit helper for case where group=True and attach=True (see hsplit
docs). Old re.find() method didn't work right when sep had special
characters (e.g. "\n").
"""
res = []
toks = text.split(sep)
max_idx = len(toks) - 1
for i, tok in enumerate(toks):
if tok:
if i < max_idx: tok += sep
res.append(tok)
elif i < max_idx:
if res:
res[-1] += sep
else:
res.append(sep)
return res
def rmvars(*args):
"""Wrapper to quickly free up memory by deleting global variables. Htools
3.0 does not provide a way to do this for local variables.
Parameters
----------
args: str
One or more variable names to delete. Do not pass in the variable
itself.
Returns
-------
None
"""
for arg in args:
del globals()[arg]
gc.collect()
def print_object_sizes(space, limit=None, exclude_underscore=True):
"""Print the object names and sizes of the currently defined objects.
Parameters
-----------
space: dict
locals(), globals(), or vars()
limit: int or None
Optionally limit the number of objects displayed (default None for no
limit).
exclude_underscore: bool
Determine whether to exclude objects whose names start with an
underscore (default True).
"""
var_size = [(var, sys.getsizeof(obj)) for var, obj in space.items()]
for var, size in sorted(var_size, key=lambda x: -x[1])[:limit]:
if not var.startswith('_') or not exclude_underscore:
print(var, size)
def eprint(arr, indent=2, spacing=1):
"""Enumerated print. Prints an iterable with one item per line accompanied
by a number specifying its index in the iterable.
Parameters
-----------
arr: iterable
The object to be iterated over.
indent: int
Width to assign to column of integer indices. Default is 2, meaning
columns will line up as long as <100 items are being printed, which is
the expected use case.
spacing: int
Line spacing. Default of 1 will print each item on a new line with no
blank lines in between. Spacing of 2 will double space output, and so
on for larger values.
Returns
--------
None
"""
for i, x in enumerate(arr):
print(f'{i:>{indent}}: {x}', end='\n'*spacing)
def _read_write_args(path, mode):
"""Helper for `save` and `load` functions.
Parameters
----------
path: str
Path to read/write object from/to.
mode: str
'w' for writing files (as in `save`), 'r' for reading files
(as in `load`).
Returns
-------
tuple: Function to open file, mode to open file with (str), object to open
file with.
"""
ext = path.rpartition('.')[-1]
if ext not in {'json', 'pkl', 'zip'}:
raise InvalidArgumentError(
'Invalid extension. Make sure your filename ends with '
'.json, .pkl, or .zip.'
)
# Store in dict to make it easier to add additional formats in future.
ext2data = {
'json': (open, '', json),
'pkl': (open, 'b', pickle),
'zip': (BZ2File, '', pickle),
}
opener, mode_suffix, saver = ext2data[ext]
return opener, mode + mode_suffix, saver
def save(obj, path, mode_pre='w', verbose=True):
"""Wrapper to save data as text, pickle (optionally zipped), or json.
Parameters
-----------
obj: any
Object to save. This will be pickled/jsonified/zipped inside the
function - do not convert it before-hand.
path: str
File name to save object to. Should end with .txt, .sh, md, .pkl, .zip,
or .json depending on desired output format. If .zip is used, object
will be zipped and then pickled. (.sh and .md will be treated
identically to .txt.)
mode_pre: str
Determines whether to write or append text. One of ('w', 'a').
verbose: bool
If True, print a message confirming that the data was pickled, along
with its path.
Returns
-------
None
"""
path = Path(path)
os.makedirs(path.parent, exist_ok=True)
if verbose: print(f'Writing data to {path}.')
if path.suffix[1:] in ('txt', 'sh', 'md', 'py'):
with path.open(mode_pre) as f:
f.write(obj)
else:
opener, mode, saver = _read_write_args(str(path), mode_pre)
with opener(path, mode) as f:
saver.dump(obj, f)
def load(path, verbose=True):
"""Wrapper to load text files or pickled (optionally zipped) or json data.
Parameters
----------
path : str
File to load. File type will be inferred from extension. Must be one of
'.txt', '.sh', 'md', '.json', '.pkl', or '.zip'.
verbose : bool, optional
If True, will print message stating where object was loaded from.
Returns
-------
object: The Python object that was pickled to the specified file.
"""
path = Path(path)
if path.suffix[1:] in ('txt', 'sh', 'md', 'py'):
return path.read_text()
opener, mode, saver = _read_write_args(str(path), 'r')
with opener(path, mode) as f:
data = saver.load(f)
if verbose: print(f'Object loaded from {path}.')
return data
def dict_sum(*args):
"""Given two or more dictionaries with numeric values, combine them into a
single dictionary. For keys that appear in multiple dictionaries, their
corresponding values are added to produce the new value.
This differs from combining two dictionaries in the following manner:
{**d1, **d2}
The method shown above will combine the keys but will retain the value
from d2, rather than adding the values from d1 and d2.
Parameters
-----------
*args: dicts
2 or more dictionaries with numeric values.
Returns
--------
dict: Contains all keys which appear in any of the dictionaries that are | ---------
>>> d1 = {'a': 1, 'b': 2, 'c': 3}
>>> d2 = {'a': 10, 'c': -20, 'd': 30}
>>> d3 = {'c': 10, 'd': 5, 'e': 0}
>>> dict_sum(d1, d2)
{'a': 11, 'b': 2, 'c': -7, 'd': 35, 'e': 0}
"""
keys = {key for d in args for key in d.keys()}
return {key: sum(d.get(key, 0) for d in args)
for key in keys}
def _select_mapping(items, keep=(), drop=()):
"""Helper function for `select`.
Parameters
----------
items: Mapping
Dict (or similar mapping) to select/drop from.
keep: Iterable[str]
Sequence of keys to keep.
drop: Iterable[str]
Sequence of keys to drop. You should specify either `keep` or `drop`,
not both.
Returns
-------
Dict
"""
if keep:
return {k: items[k] for k in keep}
return {k: v for k, v in items.items() if k not in set(drop)}
def _select_sequence(items, keep=(), drop=()):
"""Helper function for `select` that works on sequences (basically
collections that support enumeration).
Parameters
----------
items: Sequence
List, tuple, or iterable sequence of some sort to select items from.
keep: Iterable[str]
Sequence of indices to keep.
drop: Iterable[str]
Sequence of indices to drop. You should specify either `keep` or
`drop`, not both.
Returns
-------
Same type as `items` (usually a list or tuple).
"""
type_ = type(items)
if keep:
return type_(x for i, x in enumerate(items) if i in set(keep))
return type_(x for i, x in enumerate(items) if i not in set(drop))
def select(items, keep=(), drop=()):
"""Select a subset of a data structure. When used on a mapping (e.g. dict),
you can specify a list of keys to include or exclude. When used on a
sequence like a list or tuple, specify indices instead of keys.
Parameters
----------
items: abc.Sequence or abc.Mapping
The dictionary to select items from.
keep: Iterable[str]
Sequence of keys to keep.
drop: Iterable[str]
Sequence of keys to drop. You should specify either `keep` or `drop`,
not both.
Returns
-------
dict: Dictionary containing only the specified keys (when passing in
`keep`), or all keys except the specified ones (when passing in
`drop`).
"""
if bool(keep) + bool(drop) != 1:
raise InvalidArgumentError('Specify exactly one of `keep` or `drop`.')
if isinstance(items, Mapping):
return _select_mapping(items, keep, drop)
elif isinstance(items, Sequence):
return _select_sequence(items, keep, drop)
else:
raise InvalidArgumentError('`items` must be a Mapping or Sequence.')
def differences(obj1, obj2, methods=False, **kwargs):
"""Find the differences between two objects (generally of the same type -
technically this isn't enforced but we do require that the objects have
the same set of attribute names so a similar effect is achieved. Actual
type checking was causing problems comparing multiple Args instances,
presumably because each Args object is defined when called).
This is a way to get more detail beyond whether two objects are equal or
not.
Parameters
-----------
obj1: any
An object.
obj2: any, usually the same type as obj1
An object.
methods: bool
If True, include methods in the comparison. If False, only attributes
will be compared. Note that the output may not be particularly
interpretable when using method=True; for instance when comparing two
strings consisting of different characters, we get a lot of output
that looks like this:
{'islower': (<function str.islower()>, <function str.islower()>),
'isupper': (<function str.isupper()>, <function str.isupper()>),...
'istitle': (<function str.istitle()>, <function str.istitle()>)}
These attributes all reflect the same difference: if obj1 is 'abc'
and obj2 is 'def', then
'abc' != 'def' and
'ABC' != 'DEF' abd
'Abc' != 'Def'.
When method=False, we ignore all of these, such that
differences('a', 'b') returns {}. Therefore, it is important to
carefully consider what differences you care about identifying.
**kwargs: bool
Can pass args to hdir to include magics or internals.
Returns
--------
dict[str, tuple]: Maps attribute name to a tuple of values, where the
first is the corresponding value for obj1 and the second is the
corresponding value for obj2.
"""
# May built-in comparison functionality. Keep error handling broad.
try:
if obj1 == obj2:
return {}
except Exception:
pass
attr1, attr2 = hdir(obj1, **kwargs), hdir(obj2, **kwargs)
assert attr1.keys() == attr2.keys(), 'Objects must have same attributes.'
diffs = {}
for (k1, v1), (k2, v2) in zip(attr1.items(), attr2.items()):
# Only compare non-callable attributes.
if not (methods or v1 == 'attribute'):
continue
# Comparisons work differently for arrays/tensors than other objects.
val1, val2 = getattr(obj1, k1), getattr(obj2, k2)
try:
equal = (val1 == val2).all()
except AttributeError:
equal = val1 == val2
# Store values that are different for obj1 and obj2.
if not equal:
diffs[k1] = (val1, val2)
return diffs
def catch(func, *args, verbose=False):
"""Error handling for list comprehensions. In practice, it's recommended
to use the higher-level robust_comp() function which uses catch() under the
hood.
Parameters
-----------
func: function
*args: any type
Arguments to be passed to func.
verbose: bool
If True, print the error message should one occur.
Returns
--------
any type: If the function executes successfully, its output is returned.
Otherwise, return None.
Examples
---------
[catch(lambda x: 1 / x, i) for i in range(3)]
>>> [None, 1.0, 0.5]
# Note that the filtering method shown below also removes zeros which is
# okay in this case.
list(filter(None, [catch(lambda x: 1 / x, i) for i in range(3)]))
>>> [1.0, 0.5]
"""
try:
return func(*args)
except Exception as e:
if verbose: print(e)
return
def safe_map(func, seq):
"""This addresses the issue of error handling in map() or list
comprehension operations by simply skipping any items that throw an error.
Note that values of None will be removed from the resulting list.
Parameters
----------
func: function
Function to apply to each item in seq.
seq: generator, iterator
The sequence to iterate over. This could also be a generator, list,
set, etc.
Returns
-------
list
Examples
--------
# Notice that instead of throwing an error when dividing by zero, that
# entry was simply dropped.
>>> safe_map(lambda x: x/(x-2), range(4))
[-0.0, -1.0, 3.0]
"""
return list(
filter(lambda x: x is not None, (catch(func, obj) for obj in seq))
)
def flatten(nested):
"""Flatten a nested sequence where the sub-items can be sequences or
primitives. This differs slightly from itertools chain methods because
those require all sub-items to be sequences. Here, items can be primitives,
sequences, nested sequences, or any combination of these. Any iterable
items aside from strings will be completely un-nested, so use with caution
(e.g. a torch Dataset would be unpacked into separate items for each
index). This also returns a list rather than a generator.
Parameters
----------
nested: sequence (list, tuple, set)
Sequence where some or all of the items are also sequences.
Returns
-------
list: Flattened version of `nested`.
"""
def _walk(nested):
for group in nested:
if isinstance(group, Iterable) and not isinstance(group, str):
yield from _walk(group)
else:
yield group
return list(_walk(nested))
class BasicPipeline:
"""Create a simple unidirectional pipeline of functions to apply in order
with optional debugging output.
"""
def __init__(self, *funcs):
"""
Parameters
----------
*funcs: function(s)
One or more functions to apply in the specified order.
"""
# Make `funcs` mutable. Could use @htools.meta.delegate('funcs')
# but not sure if that would cause circular import issues. Check later.
self.funcs = list(funcs)
def __call__(self, x, verbose=False, attr=''):
"""Apply the pipeline of functions to x.
Parameters
----------
x: any
Object to operate on.
verbose: bool
If True, print x (or an attribute of x) after each step.
attr: str
If specified and verbose is True, will print this attribute of x
after each function is applied.
Returns
-------
output of last func in self.funcs
"""
for func in self.funcs:
x = func(x)
if verbose: print(repr(getattr(x, attr, x)))
return x
def __repr__(self):
# Try to display each item in the form that was likely passed in: for
# functions, this is the name, but for callable classes this is
# the str representation of the object, not the class itself.
names = ',\n\t'.join(str(f) if hasattr(f, '__call__') else func_name(f)
for f in self.funcs)
return f'{type(self).__name__}(\n\t{names}\n)'
def pipe(x, *funcs, verbose=False, attr=''):
"""Convenience function to apply many functions in order to some object.
This lets us replace messy notation where it's hard to keep parenthesis
straight:
list(parse_processed_text(tokenize_rows(porter_stem(strip_html_tags(
text)))))
with:
pipe(text, strip_html_tags, porter_stem, tokenize_rows,
parse_processed_text, list)
or if we have a list of functions:
pipe(x, *funcs)
Parameters
----------
x: any
Object to apply functions to.
*funcs: function(s)
Functions in the order you want to apply them. Use functools.partial
to specify other arguments.
verbose: bool
If True, print x (or an attribute of x) after each step.
attr: str
If specified and verbose is True, will print this attribute of x
after each function is applied.
Returns
-------
output of last func in *funcs
"""
return BasicPipeline(*funcs)(x, verbose=verbose, attr=attr)
def vcounts(arr, normalize=True):
"""Equivalent of pandas_htools vcounts method that we can apply on lists
or arrays. Basically just a wrapper around Counter but with optional
normalization.
Parameters
----------
arr: Iterable
Sequence of values to count. Typically a list or numpy array.
normalize: bool
If True, counts will be converted to percentages.
Returns
-------
dict: Maps unique items in `arr` to the number of times (or % of times)
that they occur in `arr`.
"""
counts = dict(Counter(arr))
if normalize:
length = len(arr)
counts = {k: v/length for k, v in counts.items()}
return counts
def item(it, random=True, try_values=True):
"""Get an item from an iterable (e.g. dict, set, torch DataLoader).
This is a quick way to access an item for iterables that don't support
indexing, or do support indexing but require us to know a key.
Parameters
----------
it: Iterable
Container that we want to access a value from.
random: bool
If True, pick a random value from `it`. Otherwise just return the first
value.
try_values: bool
If True, will check if `it` has a `values` attribute and will operate
on that if it does. We often want to see a random value from a dict
rather than a key. If we want both a key and value, we could set
try_values=False and pass in d.items().
Returns
-------
any: An item from the iterable.
"""
if try_values and hasattr(it, 'values'): it = it.values()
if random: return choice(list(it))
return next(iter(it))
def lmap(fn, *args):
"""Basically a wrapper for `map` that returns a list rather than a
generator. This is such a common pattern that I think it deserves its own
function (think of it as a concise alternative to a list comprehension).
One slight difference is that we use *args instead of passing in an
iterable. This adds a slight convenience for the intended use case (fast
prototyping). See the `Examples` for more on this.
Parameters
----------
args: any
Returns
-------
list
Examples
--------
Consider these three equivalent syntax options:
lmap(fn, x, y)
[fn(obj) for obj in (x, y)]
list(map(fn, (x, y))
When quickly iterating, option 1 saves a bit of typing. The extra
parentheses that options 2 and 3 require to put x and y in a temporary
data structure can get messy as we add more complex logic.
"""
return list(map(fn, args))
def amap(attr, *args):
"""More convenient syntax for quick data exploration. Get an attribute
value for multiple objects. Name is short for "attrmap".
Parameters
----------
attr: str
Name of attribute to retrieve for each object.
args: any
Objects (usually of same type) to retrieve attributes for.
Returns
-------
list: Result for each object.
Examples
--------
df1 = pd.DataFrame(np.random.randint(0, 10, (4, 5)))
df2 = pd.DataFrame(np.random.randint(0, 3, (4, 5)))
df3 = pd.DataFrame(np.random.randint(0, 3, (2, 3)))
>>> amap('shape', df1, df2, df3)
[(4, 5), (4, 5), (2, 3)]
net = nn.Sequential(...)
>>> amap('shape', *net.parameters())
[torch.Size([5, 3]),
torch.Size([16, 4]),
torch.Size([16, 3]),
torch.Size([16])]
"""
return [getattr(arg, attr) for arg in args]
def smap(*x):
"""Get shape of each array/tensor in a list or tuple.
Parameters
----------
*x: np.arrays or torch.tensors
We use star unpacking here to create a consistent interface with amap()
and lmap().
Returns
-------
list: Shape of each array/tensor in input.
"""
return amap('shape', *x)
def sleepy_range(*args, wait=1, wait_before=True):
"""Convenience function: we often want to create a loop that mimics doing
some time intensive thing on each iteration. This is just like the built-in
range function (not technically a function!) but with a sleep period baked
in, making it particularly useful for list comprehensions where this would
be tricky otherwise. Note: unlike range, calling this is destructive.
See examples.
Parameters
----------
args: int
Passed on to range().
wait: int or float
Number of seconds to wait on each iteration. Remember this is a keyword
only argument for compatibility with the range interface.
wait_before: bool
Determines whether to sleep before or after yielding the number.
Defaults to before to mimic "doing work" before producing some result.
Examples
--------
# Takes 6 seconds to create this list.
>>> [i for i in sleepy_range(3, wait=2)]
[0, 1, 2]
>>> srange = sleepy_range(0, 6, 2, wait_before=False)
>>> for i in srange:
>>> print(i)
0
2
4
>>> for i in srange:
>>> print(i)
# Notice this cannot be used again without manually calling sleepy_range.
"""
for i in range(*args):
if wait_before: time.sleep(wait)
yield i
if not wait_before: time.sleep(wait)
def venumerate(iterable, start=0, freq=1, print_before=True,
message_format='{}'):
"""Verbose enumerate: simple convenience function that's a drop-in
replacement for enumerate. It prints updates as we iterate over some
object. TQDM progress bar may not be available in some cases (e.g. we
don't know the length of the interval, or possible some cases using
concurrency?), and this function gives us some way to keep an eye on
progress. Mainly intended as a convenience for list comprehensions, since
in a standard for loop we could easily add this logic.
Parameters
----------
iterable: Iterable
The object to iterate over.
start: int
Passed on to enumerate - the first index to use when counting.
freq: int
Frequency with which to print updates (i.e. updates are printed when
i is divisible by freq).
print_before: bool
Specifies whether to print the message before yielding the i'th value
or after.
message_format: str
Used to format the message that will be displayed when i is divisible
by freq. Defaults to just printing i.
"""
for i, x in enumerate(iterable, start=start):
if i % freq == 0 and print_before: print(message_format.format(i))
yield i, x
if i % freq == 0 and not print_before: print(message_format.format(i))
def method_of(meth):
"""Retrieve the class a method belongs to. This will NOT work on
attributes. Also, this won't help if your goal is to retrieve an instance:
this returns the type of the instance. Not thoroughly tested but it seems
to work regardless of whether you pass in meth from an instance or a class
(the output is the same in both cases).
Parameters
----------
meth: MethodType
The method to retrieve the class of.
Returns
-------
type: The class which defines the method in question.
Examples
--------
class Foo:
def my_method(self, x):
return x*2
f = Foo()
assert method_of(Foo.my_method) == method_of(f.my_method) == Foo
"""
cls, name = meth.__qualname__.split('.')
return dict(getmembers(getmodule(meth)))[cls]
def hasstatic(cls, meth_name):
"""Check if a class possesses a staticmethod of a given name. Similar to
hasattr. Note that isinstance(cls.meth_name, staticmethod) would always
return False: we must use getattr_static or cls.__dict__[meth_name]
to potentially return True.
Parameters
----------
cls: Type or any
A class or an instance (seems to work on both, though more extensive
testing may be needed for more complex scenarios).
meth_name: str
Name of method to check. If the class/instance does not contain any
attribute with this name, function returns False.
Returns
-------
bool: True if `cls` has a staticmethod with name `meth_name`.
"""
return isinstance(getattr_static(cls, meth_name, None), staticmethod)
def isstatic(meth):
"""Companion to hasstatic that checks a method itself rather than a class
and method name. It does use hasstatic under the hood.
"""
# First check isn't required but I want to avoid reaching the hackier bits
# of code if necessary. This catches regular methods and attributes.
if ismethod(meth) or not callable(meth): return False
parts = getattr(meth, '__qualname__', '').split('.')
if len(parts) != 2: return False
cls = method_of(meth)
return hasstatic(cls, parts[-1])
def has_classmethod(cls, meth_name):
"""Check if a class has a classmethod with a given name.
Note that isinstance(cls.meth_name, classmethod) would always
return False: we must use getattr_static or cls.__dict__[meth_name]
to potentially return True.
Parameters
----------
cls: type or obj
This is generally intended to be a class but it should work on objects
(class instances) as well.
meth_name: str
The name of the potential classmethod to check for.
Returns
-------
bool: True if cls possesses a classmethod with the specified name.
"""
return isinstance(getattr_static(cls, meth_name), classmethod)
def is_classmethod(meth):
"""Companion to has_classmethod that checks a method itself rather than a
class and a method name. It does use has_classmethod under the hood.
"""
if not ismethod(meth): return False
parts = getattr(meth, '__qualname__', '').split('.')
if len(parts) != 2: return False
cls = method_of(meth)
return has_classmethod(cls, parts[-1])
def parallelize(func, items, total=None, chunksize=1_000, processes=None):
"""Apply a function to a sequence of items in parallel. A progress bar
is included.
Parameters
----------
func: function
This will be applied to each item in `items`.
items: Iterable
Sequence of items to apply `func` to.
total: int or None
This defaults to the length of `items`. In the case that items is a
generator, this lets us pass in the length explicitly. This lets tdqm
know how quickly to advance our progress bar.
chunksize: int
Positive int that determines the size of chunks submitted to the
process pool as separate tasks. Multiprocessing's default is 1 but
larger values should speed things up, especially with long sequences.
processes: None
Optionally set number of processes to run in parallel.
Returns
-------
list
"""
total = total or len(items)
with Pool(processes) as p:
res = list(tqdm(p.imap(func, items, chunksize=chunksize),
total=total))
return res
def identity(x):
"""Returns the input argument. Sometimes it is convenient to have this if
we sometimes apply a function to an item: rather than defining a None
variable, sometimes setting it to a function, then checking if it's None
every time we're about to call it, we can set the default as identity and
safely call it without checking.
Parameters
----------
x: any
Returns
-------
x: Unchanged input.
"""
return x
def always_true(x, *args, **kwargs):
"""Similar to `identity` but returns True instead of x. I'm tempted to name
this `true` but I fear that will cause some horrible bugs where I
accidentally use this when I want to use True.
"""
return True
def ifnone(arg, backup):
"""Shortcut to provide a backup value if an argument is None. Commonly used
for numpy arrays since their truthiness is ambiguous.
Parameters
----------
arg: any
We will check if this is None.
backup: any
This will be returned if arg is None.
Returns
-------
Either `arg` or `backup` will be returned.
"""
return arg if arg is not None else backup
def listlike(x):
"""Checks if an object is a list/tuple/set/array etc. Strings and
mappings (e.g. dicts) are not considered list-like.
"""
return isinstance(x, Iterable) and not isinstance(x, (str, Mapping))
def tolist(x, length_like=None, length=None,
error_message='x length does not match desired length.'):
"""Helper to let a function accept a single value or a list of values for
a certain parameter.
WARNING: if x is a primitive and you specify a length (either via
`length_like` or `length`, the resulting list will contain multiple
references to the same item). This is mostly intended for use on lists of
floats or ints so I don't think it's a problem, but keep this in mind when
considering using this on mutable objects.
Parameters
----------
x: Iterable
Usually either a list/tuple or a primitive.
length_like: None or object
If provided, we check that x is the same length. If x is a primitive,
we'll make it the same length.
length: None or int
Similar to `length_like` but lets us specify the desired length
directly. `length_like` overrides this, though you should only provide
one or the other.
error_message: str
Displayed in the event that a desired length is specified and x is
list-like and does not match that length. You can pass in your own
error message if you want something more specific to your current use
case.
Returns
-------
list
Examples
--------
def train(lrs):
lrs = tolist(lrs)
...
We can now pass in a single learning rate or multiple.
>>> train(3e-3)
>>> train([3e-4, 3e-3])
"""
if length_like is not None: length = len(length_like)
# Case 1. List-like x
if listlike(x):
if length:
assert len(x) == length, error_message
return list(x)
# Case 2. Dict-like x
if isinstance(x, Mapping):
raise ValueError('x must not be a mapping. It should probably be a '
'primitive (str, int, etc.) or a list-like object '
'(tuple, list, set).')
# Case 3. Primitive x
return [x] * (length or 1)
def xor_none(*args, n=1):
"""Checks that exactly 1 (or n) of inputs is not None. Useful for
validating optional function arguments (for example, ensuring the user
specifies either a directory name or a list of files but not both.
Parameters
----------
args: any
n: int
The desired number of non-None elements. Usually 1 but we allow the
user to specify other values.
Returns
-------
None: This will raise an error if the condition is not satisfied. Do not
use this as an if condition (e.g. `if xor_none(a, b): print('success')`.
This would always evaluate to False because the function doesn't explicitly
return a value so we get None.
"""
if sum(bool(arg is not None) for arg in args) != n:
raise ValueError(f'Exactly {n} or args must be not None.')
def max_key(d, fn=identity):
"""Find the maximum value in a dictionary and return the associated key.
If we want to compare values using something other than their numeric
values, we can specify a function. For example, with a dict mapping strings
to strings, fn=len would return the key with the longest value.
Parameters
----------
d: dict
Values to select from.
fn: callable
Takes 1 argument (a single value from d.values()) and returns a number.
This will be used to sort the items.
Returns
-------
A key from dict `d`.
"""
return max(d.items(), key=lambda x: fn(x[1]))[0]
def is_builtin(x, drop_callables=True):
"""Check if an object is a Python built-in object.
Parameters
----------
x: object
drop_callables: bool
If True, return False for callables (basically functions, methods, or
classes). These typically will return True otherwise since they are of
class `type` or `builtin_function_or_method`.
Returns
-------
bool: True if `x` is a built-in object, False otherwise.
"""
def _builtin(x, drop_callables):
if callable(x) and drop_callables:
return False
return x.__class__.__module__ == 'builtins'
builtin = partial(_builtin, drop_callables=drop_callables)
# Check mapping first because mappings are iterable.
if isinstance(x, Mapping):
return builtin(x) and all(builtin(o) for o in flatten(x.items()))
elif isinstance(x, Iterable):
return builtin(x) and all(builtin(o) for o in flatten(x))
return builtin(x)
def hashable(x):
"""Check if an object is hashable. Hashable objects will usually be
immutable though this is not guaranteed.
Parameters
----------
x: object
The item to check for hashability.
Returns
-------
bool: True if `x` is hashable (suggesting immutability), False otherwise.
"""
try:
_ = hash(x)
return True
except TypeError:
return False
def fgrep(text, term, window=25, with_idx=False, reverse=False):
"""Search a string for a given term. If found, print it with some context.
Similar to `grep -C 1 term text`. `fgrep` is short for faux grep.
Parameters
----------
text: str
Text to search.
term: str
Term to look for in text.
window: int
Number of characters to display before and after the matching term.
with_idx: bool
If True, return index as well as string.
reverse: bool
If True, reverse search direction (find last match rather than first).
Returns
-------
str or tuple[int, str]: The desired term and its surrounding context.
If the term isn't present, an empty string is returned. If
with_idx=True, a tuple of (match index, string with text) is returned.
"""
idx = text.rfind(term) if reverse else text.find(term)
if idx == -1:
res = ''
else:
res = text[max(idx-window, 0):idx+window]
return (idx, res) if with_idx else res
def spacer(char='-', n_chars=79, newlines_before=1, newlines_after=1):
""" Get string to separate output when printing output for multiple items.
Parameters
----------
char: str
The character that will be printed repeatedly.
n_chars: int
The number of times to repeat `char`. We expect that `char` is a
single character so this will be the total line length.
newlines_before: int
Number of newline characters to add before the spacer.
newlines_after: int
Number of newline characters to add after the spacer.
Returns
-------
str
"""
return '\n'*newlines_before + char * n_chars + '\n'*newlines_after
def func_name(func):
"""Usually just returns the name of a function. The difference is this is
compatible with functools.partial, which otherwise makes __name__
inaccessible.
Parameters
----------
func: callable
Can be a function, partial, or callable class.
"""
assert callable(func), 'Input must be callable.'
try:
res = func.__name__
except AttributeError:
if isinstance(func, partial):
return func_name(func.func)
else:
return func.__class__.__name__
except Exception as e:
raise e
return res
def snake2camel(text):
"""Convert snake case to camel case. This assumes the input is valid snake
case (if you have some weird hybrid of snake and camel case, for instance,
you'd want to do some preprocessing first).
Parameters
----------
text: str
Snake case string, e.g. vader_sentiment_score.
Returns
-------
str: `text` converted to camel case, e.g. vaderSentimentScore.
"""
res = []
prev = ''
for char in text:
if char != '_':
# Check if res is empty because of case with leading underscore.
res.append(char.upper() if prev == '_' and res else char)
prev = char
return ''.join(res)
def camel2snake(text):
"""Convert camel case to snake case. This assumes the input is valid camel
case (if you have some weird hybrid of camel and snake case, for instance,
you'd want to do some preprocessing first).
Parameters
----------
text: str
Camel case string, e.g. vaderSentimentScore.
Returns
-------
str: `text` converted to snake case, e.g. vader_sentiment_score.
"""
res = []
for char in text:
if char.islower():
res.append(char)
else:
res.extend(['_', char.lower()])
return ''.join(res)
def to_snake(text):
"""Experimental feature: tries to convert any common format to snake case.
This hasn't been extensively tested but it seems to work with snake case
(no change), camel case, upper camel case, words separated by
hyphens/dashes/spaces, and combinations of the above. It may occasionally
split words that should not be split, though this should be rare if names
use actual English words (this might not work so well on fastai-style
variable names (very short, e.g. "tfms" for "transforms"), but the intended
use case is mostly for fixing column names in pandas.
Parameters
----------
text: str
Returns
-------
str: Input text converted to snake case.
"""
return '_'.join(wn.split(text.lower()))
def to_camel(text):
"""Experimental feature: tries to convert any common format to camel case.
This hasn't been extensively tested but it seems to work with camel case
(no change), snake case, upper camel case, words separated by
hyphens/dashes/spaces, and combinations of the above. It may occasionally
split words that should not be split, though this should be rare if names
use actual English words (this might not work so well on fastai-style
variable names (very short, e.g. "tfms" for "transforms"), but the intended
use case is mostly for fixing column names in pandas.
Parameters
----------
text: str
Returns
-------
str: Input text converted to snake case.
"""
return ''.join(w.title() if i > 0 else w
for i, w in enumerate(wn.split(text.lower())))
def kwargs_fallback(self, *args, assign=False, **kwargs):
"""Use inside a method that accepts **kwargs. Sometimes we want to use
an instance variable for some computation but want to give the user the
option to pass in a new value to the method (often ML hyperparameters) to
be used instead. This function makes that a little more convenient.
Parameters
----------
self: object
The class instance. In most cases users will literally pass `self` in.
args: str
One or more names of variables to use this procedure on.
assign: bool
If True, any user-provided kwargs will be used to update attributes of
the instance. If False (the default), they will be used in computation
but won't change the state of the instance.
kwargs: any
Just forward along the kwargs passed to the method.
Returns
-------
list or single object: If more than one arg is specified, a list of values
is returned. For just one arg, a single value will be returned.
Examples
--------
class Foo:
def __init__(self, a, b=3, c=('a', 'b', 'c')):
self.a, self.b, self.c = a, b, c
def walk(self, d, **kwargs):
a, c = kwargs_fallback(self, 'a', 'c', **kwargs)
print(self.a, self.b, self.c)
print(a, c, end='\n\n')
b, c = kwargs_fallback(self, 'b', 'c', assign=True, **kwargs)
print(self.a, self.b, self.c)
print(b, c)
# Notice the first `kwargs_fallback` call doesn't change attributes of f
# but the second does. In the first block of print statements, the variable
# `b` does not exist yet because we didn't include it in *args.
>>> f = Foo(1)
>>> f.walk(d=0, b=10, c=100)
1 3 ('a', 'b', 'c')
1 100
1 10 100
10 100
"""
res = []
for arg in args:
# Don't just use `kwargs.get(arg) or ...` because this doesn't work
# well when we pass in a numpy array or None.
val = kwargs[arg] if arg in kwargs else getattr(self, arg)
res.append(val)
if assign: setattr(self, arg, val)
return res if len(res) > 1 else res[0]
def cd_root(root_subdir='notebooks', max_depth=4):
"""Run at start of Jupyter notebook to enter project root.
Parameters
----------
root_subdir: str
Name of a subdirectory contained in the project root directory.
If not found in the current working directory, this will move
to the parent directory repeatedly until it is found. Choose carefully:
if you have multiple directories with the same name in your directory
structure (e.g. ~/htools/lib/htools), 'htools' would be a bad choice
if you want to end up in ~).
max_depth: int
Max number of directory levels to traverse. Don't want to get stuck in
an infinite loop if we make a mistake.
Examples
--------
Sample file structure (abbreviated):
my_project/
py/
fetch_raw_data.py
notebooks/
nb01_eda.ipynb
Running cd_root() from nb01_eda.ipynb will change the working
directory from notebooks/ to my_project/, which is typically the
same directory we'd run scripts in py/ from. This makes converting
from notebooks to scripts easier.
"""
changes = 0
start_dir = os.getcwd()
while root_subdir not in next(os.walk('.'))[1]:
if changes >= max_depth:
os.chdir(start_dir)
raise RuntimeError('Exceeded max_depth. Check that your '
'root_subdir is <= max_depth directories away.')
os.chdir('..')
changes += 1
print('Current directory:', os.getcwd())
def ngrams(word, n=3, step=1, drop_last=False):
"""To get non-overlapping sequences, pass in same value for `step` as `n`.
"""
stop = max(1, step+len(word)-n)
ngrams_ = []
for i in range(0, stop, step):
ngrams_.append(word[i:i+n])
if drop_last and len(ngrams_[-1]) < n: ngrams_ = ngrams_[:-1]
return ngrams_
def shell(cmd, return_output=True):
"""Execute shell command (between subprocess and os, there's ~5 different
ways to do this and I always forget which I want. This is just a way for me
to choose once and not have to decide again. There are rare situations
where we may need a different function (subprocess.run is blocking; if we
want to launch a process and continue the script without waiting for
completion, we can use subprocess.check_call).
Parameters
----------
cmd: str
Example: 'ls *.csv'
return_output: bool
If True, return the output of the command: e.g. if cmd is
'pip show requests', this would return a string containing information
about the version of the requests library you have installed. If False,
we return a tuple of (return code (0/1), stderr, stdout). I've noticed
the latter 2 are usually None though - need to read more into
subprocess docs to figure out why this is happening.
Returns
-------
tuple: returncode (int), stderr, stdout. I believe stderr and stdout are
None if nothing is returned and str otherwise.
"""
parts = cmd.split()
if return_output:
return check_output(parts).decode()
res = run(parts)
return res.returncode, res.stderr, res.stdout
def set_summary(x1, x2, info=('first_only', 'second_only')):
"""Summarize set comparison between two iterables (they will be converted
to sets internally).
Parameters
----------
info: Iterable[str]
Determines what info to return. 'first_only' returns items only in the
first iterable, 'second_only' returns items only in the second, 'and'
returns items in both, and 'or' returns items in either.
Returns
-------
dict[str, set]: Maps str in `info` to set of items.
"""
s1, s2 = set(x1), set(x2)
res = {'and': s1 & s2,
'or': s1 | s2,
'first_only': s1 - s2,
'second_only': s2 - s1}
for k, v in res.items():
print(f'{k}: {len(v)} items')
return select(res, keep=list(info))
SENTINEL = object() | passed in. The corresponding values from each dictionary containing a
given key are summed to produce the new value.
Examples |
ef66fdd5.dec7d33a.js | (window.webpackJsonp=window.webpackJsonp||[]).push([[74],{208:function(e,t,n){"use strict";n.r(t),n.d(t,"frontMatter",(function(){return s})),n.d(t,"metadata",(function(){return r})),n.d(t,"rightToc",(function(){return l})),n.d(t,"default",(function(){return h}));var o=n(2),a=n(9),i=(n(0),n(224)),s={id:"implementing-consent",title:"Implementing Login, Consent & Logout UI",sidebar_label:"Login, Consent & Logout"},r={id:"version-v1.4/implementing-consent",title:"Implementing Login, Consent & Logout UI",description:"Let's build a simple consent app that can be used as part of the Hydra's",source:"@site/versioned_docs/version-v1.4/implement-consent.md",permalink:"/hydra/docs/v1.4/implementing-consent",editUrl:"https://github.com/ory/hydra/edit/master/docs/versioned_docs/version-v1.4/implement-consent.md",version:"v1.4",lastUpdatedBy:"hackerman",lastUpdatedAt:1588407142,sidebar_label:"Login, Consent & Logout",sidebar:"version-v1.4/docs",previous:{title:"5 Minute Tutorial",permalink:"/hydra/docs/v1.4/5min-tutorial"},next:{title:"OAuth 2.0 Case Study",permalink:"/hydra/docs/v1.4/case-study"}},l=[{value:"OAuth 2.0 Authorize Code Flow",id:"oauth-20-authorize-code-flow",children:[{value:"User Login",id:"user-login",children:[]},{value:"User Consent",id:"user-consent",children:[]}]},{value:"User Logout",id:"user-logout",children:[{value:"Logout Flow",id:"logout-flow",children:[]},{value:"OpenID Connect Front-Channel Logout 1.0",id:"openid-connect-front-channel-logout-10",children:[]},{value:"OpenID Connect Back-Channel Logout 1.0",id:"openid-connect-back-channel-logout-10",children:[]}]},{value:"Revoking consent and login sessions",id:"revoking-consent-and-login-sessions",children:[{value:"Login",id:"login",children:[]},{value:"Consent",id:"consent",children:[]}]},{value:"OAuth 2.0",id:"oauth-20",children:[{value:"OAuth 2.0 Scope",id:"oauth-20-scope",children:[]},{value:"OAuth 2.0 Access Token Audience",id:"oauth-20-access-token-audience",children:[]},{value:"OAuth 2.0 Refresh Tokens",id:"oauth-20-refresh-tokens",children:[]},{value:"OAuth 2.0 Token Introspection",id:"oauth-20-token-introspection",children:[]},{value:"OAuth 2.0 Clients",id:"oauth-20-clients",children:[]}]},{value:"Examples",id:"examples",children:[{value:"Authorize Code Flow with Refresh Token",id:"authorize-code-flow-with-refresh-token",children:[]},{value:"Client Credentials Flow",id:"client-credentials-flow",children:[]}]},{value:"OpenID Connect",id:"openid-connect",children:[{value:"Userinfo",id:"userinfo",children:[]}]}],c={rightToc:l};function | (e){var t=e.components,n=Object(a.a)(e,["components"]);return Object(i.b)("wrapper",Object(o.a)({},c,n,{components:t,mdxType:"MDXLayout"}),Object(i.b)("p",null,"Let's build a simple consent app that can be used as part of the Hydra's\n",Object(i.b)("a",Object(o.a)({parentName:"p"},{href:"login-consent-flow"}),"Login and consent workflow"),"."),Object(i.b)("h2",{id:"oauth-20-authorize-code-flow"},"OAuth 2.0 Authorize Code Flow"),Object(i.b)("p",null,"Before anything happens, the OAuth 2.0 Authorize Code Flow is initiated by an\nOAuth 2.0 Client. This usually works by generating a URL in the form of\n",Object(i.b)("inlineCode",{parentName:"p"},"https://hydra/oauth2/auth?client_id=1234&scope=foo+bar&response_type=code&..."),".\nThen, the OAuth 2.0 Client points the end user's user agent to that URL."),Object(i.b)("p",null,"Next, the user agent (browser) opens that URL."),Object(i.b)("h3",{id:"user-login"},"User Login"),Object(i.b)("p",null,"As the user agent hits the URL, ORY Hydra checks if a session cookie is set\ncontaining information about a previously successful login. Additionally,\nparameters such as ",Object(i.b)("inlineCode",{parentName:"p"},"id_token_hint"),", ",Object(i.b)("inlineCode",{parentName:"p"},"prompt"),", and ",Object(i.b)("inlineCode",{parentName:"p"},"max_age")," are evaluated and\nprocessed."),Object(i.b)("p",null,"Next, the user will be redirect to the Login Provider which was set using the\n",Object(i.b)("inlineCode",{parentName:"p"},"OAUTH2_LOGIN_URL")," environment variable. For example, the user is redirected to\n",Object(i.b)("inlineCode",{parentName:"p"},"https://login-provider/login?login_challenge=1234")," if\n",Object(i.b)("inlineCode",{parentName:"p"},"OAUTH2_LOGIN_URL=https://login-provider/login"),". This redirection happens\n",Object(i.b)("em",{parentName:"p"},"always")," and regardless of whether the user has a valid login session or if the\nuser needs to authenticate."),Object(i.b)("p",null,"The service which handles requests to ",Object(i.b)("inlineCode",{parentName:"p"},"https://login-provider/login")," must first\nfetch information on the authentication request using a REST API call. Please be\naware that for reasons of brevity, the following code snippets are pseudo-code.\nFor a fully working example, check out our reference\n",Object(i.b)("a",Object(o.a)({parentName:"p"},{href:"https://github.com/ory/hydra-login-consent-node"}),"User Login & Consent Provider implementation"),"."),Object(i.b)("p",null,"The endpoint handler at ",Object(i.b)("inlineCode",{parentName:"p"},"/login")," ",Object(i.b)("strong",{parentName:"p"},"must not remember previous sessions"),". This\ntask is solved by ORY Hydra. If the REST API call tells you to show the login\nui, you ",Object(i.b)("strong",{parentName:"p"},"must show it"),". If the REST API tells you to not show the login ui,\n",Object(i.b)("strong",{parentName:"p"},"you must not show it"),". Again, ",Object(i.b)("strong",{parentName:"p"},"do not implement any type of session here"),"."),Object(i.b)("pre",null,Object(i.b)("code",Object(o.a)({parentName:"pre"},{}),"// This is node-js pseudo code and will not work if you copy it 1:1\n\nrouter.get('/login', function (req, res, next) {\n challenge = req.url.query.login_challenge;\n\n fetch('https://hydra/oauth2/auth/requests/login?' + querystring.stringify({ login_challenge: challenge })).\n then(function (response) {\n return response.json()\n }).\n then(function (response) {\n // ...\n })\n})\n")),Object(i.b)("p",null,"The server response is a JSON object with the following keys:"),Object(i.b)("pre",null,Object(i.b)("code",Object(o.a)({parentName:"pre"},{}),'{\n // Skip, if true, let\'s us know that ORY Hydra has successfully authenticated the user and we should not show any UI\n "skip": true|false,\n\n // The user-id of the already authenticated user - only set if skip is true\n "subject": "user-id",\n\n // The OAuth 2.0 client that initiated the request\n "client": {"id": "...", ...},\n\n // The initial OAuth 2.0 request url\n "request_url": "https://hydra/oauth2/auth?client_id=1234&scope=foo+bar&response_type=code&...",\n\n // The OAuth 2.0 Scope requested by the client,\n "requested_scope": ["foo", "bar"],\n\n // Information on the OpenID Connect request - only required to process if your UI should support these values.\n "oidc_context": {"ui_locales": [...], ...},\n\n // Context is an optional object which can hold arbitrary data. The data will be made available when fetching the\n // consent request under the "context" field. This is useful in scenarios where login and consent endpoints share\n // data.\n "context": {...}\n}\n')),Object(i.b)("p",null,"For a full documentation on all available keys, please head over to the\n",Object(i.b)("a",Object(o.a)({parentName:"p"},{href:"https://www.ory.sh/docs/api/hydra/"}),"API documentation")," (make sure to select the\nright API version)."),Object(i.b)("p",null,"Depending of whether or not ",Object(i.b)("inlineCode",{parentName:"p"},"skip")," is true, you will prompt the user to log in\nby showing him/her a username/password form, or by using some other proof of\nidentity."),Object(i.b)("p",null,"If ",Object(i.b)("inlineCode",{parentName:"p"},"skip")," is true, you ",Object(i.b)("strong",{parentName:"p"},"should not")," show a user interface but accept the login\nrequest directly by making a REST call. You can use this step to update some\ninternal count of how often a user logged in, or do some other custom business\nlogic. But again, do not show the user interface."),Object(i.b)("p",null,"To accept the login request, do something along the lines of:"),Object(i.b)("pre",null,Object(i.b)("code",Object(o.a)({parentName:"pre"},{}),"// This is node-js pseudo code and will not work if you copy it 1:1\n\nconst body = {\n // This is the user ID of the user that authenticated. If `skip` is true, this must be the `subject`\n // value from the `fetch('https://hydra/oauth2/auth/requests/login?' + querystring.stringify({ login_challenge: challenge }))` response:\n //\n // subject = response.subject\n //\n // Otherwise, this can be a value of your choosing:\n subject: \"...\",\n\n // If remember is set to true, then the authentication session will be persisted in the user's browser by ORY Hydra. This will set the `skip` flag to true in future requests that are coming from this user. This value has no effect if `skip` was true.\n remember: true|false,\n\n // The time (in seconds) that the cookie should be valid for. Only has an effect if `remember` is true.\n remember_for: 3600,\n\n // This value is specified by OpenID connect and optional - it tells OpenID Connect which level of authentication the user performed - for example 2FA or using some biometric data. The concrete values are up to you here.\n acr: \"..\"\n}\n\nfetch('https://hydra/oauth2/auth/requests/login/accept?' + querystring.stringify({ login_challenge: challenge }), {\n method: 'PUT',\n body: JSON.stringify(body),\n headers: { 'Content-Type': 'application/json' }\n}).\n then(function (response) {\n return response.json()\n }).\n then(function (response) {\n // The response will contain a `redirect_to` key which contains the URL where the user's user agent must be redirected to next.\n res.redirect(response.redirect_to);\n })\n")),Object(i.b)("p",null,"You may also choose to deny the login request. This is possible regardless of\nthe ",Object(i.b)("inlineCode",{parentName:"p"},"skip")," value."),Object(i.b)("pre",null,Object(i.b)("code",Object(o.a)({parentName:"pre"},{}),"// This is node-js pseudo code and will not work if you copy it 1:1\n\nconst body = {\n error: \"...\", // This is an error ID like `login_required` or `invalid_request`\n error_description: \"...\" // This is a more detailed description of the error\n}\n\nfetch('https://hydra/oauth2/auth/requests/login/reject?' + querystring.stringify({ login_challenge: challenge }), {\n method: 'PUT',\n body: JSON.stringify(body),\n headers: { 'Content-Type': 'application/json' }\n}).\n then(function (response) {\n return response.json()\n }).\n then(function (response) {\n // The response will contain a `redirect_to` key which contains the URL where the user's user agent must be redirected to next.\n res.redirect(response.redirect_to);\n })\n")),Object(i.b)("h3",{id:"user-consent"},"User Consent"),Object(i.b)("p",null,"Now that we know who the user is, we must ask the user if he/she wants to grant\nthe requested permissions to the OAuth 2.0 Client. To do so, we check if the\nuser has previously granted that exact OAuth 2.0 Client the requested\npermissions. If the user has never granted any permissions to the client, or the\nclient requires new permissions not previously granted, the user must visually\nconfirm the request."),Object(i.b)("p",null,"This works very similar to the User Login Flow. First, the user will be redirect\nto the Consent Provider which was set using the ",Object(i.b)("inlineCode",{parentName:"p"},"OAUTH2_CONSENT_PROVIDER"),"\nenvironment variable. For example, the user is redirected to\n",Object(i.b)("inlineCode",{parentName:"p"},"https://consent-provider/consent?consent_challenge=1234")," if\n",Object(i.b)("inlineCode",{parentName:"p"},"OAUTH2_CONSENT_PROVIDER=https://consent-provider/consent"),". This redirection\nhappens ",Object(i.b)("em",{parentName:"p"},"always")," and regardless of whether the user has a valid login session or\nif the user needs to authorize the application or not."),Object(i.b)("p",null,"The service which handles requests to ",Object(i.b)("inlineCode",{parentName:"p"},"https://consent-provider/consent")," must\nfirst fetch information on the consent request using a REST API call. Please be\naware that for reasons of brevity, the following code snippets are pseudo-code.\nFor a fully working example, check out our reference\n",Object(i.b)("a",Object(o.a)({parentName:"p"},{href:"https://github.com/ory/hydra-login-consent-node"}),"User Login, Logout & Consent Provider implementation"),"."),Object(i.b)("pre",null,Object(i.b)("code",Object(o.a)({parentName:"pre"},{}),"// This is node-js pseudo code and will not work if you copy it 1:1\n\nchallenge = req.url.query.consent_challenge;\n\nfetch('https://hydra/oauth2/auth/requests/consent?' + querystring.stringify({ consent_challenge: challenge })).\n then(function (response) {\n return response.json()\n }).\n then(function (response) {\n // ...\n })\n")),Object(i.b)("p",null,"The server response is a JSON object with the following keys:"),Object(i.b)("pre",null,Object(i.b)("code",Object(o.a)({parentName:"pre"},{}),'{\n // Skip, if true, let\'s us know that the client has previously been granted the requested permissions (scope) by the end-user\n "skip": true|false,\n\n // The user-id of the user that will grant (or deny) the request\n "subject": "user-id",\n\n // The OAuth 2.0 client that initiated the request\n "client": {"id": "...", ...},\n\n // The initial OAuth 2.0 request url\n "request_url": "https://hydra/oauth2/auth?client_id=1234&scope=foo+bar&response_type=code&...",\n\n // The OAuth 2.0 Scope requested by the client.\n "requested_scope": ["foo", "bar"],\n\n // Contains the access token audience as requested by the OAuth 2.0 Client.\n requested_access_token_audience: ["foo", "bar"]\n\n // Information on the OpenID Connect request - only required to process if your UI should support these values.\n "oidc_context": {"ui_locales": [...], ...},\n\n // Contains arbitrary information set by the login endpoint or is empty if not set.\n "context": {...}\n}\n')),Object(i.b)("p",null,"If skip is true, you should not show any user interface to the user. Instead,\nyou should accept (or deny) the consent request. Typically, you will accept the\nrequest unless you have a very good reason to deny it (e.g. the OAuth 2.0 Client\nis banned)."),Object(i.b)("p",null,"If skip is false and you show the consent screen, you should use the\n",Object(i.b)("inlineCode",{parentName:"p"},"requested_scope")," array to display a list of permissions which the user must\ngrant (e.g. using a checkbox). Some people choose to always skip this step if\nthe OAuth 2.0 Client is a first-party client - meaning that the client is used\nby you or your developers in an internal application."),Object(i.b)("p",null,"Assuming the user accepts the consent request, the code looks very familiar to\nthe User Login Flow."),Object(i.b)("pre",null,Object(i.b)("code",Object(o.a)({parentName:"pre"},{}),"// This is node-js pseudo code and will not work if you copy it 1:1\n\nconst body = {\n // A list of permissions the user granted to the OAuth 2.0 Client. This can be fewer permissions that initially requested, but are rarely more or other permissions than requested.\n grant_scope: [\"foo\", \"bar\"],\n\n // Sets the audience the user authorized the client to use. Should be a subset of `requested_access_token_audience`.\n grant_access_token_audience: [\"foo\", \"bar\"],\n\n // If remember is set to true, then the consent response will be remembered for future requests. This will set the `skip` flag to true in future requests that are coming from this user for the granted permissions and that particular client. This value has no effect if `skip` was true.\n remember: true|false,\n\n // The time (in seconds) that the cookie should be valid for. Only has an effect if `remember` is true.\n remember_for: 3600,\n\n // The session allows you to set additional data in the access and ID tokens.\n session: {\n // Sets session data for the access and refresh token, as well as any future tokens issued by the\n // refresh grant. Keep in mind that this data will be available to anyone performing OAuth 2.0 Challenge Introspection.\n // If only your services can perform OAuth 2.0 Challenge Introspection, this is usually fine. But if third parties\n // can access that endpoint as well, sensitive data from the session might be exposed to them. Use with care!\n access_token: { ... },\n\n // Sets session data for the OpenID Connect ID token. Keep in mind that the session'id payloads are readable\n // by anyone that has access to the ID Challenge. Use with care! Any information added here will be mirrored at\n // the `/userinfo` endpoint.\n id_token: { ... },\n }\n}\n\nfetch('https://hydra/oauth2/auth/requests/consent/accept?' + querystring.stringify({ consent_challenge: challenge }), {\n method: 'PUT',\n body: JSON.stringify(body),\n headers: { 'Content-Type': 'application/json' }\n}).\n then(function (response) {\n return response.json()\n }).\n then(function (response) {\n // The response will contain a `redirect_to` key which contains the URL where the user's user agent must be redirected to next.\n res.redirect(response.redirect_to);\n })\n")),Object(i.b)("p",null,"You may also choose to deny the consent request. This is possible regardless of\nthe ",Object(i.b)("inlineCode",{parentName:"p"},"skip")," value."),Object(i.b)("pre",null,Object(i.b)("code",Object(o.a)({parentName:"pre"},{}),"// This is node-js pseudo code and will not work if you copy it 1:1\n\nconst body = {\n // This is an error ID like `consent_required` or `invalid_request`\n error: \"...\",\n\n // This is a more detailed description of the error\n error_description: \"...\"\n}\n\nfetch('https://hydra/oauth2/auth/requests/consent/reject?' + querystring.stringify({ consent_challenge: challenge }), {\n method: 'PUT',\n body: JSON.stringify(body),\n headers: { 'Content-Type': 'application/json' }\n}).\n then(function (response) {\n return response.json()\n }).\n then(function (response) {\n // The response will contain a `redirect_to` key which contains the URL where the user's user agent must be redirected to next.\n res.redirect(response.redirect_to);\n })\n")),Object(i.b)("p",null,"Once the user agent is redirected back, the OAuth 2.0 flow will be finalized."),Object(i.b)("h2",{id:"user-logout"},"User Logout"),Object(i.b)("p",null,"ORY Hydra supports\n",Object(i.b)("a",Object(o.a)({parentName:"p"},{href:"https://openid.net/specs/openid-connect-frontchannel-1_0.html"}),"OpenID Connect Front-Channel Logout 1.0"),"\nand\n",Object(i.b)("a",Object(o.a)({parentName:"p"},{href:"https://openid.net/specs/openid-connect-backchannel-1_0.html"}),"OpenID Connect Back-Channel Logout 1.0"),"\nflows."),Object(i.b)("p",null,"A logout request may be initiated by the OpenID Provider (OP - ",Object(i.b)("strong",{parentName:"p"},"you"),") or by\nthe Relying Party (RP - the OAuth2 Client):"),Object(i.b)("ul",null,Object(i.b)("li",{parentName:"ul"},"The OP-initiated flow does not need an ",Object(i.b)("inlineCode",{parentName:"li"},"id_token_hint"),", and it may neither\ndefine a ",Object(i.b)("inlineCode",{parentName:"li"},"state")," nor a ",Object(i.b)("inlineCode",{parentName:"li"},"post_logout_redirect_uri"),"."),Object(i.b)("li",{parentName:"ul"},"The RP-initiated flow needs an ",Object(i.b)("inlineCode",{parentName:"li"},"id_token_hint")," and may optionally define\n",Object(i.b)("inlineCode",{parentName:"li"},"state")," and ",Object(i.b)("inlineCode",{parentName:"li"},"post_logout_redirect_uri"),".")),Object(i.b)("p",null,"Both requests follow the same pattern as user login and user consent. Before the\nlogout is completed, the user is redirected to the ",Object(i.b)("strong",{parentName:"p"},"Logout UI")," (similar to\nLogin UI and Consent UI) to confirm the logout request."),Object(i.b)("p",null,"There are several possible pathways for executing this flow, explained in the\nfollowing diagram:"),Object(i.b)("p",null,Object(i.b)("a",Object(o.a)({parentName:"p"},{href:"https://mermaid-js.github.io/mermaid-live-editor/#/edit/eyJjb2RlIjoiZ3JhcGggVEQ7XG4gICAgSVtHRVQgL29hdXRoMi9zZXNzaW9uL2xvZ291dF0tLT58aGFzIGlkX3Rva2VuX2hpbnQqfFJQSVtSUC1pbml0aWF0ZWQgbG9nb3V0XTtcbiAgICBJW0dFVCAvb2F1dGgyL3Nlc3Npb24vbG9nb3V0XS0tPnxkb2VzIG5vdCBoYXZlIGlkX3Rva2VuX2hpbnQqfE9QSVtPUC1pbml0aWF0ZWQgbG9nb3V0XVxuT1BJLS0-fGhhcyBzdGF0ZSp8RVtFcnJvcl1cbk9QSS0tPnxoYXMgcG9zdF9sb2dvdXRfdXJpKnxFW0Vycm9yXVxuT1BJLS0-fGhhcyB2YWxpZCBzZXNzaW9uIGNvb2tpZXxMVUlbTG9nb3V0IFVJIHdpdGggP2xvZ291dF9jaGFsbGVuZ2U9Li4uXVxuT1BJLS0-fGhhcyBubyB2YWxpZCBzZXNpb24gY29va2llfEVuZFtSZXR1cm4gdG8gcG9zdF9sb2dvdXRfdXJsKioqXVxuUlBJLS0-fGhhcyBhY3RpdmUgc2Vzc2lvbioqKip8TFVJXG5SUEktLT58bm8gYWN0aXZlIHNlc3Npb24qKioqfFJQSTJcbkxVSS0tPnx2ZXJpZnkgbG9nb3V0IHJlcXVlc3R8TFVJXG5MVUktLT58cmVkaXJlY3Qgd2l0aCBsb2dvdXRfdmVyaWZpZXIqfFJQSTJbIC9vYXV0aDIvc2Vzc2lvbnMvbG9nb3V0P2xvZ291dF92ZXJpZmllcj0uLi5dXG5SUEkyLS0-fGV4ZWN1dGUgZnJvbnQvYmFja2NoYW5uZWwgbG9nb3V0LCByZXZva2UgY29va2llfFJQSTJcblJQSTItLT58UmVkaXJlY3QgdG98RW5kIiwibWVybWFpZCI6eyJ0aGVtZSI6ImRlZmF1bHQifX0"}),Object(i.b)("img",Object(o.a)({parentName:"a"},{src:"https://mermaid.ink/img/eyJjb2RlIjoiZ3JhcGggVEQ7XG4gICAgSVtHRVQgL29hdXRoMi9zZXNzaW9uL2xvZ291dF0tLT58aGFzIGlkX3Rva2VuX2hpbnQqfFJQSVtSUC1pbml0aWF0ZWQgbG9nb3V0XTtcbiAgICBJW0dFVCAvb2F1dGgyL3Nlc3Npb24vbG9nb3V0XS0tPnxkb2VzIG5vdCBoYXZlIGlkX3Rva2VuX2hpbnQqfE9QSVtPUC1pbml0aWF0ZWQgbG9nb3V0XVxuT1BJLS0-fGhhcyBzdGF0ZSp8RVtFcnJvcl1cbk9QSS0tPnxoYXMgcG9zdF9sb2dvdXRfdXJpKnxFW0Vycm9yXVxuT1BJLS0-fGhhcyB2YWxpZCBzZXNzaW9uIGNvb2tpZXxMVUlbTG9nb3V0IFVJIHdpdGggP2xvZ291dF9jaGFsbGVuZ2U9Li4uXVxuT1BJLS0-fGhhcyBubyB2YWxpZCBzZXNpb24gY29va2llfEVuZFtSZXR1cm4gdG8gcG9zdF9sb2dvdXRfdXJsKioqXVxuUlBJLS0-fGhhcyBhY3RpdmUgc2Vzc2lvbioqKip8TFVJXG5SUEktLT58bm8gYWN0aXZlIHNlc3Npb24qKioqfFJQSTJcbkxVSS0tPnx2ZXJpZnkgbG9nb3V0IHJlcXVlc3R8TFVJXG5MVUktLT58cmVkaXJlY3Qgd2l0aCBsb2dvdXRfdmVyaWZpZXIqfFJQSTJbIC9vYXV0aDIvc2Vzc2lvbnMvbG9nb3V0P2xvZ291dF92ZXJpZmllcj0uLi5dXG5SUEkyLS0-fGV4ZWN1dGUgZnJvbnQvYmFja2NoYW5uZWwgbG9nb3V0LCByZXZva2UgY29va2llfFJQSTJcblJQSTItLT58UmVkaXJlY3QgdG98RW5kIiwibWVybWFpZCI6eyJ0aGVtZSI6ImRlZmF1bHQifX0",alt:"User Logout"})))),Object(i.b)("p",null,"Legend:"),Object(i.b)("ul",null,Object(i.b)("li",{parentName:"ul"},Object(i.b)("inlineCode",{parentName:"li"},"*"),": This is a query parameter, for example\n",Object(i.b)("inlineCode",{parentName:"li"},"/oauth2/sessions/logout?id_token_hint=...")),Object(i.b)("li",{parentName:"ul"},Object(i.b)("inlineCode",{parentName:"li"},"**"),' Here, an "active session" implies that there has been at least one login\nrequest completed with ',Object(i.b)("inlineCode",{parentName:"li"},"remember: true")," for that user. If that's not the case,\nthe system \"does not know\" what to do (because there has never been a session\nissued that was remembered - hence it's not possible to forget it)."),Object(i.b)("li",{parentName:"ul"},Object(i.b)("inlineCode",{parentName:"li"},"***"),': Here, the "valid session cookies" implies that the browser has a valid\nauthentication cookie when calling ',Object(i.b)("inlineCode",{parentName:"li"},"/oauth2/sessions/logout"),". If you have\nproblems at this step, check if there is a cookie\n",Object(i.b)("inlineCode",{parentName:"li"},"oauth2_authentication_session")," for the domain ORY Hydra is running at. ",Object(i.b)("strong",{parentName:"li"},"Do\nnot mix up IP (e.g. ",Object(i.b)("inlineCode",{parentName:"strong"},"127.0.0.1"),", ",Object(i.b)("inlineCode",{parentName:"strong"},"192.168.1.1"),") addresses and FQDNs (e.g.\n",Object(i.b)("inlineCode",{parentName:"strong"},"localhost"),", ",Object(i.b)("inlineCode",{parentName:"strong"},"google.com"),").")),Object(i.b)("li",{parentName:"ul"},Object(i.b)("inlineCode",{parentName:"li"},"****"),": The ",Object(i.b)("inlineCode",{parentName:"li"},"post_logout_redirect")," defaults to the configuration value of\n",Object(i.b)("inlineCode",{parentName:"li"},"urls.post_logout_redirect"),". If it's an RP-initiated flow and a\n",Object(i.b)("inlineCode",{parentName:"li"},"post_logout_redirect_uri")," was set and that URL is in the array of the OAuth2 Client's\n",Object(i.b)("inlineCode",{parentName:"li"},"urls.post_logout_redirect"),", the browser will be redirected there instead.")),Object(i.b)("h3",{id:"logout-flow"},"Logout Flow"),Object(i.b)("p",null,Object(i.b)("a",Object(o.a)({parentName:"p"},{href:"https://mermaid-js.github.io/mermaid-live-editor/#/edit/eyJjb2RlIjoic2VxdWVuY2VEaWFncmFtXG4gICAgVXNlciBBZ2VudC0-Pk9SWSBIeWRyYTogQ2FsbHMgbG9nb3V0IGVuZHBvaW50XG4gICAgT1JZIEh5ZHJhLS0-Pk9SWSBIeWRyYTogVmFsaWRhdGVzIGxvZ291dCBlbmRwb2ludFxuICAgIE9SWSBIeWRyYS0-PkxvZ291dCBQcm92aWRlcjogUmVkaXJlY3RzIGVuZCB1c2VyIHdpdGggbG9nb3V0IGNoYWxsZW5nZVxuICAgIExvZ291dCBQcm92aWRlci0tPk9SWSBIeWRyYTogRmV0Y2hlcyBsb2dvdXQgcmVxdWVzdCBpbmZvXG4gICAgTG9nb3V0IFByb3ZpZGVyLS0-PkxvZ291dCBQcm92aWRlcjogQWNxdWlyZXMgdXNlciBjb25zZW50IGZvciBsb2dvdXQgKG9wdGlvbmFsKVxuICAgIExvZ291dCBQcm92aWRlci0tPk9SWSBIeWRyYTogSW5mb3JtcyB0aGF0IGxvZ291dCByZXF1ZXN0IGlzIGdyYW50ZWRcbiAgICBMb2dvdXQgUHJvdmlkZXItPj5PUlkgSHlkcmE6IFJlZGlyZWN0cyBlbmQgdXNlciB0byByZWRpcmVjdCB1cmwgd2l0aCBsb2dvdXQgY2hhbGxlbmdlXG4gICAgT1JZIEh5ZHJhLS0-Pk9SWSBIeWRyYTogUGVyZm9ybXMgbG9nb3V0IHJvdXRpbmVzXG4gICAgT1JZIEh5ZHJhLS0-VXNlciBBZ2VudDogUmVkaXJlY3RzIHRvIHNwZWNpZmllZCByZWRpcmVjdCB1cmwiLCJtZXJtYWlkIjp7InRoZW1lIjoiZGVmYXVsdCJ9fQ"}),Object(i.b)("img",Object(o.a)({parentName:"a"},{src:"https://mermaid.ink/img/eyJjb2RlIjoic2VxdWVuY2VEaWFncmFtXG4gICAgVXNlciBBZ2VudC0-Pk9SWSBIeWRyYTogQ2FsbHMgbG9nb3V0IGVuZHBvaW50XG4gICAgT1JZIEh5ZHJhLS0-Pk9SWSBIeWRyYTogVmFsaWRhdGVzIGxvZ291dCBlbmRwb2ludFxuICAgIE9SWSBIeWRyYS0-PkxvZ291dCBQcm92aWRlcjogUmVkaXJlY3RzIGVuZCB1c2VyIHdpdGggbG9nb3V0IGNoYWxsZW5nZVxuICAgIExvZ291dCBQcm92aWRlci0tPk9SWSBIeWRyYTogRmV0Y2hlcyBsb2dvdXQgcmVxdWVzdCBpbmZvXG4gICAgTG9nb3V0IFByb3ZpZGVyLS0-PkxvZ291dCBQcm92aWRlcjogQWNxdWlyZXMgdXNlciBjb25zZW50IGZvciBsb2dvdXQgKG9wdGlvbmFsKVxuICAgIExvZ291dCBQcm92aWRlci0tPk9SWSBIeWRyYTogSW5mb3JtcyB0aGF0IGxvZ291dCByZXF1ZXN0IGlzIGdyYW50ZWRcbiAgICBMb2dvdXQgUHJvdmlkZXItPj5PUlkgSHlkcmE6IFJlZGlyZWN0cyBlbmQgdXNlciB0byByZWRpcmVjdCB1cmwgd2l0aCBsb2dvdXQgY2hhbGxlbmdlXG4gICAgT1JZIEh5ZHJhLS0-Pk9SWSBIeWRyYTogUGVyZm9ybXMgbG9nb3V0IHJvdXRpbmVzXG4gICAgT1JZIEh5ZHJhLS0-VXNlciBBZ2VudDogUmVkaXJlY3RzIHRvIHNwZWNpZmllZCByZWRpcmVjdCB1cmwiLCJtZXJtYWlkIjp7InRoZW1lIjoiZGVmYXVsdCJ9fQ",alt:"User Logout Flow Diagram"})))),Object(i.b)("ol",null,Object(i.b)("li",{parentName:"ol"},"A user-agent (browser) requests the logout endpoint\n(",Object(i.b)("inlineCode",{parentName:"li"},"/oauth2/sessions/logout"),"). If the request is done on behalf of a RP:",Object(i.b)("ul",{parentName:"li"},Object(i.b)("li",{parentName:"ul"},"The URL query MUST contain an ID Token issued by ORY Hydra as the\n",Object(i.b)("inlineCode",{parentName:"li"},"id_token_hint"),": ",Object(i.b)("inlineCode",{parentName:"li"},"/oauth2/sessions/logout?id_token_hint=...")),Object(i.b)("li",{parentName:"ul"},"The URL query MAY contain key ",Object(i.b)("inlineCode",{parentName:"li"},"post_logout_redirect_uri")," indicating where\nthe user agent should be redirected after the logout completed\nsuccessfully. Each OAuth 2.0 Client can whitelist a list of URIs that can\nbe used as the value using the ",Object(i.b)("inlineCode",{parentName:"li"},"post_logout_redirect_uris")," metadata field:\n",Object(i.b)("inlineCode",{parentName:"li"},"/oauth2/sessions/logout?id_token_hint=...&post_logout_redirect_uri=https://i-must-be-whitelisted/")),Object(i.b)("li",{parentName:"ul"},"If ",Object(i.b)("inlineCode",{parentName:"li"},"post_logout_redirect_uri")," is set, the URL query SHOULD contain a\n",Object(i.b)("inlineCode",{parentName:"li"},"state")," value. On successful redirection, this state value will be appended\nto the ",Object(i.b)("inlineCode",{parentName:"li"},"post_logout_redirect_uri"),". The functionality is equal to the\n",Object(i.b)("inlineCode",{parentName:"li"},"state")," parameter when performing OAuth2 flows."))),Object(i.b)("li",{parentName:"ol"},"The user-agent is redirected to the logout provider URL (configuration item\n",Object(i.b)("inlineCode",{parentName:"li"},"urls.logout"),") and contains a challenge:\n",Object(i.b)("inlineCode",{parentName:"li"},"https://my-logout-provider/logout?challenge=...")),Object(i.b)("li",{parentName:"ol"},"The logout provider uses the ",Object(i.b)("inlineCode",{parentName:"li"},"challenge")," query parameter to fetch metadata\nabout the request. The logout provider may choose to show a UI where the user\nhas to accept the logout request. Alternatively, the logout provider MAY\nchoose to silently accept the logout request."),Object(i.b)("li",{parentName:"ol"},"To accept the logout request, the logout provider makes a ",Object(i.b)("inlineCode",{parentName:"li"},"PUT")," call to\n",Object(i.b)("inlineCode",{parentName:"li"},"/oauth2/auth/requests/logout/accept?challenge=..."),". No request body is\nrequired."),Object(i.b)("li",{parentName:"ol"},"The response contains a ",Object(i.b)("inlineCode",{parentName:"li"},"redirect_to")," value where the logout provider\nredirects the user back to."),Object(i.b)("li",{parentName:"ol"},"ORY Hydra performs OpenID Connect Front- and Back-Channel logout."),Object(i.b)("li",{parentName:"ol"},"The user agent is being redirected to a specified redirect URL. This may\neither be the default redirect URL set by ",Object(i.b)("inlineCode",{parentName:"li"},"urls.post_logout_redirect")," or to\nthe value specified by query parameter ",Object(i.b)("inlineCode",{parentName:"li"},"post_logout_redirect_uri"),".")),Object(i.b)("p",null,Object(i.b)("strong",{parentName:"p"},"This endpoint does not remove any Access/Refresh Tokens.")),Object(i.b)("h4",{id:"logout-provider-example-nodejs-pseudo-code"},"Logout Provider Example (NodeJS Pseudo-code)"),Object(i.b)("p",null,"Following step 1 from the flow above, the user-agent is redirected to the logout\nprovider (e.g. ",Object(i.b)("inlineCode",{parentName:"p"},"https://my-logout-provider/logout?challenge=..."),"). Next, the\nlogout provider fetches information about the logout request:"),Object(i.b)("pre",null,Object(i.b)("code",Object(o.a)({parentName:"pre"},{className:"language-node"}),"// This is node-js pseudo code and will not work if you copy it 1:1\n\nchallenge = req.url.query.logout_challenge;\n\nfetch(\n 'https://hydra/oauth2/auth/requests/logout?' +\n querystring.stringify({ logout_challenge: challenge })\n)\n .then(function (response) {\n return response.json();\n })\n .then(function (response) {\n // ...\n });\n")),Object(i.b)("p",null,"The server response is a JSON object with the following keys:"),Object(i.b)("pre",null,Object(i.b)("code",Object(o.a)({parentName:"pre"},{}),'{\n // The user for whom the logout was request.\n "subject": "user-id",\n\n // The login session ID that was requested to log out.\n "sid": "abc..",\n\n // The original request URL.\n "request_url": "https://hydra/oauth2/sessions/logout?id_token_hint=...",\n\n // True if the request was initiated by a Relying Party (RP) / OAuth 2.0 Client. False otherwise.\n "rp_initiated": true|false\n}\n')),Object(i.b)("p",null,"Next, the logout provider should decide if the end-user should perform a UI\naction such as confirming the logout request. It is RECOMMENDED to request\nlogout confirmation from the end-user when ",Object(i.b)("inlineCode",{parentName:"p"},"rp_initiated")," is set to true."),Object(i.b)("p",null,"When the logout provider decides to accept the logout request, the flow is\ncompleted as follows:"),Object(i.b)("pre",null,Object(i.b)("code",Object(o.a)({parentName:"pre"},{className:"language-node"}),"fetch(\n 'https://hydra/oauth2/auth/requests/logout/accept?' +\n querystring.stringify({ logout_challenge: challenge }),\n {\n method: 'PUT',\n }\n)\n .then(function (response) {\n return response.json();\n })\n .then(function (response) {\n // The response will contain a `redirect_to` key which contains the URL where the user's user agent must be redirected to next.\n res.redirect(response.redirect_to);\n });\n")),Object(i.b)("p",null,"You can also reject a logout request (e.g. if the user chose to not log out):"),Object(i.b)("pre",null,Object(i.b)("code",Object(o.a)({parentName:"pre"},{className:"language-node"}),"fetch(\n 'https://hydra/oauth2/auth/requests/logout/reject?' +\n querystring.stringify({ logout_challenge: challenge }),\n {\n method: 'PUT',\n }\n).then(function (response) {\n // Now you can do whatever you want - redirect the user back to your home page or whatever comes to mind.\n});\n")),Object(i.b)("p",null,"If the logout request was granted and the user agent redirected back to ORY\nHydra, all OpenID Connect Front-/Back-channel logout flows (if set) will be\nperformed and the user will be redirect back to his/her final destination."),Object(i.b)("h3",{id:"openid-connect-front-channel-logout-10"},Object(i.b)("a",Object(o.a)({parentName:"h3"},{href:"https://openid.net/specs/openid-connect-frontchannel-1_0.html"}),"OpenID Connect Front-Channel Logout 1.0")),Object(i.b)("p",null,"In summary\n(",Object(i.b)("a",Object(o.a)({parentName:"p"},{href:"https://openid.net/specs/openid-connect-frontchannel-1_0.html"}),"read the spec"),")\nthis feature allows an OAuth 2.0 Client to register fields\n",Object(i.b)("inlineCode",{parentName:"p"},"frontchannel_logout_uri")," and ",Object(i.b)("inlineCode",{parentName:"p"},"frontchannel_logout_session_required"),"."),Object(i.b)("p",null,"If ",Object(i.b)("inlineCode",{parentName:"p"},"frontchannel_logout_uri")," is set to a valid URL (the host, port, path must\nall match those of one of the Redirect URIs), ORY Hydra will redirect the\nuser-agent (typically browser) to that URL after a logout occurred. This allows\nthe OAuth 2.0 Client Application to log out the end-user in its own system as\nwell - for example by deleting a Cookie or otherwise invalidating the user\nsession."),Object(i.b)("p",null,"ORY Hydra always appends query parameters values ",Object(i.b)("inlineCode",{parentName:"p"},"iss")," and ",Object(i.b)("inlineCode",{parentName:"p"},"sid")," to the\nFront-Channel Logout URI, for example:"),Object(i.b)("pre",null,Object(i.b)("code",Object(o.a)({parentName:"pre"},{}),"https://rp.example.org/frontchannel_logout\n ?iss=https://server.example.com\n &sid=08a5019c-17e1-4977-8f42-65a12843ea02\n")),Object(i.b)("p",null,"Each OpenID Connect ID Token is issued with a ",Object(i.b)("inlineCode",{parentName:"p"},"sid")," claim that will match the\n",Object(i.b)("inlineCode",{parentName:"p"},"sid")," value from the Front-Channel Logout URI."),Object(i.b)("p",null,"ORY Hydra will automatically execute the required HTTP Redirects to make this\nwork. No extra work is required."),Object(i.b)("h3",{id:"openid-connect-back-channel-logout-10"},Object(i.b)("a",Object(o.a)({parentName:"h3"},{href:"https://openid.net/specs/openid-connect-backchannel-1_0.html"}),"OpenID Connect Back-Channel Logout 1.0")),Object(i.b)("p",null,"In summary\n(",Object(i.b)("a",Object(o.a)({parentName:"p"},{href:"https://openid.net/specs/openid-connect-backchannel-1_0.html"}),"read the spec"),")\nthis feature allows an OAuth 2.0 Client to register fields\n",Object(i.b)("inlineCode",{parentName:"p"},"backchannel_logout_uri")," and ",Object(i.b)("inlineCode",{parentName:"p"},"backchannel_logout_session_required"),"."),Object(i.b)("p",null,"If ",Object(i.b)("inlineCode",{parentName:"p"},"backchannel_logout_uri")," is set to a valid URL, a HTTP Post request with\nContent-Type ",Object(i.b)("inlineCode",{parentName:"p"},"application/x-www-form-urlencoded")," and a ",Object(i.b)("inlineCode",{parentName:"p"},"logout_token")," will be\nmade to that URL when a end-user logs out. The ",Object(i.b)("inlineCode",{parentName:"p"},"logout_token")," is a JWT signed\nwith the same key that is used to sign OpenID Connect ID Tokens. You should thus\nvalidate the ",Object(i.b)("inlineCode",{parentName:"p"},"logout_token")," using the ID Token Public Key (can be fetched from\n",Object(i.b)("inlineCode",{parentName:"p"},"/.well-known/jwks.json"),"). The ",Object(i.b)("inlineCode",{parentName:"p"},"logout_token")," contains the following claims:"),Object(i.b)("ul",null,Object(i.b)("li",{parentName:"ul"},Object(i.b)("inlineCode",{parentName:"li"},"iss")," - Issuer Identifier, as specified in Section 2 of ","[OpenID.Core]","."),Object(i.b)("li",{parentName:"ul"},Object(i.b)("inlineCode",{parentName:"li"},"aud")," - Audience(s), as specified in Section 2 of ","[OpenID.Core]","."),Object(i.b)("li",{parentName:"ul"},Object(i.b)("inlineCode",{parentName:"li"},"iat")," - Issued at time, as specified in Section 2 of ","[OpenID.Core]","."),Object(i.b)("li",{parentName:"ul"},Object(i.b)("inlineCode",{parentName:"li"},"jti")," - Unique identifier for the token, as specified in Section 9 of\n","[OpenID.Core]","."),Object(i.b)("li",{parentName:"ul"},Object(i.b)("inlineCode",{parentName:"li"},"events")," - Claim whose value is a JSON object containing the member name\n",Object(i.b)("a",Object(o.a)({parentName:"li"},{href:"http://schemas.openid.net/event/backchannel-logout"}),"http://schemas.openid.net/event/backchannel-logout"),". This declares that the JWT\nis a Logout Token. The corresponding member value MUST be a JSON object and\nSHOULD be the empty JSON object {}."),Object(i.b)("li",{parentName:"ul"},Object(i.b)("inlineCode",{parentName:"li"},"sid")," - Session ID - String identifier for a Session. This represents a\nSession of a User Agent or device for a logged-in End-User at an RP. Different\nsid values are used to identify distinct sessions at an OP. The sid value need\nonly be unique in the context of a particular issuer. Its contents are opaque\nto the RP. Its syntax is the same as an OAuth 2.0 Client Identifier.")),Object(i.b)("pre",null,Object(i.b)("code",Object(o.a)({parentName:"pre"},{}),'{\n "iss": "https://server.example.com",\n "aud": "s6BhdRkqt3",\n "iat": 1471566154,\n "jti": "bWJq",\n "sid": "08a5019c-17e1-4977-8f42-65a12843ea02",\n "events": {\n "http://schemas.openid.net/event/backchannel-logout": {}\n }\n}\n')),Object(i.b)("p",null,"An exemplary Back-Channel Logout Request looks as follows:"),Object(i.b)("pre",null,Object(i.b)("code",Object(o.a)({parentName:"pre"},{}),"POST /backchannel_logout HTTP/1.1\nHost: rp.example.org\nContent-Type: application/x-www-form-urlencoded\n\nlogout_token=eyJhbGci ... .eyJpc3Mi ... .T3BlbklE ...\n")),Object(i.b)("p",null,"The Logout Token must be validated as follows:"),Object(i.b)("ul",null,Object(i.b)("li",{parentName:"ul"},"Validate the Logout Token signature in the same way that an ID Token signature\nis validated, with the following refinements."),Object(i.b)("li",{parentName:"ul"},"Validate the iss, aud, and iat Claims in the same way they are validated in ID\nTokens."),Object(i.b)("li",{parentName:"ul"},"Verify that the Logout Token contains a sid Claim."),Object(i.b)("li",{parentName:"ul"},"Verify that the Logout Token contains an events Claim whose value is JSON\nobject containing the member name\n",Object(i.b)("a",Object(o.a)({parentName:"li"},{href:"http://schemas.openid.net/event/backchannel-logout"}),"http://schemas.openid.net/event/backchannel-logout"),"."),Object(i.b)("li",{parentName:"ul"},"Verify that the Logout Token does not contain a nonce Claim."),Object(i.b)("li",{parentName:"ul"},"Optionally verify that another Logout Token with the same jti value has not\nbeen recently received.")),Object(i.b)("p",null,"The endpoint then returns a HTTP 200 OK response. Cache-Control headers should\nbe set to:"),Object(i.b)("pre",null,Object(i.b)("code",Object(o.a)({parentName:"pre"},{}),"Cache-Control: no-cache, no-store\nPragma: no-cache\n")),Object(i.b)("p",null,"Because the OpenID Connect Back-Channel Logout Flow is not executed using the\nuser-agent (e.g. Browser) but from ORY Hydra directly, the session cookie of the\nend-user will not be available to the OAuth 2.0 Client and the session has to be\ninvalidated by some other means (e.g. by blacklisting the session ID)."),Object(i.b)("h2",{id:"revoking-consent-and-login-sessions"},"Revoking consent and login sessions"),Object(i.b)("h3",{id:"login"},"Login"),Object(i.b)("p",null,"You can revoke login sessions. Revoking a login session will remove all of the\nuser's cookies at ORY Hydra and will require the user to re-authenticate when\nperforming the next OAuth 2.0 Authorize Code Flow. Be aware that this option\nwill remove all cookies from all devices."),Object(i.b)("p",null,"Revoking the login sessions of a user is as easy as sending ",Object(i.b)("inlineCode",{parentName:"p"},"DELETE"),"\nto",Object(i.b)("inlineCode",{parentName:"p"},"/oauth2/auth/sessions/login?subject={subject}"),"."),Object(i.b)("p",null,"This endpoint is not compatible with OpenID Connect Front-/Backchannel logout\nand does not revoke any tokens."),Object(i.b)("h3",{id:"consent"},"Consent"),Object(i.b)("p",null,"You can revoke a user's consent either on a per application basis or for all\napplications. Revoking the consent will automatically revoke all related access\nand refresh tokens."),Object(i.b)("p",null,"Revoking all consent sessions of a user is as easy as sending ",Object(i.b)("inlineCode",{parentName:"p"},"DELETE"),"\nto",Object(i.b)("inlineCode",{parentName:"p"},"/oauth2/auth/sessions/consent?subject={subject}"),"."),Object(i.b)("p",null,"Revoking the consent sessions of a user for a specific client is as easy as\nsending ",Object(i.b)("inlineCode",{parentName:"p"},"DELETE"),"\nto",Object(i.b)("inlineCode",{parentName:"p"},"/oauth2/auth/sessions/consent?subject={subject}&client={client}"),"."),Object(i.b)("h2",{id:"oauth-20"},"OAuth 2.0"),Object(i.b)("h3",{id:"oauth-20-scope"},"OAuth 2.0 Scope"),Object(i.b)("p",null,"The scope of an OAuth 2.0 scope defines the permission the token was granted by\nthe end-user. For example, a specific token might be allowed to access public\npictures, but not private ones. The granted permissions are established during\nthe consent screen."),Object(i.b)("p",null,"Additionally, ORY Hydra has pre-defined OAuth 2.0 Scope values:"),Object(i.b)("ul",null,Object(i.b)("li",{parentName:"ul"},Object(i.b)("inlineCode",{parentName:"li"},"offline_access"),": Include this scope if you wish to receive a refresh token"),Object(i.b)("li",{parentName:"ul"},Object(i.b)("inlineCode",{parentName:"li"},"openid"),": Include this scope if you wish to perform an OpenID Connect request.")),Object(i.b)("p",null,"When performing an OAuth 2.0 Flow where the end-user is involved (e.g. Implicit\nor Authorize Code), the granted OAuth 2.0 Scope must be set when accepting the\nconsent using the ",Object(i.b)("inlineCode",{parentName:"p"},"grant_scope")," key."),Object(i.b)("blockquote",null,Object(i.b)("p",{parentName:"blockquote"},"A OAuth 2.0 Scope ",Object(i.b)("strong",{parentName:"p"},"is not a permission"),":"),Object(i.b)("ul",{parentName:"blockquote"},Object(i.b)("li",{parentName:"ul"},"A permission allows an actor to perform a certain action in a system: ",Object(i.b)("em",{parentName:"li"},"Bob\nis allowed to delete his own photos"),"."),Object(i.b)("li",{parentName:"ul"},"OAuth 2.0 Scope implies that an end-user granted certain privileges to a\nclient: ",Object(i.b)("em",{parentName:"li"},"Bob allowed the OAuth 2.0 Client to delete all users"),".")),Object(i.b)("p",{parentName:"blockquote"},'The OAuth 2.0 Scope can be granted without the end-user actually having the\nright permissions. In the examples above, Bob granted an OAuth 2.0 Client the\npermission ("scope") to delete all users in his name. However, since Bob is\nnot an administrator, that permission ("access control") is not actually\ngranted to Bob. Therefore any request by the OAuth 2.0 Client that tries to\ndelete users on behalf of Bob should fail.')),Object(i.b)("h3",{id:"oauth-20-access-token-audience"},"OAuth 2.0 Access Token Audience"),Object(i.b)("p",null,"The Audience of an Access Token refers to the Resource Servers that this token\nis intended for. The audience usually refers to one or more URLs such as"),Object(i.b)("ul",null,Object(i.b)("li",{parentName:"ul"},Object(i.b)("inlineCode",{parentName:"li"},"https://api.mydomain.com/blog/posts")),Object(i.b)("li",{parentName:"ul"},Object(i.b)("inlineCode",{parentName:"li"},"https://api.mydomain.com/users"))),Object(i.b)("p",null,"but may also refer to a subset of resources:"),Object(i.b)("ul",null,Object(i.b)("li",{parentName:"ul"},Object(i.b)("inlineCode",{parentName:"li"},"https://api.mydomain.com/tenants/foo/users"))),Object(i.b)("p",null,"When performing an OAuth 2.0 Flow where the end-user is involved (e.g. Implicit\nor Authorize Code), the granted audience must be set when accepting the consent\nusing the ",Object(i.b)("inlineCode",{parentName:"p"},"grant_access_token_audience")," key. In most cases, it is ok to grant\nthe audience without user-interaction."),Object(i.b)("h3",{id:"oauth-20-refresh-tokens"},"OAuth 2.0 Refresh Tokens"),Object(i.b)("p",null,"OAuth 2.0 Refresh Tokens are issued only when an Authorize Code Flow\n(",Object(i.b)("inlineCode",{parentName:"p"},"response_type=code"),") or an OpenID Connect Hybrid Flow with an Authorize Code\nResponse Type (",Object(i.b)("inlineCode",{parentName:"p"},"response_type=code+..."),") is executed. OAuth 2.0 Refresh Tokens\nare not returned for Implicit or Client Credentials grants:"),Object(i.b)("ul",null,Object(i.b)("li",{parentName:"ul"},"Capable of issuing an OAuth 2.0 Refresh Token:"),Object(i.b)("li",{parentName:"ul"},Object(i.b)("a",Object(o.a)({parentName:"li"},{href:"https://ory-hydra.example/oauth2/auth?response_type=code&"}),"https://ory-hydra.example/oauth2/auth?response_type=code&"),"..."),Object(i.b)("li",{parentName:"ul"},Object(i.b)("a",Object(o.a)({parentName:"li"},{href:"https://ory-hydra.example/oauth2/auth?response_type=code+token&"}),"https://ory-hydra.example/oauth2/auth?response_type=code+token&"),"..."),Object(i.b)("li",{parentName:"ul"},Object(i.b)("a",Object(o.a)({parentName:"li"},{href:"https://ory-hydra.example/oauth2/auth?response_type=code+token+id_token&"}),"https://ory-hydra.example/oauth2/auth?response_type=code+token+id_token&"),"..."),Object(i.b)("li",{parentName:"ul"},Object(i.b)("a",Object(o.a)({parentName:"li"},{href:"https://ory-hydra.example/oauth2/auth?response_type=code+id_token&"}),"https://ory-hydra.example/oauth2/auth?response_type=code+id_token&"),"..."),Object(i.b)("li",{parentName:"ul"},"Will not issue an OAuth 2.0 Refresh Token"),Object(i.b)("li",{parentName:"ul"},Object(i.b)("a",Object(o.a)({parentName:"li"},{href:"https://ory-hydra.example/oauth2/auth?response_type=token&"}),"https://ory-hydra.example/oauth2/auth?response_type=token&"),"..."),Object(i.b)("li",{parentName:"ul"},Object(i.b)("a",Object(o.a)({parentName:"li"},{href:"https://ory-hydra.example/oauth2/auth?response_type=token+id_token&"}),"https://ory-hydra.example/oauth2/auth?response_type=token+id_token&"),"..."),Object(i.b)("li",{parentName:"ul"},Object(i.b)("a",Object(o.a)({parentName:"li"},{href:"https://ory-hydra.example/oauth2/token?grant_type=client_redentials&"}),"https://ory-hydra.example/oauth2/token?grant_type=client_redentials&"),"...")),Object(i.b)("p",null,"Additionally, each OAuth 2.0 Client that wants to request an OAuth 2.0 Refresh\nToken must be allowed to request scope ",Object(i.b)("inlineCode",{parentName:"p"},"offline_access"),". When performing an\nOAuth 2.0 Authorize Code Flow, the ",Object(i.b)("inlineCode",{parentName:"p"},"offline_access")," value must be included in\nthe requested OAuth 2.0 Scope:"),Object(i.b)("pre",null,Object(i.b)("code",Object(o.a)({parentName:"pre"},{}),"https://authorization-server.com/auth\n &scope=offline_access\n ?response_type=code\n &client_id=...\n &redirect_uri=...\n &state=...\n")),Object(i.b)("p",null,"When accepting the consent request, ",Object(i.b)("inlineCode",{parentName:"p"},"offline_access")," must be in the list of\n",Object(i.b)("inlineCode",{parentName:"p"},"grant_scope"),":"),Object(i.b)("pre",null,Object(i.b)("code",Object(o.a)({parentName:"pre"},{}),"fetch('https://hydra/oauth2/auth/requests/consent/accept?challenge=' + encodeURIComponent(challenge), {\n method: 'PUT',\n body: JSON.stringify(body),\n headers: { 'Content-Type': 'application/json' }\n}).\nconst body = {\n grant_scope: [\"offline_access\"],\n}\n")),Object(i.b)("p",null,"Refresh Token Lifespan can be set using configuration key ",Object(i.b)("inlineCode",{parentName:"p"},"ttl.refresh_token"),".\nIf set to -1, Refresh Tokens never expire."),Object(i.b)("h3",{id:"oauth-20-token-introspection"},"OAuth 2.0 Token Introspection"),Object(i.b)("p",null,"OAuth2 Token Introspection is an ",Object(i.b)("a",Object(o.a)({parentName:"p"},{href:"https://tools.ietf.org/html/rfc7662"}),"IETF"),"\nstandard. It defines a method for a protected resource to query an OAuth 2.0\nauthorization server to determine the active state of an OAuth 2.0 token and to\ndetermine meta-information about this token. OAuth 2.0 deployments can use this\nmethod to convey information about the authorization context of the token from\nthe authorization server to the protected resource."),Object(i.b)("p",null,"You can find more details on this endpoint in the\n",Object(i.b)("a",Object(o.a)({parentName:"p"},{href:"https://www.ory.sh/docs/"}),"ORY Hydra API Docs"),". You can also use the CLI command\n",Object(i.b)("inlineCode",{parentName:"p"},"hydra token introspect <token>"),"."),Object(i.b)("h3",{id:"oauth-20-clients"},"OAuth 2.0 Clients"),Object(i.b)("p",null,"You can manage ",Object(i.b)("em",{parentName:"p"},"OAuth 2.0 clients")," using the cli or the HTTP REST API:"),Object(i.b)("ul",null,Object(i.b)("li",{parentName:"ul"},Object(i.b)("strong",{parentName:"li"},"CLI:")," ",Object(i.b)("inlineCode",{parentName:"li"},"hydra help clients")),Object(i.b)("li",{parentName:"ul"},Object(i.b)("strong",{parentName:"li"},"REST:")," Read the ",Object(i.b)("a",Object(o.a)({parentName:"li"},{href:"https://www.ory.sh/docs/hydra/sdk/api"}),"API Docs"))),Object(i.b)("h2",{id:"examples"},"Examples"),Object(i.b)("p",null,"This section provides a few examples to get you started with the most-used OAuth\n2.0 Clients:"),Object(i.b)("h3",{id:"authorize-code-flow-with-refresh-token"},"Authorize Code Flow with Refresh Token"),Object(i.b)("p",null,"The following command creates an OAuth 2.0 Client capable of executing the\nAuthorize Code Flow, requesting ID and Refresh Tokens and performing the OAuth\n2.0 Refresh Grant:"),Object(i.b)("pre",null,Object(i.b)("code",Object(o.a)({parentName:"pre"},{className:"language-sh"}),"hydra clients create \\\n --endpoint http://ory-hydra:4445 \\\n --id client-id \\\n --secret client-secret \\\n --grant-types authorization_code,refresh_token \\\n --response-types code \\\n --scope openid,offline \\\n --callbacks http://my-app.com/callback,http://my-other-app.com/callback\n")),Object(i.b)("p",null,"The OAuth 2.0 Client will be allowed to use values ",Object(i.b)("inlineCode",{parentName:"p"},"http://my-app.com/callback"),"\nand ",Object(i.b)("inlineCode",{parentName:"p"},"http://my-other-app.com/callback")," as ",Object(i.b)("inlineCode",{parentName:"p"},"redirect_url"),"."),Object(i.b)("blockquote",null,Object(i.b)("p",{parentName:"blockquote"},"It is expected that the OAuth 2.0 Client sends its credentials using HTTP\nBasic Authorization.")),Object(i.b)("p",null,"If you wish to send credentials in the POST Body, add the following flag to the\ncommand above:"),Object(i.b)("pre",null,Object(i.b)("code",Object(o.a)({parentName:"pre"},{})," --token-endpoint-auth-method client_secret_post \\\n")),Object(i.b)("p",null,"The same can be achieved by setting\n",Object(i.b)("inlineCode",{parentName:"p"},'"token_endpoint_auth_method": "client_secret_post"')," in the the request body of\n",Object(i.b)("inlineCode",{parentName:"p"},"POST /clients")," and ",Object(i.b)("inlineCode",{parentName:"p"},"PUT /clients/<id>"),"."),Object(i.b)("h3",{id:"client-credentials-flow"},"Client Credentials Flow"),Object(i.b)("p",null,"A client only capable of performing the Client Credentials Flow can be created\nas follows:"),Object(i.b)("pre",null,Object(i.b)("code",Object(o.a)({parentName:"pre"},{}),"hydra clients create \\\n --endpoint http://ory-hydra:4445 \\\n --id my-client \\\n --secret secret \\\n -g client_credentials\n")),Object(i.b)("h2",{id:"openid-connect"},"OpenID Connect"),Object(i.b)("h3",{id:"userinfo"},"Userinfo"),Object(i.b)("p",null,"The ",Object(i.b)("inlineCode",{parentName:"p"},"/userinfo")," endpoint returns information on a user given an access token.\nSince ORY Hydra is agnostic to any end-user data, the ",Object(i.b)("inlineCode",{parentName:"p"},"/userinfo")," endpoint\nreturns only minimal information per default:"),Object(i.b)("pre",null,Object(i.b)("code",Object(o.a)({parentName:"pre"},{}),'GET https://ory-hydra:4444/userinfo\nAuthorization: bearer access-token.xxxx\n\n{\n "acr": "oauth2",\n "sub": "[email protected]"\n}\n')),Object(i.b)("p",null,"Any information set to the key ",Object(i.b)("inlineCode",{parentName:"p"},"session.id_token")," during accepting the consent\nrequest will also be included here."),Object(i.b)("pre",null,Object(i.b)("code",Object(o.a)({parentName:"pre"},{className:"language-js"}),"\n// This is node-js pseudo code and will not work if you copy it 1:1\n\nconst body = {\n // grant_scope: [\"foo\", \"bar\"],\n // ...\n session: {\n id_token: {\n \"foo\": \"bar\"\n },\n }\n}\n\nfetch('https://hydra/oauth2/auth/requests/consent/' + challenge + '/accept', {\n method: 'PUT',\n body: JSON.stringify(body),\n headers: { 'Content-Type': 'application/json' }\n}).\n // then(function (response) {\n")),Object(i.b)("p",null,"By making the ",Object(i.b)("inlineCode",{parentName:"p"},"/userinfo")," call with a token issued by this consent request, one\nwould receive:"),Object(i.b)("pre",null,Object(i.b)("code",Object(o.a)({parentName:"pre"},{}),'GET https://ory-hydra:4444/userinfo\nAuthorization: bearer new-access-token.xxxx\n\n{\n "acr": "oauth2",\n "sub": "[email protected]",\n "foo": "bar"\n}\n')),Object(i.b)("p",null,"You should only include data that has been authorized by the end-user through an\nOAuth 2.0 Scope. If an OAuth 2.0 Client, for example, requests the ",Object(i.b)("inlineCode",{parentName:"p"},"phone")," scope\nand the end-user authorizes that scope, the phone number should be added to\n",Object(i.b)("inlineCode",{parentName:"p"},"session.id_token"),"."),Object(i.b)("blockquote",null,Object(i.b)("p",{parentName:"blockquote"},"Be aware that the ",Object(i.b)("inlineCode",{parentName:"p"},"/userinfo")," endpoint is public. Its contents are thus as\npublicly visible as those of ID Tokens. It is therefore imperative to ",Object(i.b)("strong",{parentName:"p"},"not\nexpose sensitive information without end-user consent."))))}h.isMDXComponent=!0},224:function(e,t,n){"use strict";n.d(t,"a",(function(){return u})),n.d(t,"b",(function(){return d}));var o=n(0),a=n.n(o);function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function s(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,o)}return n}function r(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?s(Object(n),!0).forEach((function(t){i(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):s(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function l(e,t){if(null==e)return{};var n,o,a=function(e,t){if(null==e)return{};var n,o,a={},i=Object.keys(e);for(o=0;o<i.length;o++)n=i[o],t.indexOf(n)>=0||(a[n]=e[n]);return a}(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(o=0;o<i.length;o++)n=i[o],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}var c=a.a.createContext({}),h=function(e){var t=a.a.useContext(c),n=t;return e&&(n="function"==typeof e?e(t):r(r({},t),e)),n},u=function(e){var t=h(e.components);return a.a.createElement(c.Provider,{value:t},e.children)},b={inlineCode:"code",wrapper:function(e){var t=e.children;return a.a.createElement(a.a.Fragment,{},t)}},p=a.a.forwardRef((function(e,t){var n=e.components,o=e.mdxType,i=e.originalType,s=e.parentName,c=l(e,["components","mdxType","originalType","parentName"]),u=h(n),p=o,d=u["".concat(s,".").concat(p)]||u[p]||b[p]||i;return n?a.a.createElement(d,r(r({ref:t},c),{},{components:n})):a.a.createElement(d,r({ref:t},c))}));function d(e,t){var n=arguments,o=t&&t.mdxType;if("string"==typeof e||o){var i=n.length,s=new Array(i);s[0]=p;var r={};for(var l in t)hasOwnProperty.call(t,l)&&(r[l]=t[l]);r.originalType=e,r.mdxType="string"==typeof e?e:o,s[1]=r;for(var c=2;c<i;c++)s[c]=n[c];return a.a.createElement.apply(null,s)}return a.a.createElement.apply(null,n)}p.displayName="MDXCreateElement"}}]); | h |
07.py | """
Rhino Python Script Tutorial
Exercise 07
Let's reorganize the previous code to store the coordinates of our points in a list.
This list is called an array.
The following lesson explains why this is useful.
"""
import rhinoscriptsyntax as rs
import math
def | ():
n = 50
radius_0 = 3
points = []
for i in range(0, n): # notice how range() accepts variables
# a little trick here: as i goes from 0 to n-1, k will go from 0 to 1
k = i / (n - 1)
# traverse the full circle
angle = k * 3 * math.pi
# increase radius
radius = radius_0 * (1 + 5 * k)
point = [radius * math.cos(angle), radius * math.sin(angle),0]
rs.AddPoint(point)
points.append(point)
Main() | Main |
env.go | // Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.
package libkb
import (
"fmt"
"os"
"os/user"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"time"
logger "github.com/keybase/client/go/logger"
keybase1 "github.com/keybase/client/go/protocol/keybase1"
"github.com/keybase/client/go/systemd"
"github.com/syndtr/goleveldb/leveldb/opt"
)
type NullConfiguration struct{}
func (n NullConfiguration) GetHome() string { return "" }
func (n NullConfiguration) GetMobileSharedHome() string { return "" }
func (n NullConfiguration) GetServerURI() (string, error) { return "", nil }
func (n NullConfiguration) GetConfigFilename() string { return "" }
func (n NullConfiguration) GetUpdaterConfigFilename() string { return "" }
func (n NullConfiguration) GetGUIConfigFilename() string { return "" }
func (n NullConfiguration) GetDeviceCloneStateFilename() string { return "" }
func (n NullConfiguration) GetSessionFilename() string { return "" }
func (n NullConfiguration) GetDbFilename() string { return "" }
func (n NullConfiguration) GetChatDbFilename() string { return "" }
func (n NullConfiguration) GetPvlKitFilename() string { return "" }
func (n NullConfiguration) GetParamProofKitFilename() string { return "" }
func (n NullConfiguration) GetExternalURLKitFilename() string { return "" }
func (n NullConfiguration) GetProveBypass() (bool, bool) { return false, false }
func (n NullConfiguration) GetUsername() NormalizedUsername { return NormalizedUsername("") }
func (n NullConfiguration) GetEmail() string { return "" }
func (n NullConfiguration) GetProxy() string { return "" }
func (n NullConfiguration) GetProxyType() string { return "" }
func (n NullConfiguration) IsCertPinningEnabled() bool { return true }
func (n NullConfiguration) GetGpgHome() string { return "" }
func (n NullConfiguration) GetBundledCA(h string) string { return "" }
func (n NullConfiguration) GetUserCacheMaxAge() (time.Duration, bool) { return 0, false }
func (n NullConfiguration) GetProofCacheSize() (int, bool) { return 0, false }
func (n NullConfiguration) GetProofCacheLongDur() (time.Duration, bool) { return 0, false }
func (n NullConfiguration) GetProofCacheMediumDur() (time.Duration, bool) { return 0, false }
func (n NullConfiguration) GetProofCacheShortDur() (time.Duration, bool) { return 0, false }
func (n NullConfiguration) GetLinkCacheSize() (int, bool) { return 0, false }
func (n NullConfiguration) GetLinkCacheCleanDur() (time.Duration, bool) { return 0, false }
func (n NullConfiguration) GetUPAKCacheSize() (int, bool) { return 0, false }
func (n NullConfiguration) GetUIDMapFullNameCacheSize() (int, bool) { return 0, false }
func (n NullConfiguration) GetPayloadCacheSize() (int, bool) { return 0, false }
func (n NullConfiguration) GetMerkleKIDs() []string { return nil }
func (n NullConfiguration) GetCodeSigningKIDs() []string { return nil }
func (n NullConfiguration) GetPinentry() string { return "" }
func (n NullConfiguration) GetUID() (ret keybase1.UID) { return }
func (n NullConfiguration) GetGpg() string { return "" }
func (n NullConfiguration) GetGpgOptions() []string { return nil }
func (n NullConfiguration) GetPGPFingerprint() *PGPFingerprint { return nil }
func (n NullConfiguration) GetSecretKeyringTemplate() string { return "" }
func (n NullConfiguration) GetSalt() []byte { return nil }
func (n NullConfiguration) GetSocketFile() string { return "" }
func (n NullConfiguration) GetPidFile() string { return "" }
func (n NullConfiguration) GetStandalone() (bool, bool) { return false, false }
func (n NullConfiguration) GetLocalRPCDebug() string { return "" }
func (n NullConfiguration) GetTimers() string { return "" }
func (n NullConfiguration) GetDeviceID() keybase1.DeviceID { return "" }
func (n NullConfiguration) GetDeviceIDForUsername(un NormalizedUsername) keybase1.DeviceID { return "" }
func (n NullConfiguration) GetDeviceIDForUID(u keybase1.UID) keybase1.DeviceID { return "" }
func (n NullConfiguration) GetProxyCACerts() ([]string, error) { return nil, nil }
func (n NullConfiguration) GetUsernameForUID(u keybase1.UID) NormalizedUsername {
return NormalizedUsername("")
}
func (n NullConfiguration) GetUIDForUsername(u NormalizedUsername) keybase1.UID {
return keybase1.UID("")
}
func (n NullConfiguration) GetStayLoggedOut() (bool, bool) { return false, false }
func (n NullConfiguration) GetAutoFork() (bool, bool) { return false, false }
func (n NullConfiguration) GetRunMode() (RunMode, error) { return NoRunMode, nil }
func (n NullConfiguration) GetNoAutoFork() (bool, bool) { return false, false }
func (n NullConfiguration) GetLogFile() string { return "" }
func (n NullConfiguration) GetEKLogFile() string { return "" }
func (n NullConfiguration) GetPerfLogFile() string { return "" }
func (n NullConfiguration) GetGUILogFile() string { return "" }
func (n NullConfiguration) GetUseDefaultLogFile() (bool, bool) { return false, false }
func (n NullConfiguration) GetUseRootConfigFile() (bool, bool) { return false, false }
func (n NullConfiguration) GetLogPrefix() string { return "" }
func (n NullConfiguration) GetScraperTimeout() (time.Duration, bool) { return 0, false }
func (n NullConfiguration) GetAPITimeout() (time.Duration, bool) { return 0, false }
func (n NullConfiguration) GetTorMode() (TorMode, error) { return TorNone, nil }
func (n NullConfiguration) GetTorHiddenAddress() string { return "" }
func (n NullConfiguration) GetTorProxy() string { return "" }
func (n NullConfiguration) GetUpdatePreferenceAuto() (bool, bool) { return false, false }
func (n NullConfiguration) GetUpdatePreferenceSnoozeUntil() keybase1.Time { return keybase1.Time(0) }
func (n NullConfiguration) GetUpdateLastChecked() keybase1.Time { return keybase1.Time(0) }
func (n NullConfiguration) GetUpdatePreferenceSkip() string { return "" }
func (n NullConfiguration) GetUpdateURL() string { return "" }
func (n NullConfiguration) GetUpdateDisabled() (bool, bool) { return false, false }
func (n NullConfiguration) GetVDebugSetting() string { return "" }
func (n NullConfiguration) GetLocalTrackMaxAge() (time.Duration, bool) { return 0, false }
func (n NullConfiguration) GetGregorURI() string { return "" }
func (n NullConfiguration) GetGregorSaveInterval() (time.Duration, bool) { return 0, false }
func (n NullConfiguration) GetGregorPingInterval() (time.Duration, bool) { return 0, false }
func (n NullConfiguration) GetGregorPingTimeout() (time.Duration, bool) { return 0, false }
func (n NullConfiguration) GetChatDelivererInterval() (time.Duration, bool) { return 0, false }
func (n NullConfiguration) GetGregorDisabled() (bool, bool) { return false, false }
func (n NullConfiguration) GetSecretStorePrimingDisabled() (bool, bool) { return false, false }
func (n NullConfiguration) GetMountDir() string { return "" }
func (n NullConfiguration) GetMountDirDefault() string { return "" }
func (n NullConfiguration) GetBGIdentifierDisabled() (bool, bool) { return false, false }
func (n NullConfiguration) GetFeatureFlags() (FeatureFlags, error) { return FeatureFlags{}, nil }
func (n NullConfiguration) GetAppType() AppType { return NoAppType }
func (n NullConfiguration) IsMobileExtension() (bool, bool) { return false, false }
func (n NullConfiguration) GetSlowGregorConn() (bool, bool) { return false, false }
func (n NullConfiguration) GetReadDeletedSigChain() (bool, bool) { return false, false }
func (n NullConfiguration) GetRememberPassphrase(NormalizedUsername) (bool, bool) {
return false, false
}
func (n NullConfiguration) GetLevelDBNumFiles() (int, bool) { return 0, false }
func (n NullConfiguration) GetLevelDBWriteBufferMB() (int, bool) { return 4, false }
func (n NullConfiguration) GetChatInboxSourceLocalizeThreads() (int, bool) { return 1, false }
func (n NullConfiguration) GetAttachmentHTTPStartPort() (int, bool) { return 0, false }
func (n NullConfiguration) GetAttachmentDisableMulti() (bool, bool) { return false, false }
func (n NullConfiguration) GetDisableTeamAuditor() (bool, bool) { return false, false }
func (n NullConfiguration) GetDisableMerkleAuditor() (bool, bool) { return false, false }
func (n NullConfiguration) GetDisableSearchIndexer() (bool, bool) { return false, false }
func (n NullConfiguration) GetDisableBgConvLoader() (bool, bool) { return false, false }
func (n NullConfiguration) GetDisableTeamBoxAuditor() (bool, bool) { return false, false }
func (n NullConfiguration) GetDisableEKBackgroundKeygen() (bool, bool) { return false, false }
func (n NullConfiguration) GetEnableBotLiteMode() (bool, bool) { return false, false }
func (n NullConfiguration) GetExtraNetLogging() (bool, bool) { return false, false }
func (n NullConfiguration) GetForceLinuxKeyring() (bool, bool) { return false, false }
func (n NullConfiguration) GetForceSecretStoreFile() (bool, bool) { return false, false }
func (n NullConfiguration) GetRuntimeStatsEnabled() (bool, bool) { return false, false }
func (n NullConfiguration) GetPassphraseState() *keybase1.PassphraseState { return nil }
func (n NullConfiguration) GetPassphraseStateForUsername(NormalizedUsername) *keybase1.PassphraseState {
return nil
}
func (n NullConfiguration) GetBug3964RepairTime(NormalizedUsername) (time.Time, error) {
return time.Time{}, nil
}
func (n NullConfiguration) GetUserConfig() (*UserConfig, error) { return nil, nil }
func (n NullConfiguration) GetUserConfigForUsername(s NormalizedUsername) (*UserConfig, error) {
return nil, nil
}
func (n NullConfiguration) GetGString(string) string { return "" }
func (n NullConfiguration) GetString(string) string { return "" }
func (n NullConfiguration) GetBool(string, bool) (bool, bool) { return false, false }
func (n NullConfiguration) GetAllUsernames() (NormalizedUsername, []NormalizedUsername, error) {
return NormalizedUsername(""), nil, nil
}
func (n NullConfiguration) GetAllUserConfigs() (*UserConfig, []UserConfig, error) {
return nil, nil, nil
}
func (n NullConfiguration) GetDebug() (bool, bool) { return false, false }
func (n NullConfiguration) GetDebugJourneycard() (bool, bool) { return false, false }
func (n NullConfiguration) GetDisplayRawUntrustedOutput() (bool, bool) {
return false, false
}
func (n NullConfiguration) GetLogFormat() string {
return ""
}
func (n NullConfiguration) GetAPIDump() (bool, bool) {
return false, false
}
func (n NullConfiguration) GetNoPinentry() (bool, bool) {
return false, false
}
func (n NullConfiguration) GetStringAtPath(string) (string, bool) {
return "", false
}
func (n NullConfiguration) GetInterfaceAtPath(string) (interface{}, error) {
return nil, nil
}
func (n NullConfiguration) GetBoolAtPath(string) (bool, bool) {
return false, false
}
func (n NullConfiguration) GetIntAtPath(string) (int, bool) {
return 0, false
}
func (n NullConfiguration) GetFloatAtPath(string) (float64, bool) {
return 0, false
}
func (n NullConfiguration) GetNullAtPath(string) bool {
return false
}
func (n NullConfiguration) GetSecurityAccessGroupOverride() (bool, bool) {
return false, false
}
func (n NullConfiguration) GetAndroidInstallReferrerChecked() bool { return false }
type TestParameters struct {
ConfigFilename string
Home string
MobileSharedHome string
GPG string
GPGHome string
GPGOptions []string
Debug bool
// Whether we are in Devel Mode
Devel bool
// If we're in dev mode, the name for this test, with a random
// suffix.
DevelName string
DevelPrefix string // when in test - name for the test without suffix.
RuntimeDir string
DisableUpgradePerUserKey bool
EnvironmentFeatureFlags FeatureFlags
// set to true to use production run mode in tests
UseProductionRunMode bool
// whether LogoutIfRevoked check should be skipped to avoid races
// during resets.
SkipLogoutIfRevokedCheck bool
// On if, in test, we want to skip sending system chat messages
SkipSendingSystemChatMessages bool
// If we need to use the real clock for NIST generation (as in really
// whacky tests liks TestRekey).
UseTimeClockForNISTs bool
// TeamNoHeadMerkleStore is used for testing to emulate older clients
// that didn't store the head merkle sequence to team chain state. We
// have an upgrade path in the code that we'd like to test.
TeamNoHeadMerkleStore bool
// TeamSkipAudit is on because some team chains are "canned" and therefore
// might point off of the merkle sequence in the database. So it's just
// easiest to skip the audit in those cases.
TeamSkipAudit bool
// NoGregor is on if we want to test the service without any gregor conection
NoGregor bool
// TeamAuditParams can be customized if we want to control the behavior
// of audits deep in a test
TeamAuditParams *TeamAuditParams
// Toggle if we want to try to 'prime' the secret store before using it.
SecretStorePrimingDisabled bool
// Extra headers for API
APIHeaders map[string]string
}
func (tp TestParameters) GetDebug() (bool, bool) {
if tp.Debug {
return true, true
}
return false, false
}
func (tp TestParameters) GetNoGregor() (bool, bool) {
if tp.NoGregor {
return true, true
}
return false, false
}
func (tp TestParameters) GetSecretStorePrimingDisabled() (bool, bool) {
if tp.SecretStorePrimingDisabled {
return true, true
}
return false, false
}
type Env struct {
sync.RWMutex
cmd CommandLine
config ConfigReader
HomeFinder HomeFinder
writer ConfigWriter
Test *TestParameters
updaterConfig UpdaterConfigReader
guiConfig *JSONFile
}
func (e *Env) GetConfig() ConfigReader {
e.RLock()
defer e.RUnlock()
return e.config
}
func (e *Env) GetConfigWriter() ConfigWriter {
e.RLock()
defer e.RUnlock()
return e.writer
}
func (e *Env) SetCommandLine(cmd CommandLine) {
e.Lock()
defer e.Unlock()
e.cmd = cmd
}
func (e *Env) GetCommandLine() CommandLine {
e.RLock()
defer e.RUnlock()
return e.cmd
}
func (e *Env) SetConfig(r ConfigReader, w ConfigWriter) {
e.Lock()
defer e.Unlock()
e.config = r
e.writer = w
}
func (e *Env) SetGUIConfig(j *JSONFile) {
e.Lock()
defer e.Unlock()
e.guiConfig = j
}
func (e *Env) GetGUIConfig() *JSONFile {
e.RLock()
defer e.RUnlock()
return e.guiConfig
}
func (e *Env) SetUpdaterConfig(r UpdaterConfigReader) {
e.Lock()
defer e.Unlock()
e.updaterConfig = r
}
func (e *Env) GetUpdaterConfig() UpdaterConfigReader {
e.RLock()
defer e.RUnlock()
return e.updaterConfig
}
func (e *Env) GetOldMountDirDefault() string {
switch RuntimeGroup() {
case keybase1.RuntimeGroup_LINUXLIKE:
return filepath.Join(e.GetDataDir(), "fs")
default:
return e.GetMountDirDefault()
}
}
func (e *Env) GetMountDirDefault() string {
switch RuntimeGroup() {
case keybase1.RuntimeGroup_DARWINLIKE:
volumes := "/Volumes"
user, err := user.Current()
var username string
if err != nil {
// The iOS simulator may not have a proper user set,
username = "<unknown>"
} else {
username = user.Username
}
var runmodeName string
switch e.GetRunMode() {
case DevelRunMode:
runmodeName = "KeybaseDevel"
case StagingRunMode:
runmodeName = "KeybaseStaging"
case ProductionRunMode:
runmodeName = "Keybase"
default:
panic("Invalid run mode")
}
return filepath.Join(volumes, fmt.Sprintf(
"%s (%s)", runmodeName, username))
case keybase1.RuntimeGroup_LINUXLIKE:
return filepath.Join(e.GetRuntimeDir(), "kbfs")
// kbfsdokan depends on an empty default
case keybase1.RuntimeGroup_WINDOWSLIKE:
return ""
default:
return filepath.Join(e.GetRuntimeDir(), "kbfs")
}
}
func (e *Env) GetMountDir() (string, error) {
return e.GetString(
func() string { return e.cmd.GetMountDir() },
func() string { return os.Getenv("KEYBASE_MOUNTDIR") },
func() string { return e.GetConfig().GetMountDir() },
e.GetMountDirDefault,
), nil
}
func NewEnv(cmd CommandLine, config ConfigReader, getLog LogGetter) *Env |
func newEnv(cmd CommandLine, config ConfigReader, osname string, getLog LogGetter) *Env {
if cmd == nil {
cmd = NullConfiguration{}
}
if config == nil {
config = NullConfiguration{}
}
e := Env{cmd: cmd, config: config, Test: &TestParameters{}}
e.HomeFinder = NewHomeFinder("keybase",
e.getHomeFromTestOrCmd,
func() string { return e.GetConfig().GetHome() },
e.getMobileSharedHomeFromCmdOrConfig,
osname,
e.GetRunMode,
getLog,
os.Getenv)
return &e
}
func (e *Env) getHomeFromTestOrCmd() string {
return e.GetString(
func() string { return e.Test.Home },
func() string {
home := e.cmd.GetHome()
if home == "" {
return ""
}
absHome, err := filepath.Abs(home)
if err != nil {
return home
}
return absHome
},
)
}
func (e *Env) getMobileSharedHomeFromCmdOrConfig() string {
return e.GetString(
func() string { return e.Test.MobileSharedHome },
func() string { return e.cmd.GetMobileSharedHome() },
func() string { return e.GetConfig().GetMobileSharedHome() },
)
}
func (e *Env) GetDownloadsDir() string { return e.HomeFinder.DownloadsDir() }
func (e *Env) GetHome() string { return e.HomeFinder.Home(false) }
func (e *Env) GetMobileSharedHome() string { return e.HomeFinder.MobileSharedHome(false) }
func (e *Env) GetConfigDir() string { return e.HomeFinder.ConfigDir() }
func (e *Env) GetCacheDir() string { return e.HomeFinder.CacheDir() }
func (e *Env) GetSharedCacheDir() string { return e.HomeFinder.SharedCacheDir() }
func (e *Env) GetSandboxCacheDir() string { return e.HomeFinder.SandboxCacheDir() }
func (e *Env) GetDataDir() string { return e.HomeFinder.DataDir() }
func (e *Env) GetSharedDataDir() string { return e.HomeFinder.SharedDataDir() }
func (e *Env) GetLogDir() string { return e.HomeFinder.LogDir() }
func (e *Env) SendSystemChatMessages() bool {
return !e.Test.SkipSendingSystemChatMessages
}
func (e *Env) UseTimeClockForNISTs() bool {
return e.Test.UseTimeClockForNISTs
}
func (e *Env) GetRuntimeDir() string {
return e.GetString(
func() string { return e.Test.RuntimeDir },
func() string { return e.HomeFinder.RuntimeDir() },
)
}
func (e *Env) GetInfoDir() string {
return e.GetString(
func() string { return e.Test.RuntimeDir }, // needed for systests
func() string { return e.HomeFinder.InfoDir() },
)
}
func (e *Env) GetServiceSpawnDir() (string, error) { return e.HomeFinder.ServiceSpawnDir() }
func (e *Env) getEnvInt(s string) (int, bool) {
v := os.Getenv(s)
if len(v) > 0 {
tmp, err := strconv.ParseInt(v, 0, 64)
if err == nil {
return int(tmp), true
}
}
return 0, false
}
func (e *Env) getEnvPath(s string) []string {
if tmp := os.Getenv(s); len(tmp) != 0 {
return strings.Split(tmp, ":")
}
return nil
}
func (e *Env) getEnvBool(s string) (bool, bool) {
return getEnvBool(s)
}
func getEnvBool(s string) (bool, bool) {
tmp := os.Getenv(s)
if len(tmp) == 0 {
return false, false
}
tmp = strings.ToLower(tmp)
if tmp == "0" || tmp[0] == byte('n') {
return false, true
}
return true, true
}
func (e *Env) getEnvDuration(s string) (time.Duration, bool) {
d, err := time.ParseDuration(os.Getenv(s))
if err != nil {
return 0, false
}
return d, true
}
func (e *Env) GetString(flist ...(func() string)) string {
var ret string
for _, f := range flist {
ret = f()
if len(ret) > 0 {
break
}
}
return ret
}
func (e *Env) GetBool(def bool, flist ...func() (bool, bool)) bool {
for _, f := range flist {
if val, isSet := f(); isSet {
return val
}
}
return def
}
type NegBoolFunc struct {
neg bool
f func() (bool, bool)
}
// GetNegBool gets a negatable bool. You can give it a list of functions,
// and also possible negations for those functions.
func (e *Env) GetNegBool(def bool, flist []NegBoolFunc) bool {
for _, f := range flist {
if val, isSet := f.f(); isSet {
return (val != f.neg)
}
}
return def
}
func (e *Env) GetInt(def int, flist ...func() (int, bool)) int {
for _, f := range flist {
if val, isSet := f(); isSet {
return val
}
}
return def
}
func (e *Env) GetDuration(def time.Duration, flist ...func() (time.Duration, bool)) time.Duration {
for _, f := range flist {
if val, isSet := f(); isSet {
return val
}
}
return def
}
func (e *Env) GetServerURI() (string, error) {
// appveyor and os x travis CI set server URI, so need to
// check for test flag here in order for production api endpoint
// tests to pass.
if e.Test.UseProductionRunMode {
server, e := ServerLookup(e, e.GetRunMode())
if e != nil {
return "", nil
}
return server, nil
}
serverURI := e.GetString(
func() string {
serverURI, err := e.cmd.GetServerURI()
if err != nil {
return ""
}
return serverURI
},
func() string { return os.Getenv("KEYBASE_SERVER_URI") },
func() string {
serverURI, err := e.GetConfig().GetServerURI()
if err != nil {
return ""
}
return serverURI
},
func() string {
serverURI, err := ServerLookup(e, e.GetRunMode())
if err != nil {
return ""
}
return serverURI
},
)
if serverURI == "" {
return "", fmt.Errorf("Env failed to read a server URI from any source!")
}
return serverURI, nil
}
func (e *Env) GetUseRootConfigFile() bool {
return e.GetBool(false, e.cmd.GetUseRootConfigFile)
}
func (e *Env) GetRootRedirectorMount() (string, error) {
switch RuntimeGroup() {
case keybase1.RuntimeGroup_LINUXLIKE, keybase1.RuntimeGroup_DARWINLIKE:
return "/keybase", nil
default:
return "", fmt.Errorf("Root redirector mount unknown on this system.")
}
}
func (e *Env) GetRootConfigDirectory() (string, error) {
// NOTE: If this ever changes to more than one level deep, the configure
// redirector CLI command needs to be updated to update the permissions
// back to 0644 for all the created directories, or other processes won't
// be able to read them.
// Alternatively, we could package a blank config.json in that directory,
// but we can't rely on that for other packages.
switch RuntimeGroup() {
case keybase1.RuntimeGroup_LINUXLIKE:
return "/etc/keybase/", nil
default:
return "", fmt.Errorf("Root config directory unknown on this system")
}
}
func (e *Env) GetRootConfigFilename() (string, error) {
dir, err := e.GetRootConfigDirectory()
if err != nil {
return "", err
}
return filepath.Join(dir, "config.json"), nil
}
func (e *Env) GetEnvFileDir() (string, error) {
switch RuntimeGroup() {
case keybase1.RuntimeGroup_LINUXLIKE:
// Do not respect $XDG_CONFIG_HOME due to debian systemd 229 not supporting %E
// see keybase.service systemd unit
return filepath.Join(e.GetHome(), ".config", "keybase"), nil
default:
return "", fmt.Errorf("No envfiledir for %s.", runtime.GOOS)
}
}
func (e *Env) GetEnvfileName() (string, error) {
dir, err := e.GetEnvFileDir()
if err != nil {
return "", err
}
return filepath.Join(dir, "keybase.autogen.env"), nil
}
func (e *Env) GetOverrideEnvfileName() (string, error) {
dir, err := e.GetEnvFileDir()
if err != nil {
return "", err
}
return filepath.Join(dir, "keybase.env"), nil
}
func (e *Env) GetConfigFilename() string {
return e.GetString(
func() string {
if e.GetUseRootConfigFile() {
ret, err := e.GetRootConfigFilename()
if err != nil {
return ""
}
return ret
}
return ""
},
func() string { return e.Test.ConfigFilename },
func() string { return e.cmd.GetConfigFilename() },
func() string { return os.Getenv("KEYBASE_CONFIG_FILE") },
func() string { return e.GetConfig().GetConfigFilename() },
func() string { return filepath.Join(e.GetConfigDir(), ConfigFile) },
)
}
func (e *Env) GetUpdaterConfigFilename() string {
return e.GetString(
func() string {
if e.GetUseRootConfigFile() {
dir, err := e.GetRootConfigDirectory()
if err != nil {
return ""
}
return filepath.Join(dir, UpdaterConfigFile)
}
return ""
},
func() string { return e.cmd.GetUpdaterConfigFilename() },
func() string { return os.Getenv("KEYBASE_UPDATER_CONFIG_FILE") },
func() string { return e.GetConfig().GetUpdaterConfigFilename() },
func() string { return filepath.Join(e.GetConfigDir(), UpdaterConfigFile) },
)
}
func (e *Env) GetGUIConfigFilename() string {
return e.GetString(
func() string {
if e.GetUseRootConfigFile() {
dir, err := e.GetRootConfigDirectory()
if err != nil {
return ""
}
return filepath.Join(dir, GUIConfigFile)
}
return ""
},
func() string { return e.cmd.GetGUIConfigFilename() },
func() string { return os.Getenv("KEYBASE_GUI_CONFIG_FILE") },
func() string { return e.GetConfig().GetGUIConfigFilename() },
func() string { return filepath.Join(e.GetConfigDir(), GUIConfigFile) },
)
}
func (e *Env) GetDeviceCloneStateFilename() string {
return e.GetString(
func() string { return e.cmd.GetDeviceCloneStateFilename() },
func() string { return os.Getenv("KEYBASE_DEVICE_CLONE_STATE_FILE") },
func() string { return e.GetConfig().GetDeviceCloneStateFilename() },
func() string { return filepath.Join(e.GetConfigDir(), DeviceCloneStateFile) },
)
}
func (e *Env) GetSessionFilename() string {
return e.GetString(
func() string { return e.cmd.GetSessionFilename() },
func() string { return os.Getenv("KEYBASE_SESSION_FILE") },
func() string { return e.GetConfig().GetSessionFilename() },
func() string { return filepath.Join(e.GetCacheDir(), SessionFile) },
)
}
func (e *Env) GetDbFilename() string {
return e.GetString(
func() string { return e.cmd.GetDbFilename() },
func() string { return os.Getenv("KEYBASE_DB_FILE") },
func() string { return e.GetConfig().GetDbFilename() },
func() string { return filepath.Join(e.GetDataDir(), DBFile) },
)
}
func (e *Env) GetChatDbFilename() string {
return e.GetString(
func() string { return e.cmd.GetChatDbFilename() },
func() string { return os.Getenv("KEYBASE_CHAT_DB_FILE") },
func() string { return e.GetConfig().GetChatDbFilename() },
func() string { return filepath.Join(e.GetDataDir(), ChatDBFile) },
)
}
// GetPvlKitFilename gets the path to pvl kit file.
// Its value is usually "" which means to use the server.
func (e *Env) GetPvlKitFilename() string {
return e.GetString(
func() string { return e.cmd.GetPvlKitFilename() },
func() string { return os.Getenv("KEYBASE_PVL_KIT_FILE") },
func() string { return e.GetConfig().GetPvlKitFilename() },
)
}
// GetParamProofKitFilename gets the path to param proof kit file. Its value
// is usually "" which means to use the server.
func (e *Env) GetParamProofKitFilename() string {
return e.GetString(
func() string { return e.cmd.GetParamProofKitFilename() },
func() string { return os.Getenv("KEYBASE_PARAM_PROOF_KIT_FILE") },
func() string { return e.GetConfig().GetParamProofKitFilename() },
)
}
// GetExternalURLKitFilename gets the path to param proof kit file. Its value
// is usually "" which means to use the server.
func (e *Env) GetExternalURLKitFilename() string {
return e.GetString(
func() string { return e.cmd.GetExternalURLKitFilename() },
func() string { return os.Getenv("KEYBASE_EXTERNAL_URL_KIT_FILE") },
func() string { return e.GetConfig().GetExternalURLKitFilename() },
)
}
// GetProveBypass ignores creation_disabled so that the client will let the user
// try to make a proof for any known service.
func (e *Env) GetProveBypass() bool {
return e.GetBool(false,
func() (bool, bool) { return e.cmd.GetProveBypass() },
func() (bool, bool) { return e.getEnvBool("KEYBASE_PROVE_BYPASS") },
func() (bool, bool) { return e.GetConfig().GetProveBypass() })
}
// GetDebugJourneycard enables experimental chat journey cards.
func (e *Env) GetDebugJourneycard() bool {
return e.GetBool(false,
func() (bool, bool) { return e.cmd.GetDebugJourneycard() },
func() (bool, bool) { return e.getEnvBool("KEYBASE_DEBUG_JOURNEYCARD") },
func() (bool, bool) { return e.GetConfig().GetDebugJourneycard() })
}
func (e *Env) GetDebug() bool {
return e.GetBool(false,
func() (bool, bool) { return e.Test.GetDebug() },
func() (bool, bool) { return e.cmd.GetDebug() },
func() (bool, bool) { return e.getEnvBool("KEYBASE_DEBUG") },
func() (bool, bool) { return e.GetConfig().GetDebug() },
)
}
func (e *Env) GetDisplayRawUntrustedOutput() bool {
return e.GetBool(false,
func() (bool, bool) { return e.cmd.GetDisplayRawUntrustedOutput() },
func() (bool, bool) { return e.getEnvBool("KEYBASE_DISPLAY_RAW_UNTRUSTED_OUTPUT") },
func() (bool, bool) { return e.GetConfig().GetDisplayRawUntrustedOutput() },
)
}
func (e *Env) GetAutoFork() bool {
// On !Darwin, we auto-fork by default
def := (runtime.GOOS != "darwin")
return e.GetNegBool(def,
[]NegBoolFunc{
{
neg: false,
f: func() (bool, bool) { return e.cmd.GetAutoFork() },
},
{
neg: true,
f: func() (bool, bool) { return e.cmd.GetNoAutoFork() },
},
{
neg: false,
f: func() (bool, bool) { return e.getEnvBool("KEYBASE_AUTO_FORK") },
},
{
neg: true,
f: func() (bool, bool) { return e.getEnvBool("KEYBASE_NO_AUTO_FORK") },
},
{
neg: false,
f: func() (bool, bool) { return e.GetConfig().GetAutoFork() },
},
},
)
}
func (e *Env) GetStandalone() bool {
return e.GetBool(false,
func() (bool, bool) { return e.cmd.GetStandalone() },
func() (bool, bool) { return e.getEnvBool("KEYBASE_STANDALONE") },
func() (bool, bool) { return e.GetConfig().GetStandalone() },
)
}
func (e *Env) GetLogFormat() string {
return e.GetString(
func() string { return e.cmd.GetLogFormat() },
func() string { return os.Getenv("KEYBASE_LOG_FORMAT") },
func() string { return e.GetConfig().GetLogFormat() },
)
}
func (e *Env) GetLabel() string {
return e.GetString(
func() string { return e.cmd.GetString("label") },
func() string { return os.Getenv("KEYBASE_LABEL") },
)
}
func (e *Env) GetServiceType() string {
return e.GetString(
func() string { return os.Getenv("KEYBASE_SERVICE_TYPE") },
)
}
func (e *Env) GetAPIDump() bool {
return e.GetBool(false,
func() (bool, bool) { return e.cmd.GetAPIDump() },
func() (bool, bool) { return e.getEnvBool("KEYBASE_API_DUMP") },
)
}
func (e *Env) GetAllowRoot() bool {
return e.GetBool(false,
func() (bool, bool) { return e.getEnvBool("KEYBASE_ALLOW_ROOT") },
)
}
func (e *Env) GetUsername() NormalizedUsername {
return e.GetConfig().GetUsername()
}
func (e *Env) GetSocketBindFile() (string, error) {
return e.GetString(
e.sandboxSocketFile,
e.defaultSocketFile,
), nil
}
func (e *Env) defaultSocketFile() string {
socketFile := e.GetString(
func() string { return e.cmd.GetSocketFile() },
func() string { return os.Getenv("KEYBASE_SOCKET_FILE") },
func() string { return e.GetConfig().GetSocketFile() },
)
if socketFile == "" {
socketFile = filepath.Join(e.GetRuntimeDir(), SocketFile)
}
return socketFile
}
// sandboxSocketFile is socket file location for sandbox (macOS only)
// Note: this was added for KBFS finder integration, which was never
// activated.
func (e *Env) sandboxSocketFile() string {
sandboxCacheDir := e.HomeFinder.SandboxCacheDir()
if sandboxCacheDir == "" {
return ""
}
return filepath.Join(sandboxCacheDir, SocketFile)
}
func (e *Env) GetSocketDialFiles() ([]string, error) {
dialFiles := []string{}
sandboxSocketFile := e.sandboxSocketFile()
if sandboxSocketFile != "" {
dialFiles = append(dialFiles, sandboxSocketFile)
}
dialFiles = append(dialFiles, e.defaultSocketFile())
return dialFiles, nil
}
func (e *Env) GetGregorURI() string {
return e.GetString(
func() string { return os.Getenv("KEYBASE_PUSH_SERVER_URI") },
func() string { return e.GetConfig().GetGregorURI() },
func() string { return e.cmd.GetGregorURI() },
func() string { return GregorServerLookup[e.GetRunMode()] },
)
}
func (e *Env) GetGregorSaveInterval() time.Duration {
return e.GetDuration(time.Minute,
func() (time.Duration, bool) { return e.getEnvDuration("KEYBASE_PUSH_SAVE_INTERVAL") },
func() (time.Duration, bool) { return e.GetConfig().GetGregorSaveInterval() },
func() (time.Duration, bool) { return e.cmd.GetGregorSaveInterval() },
)
}
func (e *Env) GetGregorDisabled() bool {
return e.GetBool(false,
func() (bool, bool) { return e.Test.GetNoGregor() },
func() (bool, bool) { return e.cmd.GetGregorDisabled() },
func() (bool, bool) { return getEnvBool("KEYBASE_PUSH_DISABLED") },
func() (bool, bool) { return e.GetConfig().GetGregorDisabled() },
)
}
func (e *Env) GetSecretStorePrimingDisabled() bool {
return e.GetBool(false,
func() (bool, bool) { return e.Test.GetSecretStorePrimingDisabled() },
)
}
func (e *Env) GetBGIdentifierDisabled() bool {
return e.GetBool(true,
func() (bool, bool) { return e.cmd.GetBGIdentifierDisabled() },
func() (bool, bool) { return getEnvBool("KEYBASE_BG_IDENTIFIER_DISABLED") },
func() (bool, bool) { return e.GetConfig().GetBGIdentifierDisabled() },
)
}
func (e *Env) GetGregorPingInterval() time.Duration {
return e.GetDuration(10*time.Second,
func() (time.Duration, bool) { return e.getEnvDuration("KEYBASE_PUSH_PING_INTERVAL") },
func() (time.Duration, bool) { return e.GetConfig().GetGregorPingInterval() },
func() (time.Duration, bool) { return e.cmd.GetGregorPingInterval() },
)
}
func (e *Env) GetGregorPingTimeout() time.Duration {
return e.GetDuration(5*time.Second,
func() (time.Duration, bool) { return e.getEnvDuration("KEYBASE_PUSH_PING_TIMEOUT") },
func() (time.Duration, bool) { return e.GetConfig().GetGregorPingTimeout() },
func() (time.Duration, bool) { return e.cmd.GetGregorPingTimeout() },
)
}
func (e *Env) GetChatDelivererInterval() time.Duration {
return e.GetDuration(5*time.Second,
func() (time.Duration, bool) { return e.getEnvDuration("KEYBASE_CHAT_DELIVERER_INTERVAL") },
func() (time.Duration, bool) { return e.GetConfig().GetChatDelivererInterval() },
func() (time.Duration, bool) { return e.cmd.GetChatDelivererInterval() },
)
}
func (e *Env) GetAttachmentHTTPStartPort() int {
return e.GetInt(16423,
e.cmd.GetAttachmentHTTPStartPort,
func() (int, bool) { return e.getEnvInt("KEYBASE_ATTACHMENT_HTTP_START") },
e.GetConfig().GetAttachmentHTTPStartPort,
)
}
func (e *Env) GetAttachmentDisableMulti() bool {
return e.GetBool(false,
e.cmd.GetAttachmentDisableMulti,
func() (bool, bool) { return e.getEnvBool("KEYBASE_ATTACHMENT_DISABLE_MULTI") },
e.GetConfig().GetAttachmentDisableMulti,
)
}
func (e *Env) GetDisableTeamAuditor() bool {
return e.GetBool(false,
e.cmd.GetDisableTeamAuditor,
func() (bool, bool) { return e.getEnvBool("KEYBASE_DISABLE_TEAM_AUDITOR") },
e.GetConfig().GetDisableTeamAuditor,
// If unset, use the BotLite setting
func() (bool, bool) { return e.GetEnableBotLiteMode(), true },
)
}
func (e *Env) GetDisableTeamBoxAuditor() bool {
return e.GetBool(false,
e.cmd.GetDisableTeamBoxAuditor,
func() (bool, bool) { return e.getEnvBool("KEYBASE_DISABLE_TEAM_BOX_AUDITOR") },
e.GetConfig().GetDisableTeamBoxAuditor,
// If unset, use the BotLite setting
func() (bool, bool) { return e.GetEnableBotLiteMode(), true },
)
}
func (e *Env) GetDisableEKBackgroundKeygen() bool {
return e.GetBool(false,
e.cmd.GetDisableEKBackgroundKeygen,
func() (bool, bool) { return e.getEnvBool("KEYBASE_DISABLE_EK_BACKGROUND_KEYGEN") },
e.GetConfig().GetDisableEKBackgroundKeygen,
)
}
func (e *Env) GetDisableMerkleAuditor() bool {
return e.GetBool(false,
e.cmd.GetDisableMerkleAuditor,
func() (bool, bool) { return e.getEnvBool("KEYBASE_DISABLE_MERKLE_AUDITOR") },
e.GetConfig().GetDisableMerkleAuditor,
// If unset, use the BotLite setting
func() (bool, bool) { return e.GetEnableBotLiteMode(), true },
)
}
func (e *Env) GetDisableSearchIndexer() bool {
return e.GetBool(false,
e.cmd.GetDisableSearchIndexer,
func() (bool, bool) { return e.getEnvBool("KEYBASE_DISABLE_SEARCH_INDEXER") },
e.GetConfig().GetDisableSearchIndexer,
// If unset, use the BotLite setting
func() (bool, bool) { return e.GetEnableBotLiteMode(), true },
)
}
func (e *Env) GetDisableBgConvLoader() bool {
return e.GetBool(false,
e.cmd.GetDisableBgConvLoader,
func() (bool, bool) { return e.getEnvBool("KEYBASE_DISABLE_BG_CONV_LOADER") },
e.GetConfig().GetDisableBgConvLoader,
// If unset, use the BotLite setting
func() (bool, bool) { return e.GetEnableBotLiteMode(), true },
)
}
func (e *Env) GetEnableBotLiteMode() bool {
return e.GetBool(false,
e.cmd.GetEnableBotLiteMode,
func() (bool, bool) { return e.getEnvBool("KEYBASE_ENABLE_BOT_LITE_MODE") },
e.GetConfig().GetEnableBotLiteMode,
)
}
func (e *Env) GetExtraNetLogging() bool {
return e.GetBool(false,
e.cmd.GetExtraNetLogging,
func() (bool, bool) { return e.getEnvBool("KEYBASE_EXTRA_NET_LOGGING") },
e.GetConfig().GetExtraNetLogging,
)
}
func (e *Env) GetPidFile() (ret string, err error) {
ret = e.GetString(
func() string { return e.cmd.GetPidFile() },
func() string { return os.Getenv("KEYBASE_PID_FILE") },
func() string { return e.GetConfig().GetPidFile() },
)
if len(ret) == 0 {
ret = filepath.Join(e.GetInfoDir(), PIDFile)
}
return
}
func (e *Env) GetEmail() string {
return e.GetString(
func() string { return os.Getenv("KEYBASE_EMAIL") },
)
}
func (e *Env) GetStayLoggedOut() bool {
return e.GetBool(false,
func() (bool, bool) { return e.GetConfig().GetStayLoggedOut() },
)
}
// Upgrade sigchains to contain per-user-keys.
func (e *Env) GetUpgradePerUserKey() bool {
return !e.Test.DisableUpgradePerUserKey
}
// If true, do not logout after user.key_change notification handler
// decides that current device has been revoked.
func (e *Env) GetSkipLogoutIfRevokedCheck() bool {
return e.Test.SkipLogoutIfRevokedCheck
}
// Get the ProxyType based off of the configured proxy and tor settings
func (e *Env) GetProxyType() ProxyType {
if e.GetTorMode() != TorNone {
// Tor mode is enabled. Tor mode is implemented via a socks proxy
return Socks
}
var proxyTypeStr = e.GetString(
func() string { return e.cmd.GetProxyType() },
func() string { return os.Getenv("PROXY_TYPE") },
func() string { return e.GetConfig().GetProxyType() },
)
return ProxyTypeStrToEnumFunc(proxyTypeStr)
}
func ProxyTypeStrToEnumFunc(proxyTypeStr string) ProxyType {
proxyType, ok := ProxyTypeStrToEnum[strings.ToLower(proxyTypeStr)]
if ok {
return proxyType
}
// If they give us a bogus proxy type we just don't enable a proxy
return NoProxy
}
// Get the address (optionally including a port) of the currently configured proxy. Returns an empty string if no proxy
// is configured.
func (e *Env) GetProxy() string {
return e.GetString(
func() string {
// Only return the tor proxy address if tor mode is enabled to ensure we fall through to the other options
if e.GetTorMode() != TorNone {
return e.GetTorProxy()
}
return ""
},
// Prioritze tor mode over configured proxies
func() string { return e.cmd.GetProxy() },
func() string { return e.GetConfig().GetProxy() },
func() string { return os.Getenv("PROXY") },
// Prioritize the keybase specific methods of configuring a proxy above the standard unix env variables
func() string { return os.Getenv("HTTPS_PROXY") },
func() string { return os.Getenv("HTTP_PROXY") },
)
}
func (e *Env) IsCertPinningEnabled() bool {
// SSL Pinning is enabled if none of the config options say it is disabled
if !e.cmd.IsCertPinningEnabled() {
return false
}
res, isSet := e.getEnvBool("DISABLE_SSL_PINNING")
if isSet && res {
return false
}
if !e.GetConfig().IsCertPinningEnabled() {
return false
}
return true
}
func (e *Env) GetGpgHome() string {
return e.GetString(
func() string { return e.Test.GPGHome },
func() string { return e.cmd.GetGpgHome() },
func() string { return os.Getenv("GNUPGHOME") },
func() string { return e.GetConfig().GetGpgHome() },
func() string { return filepath.Join(e.GetHome(), ".gnupg") },
)
}
func (e *Env) GetPinentry() string {
return e.GetString(
func() string { return e.cmd.GetPinentry() },
func() string { return os.Getenv("KEYBASE_PINENTRY") },
func() string { return e.GetConfig().GetPinentry() },
)
}
func (e *Env) GetNoPinentry() bool {
isno := func(s string) (bool, bool) {
s = strings.ToLower(s)
if s == "0" || s == "no" || s == "n" || s == "none" {
return true, true
}
return false, false
}
return e.GetBool(false,
func() (bool, bool) { return isno(e.cmd.GetPinentry()) },
func() (bool, bool) { return isno(os.Getenv("KEYBASE_PINENTRY")) },
func() (bool, bool) { return e.GetConfig().GetNoPinentry() },
)
}
func (e *Env) GetBundledCA(host string) string {
return e.GetString(
func() string { return e.GetConfig().GetBundledCA(host) },
func() string {
ret, ok := GetBundledCAsFromHost(host)
if !ok {
return ""
}
return string(ret)
},
)
}
func (e *Env) GetUserCacheMaxAge() time.Duration {
return e.GetDuration(UserCacheMaxAge,
func() (time.Duration, bool) { return e.cmd.GetUserCacheMaxAge() },
func() (time.Duration, bool) { return e.getEnvDuration("KEYBASE_USER_CACHE_MAX_AGE") },
func() (time.Duration, bool) { return e.GetConfig().GetUserCacheMaxAge() },
)
}
func (e *Env) GetAPITimeout() time.Duration {
return e.GetDuration(HTTPDefaultTimeout,
func() (time.Duration, bool) { return e.cmd.GetAPITimeout() },
func() (time.Duration, bool) { return e.getEnvDuration("KEYBASE_API_TIMEOUT") },
func() (time.Duration, bool) { return e.GetConfig().GetAPITimeout() },
)
}
func (e *Env) GetScraperTimeout() time.Duration {
return e.GetDuration(HTTPDefaultScraperTimeout,
func() (time.Duration, bool) { return e.cmd.GetScraperTimeout() },
func() (time.Duration, bool) { return e.getEnvDuration("KEYBASE_SCRAPER_TIMEOUT") },
func() (time.Duration, bool) { return e.GetConfig().GetScraperTimeout() },
)
}
func (e *Env) GetLocalTrackMaxAge() time.Duration {
return e.GetDuration(LocalTrackMaxAge,
func() (time.Duration, bool) { return e.cmd.GetLocalTrackMaxAge() },
func() (time.Duration, bool) { return e.getEnvDuration("KEYBASE_LOCAL_TRACK_MAX_AGE") },
func() (time.Duration, bool) { return e.GetConfig().GetLocalTrackMaxAge() },
)
}
func (e *Env) GetProofCacheSize() int {
return e.GetInt(ProofCacheSize,
e.cmd.GetProofCacheSize,
func() (int, bool) { return e.getEnvInt("KEYBASE_PROOF_CACHE_SIZE") },
e.GetConfig().GetProofCacheSize,
)
}
func (e *Env) GetProofCacheLongDur() time.Duration {
return e.GetDuration(ProofCacheLongDur,
func() (time.Duration, bool) { return e.getEnvDuration("KEYBASE_PROOF_CACHE_LONG_DUR") },
e.GetConfig().GetProofCacheLongDur,
)
}
func (e *Env) GetProofCacheMediumDur() time.Duration {
return e.GetDuration(ProofCacheMediumDur,
func() (time.Duration, bool) { return e.getEnvDuration("KEYBASE_PROOF_CACHE_MEDIUM_DUR") },
e.GetConfig().GetProofCacheMediumDur,
)
}
func (e *Env) GetProofCacheShortDur() time.Duration {
return e.GetDuration(ProofCacheShortDur,
func() (time.Duration, bool) { return e.getEnvDuration("KEYBASE_PROOF_CACHE_SHORT_DUR") },
e.GetConfig().GetProofCacheShortDur,
)
}
func (e *Env) GetLinkCacheSize() int {
return e.GetInt(LinkCacheSize,
e.cmd.GetLinkCacheSize,
func() (int, bool) { return e.getEnvInt("KEYBASE_LINK_CACHE_SIZE") },
e.GetConfig().GetLinkCacheSize,
)
}
func (e *Env) GetUPAKCacheSize() int {
return e.GetInt(UPAKCacheSize,
e.cmd.GetUPAKCacheSize,
func() (int, bool) { return e.getEnvInt("KEYBASE_UPAK_CACHE_SIZE") },
e.GetConfig().GetUPAKCacheSize,
)
}
func (e *Env) GetUIDMapFullNameCacheSize() int {
return e.GetInt(UIDMapFullNameCacheSize,
e.cmd.GetUIDMapFullNameCacheSize,
func() (int, bool) { return e.getEnvInt("KEYBASE_UID_MAP_FULL_NAME_CACHE_SIZE") },
e.GetConfig().GetUIDMapFullNameCacheSize,
)
}
func (e *Env) GetLevelDBNumFiles() int {
return e.GetInt(LevelDBNumFiles,
e.cmd.GetLevelDBNumFiles,
func() (int, bool) { return e.getEnvInt("KEYBASE_LEVELDB_NUM_FILES") },
e.GetConfig().GetLevelDBNumFiles,
)
}
func (e *Env) GetLevelDBWriteBufferMB() int {
return e.GetInt(LevelDBWriteBufferMB,
e.cmd.GetLevelDBWriteBufferMB,
func() (int, bool) { return e.getEnvInt("KEYBASE_LEVELDB_WRITE_BUFFER_MB") },
e.GetConfig().GetLevelDBWriteBufferMB,
)
}
func (e *Env) GetLinkCacheCleanDur() time.Duration {
return e.GetDuration(LinkCacheCleanDur,
func() (time.Duration, bool) { return e.getEnvDuration("KEYBASE_LINK_CACHE_CLEAN_DUR") },
e.GetConfig().GetLinkCacheCleanDur,
)
}
func (e *Env) GetPayloadCacheSize() int {
return e.GetInt(PayloadCacheSize,
e.cmd.GetPayloadCacheSize,
func() (int, bool) { return e.getEnvInt("KEYBASE_PAYLOAD_CACHE_SIZE") },
e.GetConfig().GetPayloadCacheSize,
)
}
func (e *Env) GetEmailOrUsername() string {
un := e.GetUsername().String()
if len(un) > 0 {
return un
}
em := e.GetEmail()
return em
}
func (e *Env) GetRunMode() RunMode {
// If testing production run mode, then use it:
if e.Test.UseProductionRunMode {
return ProductionRunMode
}
var ret RunMode
pick := func(m RunMode, err error) {
if ret == NoRunMode && err == nil {
ret = m
}
}
pick(e.cmd.GetRunMode())
pick(StringToRunMode(os.Getenv("KEYBASE_RUN_MODE")))
pick(e.GetConfig().GetRunMode())
pick(DefaultRunMode, nil)
// If we aren't running in devel or staging and we're testing. Let's run in devel.
if e.Test.Devel && ret != DevelRunMode && ret != StagingRunMode {
return DevelRunMode
}
return ret
}
func (e *Env) GetAppType() AppType {
switch {
case e.cmd.GetAppType() != NoAppType:
return e.cmd.GetAppType()
case StringToAppType(os.Getenv("KEYBASE_APP_TYPE")) != NoAppType:
return StringToAppType(os.Getenv("KEYBASE_APP_TYPE"))
case e.GetConfig().GetAppType() != NoAppType:
return e.GetConfig().GetAppType()
default:
return NoAppType
}
}
func (e *Env) IsMobileExtension() bool {
return e.GetBool(false,
func() (bool, bool) { return e.cmd.IsMobileExtension() },
func() (bool, bool) { return e.getEnvBool("KEYBASE_MOBILE_EXTENSION") },
func() (bool, bool) { return e.GetConfig().IsMobileExtension() },
)
}
func (e *Env) GetSlowGregorConn() bool {
return e.GetBool(false,
func() (bool, bool) { return e.cmd.GetSlowGregorConn() },
func() (bool, bool) { return e.getEnvBool("KEYBASE_SLOW_GREGOR_CONN") },
func() (bool, bool) { return e.GetConfig().GetSlowGregorConn() },
)
}
func (e *Env) GetReadDeletedSigChain() bool {
return e.GetBool(false,
func() (bool, bool) { return e.cmd.GetReadDeletedSigChain() },
func() (bool, bool) { return e.getEnvBool("KEYBASE_READ_DELETED_SIGCHAIN") },
func() (bool, bool) { return e.GetConfig().GetReadDeletedSigChain() },
)
}
func (e *Env) GetFeatureFlags() FeatureFlags {
var ret FeatureFlags
pick := func(f FeatureFlags, err error) {
if ret.Empty() && err == nil {
ret = f
}
}
if e.Test.EnvironmentFeatureFlags != nil {
pick(e.Test.EnvironmentFeatureFlags, nil)
}
pick(e.cmd.GetFeatureFlags())
pick(StringToFeatureFlags(os.Getenv("KEYBASE_FEATURES")), nil)
pick(e.GetConfig().GetFeatureFlags())
return ret
}
func (e *Env) GetUID() keybase1.UID { return e.GetConfig().GetUID() }
func (e *Env) GetStringList(list ...(func() []string)) []string {
for _, f := range list {
if res := f(); res != nil {
return res
}
}
return []string{}
}
func (e *Env) GetMerkleKIDs() []keybase1.KID {
slist := e.GetStringList(
func() []string { return e.cmd.GetMerkleKIDs() },
func() []string { return e.getEnvPath("KEYBASE_MERKLE_KIDS") },
func() []string { return e.GetConfig().GetMerkleKIDs() },
func() []string {
ret := MerkleProdKIDs
if e.GetRunMode() == DevelRunMode || e.GetRunMode() == StagingRunMode {
ret = append(ret, MerkleTestKIDs...)
ret = append(ret, MerkleStagingKIDs...)
}
return ret
},
)
if slist == nil {
return nil
}
var ret []keybase1.KID
for _, s := range slist {
ret = append(ret, keybase1.KIDFromString(s))
}
return ret
}
func (e *Env) GetCodeSigningKIDs() []keybase1.KID {
slist := e.GetStringList(
func() []string { return e.cmd.GetCodeSigningKIDs() },
func() []string { return e.getEnvPath("KEYBASE_CODE_SIGNING_KIDS") },
func() []string { return e.GetConfig().GetCodeSigningKIDs() },
func() []string {
ret := CodeSigningProdKIDs
if e.GetRunMode() == DevelRunMode || e.GetRunMode() == StagingRunMode {
ret = append(ret, CodeSigningTestKIDs...)
ret = append(ret, CodeSigningStagingKIDs...)
}
return ret
},
)
if slist == nil {
return nil
}
var ret []keybase1.KID
for _, s := range slist {
ret = append(ret, keybase1.KIDFromString(s))
}
return ret
}
func (e *Env) GetGpg() string {
return e.GetString(
func() string { return e.Test.GPG },
func() string { return e.cmd.GetGpg() },
func() string { return os.Getenv("GPG") },
func() string { return e.GetConfig().GetGpg() },
)
}
func (e *Env) GetGpgOptions() []string {
return e.GetStringList(
func() []string { return e.Test.GPGOptions },
func() []string { return e.cmd.GetGpgOptions() },
func() []string { return e.GetConfig().GetGpgOptions() },
)
}
func (e *Env) GetSecretKeyringTemplate() string {
return e.GetString(
func() string { return e.cmd.GetSecretKeyringTemplate() },
func() string { return os.Getenv("KEYBASE_SECRET_KEYRING_TEMPLATE") },
func() string { return e.GetConfig().GetSecretKeyringTemplate() },
func() string { return filepath.Join(e.GetConfigDir(), SecretKeyringTemplate) },
)
}
func (e *Env) GetLocalRPCDebug() string {
return e.GetString(
func() string { return e.cmd.GetLocalRPCDebug() },
func() string { return os.Getenv("KEYBASE_LOCAL_RPC_DEBUG") },
func() string { return e.GetConfig().GetLocalRPCDebug() },
)
}
func (e *Env) GetDoLogForward() bool {
return e.GetLocalRPCDebug() == ""
}
func (e *Env) GetTimers() string {
return e.GetString(
func() string { return e.cmd.GetTimers() },
func() string { return os.Getenv("KEYBASE_TIMERS") },
func() string { return e.GetConfig().GetTimers() },
)
}
func (e *Env) GetConvSourceType() string {
return e.GetString(
func() string { return os.Getenv("KEYBASE_CONV_SOURCE_TYPE") },
func() string { return "hybrid" },
)
}
func (e *Env) GetInboxSourceType() string {
return e.GetString(
func() string { return os.Getenv("KEYBASE_INBOX_SOURCE_TYPE") },
func() string { return "hybrid" },
)
}
func (e *Env) GetChatInboxSourceLocalizeThreads() int {
return e.GetInt(
10,
e.cmd.GetChatInboxSourceLocalizeThreads,
func() (int, bool) { return e.getEnvInt("KEYBASE_INBOX_SOURCE_LOCALIZE_THREADS") },
e.GetConfig().GetChatInboxSourceLocalizeThreads,
)
}
// GetChatMemberType returns the default member type for new conversations.
func (e *Env) GetChatMemberType() string {
return e.GetString(
func() string { return os.Getenv("KEYBASE_CHAT_MEMBER_TYPE") },
func() string { return "impteam" },
)
}
func (e *Env) GetAvatarSource() string {
return e.GetString(
func() string { return os.Getenv("KEYBASE_AVATAR_SOURCE") },
func() string { return "full" },
)
}
func (e *Env) GetDeviceID() keybase1.DeviceID {
return e.GetConfig().GetDeviceID()
}
func (e *Env) GetDeviceIDForUsername(u NormalizedUsername) keybase1.DeviceID {
return e.GetConfig().GetDeviceIDForUsername(u)
}
func (e *Env) GetDeviceIDForUID(u keybase1.UID) keybase1.DeviceID {
return e.GetConfig().GetDeviceIDForUID(u)
}
func (e *Env) GetUsernameForUID(u keybase1.UID) NormalizedUsername {
return e.GetConfig().GetUsernameForUID(u)
}
func (e *Env) GetInstallID() (ret InstallID) {
if rdr := e.GetUpdaterConfig(); rdr != nil {
ret = rdr.GetInstallID()
}
return ret
}
func (e *Env) GetEffectiveLogFile() (filename string, ok bool) {
logFile := e.GetLogFile()
if logFile != "" {
return logFile, true
}
filePrefix := e.GetLogPrefix()
if filePrefix != "" {
filePrefix += time.Now().Format("20060102T150405.999999999Z0700")
logFile = filePrefix + ".log"
return logFile, true
}
return e.GetDefaultLogFile(), e.GetUseDefaultLogFile()
}
func (e *Env) GetLogFile() string {
return e.GetString(
func() string { return e.cmd.GetLogFile() },
func() string { return os.Getenv("KEYBASE_LOG_FILE") },
)
}
func (e *Env) GetEKLogFile() string {
return e.GetString(
func() string { return e.cmd.GetEKLogFile() },
func() string { return os.Getenv("KEYBASE_EK_LOG_FILE") },
func() string { return filepath.Join(e.GetLogDir(), EKLogFileName) },
)
}
func (e *Env) GetPerfLogFile() string {
return e.GetString(
func() string { return e.cmd.GetPerfLogFile() },
func() string { return os.Getenv("KEYBASE_PERF_LOG_FILE") },
func() string { return filepath.Join(e.GetLogDir(), PerfLogFileName) },
)
}
func (e *Env) GetGUILogFile() string {
return e.GetString(
func() string { return e.cmd.GetGUILogFile() },
func() string { return os.Getenv("KEYBASE_GUI_LOG_FILE") },
func() string { return filepath.Join(e.GetLogDir(), GUILogFileName) },
)
}
func (e *Env) GetUseDefaultLogFile() bool {
return e.GetBool(false,
e.cmd.GetUseDefaultLogFile,
func() (bool, bool) { return e.getEnvBool("KEYBASE_USE_DEFAULT_LOG_FILE") },
)
}
func (e *Env) GetLogPrefix() string {
return e.cmd.GetLogPrefix()
}
func (e *Env) GetDefaultLogFile() string {
return filepath.Join(e.GetLogDir(), ServiceLogFileName)
}
func (e *Env) GetTorMode() TorMode {
var ret TorMode
pick := func(m TorMode, err error) {
if ret == TorNone && err == nil {
ret = m
}
}
pick(e.cmd.GetTorMode())
pick(StringToTorMode(os.Getenv("KEYBASE_TOR_MODE")))
pick(e.GetConfig().GetTorMode())
return ret
}
func (e *Env) GetTorHiddenAddress() string {
return e.GetString(
func() string { return e.cmd.GetTorHiddenAddress() },
func() string { return os.Getenv("KEYBASE_TOR_HIDDEN_ADDRESS") },
func() string { return e.GetConfig().GetTorHiddenAddress() },
func() string { return TorServerURI },
)
}
func (e *Env) GetTorProxy() string {
return e.GetString(
func() string { return e.cmd.GetTorProxy() },
func() string { return os.Getenv("KEYBASE_TOR_PROXY") },
func() string { return e.GetConfig().GetTorProxy() },
func() string { return TorProxy },
)
}
func (e *Env) GetStoredSecretAccessGroup() string {
var override = e.GetBool(
false,
func() (bool, bool) { return e.GetConfig().GetSecurityAccessGroupOverride() },
)
if override {
return ""
}
return "99229SGT5K.group.keybase"
}
func (e *Env) GetStoredSecretServiceBaseName() string {
var serviceName string
switch e.GetRunMode() {
case DevelRunMode:
serviceName = "keybase-devel"
case StagingRunMode:
serviceName = "keybase-staging"
case ProductionRunMode:
serviceName = "keybase"
default:
panic("Invalid run mode")
}
if e.Test.Devel {
// Append DevelName so that tests won't clobber each
// other's keychain entries on shutdown.
serviceName += "-test"
}
return serviceName
}
func (e *Env) GetStoredSecretServiceName() string {
serviceName := e.GetStoredSecretServiceBaseName()
if e.Test.Devel {
// Append DevelName so that tests won't clobber each
// other's keychain entries on shutdown.
serviceName += fmt.Sprintf("(%s)", e.Test.DevelName)
}
return serviceName
}
type AppConfig struct {
NullConfiguration
DownloadsDir string
HomeDir string
MobileSharedHomeDir string
LogFile string
EKLogFile string
PerfLogFile string
GUILogFile string
UseDefaultLogFile bool
RunMode RunMode
Debug bool
LocalRPCDebug string
ServerURI string
VDebugSetting string
SecurityAccessGroupOverride bool
ChatInboxSourceLocalizeThreads int
MobileExtension bool
AttachmentHTTPStartPort int
AttachmentDisableMulti bool
LinkCacheSize int
UPAKCacheSize int
PayloadCacheSize int
ProofCacheSize int
DisableTeamAuditor bool
DisableMerkleAuditor bool
DisableTeamBoxAuditor bool
DisableEKBackgroundKeygen bool
LevelDBWriteBufferMB int
LevelDBNumFiles int
}
var _ CommandLine = AppConfig{}
func (c AppConfig) GetLogFile() string {
return c.LogFile
}
func (c AppConfig) GetEKLogFile() string {
return c.EKLogFile
}
func (c AppConfig) GetPerfLogFile() string {
return c.PerfLogFile
}
func (c AppConfig) GetGUILogFile() string {
return c.GUILogFile
}
func (c AppConfig) GetUseDefaultLogFile() (bool, bool) {
return c.UseDefaultLogFile, true
}
func (c AppConfig) GetDebug() (bool, bool) {
return c.Debug, c.Debug
}
func (c AppConfig) GetLocalRPCDebug() string {
return c.LocalRPCDebug
}
func (c AppConfig) GetRunMode() (RunMode, error) {
return c.RunMode, nil
}
func (c AppConfig) GetDownloadsDir() string {
return c.DownloadsDir
}
func (c AppConfig) GetHome() string {
return c.HomeDir
}
func (c AppConfig) GetMobileSharedHome() string {
return c.MobileSharedHomeDir
}
func (c AppConfig) GetServerURI() (string, error) {
return c.ServerURI, nil
}
func (c AppConfig) GetSecurityAccessGroupOverride() (bool, bool) {
return c.SecurityAccessGroupOverride, c.SecurityAccessGroupOverride
}
func (c AppConfig) GetAppType() AppType {
return MobileAppType
}
func (c AppConfig) IsMobileExtension() (bool, bool) {
return c.MobileExtension, true
}
func (c AppConfig) GetSlowGregorConn() (bool, bool) {
return false, false
}
func (c AppConfig) GetReadDeletedSigChain() (bool, bool) {
return false, false
}
func (c AppConfig) GetVDebugSetting() string {
return c.VDebugSetting
}
func (c AppConfig) GetChatInboxSourceLocalizeThreads() (int, bool) {
return c.ChatInboxSourceLocalizeThreads, true
}
func (c AppConfig) GetLevelDBWriteBufferMB() (int, bool) {
if c.LevelDBWriteBufferMB > 0 {
return c.LevelDBWriteBufferMB, true
}
return LevelDBWriteBufferMBMobile, true
}
func (c AppConfig) GetLevelDBNumFiles() (int, bool) {
if c.LevelDBNumFiles > 0 {
return c.LevelDBNumFiles, true
}
return LevelDBNumFiles, true
}
func (c AppConfig) GetAttachmentHTTPStartPort() (int, bool) {
if c.AttachmentHTTPStartPort != 0 {
return c.AttachmentHTTPStartPort, true
}
return 0, false
}
func (c AppConfig) GetLinkCacheSize() (int, bool) {
if c.LinkCacheSize != 0 {
return c.LinkCacheSize, true
}
return 0, false
}
func (c AppConfig) GetUPAKCacheSize() (int, bool) {
if c.UPAKCacheSize != 0 {
return c.UPAKCacheSize, true
}
return 0, false
}
func (c AppConfig) GetPayloadCacheSize() (int, bool) {
if c.PayloadCacheSize != 0 {
return c.PayloadCacheSize, true
}
return 0, false
}
func (c AppConfig) GetProofCacheSize() (int, bool) {
if c.ProofCacheSize != 0 {
return c.ProofCacheSize, true
}
return 0, false
}
func (c AppConfig) GetDisableTeamAuditor() (bool, bool) {
return c.DisableTeamAuditor, true
}
func (c AppConfig) GetDisableMerkleAuditor() (bool, bool) {
return c.DisableMerkleAuditor, true
}
func (c AppConfig) GetDisableTeamBoxAuditor() (bool, bool) {
return c.DisableTeamBoxAuditor, true
}
func (c AppConfig) GetDisableEKBackgroundKeygen() (bool, bool) {
return c.DisableEKBackgroundKeygen, true
}
func (c AppConfig) GetAttachmentDisableMulti() (bool, bool) {
return c.AttachmentDisableMulti, true
}
func (e *Env) GetUpdatePreferenceAuto() (bool, bool) {
return e.GetConfig().GetUpdatePreferenceAuto()
}
func (e *Env) GetUpdatePreferenceSkip() string {
return e.GetConfig().GetUpdatePreferenceSkip()
}
func (e *Env) GetUpdatePreferenceSnoozeUntil() keybase1.Time {
return e.GetConfig().GetUpdatePreferenceSnoozeUntil()
}
func (e *Env) GetUpdateLastChecked() keybase1.Time {
return e.GetConfig().GetUpdateLastChecked()
}
func (e *Env) SetUpdatePreferenceAuto(b bool) error {
return e.GetConfigWriter().SetUpdatePreferenceAuto(b)
}
func (e *Env) SetUpdatePreferenceSkip(v string) error {
return e.GetConfigWriter().SetUpdatePreferenceSkip(v)
}
func (e *Env) SetUpdatePreferenceSnoozeUntil(t keybase1.Time) error {
return e.GetConfigWriter().SetUpdatePreferenceSnoozeUntil(t)
}
func (e *Env) SetUpdateLastChecked(t keybase1.Time) error {
return e.GetConfigWriter().SetUpdateLastChecked(t)
}
func (e *Env) GetUpdateURL() string {
return e.GetConfig().GetUpdateURL()
}
func (e *Env) GetUpdateDisabled() (bool, bool) {
return e.GetConfig().GetUpdateDisabled()
}
func (e *Env) GetVDebugSetting() string {
return e.GetString(
func() string { return e.cmd.GetVDebugSetting() },
func() string { return os.Getenv("KEYBASE_VDEBUG") },
func() string { return e.GetConfig().GetVDebugSetting() },
func() string { return "" },
)
}
func (e *Env) GetRunModeAsString() string {
return string(e.GetRunMode())
}
// GetServiceInfoPath returns path to info file written by the Keybase service after startup
func (e *Env) GetServiceInfoPath() string {
return filepath.Join(e.GetRuntimeDir(), "keybased.info")
}
// GetKBFSInfoPath returns path to info file written by the KBFS service after startup
func (e *Env) GetKBFSInfoPath() string {
return filepath.Join(e.GetRuntimeDir(), "kbfs.info")
}
func (e *Env) GetUpdateDefaultInstructions() (string, error) {
return PlatformSpecificUpgradeInstructionsString()
}
func (e *Env) RunningInCI() bool {
return e.GetBool(false,
func() (bool, bool) { return e.getEnvBool("KEYBASE_RUN_CI") },
)
}
func (e *Env) WantsSystemd() bool {
isNonstandard, isNonstandardErr := e.HomeFinder.IsNonstandardHome()
return (e.GetRunMode() == ProductionRunMode && e.ModelessWantsSystemd() && (isNonstandardErr != nil || !isNonstandard))
}
func (e *Env) ModelessWantsSystemd() bool {
return (systemd.IsRunningSystemd() &&
os.Getenv("KEYBASE_SYSTEMD") != "0")
}
func (e *Env) ForceSecretStoreFile() bool {
// By default use system-provided secret store (like MacOS Keychain), but
// allow users to fall back to file-based store for testing and debugging.
return e.GetBool(false,
func() (bool, bool) { return e.getEnvBool("KEYBASE_SECRET_STORE_FILE") },
func() (bool, bool) { return e.GetConfig().GetForceSecretStoreFile() },
)
}
func (e *Env) GetRuntimeStatsEnabled() bool {
return e.GetBool(false,
func() (bool, bool) { return e.getEnvBool("KEYBASE_RUNTIME_STATS_ENABLED") },
func() (bool, bool) { return e.GetConfig().GetRuntimeStatsEnabled() },
)
}
func (e *Env) GetRememberPassphrase(username NormalizedUsername) bool {
return e.GetBool(true,
func() (bool, bool) { return e.cmd.GetRememberPassphrase(username) },
func() (bool, bool) { return e.GetConfig().GetRememberPassphrase(username) },
)
}
func GetPlatformString() string {
if IsIPad {
return "ipad"
}
if isIOS {
return "ios"
}
return runtime.GOOS
}
func IsMobilePlatform() bool {
s := GetPlatformString()
return (s == "ios" || s == "android" || s == "ipad")
}
func IsAndroid() bool {
return GetPlatformString() == "android"
}
func (e *Env) AllowPTrace() bool {
return e.GetBool(false,
func() (bool, bool) { return e.getEnvBool("KEYBASE_ALLOW_PTRACE") },
)
}
func (e *Env) GetLogFileConfig(filename string) *logger.LogFileConfig {
var maxKeepFiles int
var maxSize int64
if e.GetAppType() == MobileAppType && !e.GetFeatureFlags().Admin(e.GetUID()) {
maxKeepFiles = 2
maxSize = 16 * opt.MiB
} else {
maxKeepFiles = 3
maxSize = 128 * opt.MiB
}
return &logger.LogFileConfig{
Path: filename,
MaxAge: 30 * 24 * time.Hour, // 30 days
MaxSize: maxSize,
MaxKeepFiles: maxKeepFiles,
}
}
func (e *Env) GetForceLinuxKeyring() bool {
return e.GetBool(false,
func() (bool, bool) { return e.cmd.GetForceLinuxKeyring() },
func() (bool, bool) { return e.getEnvBool("KEYBASE_FORCE_LINUX_KEYRING") },
func() (bool, bool) { return e.GetConfig().GetForceLinuxKeyring() })
}
| {
return newEnv(cmd, config, runtime.GOOS, getLog)
} |
presenter.go | package notice
import (
"fmt"
"github.com/AriNoa/SysLabHelper/handler/webhook"
"github.com/bwmarrin/discordgo"
)
type Presenter struct {
Session *discordgo.Session
}
func (p *Presenter) IssueOpened(channelID string, hc *webhook.HookContext) error {
payload, err := getPayloadMap(hc)
if err != nil {
return err
}
issue, _ := getObject(payload, "issue")
url, _ := getString(issue, "html_url")
number, _ := getNumber(issue, "number")
title, _ := getString(issue, "title")
description, _ := getString(issue, "body")
repository, _ := getObject(payload, "repository")
repoName, _ := getString(repository, "full_name")
user, _ := getObject(issue, "user")
userName, _ := getString(user, "login")
userURL, _ := getString(user, "html_url")
userAvatar, _ := getString(user, "avatar_url")
embed := discordgo.MessageEmbed{
URL: url,
Title: fmt.Sprintf("[%s] Issue opened: #%d %s", repoName, number, title),
Description: description,
Author: &discordgo.MessageEmbedAuthor{
URL: userURL,
Name: userName,
IconURL: userAvatar,
},
}
_, err = p.Session.ChannelMessageSendEmbed(channelID, &embed)
return err
}
func (p *Presenter) PullRequestOpened(channelID string, hc *webhook.HookContext) error {
payload, err := getPayloadMap(hc)
if err != nil |
PR, _ := getObject(payload, "pull_request")
url, _ := getString(PR, "html_url")
number, _ := getNumber(PR, "number")
title, _ := getString(PR, "title")
description, _ := getString(PR, "body")
repository, _ := getObject(payload, "repository")
repoName, _ := getString(repository, "full_name")
user, _ := getObject(PR, "user")
userName, _ := getString(user, "login")
userURL, _ := getString(user, "html_url")
userAvatar, _ := getString(user, "avatar_url")
embed := discordgo.MessageEmbed{
URL: url,
Title: fmt.Sprintf("[%s] Pull request opened: #%d %s", repoName, number, title),
Description: description,
Author: &discordgo.MessageEmbedAuthor{
URL: userURL,
Name: userName,
IconURL: userAvatar,
},
}
_, err = p.Session.ChannelMessageSendEmbed(channelID, &embed)
return err
}
func (p *Presenter) Pushed(channelID string, hc *webhook.HookContext) error {
payload, err := getPayloadMap(hc)
if err != nil {
return err
}
commits, _ := getSlice(payload, "commits")
if len(commits) <= 0 {
return nil
}
_, err = p.Session.ChannelMessageSend(channelID, "pushed")
return err
}
| {
return err
} |
accesslogformatter_test.go | package helper
import (
"io/ioutil"
"testing"
"time"
| log "github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
)
func TestAccessLogFormatter_Format(t *testing.T) {
discardLogger := log.New()
discardLogger.Out = ioutil.Discard
tests := []struct {
name string
entry *log.Entry
want string
}{
{
"blank",
discardLogger.WithField("blank", ""),
"- - - [2018/01/07:00:00:00 +0000] \" \" 0 0 \"\" \"\" 0.000\n",
},
{
"full",
discardLogger.WithFields(log.Fields{
"host": "gitlab.com",
"remoteAddr": "127.0.0.1",
"method": "GET",
"uri": "/",
"proto": "HTTP/1.1",
"status": 200,
"written": 100,
"referer": "http://localhost",
"userAgent": "Mozilla/1.0",
"duration": 5.0,
}),
"gitlab.com 127.0.0.1 - - [2018/01/07:00:00:00 +0000] \"GET / HTTP/1.1\" 200 100 \"http://localhost\" \"Mozilla/1.0\" 5.000\n",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f := &accessLogFormatter{clock: &StubClock{time.Unix(1515283200, 0).UTC()}}
got, err := f.Format(tt.entry)
if err != nil {
t.Errorf("AccessLogFormatter.Format() error = %v", err)
return
}
assert.Equal(t, tt.want, string(got))
})
}
} | |
1ef399cbd2b_add_downloads_and_followers_to_mod.py | """Add downloads and followers to Mod
Revision ID: 1ef399cbd2b
Revises: 29cdccab86f
Create Date: 2014-06-11 17:10:26.480478
"""
# revision identifiers, used by Alembic.
revision = '1ef399cbd2b'
down_revision = '29cdccab86f'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
|
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('mod', 'follower_count')
op.drop_column('mod', 'download_count')
### end Alembic commands ###
| op.add_column('mod', sa.Column('download_count', sa.Integer(), server_default='0', nullable=False))
op.add_column('mod', sa.Column('follower_count', sa.Integer(), server_default='0', nullable=False))
### end Alembic commands ### |
712.js | var NISLFuzzingFunc = function() {
this.isOpen ? this.close() : this.open(); | };
NISLFuzzingFunc(); |
|
model_util.py | import torch
import torch.nn as nn
import torch.nn.init as init
from .nets.backbone import HourglassBackbone, SuperpointBackbone
from .nets.junction_decoder import SuperpointDecoder
from .nets.heatmap_decoder import PixelShuffleDecoder
from .nets.descriptor_decoder import SuperpointDescriptor
def get_model(model_cfg=None, loss_weights=None, mode="train"):
""" Get model based on the model configuration. """
# Check dataset config is given
if model_cfg is None:
raise ValueError("[Error] The model config is required!")
# List the supported options here
print("\n\n\t--------Initializing model----------")
supported_arch = ["simple"]
if not model_cfg["model_architecture"] in supported_arch:
raise ValueError(
"[Error] The model architecture is not in supported arch!")
if model_cfg["model_architecture"] == "simple":
model = SOLD2Net(model_cfg)
else:
raise ValueError(
"[Error] The model architecture is not in supported arch!")
# Optionally register loss weights to the model
if mode == "train":
if loss_weights is not None:
for param_name, param in loss_weights.items():
if isinstance(param, nn.Parameter):
print("\t [Debug] Adding %s with value %f to model"
% (param_name, param.item()))
model.register_parameter(param_name, param)
else:
raise ValueError(
"[Error] the loss weights can not be None in dynamic weighting mode during training.")
# Display some summary info.
print("\tModel architecture: %s" % model_cfg["model_architecture"])
print("\tBackbone: %s" % model_cfg["backbone"])
print("\tJunction decoder: %s" % model_cfg["junction_decoder"])
print("\tHeatmap decoder: %s" % model_cfg["heatmap_decoder"])
print("\t-------------------------------------")
return model
class SOLD2Net(nn.Module):
""" Full network for SOLD². """
def __init__(self, model_cfg):
super(SOLD2Net, self).__init__()
self.name = model_cfg["model_name"]
self.cfg = model_cfg
# List supported network options
self.supported_backbone = ["lcnn", "superpoint"]
self.backbone_net, self.feat_channel = self.get_backbone()
# List supported junction decoder options
self.supported_junction_decoder = ["superpoint_decoder"]
self.junction_decoder = self.get_junction_decoder()
# List supported heatmap decoder options
self.supported_heatmap_decoder = ["pixel_shuffle",
"pixel_shuffle_single"]
self.heatmap_decoder = self.get_heatmap_decoder()
# List supported descriptor decoder options
if "descriptor_decoder" in self.cfg:
self.supported_descriptor_decoder = ["superpoint_descriptor"]
self.descriptor_decoder = self.get_descriptor_decoder()
# Initialize the model weights
self.apply(weight_init)
def forward(self, input_images):
# The backbone
features = self.backbone_net(input_images)
# junction decoder
junctions = self.junction_decoder(features)
# heatmap decoder
heatmaps = self.heatmap_decoder(features)
outputs = {"junctions": junctions, "heatmap": heatmaps}
# Descriptor decoder
if "descriptor_decoder" in self.cfg:
outputs["descriptors"] = self.descriptor_decoder(features)
| return outputs
def get_backbone(self):
""" Retrieve the backbone encoder network. """
if not self.cfg["backbone"] in self.supported_backbone:
raise ValueError(
"[Error] The backbone selection is not supported.")
# lcnn backbone (stacked hourglass)
if self.cfg["backbone"] == "lcnn":
backbone_cfg = self.cfg["backbone_cfg"]
backbone = HourglassBackbone(**backbone_cfg)
feat_channel = 256
elif self.cfg["backbone"] == "superpoint":
backbone_cfg = self.cfg["backbone_cfg"]
backbone = SuperpointBackbone()
feat_channel = 128
else:
raise ValueError(
"[Error] The backbone selection is not supported.")
return backbone, feat_channel
def get_junction_decoder(self):
""" Get the junction decoder. """
if (not self.cfg["junction_decoder"]
in self.supported_junction_decoder):
raise ValueError(
"[Error] The junction decoder selection is not supported.")
# superpoint decoder
if self.cfg["junction_decoder"] == "superpoint_decoder":
decoder = SuperpointDecoder(self.feat_channel,
self.cfg["backbone"])
else:
raise ValueError(
"[Error] The junction decoder selection is not supported.")
return decoder
def get_heatmap_decoder(self):
""" Get the heatmap decoder. """
if not self.cfg["heatmap_decoder"] in self.supported_heatmap_decoder:
raise ValueError(
"[Error] The heatmap decoder selection is not supported.")
# Pixel_shuffle decoder
if self.cfg["heatmap_decoder"] == "pixel_shuffle":
if self.cfg["backbone"] == "lcnn":
decoder = PixelShuffleDecoder(self.feat_channel,
num_upsample=2)
elif self.cfg["backbone"] == "superpoint":
decoder = PixelShuffleDecoder(self.feat_channel,
num_upsample=3)
else:
raise ValueError("[Error] Unknown backbone option.")
# Pixel_shuffle decoder with single channel output
elif self.cfg["heatmap_decoder"] == "pixel_shuffle_single":
if self.cfg["backbone"] == "lcnn":
decoder = PixelShuffleDecoder(
self.feat_channel, num_upsample=2, output_channel=1)
elif self.cfg["backbone"] == "superpoint":
decoder = PixelShuffleDecoder(
self.feat_channel, num_upsample=3, output_channel=1)
else:
raise ValueError("[Error] Unknown backbone option.")
else:
raise ValueError(
"[Error] The heatmap decoder selection is not supported.")
return decoder
def get_descriptor_decoder(self):
""" Get the descriptor decoder. """
if (not self.cfg["descriptor_decoder"]
in self.supported_descriptor_decoder):
raise ValueError(
"[Error] The descriptor decoder selection is not supported.")
# SuperPoint descriptor
if self.cfg["descriptor_decoder"] == "superpoint_descriptor":
decoder = SuperpointDescriptor(self.feat_channel)
else:
raise ValueError(
"[Error] The descriptor decoder selection is not supported.")
return decoder
def weight_init(m):
""" Weight initialization function. """
# Conv2D
if isinstance(m, nn.Conv2d):
init.xavier_normal_(m.weight.data)
if m.bias is not None:
init.normal_(m.bias.data)
# Batchnorm
elif isinstance(m, nn.BatchNorm2d):
init.normal_(m.weight.data, mean=1, std=0.02)
init.constant_(m.bias.data, 0)
# Linear
elif isinstance(m, nn.Linear):
init.xavier_normal_(m.weight.data)
init.normal_(m.bias.data)
else:
pass | |
wallet_listtransactions.py | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Copyright (c) 2017-2020 The Raven Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the listtransactions API."""
from io import BytesIO
from decimal import Decimal
from test_framework.test_framework import AvianTestFramework
from test_framework.util import hex_str_to_bytes, assert_array_result, sync_mempools, assert_equal, bytes_to_hex_str
from test_framework.mininode import CTransaction, COIN
def from_hex(hexstring):
tx = CTransaction()
f = BytesIO(hex_str_to_bytes(hexstring))
tx.deserialize(f)
return tx
class ListTransactionsTest(AvianTestFramework):
def set_test_params(self):
self.num_nodes = 2
self.enable_mocktime()
self.extra_args = [["-mempoolreplacement".format(i)] for i in range(self.num_nodes)]
def run_test(self):
# Simple send, 0 to 1:
txid = self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 0.1)
self.sync_all()
assert_array_result(self.nodes[0].listtransactions(),
{"txid": txid},
{"category": "send", "account": "", "amount": Decimal("-0.1"), "confirmations": 0})
assert_array_result(self.nodes[1].listtransactions(),
{"txid": txid},
{"category": "receive", "account": "", "amount": Decimal("0.1"), "confirmations": 0})
# mine a block, confirmations should change:
self.nodes[0].generate(1)
self.sync_all()
assert_array_result(self.nodes[0].listtransactions(),
{"txid": txid},
{"category": "send", "account": "", "amount": Decimal("-0.1"), "confirmations": 1})
assert_array_result(self.nodes[1].listtransactions(),
{"txid": txid}, |
# send-to-self:
txid = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 0.2)
assert_array_result(self.nodes[0].listtransactions(),
{"txid": txid, "category": "send"},
{"amount": Decimal("-0.2")})
assert_array_result(self.nodes[0].listtransactions(),
{"txid": txid, "category": "receive"},
{"amount": Decimal("0.2")})
# sendmany from node1: twice to self, twice to node2:
send_to = {self.nodes[0].getnewaddress(): 0.11,
self.nodes[1].getnewaddress(): 0.22,
self.nodes[0].getaccountaddress("from1"): 0.33,
self.nodes[1].getaccountaddress("toself"): 0.44}
txid = self.nodes[1].sendmany("", send_to)
self.sync_all()
assert_array_result(self.nodes[1].listtransactions(),
{"category": "send", "amount": Decimal("-0.11")},
{"txid": txid})
assert_array_result(self.nodes[0].listtransactions(),
{"category": "receive", "amount": Decimal("0.11")},
{"txid": txid})
assert_array_result(self.nodes[1].listtransactions(),
{"category": "send", "amount": Decimal("-0.22")},
{"txid": txid})
assert_array_result(self.nodes[1].listtransactions(),
{"category": "receive", "amount": Decimal("0.22")},
{"txid": txid})
assert_array_result(self.nodes[1].listtransactions(),
{"category": "send", "amount": Decimal("-0.33")},
{"txid": txid})
assert_array_result(self.nodes[0].listtransactions(),
{"category": "receive", "amount": Decimal("0.33")},
{"txid": txid, "account": "from1"})
assert_array_result(self.nodes[1].listtransactions(),
{"category": "send", "amount": Decimal("-0.44")},
{"txid": txid, "account": ""})
assert_array_result(self.nodes[1].listtransactions(),
{"category": "receive", "amount": Decimal("0.44")},
{"txid": txid, "account": "toself"})
multisig = self.nodes[1].createmultisig(1, [self.nodes[1].getnewaddress()])
self.nodes[0].importaddress(multisig["redeemScript"], "watchonly", False, True)
txid = self.nodes[1].sendtoaddress(multisig["address"], 0.1)
self.nodes[1].generate(1)
self.sync_all()
assert (len(self.nodes[0].listtransactions("watchonly", 100, 0, False)) == 0)
assert_array_result(self.nodes[0].listtransactions("watchonly", 100, 0, True),
{"category": "receive", "amount": Decimal("0.1")},
{"txid": txid, "account": "watchonly"})
# - This section of the test is removed since we are no longer supporting RBF (for now)
#self.run_rbf_opt_in_test()
# Check that the opt-in-rbf flag works properly, for sent and received
# transactions.
def run_rbf_opt_in_test(self):
# Check whether a transaction signals opt-in RBF itself
def is_opt_in(node, txid):
rawtx = node.getrawtransaction(txid, 1)
for x in rawtx["vin"]:
if x["sequence"] < 0xfffffffe:
return True
return False
# Find an unconfirmed output matching a certain txid
def get_unconfirmed_utxo_entry(node, txid_to_match):
utxo = node.listunspent(0, 0)
for i in utxo:
if i["txid"] == txid_to_match:
return i
return None
# 1. Chain a few transactions that don't opt-in.
txid_1 = self.nodes[0].sendtoaddress(self.nodes[1].getnewaddress(), 1)
assert (not is_opt_in(self.nodes[0], txid_1))
assert_array_result(self.nodes[0].listtransactions(), {"txid": txid_1}, {"bip125-replaceable": "no"})
sync_mempools(self.nodes)
assert_array_result(self.nodes[1].listtransactions(), {"txid": txid_1}, {"bip125-replaceable": "no"})
# Tx2 will build off txid_1, still not opting in to RBF.
utxo_to_use = get_unconfirmed_utxo_entry(self.nodes[0], txid_1)
assert_equal(utxo_to_use["safe"], True)
#utxo_to_use = get_unconfirmed_utxo_entry(self.nodes[1], txid_1)
utxo_to_use = get_unconfirmed_utxo_entry(self.nodes[1], txid_1)
assert_equal(utxo_to_use["safe"], False)
# Create tx2 using createrawtransaction
inputs = [{"txid": utxo_to_use["txid"], "vout": utxo_to_use["vout"]}]
outputs = {self.nodes[0].getnewaddress(): 0.999}
tx2 = self.nodes[1].createrawtransaction(inputs, outputs)
tx2_signed = self.nodes[1].signrawtransaction(tx2)["hex"]
txid_2 = self.nodes[1].sendrawtransaction(tx2_signed)
# ...and check the result
assert (not is_opt_in(self.nodes[1], txid_2))
assert_array_result(self.nodes[1].listtransactions(), {"txid": txid_2}, {"bip125-replaceable": "no"})
sync_mempools(self.nodes)
assert_array_result(self.nodes[0].listtransactions(), {"txid": txid_2}, {"bip125-replaceable": "no"})
# Tx3 will opt-in to RBF
utxo_to_use = get_unconfirmed_utxo_entry(self.nodes[0], txid_2)
inputs = [{"txid": txid_2, "vout": utxo_to_use["vout"]}]
outputs = {self.nodes[1].getnewaddress(): 0.998}
tx3 = self.nodes[0].createrawtransaction(inputs, outputs)
tx3_modified = from_hex(tx3)
tx3_modified.vin[0].nSequence = 0
tx3 = bytes_to_hex_str(tx3_modified.serialize())
tx3_signed = self.nodes[0].signrawtransaction(tx3)['hex']
txid_3 = self.nodes[0].sendrawtransaction(tx3_signed)
assert (is_opt_in(self.nodes[0], txid_3))
assert_array_result(self.nodes[0].listtransactions(), {"txid": txid_3}, {"bip125-replaceable": "yes"})
sync_mempools(self.nodes)
assert_array_result(self.nodes[1].listtransactions(), {"txid": txid_3}, {"bip125-replaceable": "yes"})
# Tx4 will chain off tx3. Doesn't signal itself, but depends on one
# that does.
utxo_to_use = get_unconfirmed_utxo_entry(self.nodes[1], txid_3)
inputs = [{"txid": txid_3, "vout": utxo_to_use["vout"]}]
outputs = {self.nodes[0].getnewaddress(): 0.997}
tx4 = self.nodes[1].createrawtransaction(inputs, outputs)
tx4_signed = self.nodes[1].signrawtransaction(tx4)["hex"]
txid_4 = self.nodes[1].sendrawtransaction(tx4_signed)
assert (not is_opt_in(self.nodes[1], txid_4))
assert_array_result(self.nodes[1].listtransactions(), {"txid": txid_4}, {"bip125-replaceable": "yes"})
sync_mempools(self.nodes)
assert_array_result(self.nodes[0].listtransactions(), {"txid": txid_4}, {"bip125-replaceable": "yes"})
# Replace tx3, and check that tx4 becomes unknown
tx3_b = tx3_modified
tx3_b.vout[0].nValue -= int(Decimal("0.004") * COIN) # bump the fee
tx3_b = bytes_to_hex_str(tx3_b.serialize())
tx3_b_signed = self.nodes[0].signrawtransaction(tx3_b)['hex']
txid_3b = self.nodes[0].sendrawtransaction(tx3_b_signed, True)
assert (is_opt_in(self.nodes[0], txid_3b))
assert_array_result(self.nodes[0].listtransactions(), {"txid": txid_4}, {"bip125-replaceable": "unknown"})
sync_mempools(self.nodes)
assert_array_result(self.nodes[1].listtransactions(), {"txid": txid_4}, {"bip125-replaceable": "unknown"})
# Check gettransaction as well:
for n in self.nodes[0:2]:
assert_equal(n.gettransaction(txid_1)["bip125-replaceable"], "no")
assert_equal(n.gettransaction(txid_2)["bip125-replaceable"], "no")
assert_equal(n.gettransaction(txid_3)["bip125-replaceable"], "yes")
assert_equal(n.gettransaction(txid_3b)["bip125-replaceable"], "yes")
assert_equal(n.gettransaction(txid_4)["bip125-replaceable"], "unknown")
# After mining a transaction, it's no longer BIP125-replaceable
self.nodes[0].generate(1)
assert (txid_3b not in self.nodes[0].getrawmempool())
assert_equal(self.nodes[0].gettransaction(txid_3b)["bip125-replaceable"], "no")
assert_equal(self.nodes[0].gettransaction(txid_4)["bip125-replaceable"], "unknown")
if __name__ == '__main__':
ListTransactionsTest().main() | {"category": "receive", "account": "", "amount": Decimal("0.1"), "confirmations": 1}) |
structs1.rs | // structs1.rs
// Address all the TODOs to make the tests pass!
struct ColorClassicStruct {
name: String,
hex: String,
}
struct ColorTupleStruct(String, String);
#[derive(Debug)]
struct UnitStruct;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn classic_c_structs() {
let green = ColorClassicStruct{name: "green".to_string(), hex: "#00FF00".to_string()};
assert_eq!(green.name, "green");
assert_eq!(green.hex, "#00FF00");
}
#[test]
fn | () {
let green = ColorTupleStruct("green".to_string(), "#00FF00".to_string());
assert_eq!(green.0, "green");
assert_eq!(green.1, "#00FF00");
}
#[test]
fn unit_structs() {
let unit_struct = UnitStruct;
let message = format!("{:?}s are fun!", unit_struct);
assert_eq!(message, "UnitStructs are fun!");
}
}
| tuple_structs |
main.min.js | ! function() { "use strict"; var t = { Android: function() { return navigator.userAgent.match(/Android/i) }, BlackBerry: function() { return navigator.userAgent.match(/BlackBerry/i) }, iOS: function() { return navigator.userAgent.match(/iPhone|iPad|iPod/i) }, Opera: function() { return navigator.userAgent.match(/Opera Mini/i) }, Windows: function() { return navigator.userAgent.match(/IEMobile/i) }, any: function() { return t.Android() || t.BlackBerry() || t.iOS() || t.Opera() || t.Windows() } },
e = function() { $(".js-counter").countTo({ formatter: function(t, e) { return t.toFixed(e.decimals) } }) }, | $(function() { var a, n;
t.any() || ($(".js-fullheight").css("height", $(window).height()), $(window).resize(function() { $(".js-fullheight").css("height", $(window).height()) })), e(), $("#colorlib-counter").length > 0 && $("#colorlib-counter").waypoint(function(t) { "down" !== t || $(this.element).hasClass("animated") || (setTimeout(e, 400), $(this.element).addClass("animated")) }, { offset: "90%" }), $(".animate-box").waypoint(function(t) { "down" !== t || $(this.element).hasClass("animated") || ($(this.element).addClass("item-animate"), setTimeout(function() { $("body .animate-box.item-animate").each(function(t) { var e = $(this);
setTimeout(function() { var t = e.data("animate-effect"); "fadeIn" === t ? e.addClass("fadeIn animated") : "fadeInLeft" === t ? e.addClass("fadeInLeft animated") : "fadeInRight" === t ? e.addClass("fadeInRight animated") : e.addClass("fadeInUp animated"), e.removeClass("item-animate") }, 0) }) }, 0)) }, { offset: "85%" }), $(".js-colorlib-nav-toggle").on("click", function(t) { t.preventDefault(); var e = $(this);
$("body").hasClass("offcanvas") ? (e.removeClass("active"), $("body").removeClass("offcanvas")) : (e.addClass("active"), $("body").addClass("offcanvas")) }), $('#navbar a:not([class="external"])').click(function(t) { var e = $(this).data("nav-section"),
i = $("#navbar"); return $('[data-section="' + e + '"]').length && $("html, body").animate({ scrollTop: $('[data-section="' + e + '"]').offset().top - 55 }, 500), i.is(":visible") && (i.removeClass("in"), i.attr("aria-expanded", "false"), $(".js-colorlib-nav-toggle").removeClass("active")), t.preventDefault(), !1 }), (a = $("section[data-section]")).waypoint(function(t) { "down" === t && i($(this.element).data("section")) }, { offset: "150px" }), a.waypoint(function(t) { "up" === t && i($(this.element).data("section")) }, { offset: function() { return 155 - $(this.element).height() } }), $(document).click(function(t) { var e = $("#colorlib-aside, .js-colorlib-nav-toggle");
e.is(t.target) || 0 !== e.has(t.target).length || $("body").hasClass("offcanvas") && ($("body").removeClass("offcanvas"), $(".js-colorlib-nav-toggle").removeClass("active")) }), $(window).scroll(function() { $("body").hasClass("offcanvas") && ($("body").removeClass("offcanvas"), $(".js-colorlib-nav-toggle").removeClass("active")) }), $("#colorlib-hero .flexslider").flexslider({ animation: "fade", slideshowSpeed: 5e3, directionNav: !0, start: function() { setTimeout(function() { $(".slider-text").removeClass("animated fadeInUp"), $(".flex-active-slide").find(".slider-text").addClass("animated fadeInUp") }, 500) }, before: function() { setTimeout(function() { $(".slider-text").removeClass("animated fadeInUp"), $(".flex-active-slide").find(".slider-text").addClass("animated fadeInUp") }, 500) } }), n = $(".image-content").outerHeight(), $(window).width() <= 992 ? $("#sticky_item").trigger("sticky_kit:detach") : ($(".sticky-parent").removeClass("stick-detach"), $("#sticky_item").trigger("sticky_kit:detach"), $("#sticky_item").trigger("sticky_kit:unstick")), $(window).resize(function() { var t = $(".image-content").outerHeight();
$(".sticky-parent").css("height", t), $(window).width() <= 992 ? $("#sticky_item").trigger("sticky_kit:detach") : ($(".sticky-parent").removeClass("stick-detach"), $("#sticky_item").trigger("sticky_kit:detach"), $("#sticky_item").trigger("sticky_kit:unstick"), $("#sticky_item").stick_in_parent()) }), $(".sticky-parent").css("height", n), $("#sticky_item").stick_in_parent(), $(".owl-carousel").owlCarousel({ animateOut: "fadeOut", animateIn: "fadeIn", autoplay: !0, loop: !0, margin: 0, nav: !0, dots: !1, autoHeight: !0, items: 1, navText: ["<i class='icon-arrow-left3 owl-direction'></i>", "<i class='icon-arrow-right3 owl-direction'></i>"] }) }) }(); | i = function(t) { var e = $("#navbar > ul");
e.find("li").removeClass("active"), e.each(function() { $(this).find('a[data-nav-section="' + t + '"]').closest("li").addClass("active") }) }; |
utility.go | // Copyright 2018 Amazon.com, Inc. or its affiliates. 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. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file 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.
// utility package implements all the shared methods between clients.
package utility
import (
"crypto/rand"
"errors"
"math/big"
"github.com/aws/amazon-ssm-agent/agent/context"
)
const (
lowerCaseLetters = "abcdefghijklmnopqrstuvwxyz"
upperCaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
digits = "0123456789"
// https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/hh994562(v=ws.10)
// https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/password-must-meet-complexity-requirements
symbols = "!#%"
defaultMinPasswordLength = 30
defaultMaxPasswordLength = 63
)
type ISessionUtil interface {
GeneratePasswordForDefaultUser() (string, error)
ChangePassword(username string, password string) error
ResetPasswordIfDefaultUserExists(context context.T) (err error)
DoesUserExist(username string) (bool, error)
}
type SessionUtil struct {
MinPasswordLength int
MaxPasswordLength int
}
// GeneratePasswordForDefaultUser generates a random password using go lang crypto rand package.
// Public docs: https://golang.org/pkg/crypto/rand/
// On Windows systems, it uses the CryptGenRandom API.
func (u *SessionUtil) GeneratePasswordForDefaultUser() (string, error) {
// Set password min and max length to default if not provided.
if u.MinPasswordLength <= 0 || u.MaxPasswordLength <= 0 {
u.MinPasswordLength = defaultMinPasswordLength
u.MaxPasswordLength = defaultMaxPasswordLength
}
// Enforce max length to be greater than min length of the password.
if u.MaxPasswordLength <= u.MinPasswordLength {
return "", errors.New("Max password length should be greater than Min password length")
}
// Generate a set of characters that comply with the Microsoft password policy.
// References:
// https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/hh994562(v=ws.10)
// https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/password-must-meet-complexity-requirements
letters := lowerCaseLetters
letters += upperCaseLetters
letters += digits
letters += symbols
// Select a random length between min and max
length, err := randomLength(u.MinPasswordLength, u.MaxPasswordLength)
if err != nil {
return "", err
}
var result string
// Enforce adding atleast one of all the 4 categories.
// atleast one uppercase letter
ch, err := randomElement(upperCaseLetters)
if err != nil {
return "", err
}
result = result + ch
// atleast one lowercase letter
ch, err = randomElement(lowerCaseLetters)
if err != nil {
return "", err
}
result = result + ch
// atleast one digit
ch, err = randomElement(digits)
if err != nil {
return "", err
}
result = result + ch
// atleast one symbol
ch, err = randomElement(symbols)
if err != nil {
return "", err
}
result = result + ch
// mix up the rest
// We call randomInsert as a part of this for loop which will also randomize the first 4 added characters.
for i := len(result); i < length; i++ {
// Randomly select an element from the character set.
ch, err := randomElement(letters)
if err != nil {
return "", err
}
// Now, insert this new selected element at a random position in the final string.
result, err = randomInsert(result, ch)
if err != nil {
return "", err
}
}
return result, nil
}
// randomLength selects a random number between min and max.
func randomLength(minLength, maxLength int) (int, error) {
n, err := rand.Int(rand.Reader, big.NewInt(int64(maxLength-minLength)))
if err != nil {
return 0, err
}
return int(n.Int64() + int64(minLength)), nil
}
// randomInsert randomly inserts the given value into the given string.
func | (s, val string) (string, error) {
if s == "" {
return val, nil
}
n, err := rand.Int(rand.Reader, big.NewInt(int64(len(s))))
if err != nil {
return "", err
}
i := n.Int64()
return s[0:i] + val + s[i:], nil
}
// randomElement extracts a random element from the given string.
func randomElement(s string) (string, error) {
n, err := rand.Int(rand.Reader, big.NewInt(int64(len(s))))
if err != nil {
return "", err
}
return string(s[n.Int64()]), nil
}
| randomInsert |
wheater-object.utils.js | const { compose, head, of } = require('ramda');
const mapOver = require('./map-over.utils'); | /** @: wheaterObject :: view -> object -> map vector -> object */
const wheaterObject = (view) => compose(head, mapOver(view), of);
module.exports = wheaterObject; | |
views.py | from django.conf import settings
from django.contrib.auth import get_user, views as auth_views
from django.contrib.auth.decorators import login_required
from django.core.files import File
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render, get_object_or_404
from django.urls import reverse
from django.utils import timezone
from .forms import ScoreForm
from .models import Score, Result
from . import voiceleading
from music21 import converter
import os.path
# Create your views here.
def index(request):
|
def checked(request, score_id):
user = get_user(request)
score = get_object_or_404(Score, pk=score_id)
results = Result.objects.filter(score=score_id)
#generate checked score display name
return render(
request,
'harmony_checker/checked.html',
{
'score': score,
'results': results,
'user': user,
'title': 'Results'
}
)
def checked_score(request, score_id):
score = get_object_or_404(Score, pk=score_id)
response = HttpResponse(score.checked_score, content_type='application/xml')
response['Content-Disposition'] = f"attachment; filename={score.checked_score_display_name}"
return response
def score(request, score_id):
score = get_object_or_404(Score, pk=score_id)
response = HttpResponse(score.score, content_type='application/xml')
response['Content-Disposition'] = f"attachment; filename={score.score_display_name}"
return response
@login_required
def profile(request):
user = get_user(request)
scores = Score.objects.filter(user=user).order_by('-upload_date')
return render(
request,
'harmony_checker/profile.html',
{
'user': user,
'scores': scores,
'title': "User Profile"
}
) | user = get_user(request)
if request.method == 'POST':
score_form = ScoreForm(request.POST, request.FILES)
new_score = score_form.save()
if user.is_authenticated:
new_score.user = user
new_score.score_display_name = os.path.basename(new_score.score.name)
new_score.save()
fname = str.format('{0}/{1}', settings.MEDIA_ROOT, new_score.score.url)
stream = converter.parse(fname)
end_height = 1
for musical_test in new_score.musical_tests.all():
musical_test_failures = getattr(voiceleading, musical_test.func)(
stream,
chordified_stream=stream.chordify(),
)
r = Result(score=new_score,musical_test=musical_test)
r.passed = (len(musical_test_failures) == 0)
r.save()
stream, end_height = voiceleading.annotate_stream(musical_test_failures, stream, end_height)
output_path = os.path.join("{}_checked.xml".format(fname[:-4]))
stream.write(
"musicxml", output_path
)
with open(output_path) as fp:
contents = File(fp)
new_score.checked_score.save(output_path, contents)
new_score.checked_score_display_name = f"{new_score.score_display_name[:-4]}_checked.xml"
new_score.save()
return HttpResponseRedirect(
reverse('harmony_checker:checked', args=(new_score.id,))
)
else:
score_form = ScoreForm()
return render(
request,
'harmony_checker/index.html',
{'score_form': score_form, 'user': user, 'title': "Check Harmony"}
) |
test-relay.py | #!/usr/bin/env python |
GPIO.setmode(GPIO.BCM)
GPIO.setup(21, GPIO.OUT)
GPIO.output(21, GPIO.LOW)
time.sleep(3.00)
GPIO.output(21, GPIO.HIGH)
GPIO.cleanup() |
import time
import RPi.GPIO as GPIO |
Channel.js | const Snowflake = require('../util/Snowflake');
const Base = require('./Base');
const Constants = require('../util/Constants');
/**
* Represents any channel on Discord.
* @extends {Base}
*/
class Channel extends Base {
constructor(client, data) {
super(client);
const type = Object.keys(Constants.ChannelTypes)[data.type];
/**
* The type of the channel, either:
* * `dm` - a DM channel
* * `group` - a Group DM channel
* * `text` - a guild text channel
* * `voice` - a guild voice channel | */
this.type = type ? type.toLowerCase() : 'unknown';
if (data) this._patch(data);
}
_patch(data) {
/**
* The unique ID of the channel
* @type {Snowflake}
*/
this.id = data.id;
}
/**
* The timestamp the channel was created at
* @type {number}
* @readonly
*/
get createdTimestamp() {
return Snowflake.deconstruct(this.id).timestamp;
}
/**
* The time the channel was created
* @type {Date}
* @readonly
*/
get createdAt() {
return new Date(this.createdTimestamp);
}
/**
* Deletes this channel.
* @returns {Promise<Channel>}
* @example
* // Delete the channel
* channel.delete()
* .then() // Success
* .catch(console.error); // Log error
*/
delete() {
return this.client.api.channels(this.id).delete().then(() => this);
}
static create(client, data, guild) {
const DMChannel = require('./DMChannel');
const GroupDMChannel = require('./GroupDMChannel');
const TextChannel = require('./TextChannel');
const VoiceChannel = require('./VoiceChannel');
const GuildChannel = require('./GuildChannel');
const types = Constants.ChannelTypes;
let channel;
if (data.type === types.DM) {
channel = new DMChannel(client, data);
} else if (data.type === types.GROUP) {
channel = new GroupDMChannel(client, data);
} else {
guild = guild || client.guilds.get(data.guild_id);
if (guild) {
switch (data.type) {
case types.TEXT:
channel = new TextChannel(guild, data);
break;
case types.VOICE:
channel = new VoiceChannel(guild, data);
break;
default:
channel = new GuildChannel(guild, data);
}
guild.channels.set(channel.id, channel);
}
}
return channel;
}
}
module.exports = Channel; | * * `unknown` - a generic channel of unknown type, could be Channel or GuildChannel
* @type {string} |
filecoin_views.py | import os
from datetime import datetime
from flask import Flask, render_template, flash, safe_join, send_file
from flask_user import login_required, current_user
from werkzeug.utils import secure_filename
from pygate_grpc.client import PowerGateClient
from deplatformr.models.filecoin_models import Ffs, Files, Logs
from deplatformr import app, db
@app.route('/filecoin-files')
@login_required
def filecoin_files():
files = Files.query.filter_by(user_id=current_user.id).all()
return render_template("filecoin/filecoin-files.html", files=files, breadcrumb="Filecoin / Files")
@app.route("/filecoin-download/<cid>", methods=["GET"])
@login_required
def filecoin_download(cid):
"""
Retrieve a file from Filecoin via IPFS using Powergate and offer the user
the option to save it to their machine.
"""
# Retrieve File and FFS info using the CID
file = Files.query.filter_by(CID=cid, user_id=current_user.id).first()
ffs = Ffs.query.get(file.ffs_id)
try:
# Retrieve data from Filecoin
powergate = PowerGateClient(app.config["POWERGATE_ADDRESS"])
data_ = powergate.ffs.get(file.CID, ffs.token)
# Save the downloaded data as a file
# Use the user data directory configured for the app
user_data = app.config["USER_DATA_DIR"]
if not os.path.exists(user_data):
os.makedirs(user_data)
print(user_data)
# Create a subdirectory per username. Usernames are unique.
user_dir = os.path.join(
user_data, str(current_user.id) + "-" + current_user.username)
if not os.path.exists(user_dir):
os.makedirs(user_dir)
print(user_dir)
# Create a Filecoin downloads subdirectory.
filecoin_dir = os.path.join(user_dir, "filecoin/downloads")
if not os.path.exists(filecoin_dir):
|
print(filecoin_dir)
with open(os.path.join(filecoin_dir, file.file_name), "wb") as out_file:
# Iterate over the data byte chunks and save them to an output file
for data in data_:
out_file.write(data)
# Create path to download file
safe_path = safe_join("../" + filecoin_dir, file.file_name)
print(safe_path)
# Offer the file for download to local machine
return send_file(safe_path, as_attachment=True)
# TODO: CLEAR CACHED FILES IN DOWNLOAD DIRECTORY
except Exception as e:
# Output error message if download from Filecoin fails
flash("failed to download '{}' from Filecoin. {}".format(
file.file_name, e), "alert-danger")
# Update log table with error
event = Logs(
timestamp=datetime.now().replace(microsecond=0),
event="Download ERROR: "
+ file.file_name
+ " CID: "
+ file.CID
+ " "
+ str(e),
user_id=current_user.id,
)
db.session.add(event)
db.session.commit()
files = Files.query.filter_by(user_id=current_user.id).all()
return render_template("filecoin/filecoin-files.html", files=files, breadcrumb="Filecoin / Files")
@ app.route('/filecoin-wallets')
@ login_required
def filecoin_wallets():
"""
Retrieve all wallets from all FFSes and save them in a list for
presentation on the UI template
"""
powergate = PowerGateClient(app.config["POWERGATE_ADDRESS"])
try:
ffs = Ffs.query.filter_by(user_id=current_user.id).one()
except:
flash("No wallets created yet.", "alert-danger")
return render_template("filecoin/filecoin-wallets.html", wallets=None, breadcrumb="Filecoin / Wallets")
wallets = []
addresses = powergate.ffs.addrs_list(ffs.token)
for address in addresses.addrs:
balance = powergate.wallet.balance(address.addr)
wallets.append(
{
"ffs": ffs.ffs_id,
"name": address.name,
"address": address.addr,
"type": address.type,
"balance": str(balance.balance),
}
)
return render_template("filecoin/filecoin-wallets.html", wallets=wallets, breadcrumb="Filecoin / Wallets")
| os.makedirs(filecoin_dir) |
dataflow.go | // Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF 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.
// Package dataflow contains the Dataflow runner for submitting pipelines
// to Google Cloud Dataflow.
package dataflow
import (
"context"
"encoding/json"
"flag"
"fmt"
"io"
"path"
"strings"
"sync/atomic"
"time"
"cloud.google.com/go/storage"
"github.com/apache/beam/sdks/go/pkg/beam"
"github.com/apache/beam/sdks/go/pkg/beam/core/runtime/graphx"
"github.com/apache/beam/sdks/go/pkg/beam/core/util/hooks"
"github.com/apache/beam/sdks/go/pkg/beam/internal/errors"
"github.com/apache/beam/sdks/go/pkg/beam/log"
"github.com/apache/beam/sdks/go/pkg/beam/options/gcpopts"
"github.com/apache/beam/sdks/go/pkg/beam/options/jobopts"
"github.com/apache/beam/sdks/go/pkg/beam/runners/dataflow/dataflowlib"
"github.com/apache/beam/sdks/go/pkg/beam/util/gcsx"
"github.com/apache/beam/sdks/go/pkg/beam/x/hooks/perf"
"github.com/golang/protobuf/proto"
)
// TODO(herohde) 5/16/2017: the Dataflow flags should match the other SDKs.
var (
endpoint = flag.String("dataflow_endpoint", "", "Dataflow endpoint (optional).")
stagingLocation = flag.String("staging_location", "", "GCS staging location (required).")
image = flag.String("worker_harness_container_image", "", "Worker harness container image (required).")
labels = flag.String("labels", "", "JSON-formatted map[string]string of job labels (optional).")
serviceAccountEmail = flag.String("service_account_email", "", "Service account email (optional).")
numWorkers = flag.Int64("num_workers", 0, "Number of workers (optional).")
maxNumWorkers = flag.Int64("max_num_workers", 0, "Maximum number of workers during scaling (optional).")
autoscalingAlgorithm = flag.String("autoscaling_algorithm", "", "Autoscaling mode to use (optional).")
zone = flag.String("zone", "", "GCP zone (optional)")
network = flag.String("network", "", "GCP network (optional)")
subnetwork = flag.String("subnetwork", "", "GCP subnetwork (optional)")
noUsePublicIPs = flag.Bool("no_use_public_ips", false, "Workers must not use public IP addresses (optional)")
tempLocation = flag.String("temp_location", "", "Temp location (optional)")
machineType = flag.String("worker_machine_type", "", "GCE machine type (optional)")
minCPUPlatform = flag.String("min_cpu_platform", "", "GCE minimum cpu platform (optional)")
workerJar = flag.String("dataflow_worker_jar", "", "Dataflow worker jar (optional)")
executeAsync = flag.Bool("execute_async", false, "Asynchronous execution. Submit the job and return immediately.")
dryRun = flag.Bool("dry_run", false, "Dry run. Just print the job, but don't submit it.")
teardownPolicy = flag.String("teardown_policy", "", "Job teardown policy (internal only).")
// SDK options
cpuProfiling = flag.String("cpu_profiling", "", "Job records CPU profiles to this GCS location (optional)")
sessionRecording = flag.String("session_recording", "", "Job records session transcripts")
)
func init() {
// Note that we also _ import harness/init to setup the remote execution hook.
beam.RegisterRunner("dataflow", Execute)
perf.RegisterProfCaptureHook("gcs_profile_writer", gcsRecorderHook)
}
var unique int32
// Execute runs the given pipeline on Google Cloud Dataflow. It uses the
// default application credentials to submit the job.
func Execute(ctx context.Context, p *beam.Pipeline) error {
// (1) Gather job options
project := *gcpopts.Project
if project == "" {
return errors.New("no Google Cloud project specified. Use --project=<project>")
}
region := gcpopts.GetRegion(ctx)
if region == "" {
return errors.New("No Google Cloud region specified. Use --region=<region>. See https://cloud.google.com/dataflow/docs/concepts/regional-endpoints")
}
if *stagingLocation == "" {
return errors.New("no GCS staging location specified. Use --staging_location=gs://<bucket>/<path>")
}
var jobLabels map[string]string
if *labels != "" {
if err := json.Unmarshal([]byte(*labels), &jobLabels); err != nil {
return errors.Wrapf(err, "error reading --label flag as JSON")
}
}
if *cpuProfiling != "" {
perf.EnableProfCaptureHook("gcs_profile_writer", *cpuProfiling)
}
if *sessionRecording != "" {
// TODO(wcn): BEAM-4017
// It's a bit inconvenient for GCS because the whole object is written in
// one pass, whereas the session logs are constantly appended. We wouldn't
// want to hold all the logs in memory to flush at the end of the pipeline
// as we'd blow out memory on the worker. The implementation of the
// CaptureHook should create an internal buffer and write chunks out to GCS
// once they get to an appropriate size (50M or so?)
}
if *autoscalingAlgorithm != "" {
if *autoscalingAlgorithm != "NONE" && *autoscalingAlgorithm != "THROUGHPUT_BASED" {
return errors.New("invalid autoscaling algorithm. Use --autoscaling_algorithm=(NONE|THROUGHPUT_BASED)")
}
}
hooks.SerializeHooksToOptions()
experiments := jobopts.GetExperiments()
// Always use runner v2, unless set already.
var v2set bool
for _, e := range experiments {
if strings.Contains(e, "use_runner_v2") || strings.Contains(e, "use_unified_worker") {
v2set = true
break
}
}
if !v2set {
experiments = append(experiments, "use_unified_worker")
}
if *minCPUPlatform != "" {
experiments = append(experiments, fmt.Sprintf("min_cpu_platform=%v", *minCPUPlatform))
}
opts := &dataflowlib.JobOptions{
Name: jobopts.GetJobName(),
Experiments: experiments,
Options: beam.PipelineOptions.Export(),
Project: project,
Region: region,
Zone: *zone,
Network: *network,
Subnetwork: *subnetwork,
NoUsePublicIPs: *noUsePublicIPs,
NumWorkers: *numWorkers,
MaxNumWorkers: *maxNumWorkers,
Algorithm: *autoscalingAlgorithm,
MachineType: *machineType,
Labels: jobLabels,
ServiceAccountEmail: *serviceAccountEmail,
TempLocation: *tempLocation,
Worker: *jobopts.WorkerBinary,
WorkerJar: *workerJar,
TeardownPolicy: *teardownPolicy,
}
if opts.TempLocation == "" {
opts.TempLocation = gcsx.Join(*stagingLocation, "tmp")
}
// (1) Build and submit
edges, _, err := p.Build()
if err != nil {
return err
}
model, err := graphx.Marshal(edges, &graphx.Options{Environment: graphx.CreateEnvironment(
ctx, jobopts.GetEnvironmentUrn(ctx), getContainerImage)})
if err != nil {
return errors.WithContext(err, "generating model pipeline")
}
// NOTE(herohde) 10/8/2018: the last segment of the names must be "worker" and "dataflow-worker.jar".
id := fmt.Sprintf("go-%v-%v", atomic.AddInt32(&unique, 1), time.Now().UnixNano())
modelURL := gcsx.Join(*stagingLocation, id, "model")
workerURL := gcsx.Join(*stagingLocation, id, "worker")
jarURL := gcsx.Join(*stagingLocation, id, "dataflow-worker.jar")
if *dryRun {
log.Info(ctx, "Dry-run: not submitting job!")
log.Info(ctx, proto.MarshalTextString(model))
job, err := dataflowlib.Translate(model, opts, workerURL, jarURL, modelURL)
if err != nil {
return err
}
dataflowlib.PrintJob(ctx, job)
return nil
}
_, err = dataflowlib.Execute(ctx, model, opts, workerURL, jarURL, modelURL, *endpoint, *executeAsync)
return err
}
func | (opts []string) perf.CaptureHook {
bucket, prefix, err := gcsx.ParseObject(opts[0])
if err != nil {
panic(fmt.Sprintf("Invalid hook configuration for gcsRecorderHook: %s", opts))
}
return func(ctx context.Context, spec string, r io.Reader) error {
client, err := gcsx.NewClient(ctx, storage.ScopeReadWrite)
if err != nil {
return errors.WithContext(err, "establishing GCS client")
}
return gcsx.WriteObject(ctx, client, bucket, path.Join(prefix, spec), r)
}
}
func getContainerImage(ctx context.Context) string {
urn := jobopts.GetEnvironmentUrn(ctx)
if urn == "" || urn == "beam:env:docker:v1" {
if *image != "" {
return *image
}
return jobopts.GetEnvironmentConfig(ctx)
}
panic(fmt.Sprintf("Unsupported environment %v", urn))
}
| gcsRecorderHook |
scrollability.js | /* See LICENSE for terms of usage */
"style scrollbar.css"
// var logs = [];
// function D() {
// var args = []; args.push.apply(args, arguments);
// console.log(args.join(' '));
// // logs.push(args.join(' '));
// }
// window.showLog = function() {
// document.querySelector('.scrollable').innerHTML = logs.join('<br>');
// document.querySelector('.scrollable').style.webkitAnimation = '';
// document.querySelector('.scrollable').style.webkitTransform = 'translate3d(0,0,0)';
// }
// *************************************************************************************************
var isWebkit = "webkitTransform" in document.documentElement.style;
var isiOS5 = isWebkit && /OS 5_/.exec(navigator.userAgent);
var isTouch = "ontouchstart" in window;
// *************************************************************************************************
// The friction applied while decelerating
var kFriction = 0.9925;
// If the velocity is below this threshold when the finger is released, animation will stop
var kStoppedThreshold = 4;
// Number of pixels finger must move to determine horizontal or vertical motion
var kLockThreshold = 10;
// Percentage of the page which content can be overscrolled before it must bounce back
var kBounceLimit = 0.75;
// Rate of deceleration when content has overscrolled and is slowing down before bouncing back
var kBounceDecelRate = 0.01;
// Duration of animation when bouncing back
var kBounceTime = 240;
var kPageBounceTime = 160;
// Percentage of viewport which must be scrolled past in order to snap to the next page
var kPageLimit = 0.5;
// Velocity at which the animation will advance to the next page
var kPageEscapeVelocity = 2;
// Vertical margin of scrollbar
var kScrollbarMargin = 2;
// The width or height of the scrollbar along the animated axis
var kScrollbarSize = 7;
// The number of milliseconds to increment while simulating animation
var kAnimationStep = 4;
// The number of milliseconds of animation to condense into a keyframe
var kKeyframeIncrement = 24;
// *************************************************************************************************
var startX, startY, touchX, touchY, touchMoved;
var animationInterval = 0;
var touchAnimators = [];
var animationIndex = 0;
var globalStyleSheet;
var directions = {
'horizontal': createXDirection,
'vertical': createYDirection
};
//exports.directions = directions;
//
//exports.flashIndicators = function() {
// // var scrollables = document.querySelectorAll('.scrollable.vertical');
// // for (var i = 0; i < scrollables.length; ++i) {
// // exports.scrollTo(scrollables[i], 0, 0, 20, true);
// // }
//}
function onLoad() {
var ss = document.createElement("style");
document.head.appendChild(ss);
globalStyleSheet = document.styleSheets[document.styleSheets.length-1];
// exports.flashIndicators();
}
document.addEventListener('DOMContentLoaded',function(){
document.addEventListener(isTouch ? 'touchstart' : 'mousedown', onTouchStart, false);
window.addEventListener('load', onLoad, false);
});
function onTouchStart(event) {
var touch = isTouch ? event.touches[0] : event;
var touched = null;
touchX = startX = touch.clientX;
touchY = startY = touch.clientY;
touchMoved = false;
touchAnimators = getTouchAnimators(event.target, touchX, touchY, event.timeStamp);
if (!touchAnimators.length) {
return true;
}
var touchCandidate = event.target;
var holdTimeout = setTimeout(function() {
holdTimeout = 0;
touched = setTouched(touchCandidate);
}, 50);
document.addEventListener(isTouch ? 'touchmove' : 'mousemove', onTouchMove, false);
document.addEventListener(isTouch ? 'touchend' : 'mouseup', onTouchEnd, false);
// if (D) event.preventDefault();
function onTouchMove(event) {
event.preventDefault();
touchMoved = true;
if (holdTimeout) {
clearTimeout(holdTimeout);
holdTimeout = 0;
}
if (touched) {
releaseTouched(touched);
touched = null;
}
var touch = isTouch ? event.touches[0] : event;
touchX = touch.clientX;
touchY = touch.clientY;
// Reduce the candidates down to the one whose axis follows the finger most closely
if (touchAnimators.length > 1) {
for (var i = 0; i < touchAnimators.length; ++i) {
var animator = touchAnimators[i];
if (animator.disable && animator.disable(touchX, touchY, startX, startY)) {
animator.terminate();
touchAnimators.splice(i--, 1);
if (touchAnimators.length == 1) {
var locked = touchAnimators[0];
dispatch("scrollability-lock", locked.node, {direction: locked.direction});
}
}
}
}
touchAnimators.forEach(function(animator) {
var touch = animator.filter(touchX, touchY);
animator.track(touch, event.timeStamp);
});
}
function | (event) {
// Simulate a click event when releasing the finger
if (touched) {
var evt = document.createEvent('MouseEvents');
evt.initMouseEvent('click', true, true, window, 1);
touched[0].dispatchEvent(evt);
releaseTouched(touched);
}
document.removeEventListener(isTouch ? 'touchmove' : 'mousemove', onTouchMove, false);
document.removeEventListener(isTouch ? 'touchend' : 'mouseup', onTouchEnd, false);
touchAnimators.forEach(function(animator) {
animator.takeoff();
});
}
}
function wrapAnimator(animator, startX, startY, startTime) {
var node = animator.node;
var constrained = animator.constrained;
var paginated = animator.paginated;
var viewport = animator.viewport || 0;
var scrollbar = animator.scrollbar;
var position = animator.position;
var min = animator.min;
var max = animator.max;
var absMin = min;
var absMax = Math.round(max/viewport)*viewport;
var pageSpacing = 0;
var velocity = 0;
var bounceTime = paginated ? kPageBounceTime : kBounceTime;
var bounceLimit = animator.bounce;
var pageLimit = viewport * kPageLimit;
var lastTouch = startTouch = animator.filter(startX, startY);
var lastTime = startTime;
var timeStep = 0;
var stopped = 0;
var tracked = [];
var offset = node.scrollableOffset||0;
if (!animator.mute) {
var event = {
position: position,
min: min,
max: max,
track: addTracker,
setSpacing: setSpacing,
setOffset: setOffset,
setBounds: setBounds
};
if (!dispatch("scrollability-start", node, event)) {
return null;
}
}
if (paginated) {
if (pageSpacing === undefined) {
var excess = Math.round(Math.abs(absMin) % viewport);
var pageCount = ((Math.abs(absMin)-excess) / viewport)+1;
pageSpacing = excess / pageCount;
}
var pageIndex = Math.round(position/(viewport+pageSpacing));
min = max = pageIndex * (viewport+pageSpacing);
absMin += pageSpacing;
}
if (scrollbar) {
addTracker(scrollbar, trackScrollbar);
if (!scrollbar.parentNode) {
node.parentNode.appendChild(scrollbar);
}
}
if (node.earlyEnd) {
play(node);
tracked.forEach(function(item) {
play(item.node);
});
node.earlyEnd();
update(position);
}
animator.reposition = update;
animator.track = track;
animator.takeoff = takeoff;
animator.terminate = terminate;
return animator;
function addTracker(node, callback) {
tracked.push({node: node, callback: callback, keyframes: []});
}
function setSpacing(x) {
pageSpacing = x
}
function setOffset(x) {
offset = x;
track(lastTouch, lastTime);
}
function setBounds(newMin, newMax) {
min = newMin;
max = newMax;
}
function track(touch, time) {
timeStep = time - lastTime;
lastTime = time;
velocity = touch - lastTouch;
lastTouch = touch;
if (Math.abs(velocity) >= kStoppedThreshold) {
if (stopped) {
--stopped;
}
stopped = 0;
} else {
++stopped;
}
// Apply resistance along the edges
if (constrained) {
if (position > max && absMax == max) {
var excess = position - max;
velocity *= (1.0 - excess / bounceLimit)*kBounceLimit;
} else if (position < min && absMin == min) {
var excess = min - position;
velocity *= (1.0 - excess / bounceLimit)*kBounceLimit;
}
}
position += velocity;
update(position);
node.style.webkitAnimationName = '';
tracked.forEach(function(item) {
item.node.style.webkitAnimationName = '';
});
return true;
}
function trackScrollbar(position) {
var range = max - min;
if (scrollbar && min < 0) {
var viewable = viewport - kScrollbarMargin*2;
var height = (viewable/(range+viewport)) * viewable;
var scrollPosition;
if (position > max) {
height = Math.max(height - (position-max), kScrollbarSize);
scrollPosition = 0;
} else if (position < min) {
var h = height - (min - position);
height = Math.max(height - (min - position), kScrollbarSize);
scrollPosition = viewable-height;
} else {
scrollPosition = (Math.abs((max-position)) / range) * (viewable-height);
}
scrollPosition += kScrollbarMargin;
return 'translate3d(0, ' + Math.round(scrollPosition) + 'px, 0) '
+ 'scaleY(' + Math.round(height) + ')';
}
}
function takeoff() {
dispatch("scrollability-takeoff", node, {
position: position,
min: min,
max: max,
setBounds: setBounds
});
if (stopped) {
velocity = 0;
}
position += velocity;
update(position);
velocity = (velocity/timeStep) * kAnimationStep;
var timeline = createTimeline();
if (!timeline.time) {
terminate();
return;
}
dispatch("scrollability-animate", node, {
direction: animator.direction,
time: timeline.time,
keyframes: timeline.keyframes
});
if (node.cleanup) {
node.cleanup();
}
globalStyleSheet.insertRule(timeline.css, 0);
tracked.forEach(function(item, i) {
item.name = 'scrollability-track'+(animationIndex++);
var css = generateCSSKeyframes(animator, item.keyframes, item.name, timeline.time);
globalStyleSheet.insertRule(css, 0);
});
node.earlyEnd = function() {
terminex(true);
}
node.normalEnd = function() {
reposition(timeline.keyframes[timeline.keyframes.length-1].position);
terminex();
}
node.cleanup = function() {
delete node.cleanup;
globalStyleSheet.deleteRule(0);
tracked.forEach(function(item) {
globalStyleSheet.deleteRule(0);
});
}
node.addEventListener("webkitAnimationEnd", node.normalEnd, false);
play(node, timeline.name, timeline.time);
tracked.forEach(function(item) {
play(item.node, item.name, timeline.time);
});
}
function createTimeline() {
var time = 0;
var lastPosition = position;
var lastKeyTime = 0;
var lastDiff = 0;
var decelOrigin;
var decelDelta;
var decelStep = 0;
var decelTime;
// var enterVelocity;
var keyframes = [];
if (paginated) {
// When finger is released, decide whether to jump to next/previous page
// or to snap back to the current page
if (Math.abs(position - max) > pageLimit || Math.abs(velocity) > kPageEscapeVelocity) {
if (position > max) {
if (max != absMax) {
max += viewport+pageSpacing;
min += viewport+pageSpacing;
// XXXjoe Only difference between this and code below is -viewport. Merge 'em!
var totalSpacing = min % viewport;
var page = -Math.round((position+viewport-totalSpacing)/(viewport+pageSpacing));
dispatch("scrollability-page", animator.node, {page: page});
}
} else {
if (min != absMin) {
max -= viewport+pageSpacing;
min -= viewport+pageSpacing;
var totalSpacing = min % viewport;
var page = -Math.round((position-viewport-totalSpacing)/(viewport+pageSpacing));
dispatch("scrollability-page", animator.node, {page: page});
}
}
}
}
var continues = true;
while (continues) {
if (position > max && constrained) {
if (velocity > 0) {
// Slowing down
var excess = position - max;
var elasticity = (1.0 - excess / bounceLimit);
velocity = Math.max(velocity - kBounceDecelRate, 0) * elasticity;
// D&&D('slowing down', velocity);
position += velocity;
} else {
// Bouncing back
if (!decelStep) {
decelOrigin = position;
decelDelta = max - position;
}
// D&&D('bouncing back');
position = easeOutExpo(decelStep, decelOrigin, decelDelta, bounceTime);
continues = ++decelStep <= bounceTime && Math.floor(Math.abs(position)) > max;
}
} else if (position < min && constrained) {
if (velocity < 0) {
// if (!enterVelocity) {
// enterVelocity = velocity;
// }
// Slowing down
var excess = min - position;
var elasticity = (1.0 - excess / bounceLimit);
velocity = Math.min(velocity + kBounceDecelRate, 0) * elasticity;
position += velocity;
} else {
// Bouncing back
if (!decelStep) {
decelOrigin = position;
decelDelta = min - position;
// XXXjoe Record velocity when going past limit, use to shrink bounceTime
// decelTime = bounceTime * (-enterVelocity / 10);
// D&&D(decelTime);
}
position = easeOutExpo(decelStep, decelOrigin, decelDelta, bounceTime);
continues = ++decelStep <= bounceTime && Math.ceil(position) < min;
}
} else {
continues = Math.floor(Math.abs(velocity)*10) > 0;
if (!continues)
break;
velocity *= kFriction;
position += velocity;
}
saveKeyframe(!continues);
time += kAnimationStep;
}
if (paginated) {
var pageIndex = Math.round(position/(viewport+pageSpacing));
position = pageIndex * (viewport+pageSpacing);
saveKeyframe(true);
} else if (position > max && constrained) {
position = max;
saveKeyframe(true);
} else if (position < min && constrained) {
position = min;
saveKeyframe(true);
}
var totalTime = keyframes.length ? keyframes[keyframes.length-1].time : 0;
var name = "scrollability" + (animationIndex++);
var css = generateCSSKeyframes(animator, keyframes, name, totalTime, offset);
return {time: totalTime, position: position, keyframes: keyframes, name: name, css: css};
function saveKeyframe(force) {
var diff = position - lastPosition;
// Add a new frame when we've changed direction, or passed the prescribed granularity
if (force || (time-lastKeyTime >= kKeyframeIncrement || (lastDiff < 0 != diff < 0))) {
keyframes.push({position: position, time: time});
tracked.forEach(function(item) {
item.keyframes.push({time: time, css: item.callback(position)});
});
lastDiff = diff;
lastPosition = position;
lastKeyTime = time;
}
}
}
function update(pos) {
if (!dispatch("scrollability-scroll", node,
{direction: animator.direction, position: pos, max: max, min: min})) {
return;
}
reposition(pos);
if (scrollbar && touchMoved) {
fadeIn(scrollbar);
}
}
function reposition(pos) {
// D&&D('move to', pos, offset);
node.style.webkitTransform = animator.update(pos+offset);
node.scrollableOffset = offset;
tracked.forEach(function(item) {
item.node.style.webkitTransform = item.callback(pos);
});
}
function terminex(showScrollbar) {
if (scrollbar) {
if (showScrollbar) {
fadeIn(scrollbar);
} else {
scrollbar.style.opacity = '0';
scrollbar.style.webkitTransition = 'opacity 0.33s linear';
}
}
node.removeEventListener("webkitAnimationEnd", node.normalEnd, false);
delete node.earlyEnd;
delete node.normalEnd;
if (!animator.mute) {
dispatch("scrollability-end", node);
}
}
function terminate() {
terminex();
}
}
// *************************************************************************************************
function getTouchAnimators(node, touchX, touchY, startTime) {
var animators = [];
// Get universally scrollable elements
var candidates = document.querySelectorAll('.scrollable.universal');
for (var j = 0; j < candidates.length; ++j) {
findAnimators(candidates[j], animators, touchX, touchY, startTime);
}
if (!candidates.length) {
// Find scrollable nodes that were directly touched
findAnimators(node, animators, touchX, touchY, startTime);
}
return animators;
}
function findAnimators(element, animators, touchX, touchY, startTime) {
while (element) {
if (element.nodeType == 1) {
var animator = createAnimatorForElement(element, touchX, touchY, startTime);
if (animator) {
// Look out for duplicates
var exists = false;
for (var j = 0; j < animators.length; ++j) {
if (animators[j].node == element) {
exists = true;
break;
}
}
if (!exists) {
animator = wrapAnimator(animator, touchX, touchY, startTime);
if (animator) {
animators.push(animator);
}
}
}
}
element = element.parentNode;
}
}
function createAnimatorForElement(element, touchX, touchY, startTime) {
var classes = element.className.split(' ');
if (classes.indexOf("scrollable") == -1)
return;
for (var i = 0; i < classes.length; ++i) {
var name = classes[i];
if (directions[name]) {
var animator = directions[name](element);
animator.direction = name;
animator.paginated = classes.indexOf('paginated') != -1;
return animator;
}
}
}
function generateCSSKeyframes(animator, keyframes, name, time, offset) {
var lines = ['@-webkit-keyframes ' + name + ' {'];
keyframes.forEach(function(keyframe) {
var percent = (keyframe.time / time) * 100;
var frame = Math.floor(percent) + '% {'
+ '-webkit-transform: ' + (keyframe.css || animator.update(keyframe.position+offset)) + ';'
+ '}';
// D&&D(frame);
lines.push(frame);
});
lines.push('}');
return lines.join('\n');
}
function setTouched(target) {
var touched = [];
for (var n = target; n; n = n.parentNode) {
if (n.nodeType == 1) {
n.className = (n.className ? n.className + ' ' : '') + 'touched';
touched.push(n);
}
}
return touched;
}
function releaseTouched(touched) {
for (var i = 0; i < touched.length; ++i) {
var n = touched[i];
n.className = n.className.replace('touched', '');
}
}
function initScrollbar(element) {
if (!element.scrollableScrollbar) {
var scrollbar = element.scrollableScrollbar = document.createElement('div');
scrollbar.className = 'scrollability-scrollbar';
}
return element.scrollableScrollbar;
}
function easeOutExpo(t, b, c, d) {
return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
}
// *************************************************************************************************
function createXDirection(node) {
var parent = node.parentNode;
var clipper = node.querySelector(".scrollable > .clipper") || node;
// Necessary to pause animation in order to get correct transform value
if (node.style.webkitAnimation) {
node.style.webkitAnimationPlayState = "paused";
}
var transform = getComputedStyle(node).webkitTransform;
var position = new WebKitCSSMatrix(transform).m41 - (node.scrollableOffset||0);
return {
node: node,
min: -clipper.offsetWidth + parent.offsetWidth,
max: 0,
position: position,
viewport: parent.offsetWidth,
bounce: parent.offsetWidth * kBounceLimit,
constrained: true,
filter: function(x, y) {
return x;
},
disable: function (x, y, startX, startY) {
var dx = Math.abs(x - startX);
var dy = Math.abs(y - startY);
if (dy > dx && dy > kLockThreshold) {
return true;
}
},
update: function(position) {
return 'translate3d(' + Math.round(position) + 'px, 0, 0)';
}
};
}
function createYDirection(node) {
var parent = node.parentNode;
var clipper = node.querySelector(".scrollable > .clipper") || node;
// Necessary to pause animation in order to get correct transform value
if (node.style.webkitAnimation) {
node.style.webkitAnimationPlayState = "paused";
}
var transform = getComputedStyle(node).webkitTransform;
var position = new WebKitCSSMatrix(transform).m42;
// D&&D('start ' + position);
return {
node: node,
scrollbar: initScrollbar(node),
position: position,
min: -clipper.offsetHeight + parent.offsetHeight,
max: 0,
viewport: parent.offsetHeight,
bounce: parent.offsetHeight * kBounceLimit,
constrained: true,
filter: function(x, y) {
return y;
},
disable: function(x, y, startX, startY) {
var dx = Math.abs(x - startX);
var dy = Math.abs(y - startY);
if (dx > dy && dx > kLockThreshold) {
return true;
}
},
update: function(position) {
return 'translate3d(0, ' + Math.round(position) + 'px, 0)';
}
};
}
function play(node, name, time) {
if (name) {
node.style.webkitAnimation = name + " " + time + "ms linear both";
}
node.style.webkitAnimationPlayState = name ? "running" : "paused";
}
function fadeIn(node) {
node.style.webkitTransition = '';
node.style.opacity = '1';
}
function dispatch(name, target, props) {
var e = document.createEvent("Events");
e.initEvent(name, false, true);
if (props) {
for (var name in props) {
e[name] = props[name];
}
}
return target.dispatchEvent(e);
} | onTouchEnd |
hyperVCollector.ts | // *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs, enums } from "../types";
import * as utilities from "../utilities";
/**
* API Version: 2019-10-01.
*/
export class HyperVCollector extends pulumi.CustomResource {
/**
* Get an existing HyperVCollector resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
*
* @param name The _unique_ name of the resulting resource.
* @param id The _unique_ provider ID of the resource to lookup.
* @param opts Optional settings to control the behavior of the CustomResource.
*/
public static get(name: string, id: pulumi.Input<pulumi.ID>, opts?: pulumi.CustomResourceOptions): HyperVCollector {
return new HyperVCollector(name, undefined as any, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'azure-native:migrate:HyperVCollector';
/**
* Returns true if the given object is an instance of HyperVCollector. This is designed to work even
* when multiple copies of the Pulumi SDK have been loaded into the same process.
*/
public static isInstance(obj: any): obj is HyperVCollector {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === HyperVCollector.__pulumiType;
}
public readonly eTag!: pulumi.Output<string | undefined>;
public /*out*/ readonly name!: pulumi.Output<string>;
public readonly properties!: pulumi.Output<outputs.migrate.CollectorPropertiesResponse>;
public /*out*/ readonly type!: pulumi.Output<string>;
/**
* Create a HyperVCollector resource with the given unique name, arguments, and options.
*
* @param name The _unique_ name of the resource.
* @param args The arguments to use to populate this resource's properties.
* @param opts A bag of options that control this resource's behavior.
*/
constructor(name: string, args: HyperVCollectorArgs, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (!opts.id) {
if ((!args || args.projectName === undefined) && !opts.urn) {
throw new Error("Missing required property 'projectName'");
}
if ((!args || args.resourceGroupName === undefined) && !opts.urn) {
throw new Error("Missing required property 'resourceGroupName'");
}
inputs["eTag"] = args ? args.eTag : undefined;
inputs["hyperVCollectorName"] = args ? args.hyperVCollectorName : undefined;
inputs["projectName"] = args ? args.projectName : undefined;
inputs["properties"] = args ? args.properties : undefined;
inputs["resourceGroupName"] = args ? args.resourceGroupName : undefined;
inputs["name"] = undefined /*out*/;
inputs["type"] = undefined /*out*/;
} else {
inputs["eTag"] = undefined /*out*/;
inputs["name"] = undefined /*out*/;
inputs["properties"] = undefined /*out*/;
inputs["type"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
} | const aliasOpts = { aliases: [{ type: "azure-nextgen:migrate:HyperVCollector" }, { type: "azure-native:migrate/v20191001:HyperVCollector" }, { type: "azure-nextgen:migrate/v20191001:HyperVCollector" }] };
opts = pulumi.mergeOptions(opts, aliasOpts);
super(HyperVCollector.__pulumiType, name, inputs, opts);
}
}
/**
* The set of arguments for constructing a HyperVCollector resource.
*/
export interface HyperVCollectorArgs {
eTag?: pulumi.Input<string>;
/**
* Unique name of a Hyper-V collector within a project.
*/
hyperVCollectorName?: pulumi.Input<string>;
/**
* Name of the Azure Migrate project.
*/
projectName: pulumi.Input<string>;
properties?: pulumi.Input<inputs.migrate.CollectorPropertiesArgs>;
/**
* Name of the Azure Resource Group that project is part of.
*/
resourceGroupName: pulumi.Input<string>;
} | |
cli.rs | use clap::{App, Arg};
pub(crate) fn | <'a, 'b: 'a>() -> App<'a, 'b> {
App::new(clap::crate_name!())
.version(clap::crate_version!())
.author(clap::crate_authors!())
.about(clap::crate_description!())
.arg(Arg::with_name("alphabetic")
.short("a")
.long("alphabetic")
.alias("alpha")
.help("include upper and lowercase alphabetic characters"))
.arg(Arg::with_name("lowercase")
.short("l")
.long("lowercase")
.alias("lower")
.help("include lowercase characters"))
.arg(Arg::with_name("uppercase")
.short("u")
.long("uppercase")
.alias("upper")
.help("include uppercase characters"))
.arg(Arg::with_name("numerals")
.short("n")
.long("numerals")
.help("include numerals"))
.arg(Arg::with_name("symbols")
.short("s")
.long("symbols")
.help("include symbols"))
.arg(Arg::with_name("custom")
.short("c")
.long("custom")
.help("provide characters to include")
.takes_value(true))
.arg(Arg::with_name("length")
.help("the length of passwords to generate")
.validator(is_numeric)
.required(true))
.arg(Arg::with_name("amount")
.help("the amount of passwords to generate")
.validator(is_numeric)
.default_value("1"))
}
fn is_numeric(s: String) -> Result<(), String> {
if s.chars().all(|x| x.is_digit(10)) {
Ok(())
} else {
Err("string must be numeric".into())
}
}
| app |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.