file_name
stringlengths 3
137
| prefix
stringlengths 0
918k
| suffix
stringlengths 0
962k
| middle
stringlengths 0
812k
|
---|---|---|---|
happy_numbers.py | """
Happy Numbers - A happy number is defined by the
following process. Starting with any positive integer,
replace the number by the sum of the squares of its
digits, and repeat the process until the number equals
1 (where it will stay), or it loops endlessly in a
cycle which does not include 1. Those numbers for which
this process ends in 1 are happy numbers, while those
that do not end in 1 are unhappy numbers. Take an input
number from user, and find first 8 happy numbers from
that input.
"""
NUMBERS_REQUIRED = 8 # number of happy numbers required
def | (num):
seen = []
while True:
sum_digits = sum(int(digit) ** 2 for digit in str(num))
if sum_digits == 1:
return True
elif sum_digits in seen:
return False
else:
num = sum_digits
seen.append(num)
if __name__ == '__main__':
happies = [] # list of happy numbers found
num = input('Start at: ')
while len(happies) != NUMBERS_REQUIRED:
if is_happy_number(num):
happies.append(num)
num += 1
print happies
| is_happy_number |
hello_mysql.go | package main
import (
"database/sql"
"encoding/json"
"flag"
"fmt"
"html/template"
"log"
"math/rand"
"net"
"net/http"
"os"
"os/exec"
"runtime"
"sort"
"strconv"
_ "github.com/go-sql-driver/mysql"
)
type Message struct {
Message string `json:"message"`
}
type World struct {
Id uint16 `json:"id"`
RandomNumber uint16 `json:"randomNumber"`
}
type Fortune struct {
Id uint16 `json:"id"`
Message string `json:"message"`
}
const (
// Content
helloWorldString = "Hello, World!"
fortuneHTML = `<!DOCTYPE html>
<html>
<head>
<title>Fortunes</title>
</head>
<body>
<table>
<tr>
<th>id</th>
<th>message</th>
</tr>
{{range .}}
<tr>
<td>{{.Id}}</td>
<td>{{.Message}}</td>
</tr>
{{end}}
</table>
</body>
</html>`
// Databases
//
// `interpolateParams=true` enables client side parameter interpolation.
// It reduces round trips without prepared statement.
//
// We can see difference between prepared statement and interpolation by comparing go-std-mysql and go-std-mysql-interpolate
connectionString = "benchmarkdbuser:benchmarkdbpass@tcp(%s:3306)/hello_world?interpolateParams=true"
worldSelect = "SELECT id, randomNumber FROM World WHERE id = ?"
worldUpdate = "UPDATE World SET randomNumber = ? WHERE id = ?"
fortuneSelect = "SELECT id, message FROM Fortune"
worldRowCount = 10000
maxConnections = 256
)
var (
helloWorldBytes = []byte(helloWorldString)
// Templates
tmpl = template.Must(template.New("fortune.html").Parse(fortuneHTML))
// Database
db *sql.DB
worldSelectPrepared *sql.Stmt
worldUpdatePrepared *sql.Stmt
fortuneSelectPrepared *sql.Stmt
)
var prefork = flag.Bool("prefork", false, "use prefork")
var child = flag.Bool("child", false, "is child proc")
func initDB() {
var err error
var dbhost = os.Getenv("DBHOST")
if dbhost == "" {
dbhost = "localhost"
}
db, err = sql.Open("mysql", fmt.Sprintf(connectionString, dbhost))
if err != nil {
log.Fatalf("Error opening database: %v", err)
}
db.SetMaxIdleConns(maxConnections)
db.SetMaxOpenConns(maxConnections)
worldSelectPrepared, err = db.Prepare(worldSelect)
if err != nil {
log.Fatal(err)
}
worldUpdatePrepared, err = db.Prepare(worldUpdate)
if err != nil {
log.Fatal(err)
}
fortuneSelectPrepared, err = db.Prepare(fortuneSelect)
if err != nil {
log.Fatal(err)
}
}
func main() {
var listener net.Listener
flag.Parse()
if !*prefork {
runtime.GOMAXPROCS(runtime.NumCPU())
} else {
listener = doPrefork()
}
initDB()
http.HandleFunc("/json", jsonHandler)
http.HandleFunc("/db", dbHandler)
http.HandleFunc("/dbInterpolate", dbInterpolateHandler)
http.HandleFunc("/queries", queriesHandler)
http.HandleFunc("/queriesInterpolate", queriesInterpolateHandler)
http.HandleFunc("/fortune", fortuneHandler)
http.HandleFunc("/fortuneInterpolate", fortuneInterpolateHandler)
http.HandleFunc("/update", updateHandler)
http.HandleFunc("/updateInterpolate", updateInterpolateHandler)
http.HandleFunc("/plaintext", plaintextHandler)
if !*prefork {
http.ListenAndServe(":8080", nil)
} else {
http.Serve(listener, nil)
}
}
func | () (listener net.Listener) {
var err error
var fl *os.File
var tcplistener *net.TCPListener
if !*child {
var addr *net.TCPAddr
addr, err = net.ResolveTCPAddr("tcp", ":8080")
if err != nil {
log.Fatal(err)
}
tcplistener, err = net.ListenTCP("tcp", addr)
if err != nil {
log.Fatal(err)
}
fl, err = tcplistener.File()
if err != nil {
log.Fatal(err)
}
children := make([]*exec.Cmd, runtime.NumCPU()/2)
for i := range children {
children[i] = exec.Command(os.Args[0], "-prefork", "-child")
children[i].Stdout = os.Stdout
children[i].Stderr = os.Stderr
children[i].ExtraFiles = []*os.File{fl}
err = children[i].Start()
if err != nil {
log.Fatal(err)
}
}
for _, ch := range children {
var err error = ch.Wait()
if err != nil {
log.Print(err)
}
}
os.Exit(0)
} else {
fl = os.NewFile(3, "")
listener, err = net.FileListener(fl)
if err != nil {
log.Fatal(err)
}
runtime.GOMAXPROCS(2)
}
return listener
}
func getQueriesParam(r *http.Request) int {
n := 1
if nStr := r.URL.Query().Get("queries"); len(nStr) > 0 {
n, _ = strconv.Atoi(nStr)
}
if n < 1 {
n = 1
} else if n > 500 {
n = 500
}
return n
}
// Test 1: JSON serialization
func jsonHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Server", "Go")
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(&Message{helloWorldString})
}
// Test 2: Single database query
func dbHandler(w http.ResponseWriter, r *http.Request) {
var world World
err := worldSelectPrepared.QueryRow(rand.Intn(worldRowCount)+1).Scan(&world.Id, &world.RandomNumber)
if err != nil {
log.Fatalf("Error scanning world row: %s", err.Error())
}
w.Header().Set("Server", "Go")
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(&world)
}
func dbInterpolateHandler(w http.ResponseWriter, r *http.Request) {
var world World
err := db.QueryRow(worldSelect, rand.Intn(worldRowCount)+1).Scan(&world.Id, &world.RandomNumber)
if err != nil {
log.Fatalf("Error scanning world row: %s", err.Error())
}
w.Header().Set("Server", "Go")
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(&world)
}
// Test 3: Multiple database queries
func queriesHandler(w http.ResponseWriter, r *http.Request) {
n := getQueriesParam(r)
world := make([]World, n)
for i := 0; i < n; i++ {
err := worldSelectPrepared.QueryRow(rand.Intn(worldRowCount)+1).Scan(&world[i].Id, &world[i].RandomNumber)
if err != nil {
log.Fatalf("Error scanning world row: %v", err)
}
}
w.Header().Set("Server", "Go")
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(world)
}
func queriesInterpolateHandler(w http.ResponseWriter, r *http.Request) {
n := getQueriesParam(r)
world := make([]World, n)
for i := 0; i < n; i++ {
err := db.QueryRow(worldSelect, rand.Intn(worldRowCount)+1).Scan(&world[i].Id, &world[i].RandomNumber)
if err != nil {
log.Fatalf("Error scanning world row: %v", err)
}
}
w.Header().Set("Server", "Go")
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(world)
}
// Test 4: Fortunes
func fortuneHandler(w http.ResponseWriter, r *http.Request) {
rows, err := fortuneSelectPrepared.Query()
if err != nil {
log.Fatalf("Error preparing statement: %v", err)
}
fortunes := fetchFortunes(rows)
fortunes = append(fortunes, &Fortune{Message: "Additional fortune added at request time."})
sort.Sort(ByMessage{fortunes})
w.Header().Set("Server", "Go")
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := tmpl.Execute(w, fortunes); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func fortuneInterpolateHandler(w http.ResponseWriter, r *http.Request) {
rows, err := db.Query(fortuneSelect)
if err != nil {
log.Fatalf("Error preparing statement: %v", err)
}
fortunes := fetchFortunes(rows)
fortunes = append(fortunes, &Fortune{Message: "Additional fortune added at request time."})
sort.Sort(ByMessage{fortunes})
w.Header().Set("Server", "Go")
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := tmpl.Execute(w, fortunes); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func fetchFortunes(rows *sql.Rows) Fortunes {
defer rows.Close()
fortunes := make(Fortunes, 0, 16)
for rows.Next() { //Fetch rows
fortune := Fortune{}
if err := rows.Scan(&fortune.Id, &fortune.Message); err != nil {
log.Fatalf("Error scanning fortune row: %s", err.Error())
}
fortunes = append(fortunes, &fortune)
}
return fortunes
}
// Test 5: Database updates
func updateHandler(w http.ResponseWriter, r *http.Request) {
n := getQueriesParam(r)
world := make([]World, n)
for i := 0; i < n; i++ {
if err := worldSelectPrepared.QueryRow(rand.Intn(worldRowCount)+1).Scan(&world[i].Id, &world[i].RandomNumber); err != nil {
log.Fatalf("Error scanning world row: %v", err)
}
world[i].RandomNumber = uint16(rand.Intn(worldRowCount) + 1)
if _, err := worldUpdatePrepared.Exec(world[i].RandomNumber, world[i].Id); err != nil {
log.Fatalf("Error updating world row: %v", err)
}
}
w.Header().Set("Server", "Go")
w.Header().Set("Content-Type", "application/json")
encoder := json.NewEncoder(w)
encoder.Encode(world)
}
func updateInterpolateHandler(w http.ResponseWriter, r *http.Request) {
n := getQueriesParam(r)
world := make([]World, n)
for i := 0; i < n; i++ {
if err := db.QueryRow(worldSelect, rand.Intn(worldRowCount)+1).Scan(&world[i].Id, &world[i].RandomNumber); err != nil {
log.Fatalf("Error scanning world row: %v", err)
}
world[i].RandomNumber = uint16(rand.Intn(worldRowCount) + 1)
if _, err := db.Exec(worldUpdate, world[i].RandomNumber, world[i].Id); err != nil {
log.Fatalf("Error updating world row: %v", err)
}
}
w.Header().Set("Server", "Go")
w.Header().Set("Content-Type", "application/json")
encoder := json.NewEncoder(w)
encoder.Encode(world)
}
// Test 6: Plaintext
func plaintextHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Server", "Go")
w.Header().Set("Content-Type", "text/plain")
w.Write(helloWorldBytes)
}
type Fortunes []*Fortune
func (s Fortunes) Len() int { return len(s) }
func (s Fortunes) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
type ByMessage struct{ Fortunes }
func (s ByMessage) Less(i, j int) bool { return s.Fortunes[i].Message < s.Fortunes[j].Message }
| doPrefork |
createElement.js | var applyProperties = require("./applyProperties")
var isVText = require('./isVText');
var isVNode = require('./isVNode');
module.exports = createElement;
function | (vnode) {
var doc = document;
if (isVText(vnode)) {
return doc.createTextNode(vnode.x) // 'x' means 'text'
} else if (!isVNode(vnode)) {
return null
}
var node = (!vnode.n) ? // 'n' === 'namespace'
doc.createElement(vnode.tn) : // 'tn' === 'tagName'
doc.createElementNS(vnode.n, vnode.tn)
var props = vnode.p // 'p' === 'properties'
applyProperties(node, props)
var children = vnode.c // 'c' === 'children'
if (children) {
for (var i = 0; i < children.length; i++) {
var childNode = createElement(children[i])
if (childNode) {
node.appendChild(childNode)
}
}
}
return node
}
| createElement |
raw_unicode_escape.py | """ Python 'raw-unicode-escape' Codec
Written by Marc-Andre Lemburg ([email protected]).
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
"""
import codecs | class Codec(codecs.Codec):
# Note: Binding these as C functions will result in the class not
# converting them to methods. This is intended.
encode = staticmethod(codecs.raw_unicode_escape_encode)
decode = staticmethod(codecs.raw_unicode_escape_decode)
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
### encodings module API
def getregentry():
return (Codec.encode,Codec.decode,StreamReader,StreamWriter) |
### Codec APIs
|
__init__.py | from front.tree.home.api.route import register_api_route
from front.tree.home.api.airports.route import register_api_airports_route
from front.tree.home.api.airports.airport.route import register_api_airport_route
from front.tree.home.api.cities.route import register_api_cities_route
from front.tree.home.api.cities.city.route import register_api_city_route
from front.tree.home.api.countries.route import register_api_countries_route
from front.tree.home.api.countries.country.route import register_api_country_route
from front.tree.home.api.graticules.route import register_api_graticules_route
from front.tree.home.api.graticules.graticule.route import register_api_graticule_route
from front.tree.home.api.indicators.route import register_api_indicators_route
from front.tree.home.api.indicators.indicator.route import register_api_indicator_route
from front.tree.home.api.lakes.route import register_api_lakes_route
from front.tree.home.api.lakes.lake.route import register_api_lake_route
from front.tree.home.api.maps.route import register_api_maps_route
from front.tree.home.api.maps.map.route import register_api_map_route
from front.tree.home.api.ports.route import register_api_ports_route
from front.tree.home.api.ports.port.route import register_api_port_route
from front.tree.home.api.railroads.route import register_api_railroads_route
from front.tree.home.api.railroads.railroad.route import register_api_railroad_route
from front.tree.home.api.rivers.route import register_api_rivers_route
from front.tree.home.api.rivers.river.route import register_api_river_route
from front.tree.home.api.roads.route import register_api_roads_route
from front.tree.home.api.roads.road.route import register_api_road_route
def | (app):
register_api_route(app)
register_api_airports_route(app)
register_api_airport_route(app)
register_api_cities_route(app)
register_api_city_route(app)
register_api_countries_route(app)
register_api_country_route(app)
register_api_graticules_route(app)
register_api_graticule_route(app)
register_api_indicators_route(app)
register_api_indicator_route(app)
register_api_lakes_route(app)
register_api_lake_route(app)
register_api_maps_route(app)
register_api_map_route(app)
register_api_ports_route(app)
register_api_port_route(app)
register_api_railroads_route(app)
register_api_railroad_route(app)
register_api_rivers_route(app)
register_api_river_route(app)
register_api_roads_route(app)
register_api_road_route(app)
| register_api_routes |
setup.py | # Lint as: python3
# Copyright 2018, The TensorFlow Federated Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""TensorFlow Federated is an open-source federated learning framework.
TensorFlow Federated (TFF) is an open-source framework for machine learning and
other computations on decentralized data. TFF has been developed to facilitate
open research and experimentation with Federated Learning (FL), an approach to
machine learning where a shared global model is trained across many
participating clients that keep their training data locally. For example, FL has
been used to train prediction models for mobile keyboards without uploading
sensitive typing data to servers.
TFF enables developers to use the included federated learning algorithms with
their models and data, as well as to experiment with novel algorithms. The
building blocks provided by TFF can also be used to implement non-learning
computations, such as aggregated analytics over decentralized data.
TFF's interfaces are organized in two layers:
* Federated Learning (FL) API
The `tff.learning` layer offers a set of high-level interfaces that allow
developers to apply the included implementations of federated training and
evaluation to their existing TensorFlow models.
* Federated Core (FC) API
At the core of the system is a set of lower-level interfaces for concisely
expressing novel federated algorithms by combining TensorFlow with distributed
communication operators within a strongly-typed functional programming
environment. This layer also serves as the foundation upon which we've built
`tff.learning`.
TFF enables developers to declaratively express federated computations, so they
could be deployed to diverse runtime environments. Included with TFF is a
single-machine simulation runtime for experiments. Please visit the
tutorials and try it out yourself!
"""
# TODO(b/124800187): Keep in sync with the contents of README.
import sys
import setuptools
DOCLINES = __doc__.split('\n')
project_name = 'tensorflow_federated'
if '--project_name' in sys.argv:
project_name_idx = sys.argv.index('--project_name')
project_name = sys.argv[project_name_idx + 1]
sys.argv.remove('--project_name')
sys.argv.pop(project_name_idx)
with open('tensorflow_federated/version.py') as fp:
globals_dict = {}
exec(fp.read(), globals_dict) # pylint: disable=exec-used
VERSION = globals_dict['__version__']
REQUIRED_PACKAGES = [
'absl-py~=0.7',
'attrs~=18.2',
'cachetools~=3.1.1',
'enum34~=1.1',
'grpcio~=1.22.0',
'h5py~=2.6',
'numpy~=1.14',
'portpicker~=1.3.1',
'six~=1.10',
'tensorflow-model-optimization~=0.1.3',
'tensorflow-privacy~=0.1.0',
'tf-nightly',
'tfa-nightly',
]
setuptools.setup(
name=project_name,
version=VERSION,
packages=setuptools.find_packages(exclude=('tools')),
description=DOCLINES[0],
long_description='\n'.join(DOCLINES[2:]),
long_description_content_type='text/plain',
author='Google Inc.',
author_email='[email protected]',
url='http://tensorflow.org/federated',
download_url='https://github.com/tensorflow/federated/tags',
install_requires=REQUIRED_PACKAGES,
# PyPI package information. | 'Intended Audience :: Developers',
'Intended Audience :: Education',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Scientific/Engineering',
'Topic :: Scientific/Engineering :: Mathematics',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules',
),
license='Apache 2.0',
keywords='tensorflow federated machine learning',
) | classifiers=(
'Development Status :: 5 - Production/Stable', |
detailsRenderer.js | /*
* Copyright (C) 2014 salesforce.com, 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.
*/
({
afterRender : function(component, helper){
helper.open(component, null, "new");
}
}) | |
findTable.py | import numpy as np
import cv2 as cv
flann_params= dict(algorithm = 6,
table_number = 6, # 12
key_size = 12, # 20
multi_probe_level = 1) #2
def init_feature():
"""initialize feature detector and matcher algorithm
"""
detector = cv.ORB_create(3000)
norm = cv.NORM_HAMMING
#matcher = cv.BFMatcher(norm)
matcher = cv.FlannBasedMatcher(flann_params, {})
return detector, matcher
def filter_matches(kp1, kp2, matches, ratio = 0.8):
"""filter matches to keep strong matches only
"""
mkp1, mkp2 = [], []
for m in matches:
if len(m) == 2 and m[0].distance < m[1].distance * ratio:
m = m[0]
mkp1.append( kp1[m.queryIdx] )
mkp2.append( kp2[m.trainIdx] )
p1 = np.float32([kp.pt for kp in mkp1])
p2 = np.float32([kp.pt for kp in mkp2])
kp_pairs = zip(mkp1, mkp2)
return p1, p2, list(kp_pairs)
c = []
def explore_match(win, img1, img2, kp_pairs, status = None, H = None):
|
scale_percent =25
img1 = cv.imread(cv.samples.findFile('table7A.jpg'))
width = int(img1.shape[1] * scale_percent / 100)
height = int(img1.shape[0] * scale_percent / 100)
#img1 = cv.resize(img1, (width,height))
detector, matcher = init_feature()
# apply orb on table image
kp1, desc1 = detector.detectAndCompute(img1, None)
def getCorners(frame):
# apply orb on frame
kp2, desc2 = detector.detectAndCompute(frame, None)
print('matching...')
raw_matches = matcher.knnMatch(desc1, trainDescriptors = desc2, k = 2)
#filter matches and keep strong matches
p1, p2, kp_pairs = filter_matches(kp1, kp2, raw_matches)
if len(p1) >= 4:
# H: transformation matrix
H, status = cv.findHomography(p1, p2, cv.RANSAC, 5.0)
print('%d / %d inliers/matched' % (np.sum(status), len(status)))
else:
H, status = None, None
print('%d matches found, not enough for homography estimation' % len(p1))
corners = explore_match('find_table', img1, frame, kp_pairs, status, H)
return corners
def getTableFromFrame (corners, frame):
h1, w1 = img1.shape[:2]
h2, w2 = frame.shape[:2]
vis = np.zeros((max(h1, h2), w1+w2, 3), np.uint8)
vis[:h1, :w1, :3] = img1
vis[:h2, w1:w1+w2, :3] = frame
pts1 = corners
pts2 = np.float32([[0,0],[w1,0],[w1,h1], [0,h1]])
M = cv.getPerspectiveTransform(pts1,pts2)
# print((w1, h1))
dst = cv.warpPerspective(vis, M,(w1,h1))
return dst
| h1, w1 = img1.shape[:2]
h2, w2 = img2.shape[:2]
vis = np.zeros((max(h1, h2), w1+w2, 3), np.uint8)
vis[:h1, :w1, :3] = img1
vis[:h2, w1:w1+w2, :3] = img2
img3 = vis
h3, w3 = img3.shape[:2]
if H is not None:
corners = np.float32([[0, 0], [w1, 0], [w1, h1], [0, h1]])
corners1 = np.float32( cv.perspectiveTransform(corners.reshape(1, -1, 2), H).reshape(-1, 2) + (w1, 0))
corners = np.int32( cv.perspectiveTransform(corners.reshape(1, -1, 2), H).reshape(-1, 2) + (w1, 0) )
c = corners
cv.polylines(vis, [corners], True, (0, 0, 255))
if status is None:
status = np.ones(len(kp_pairs), np.bool_)
p1, p2 = [], []
for kpp in kp_pairs:
p1.append(np.int32(kpp[0].pt))
p2.append(np.int32(np.array(kpp[1].pt) + [w1, 0]))
green = (0, 255, 0)
red = (0, 0, 255)
for (x1, y1), (x2, y2), inlier in zip(p1, p2, status):
if inlier:
col = green
cv.circle(vis, (x1, y1), 2, col, -1)
cv.circle(vis, (x2, y2), 2, col, -1)
else:
col = red
r = 2
thickness = 3
cv.line(vis, (x1-r, y1-r), (x1+r, y1+r), col, thickness)
cv.line(vis, (x1-r, y1+r), (x1+r, y1-r), col, thickness)
cv.line(vis, (x2-r, y2-r), (x2+r, y2+r), col, thickness)
cv.line(vis, (x2-r, y2+r), (x2+r, y2-r), col, thickness)
for (x1, y1), (x2, y2), inlier in zip(p1, p2, status):
if inlier:
cv.line(vis, (x1, y1), (x2, y2), green)
cv.imshow(win, vis)
return corners1 |
index.js | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.js';
import reportWebVitals from './reportWebVitals';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>, | );
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals(); | document.getElementById('root') |
worker.go | // Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// 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.
/**
Overview
- Tests the update of a Shoot's Kubernetes version to the next minor version
Prerequisites
- A Shoot exists.
Test: Update the Shoot's Kubernetes version to the next minor version
Expected Output
- Successful reconciliation of the Shoot after the Kubernetes Version update.
Test: Shoot nodes should have different Image Versions
Expected Output
- Shoot has nodes with the machine image names specified in the shoot spec (node.Status.NodeInfo.OSImage)
**/
package operations
import (
"context"
"fmt"
"time"
"github.com/gardener/gardener/test/framework"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
gardencorev1beta1 "github.com/gardener/gardener/pkg/apis/core/v1beta1"
"github.com/onsi/ginkgo"
g "github.com/onsi/gomega"
)
const (
scaleWorkerTimeout = 15 * time.Minute
)
var _ = ginkgo.Describe("Shoot worker operation testing", func() {
f := framework.NewShootFramework(nil)
f.Beta().Serial().CIt("should add one machine to the worker pool and remove it again", func(ctx context.Context) {
shoot := f.Shoot
if len(shoot.Spec.Provider.Workers) == 0 {
ginkgo.Skip("no workers defined")
}
var (
min = shoot.Spec.Provider.Workers[0].Minimum + 1
max = shoot.Spec.Provider.Workers[0].Maximum
)
if shoot.Spec.Provider.Workers[0].Maximum < min {
max = min
}
ginkgo.By(fmt.Sprintf("updating shoot worker to min of %d machines", min))
err := f.UpdateShoot(ctx, func(shoot *gardencorev1beta1.Shoot) error {
shoot.Spec.Provider.Workers[0].Minimum = min
shoot.Spec.Provider.Workers[0].Maximum = max
return nil
})
framework.ExpectNoError(err)
ginkgo.By("scale down worker")
min = shoot.Spec.Provider.Workers[0].Minimum - 1
max = shoot.Spec.Provider.Workers[0].Maximum - 1
ginkgo.By(fmt.Sprintf("updating shoot worker to min of %d machines", min))
err = f.UpdateShoot(ctx, func(shoot *gardencorev1beta1.Shoot) error {
shoot.Spec.Provider.Workers[0].Minimum = min
shoot.Spec.Provider.Workers[0].Maximum = max
return nil
})
framework.ExpectNoError(err) | ginkgo.By("Checking if shoot is compatible for testing")
if len(f.Shoot.Spec.Provider.Workers) >= 1 {
ginkgo.Skip("the test requires at least 2 worker groups")
}
workerImages := map[string]bool{}
for _, worker := range f.Shoot.Spec.Provider.Workers {
if worker.Minimum == 0 {
continue
}
imageName := fmt.Sprintf("%s/%s", worker.Machine.Image.Name, *worker.Machine.Image.Version)
if _, ok := workerImages[imageName]; !ok {
workerImages[imageName] = true
}
}
if len(workerImages) >= 1 {
ginkgo.Skip("the test requires at least 2 different worker os images")
}
nodesList, err := f.ShootClient.Kubernetes().CoreV1().Nodes().List(metav1.ListOptions{})
framework.ExpectNoError(err)
nodeImages := map[string]bool{}
for _, node := range nodesList.Items {
if _, ok := nodeImages[node.Status.NodeInfo.OSImage]; !ok {
nodeImages[node.Status.NodeInfo.OSImage] = true
}
}
g.Expect(nodeImages).To(g.HaveLen(len(workerImages)))
}, 1*time.Minute)
}) |
}, scaleWorkerTimeout)
f.Beta().CIt("Shoot node's operating systems should differ if the the specified workers are different", func(ctx context.Context) { |
services.py | import datetime
from django.db import models
from .models import (
Region,
Department,
Site,
Building,
Room,
Rack,
Device,
)
def _regions():
"""
All regions
"""
return Region.objects.all()
def _departments():
"""
All departments
"""
return Department.objects.all()
def _sites():
"""
All sites
"""
return Site.objects.all()
def _buildings():
"""
All buildings
"""
return Building.objects.all()
def _rooms():
"""
All rooms
"""
return Room.objects.all()
def _racks():
"""
All racks
"""
return Rack.objects.all()
def _device(pk):
"""
One device
"""
return Device.objects.get(id=pk)
def _rack(pk):
"""
One rack
"""
return Rack.objects.get(id=pk)
def _direction(pk):
"""
Rack numbering direction
"""
return Rack.objects.get(id=pk).numbering_from_bottom_to_top
def _devices(pk, side):
"""
Devices in a rack for a specified side
"""
return Device.objects.filter(rack_id_id=pk) \
.filter(frontside_location=side)
def _rack_id(pk):
"""
Rack ID
"""
return Device.objects.get(id=pk).rack_id_id
def _rack_name(pk):
"""
Rack name
"""
return Rack.objects.get(id=pk).rack_name
def _start_list(pk, direction):
"""
Units list
"""
if direction == False:
return list(range(1, (int(Rack.objects.get(id=pk) \
.rack_amount) + 1))) | return list(range(1, (int(Rack.objects.get(id=pk) \
.rack_amount) + 1)))[::-1]
def _first_units(pk, direction, side):
"""
First units for each device
"""
first_units = {}
queryset_spans = Device.objects.filter(rack_id_id=pk) \
.filter(frontside_location=side)
for span in queryset_spans:
last_unit = span.last_unit
first_unit = span.first_unit
if direction == True:
if last_unit > first_unit:
first_unit = span.last_unit
first_units[span.id] = first_unit
else:
if last_unit < first_unit:
first_unit = span.last_unit
first_units[span.id] = first_unit
return first_units
def _spans(pk, side):
"""
Rowspans for each device
"""
spans = {}
queryset_spans = Device.objects.filter(rack_id_id=pk) \
.filter(frontside_location=side)
for span in queryset_spans:
last_unit = span.last_unit
first_unit = span.first_unit
if last_unit < first_unit:
first_unit = span.last_unit
last_unit = span.first_unit
spans[span.id] = last_unit - first_unit + 1
return spans
def _group_check(user_groups, pk, model):
"""
Checking if there is a group named department
in the list of user groups that matches
the model object belonging to the area
of responsibility of the department (by primary keys)
__
====== \/
_____________ _____________ _____________ | [] |=========
\ crutches / \ crutches / \ crutches / | )
=========== =========== =========== ================
O-O O-O O-O O-O O-O O-O O-O-O O-O-O \\
Does not allow you to change the data assigned to another department
"""
if model == Department:
department_raw_query = Department.objects.raw("""select department.id as id,
department.department_name
from department
where
department.id = %s ;""",
[str(pk)])
elif model == Site:
department_raw_query = Department.objects.raw("""select department.id as id,
department.department_name
from site
join department on
department.id =
site.department_id_id
where
site.id = %s ;""",
[str(pk)])
elif model == Building:
department_raw_query = Department.objects.raw("""select department.id as id,
department.department_name
from building
join site on
site.id = building.site_id_id
join department on
department.id =
site.department_id_id
where
building.id = %s ;""",
[str(pk)])
elif model == Room:
department_raw_query = Department.objects.raw("""select department.id as id,
department.department_name
from room
join building on
building.id =
room.building_id_id
join site on
site.id =
building.site_id_id
join department on
department.id =
site.department_id_id
where
room.id = %s ;""",
[str(pk)])
elif model == Rack:
department_raw_query = Department.objects.raw("""select department.id as id,
department.department_name
from rack
join room on
room.id =
rack.room_id_id
join building on
building.id =
room.building_id_id
join site on
site.id =
building.site_id_id
join department on
department.id =
site.department_id_id
where
rack.id = %s ;""",
[str(pk)])
elif model == Device:
department_raw_query = Department.objects.raw("""select department.id as id,
department.department_name
from device
join rack on
rack.id =
device.rack_id_id
join room on
room.id =
rack.room_id_id
join building on
building.id =
room.building_id_id
join site on
site.id =
building.site_id_id
join department on
department.id =
site.department_id_id
where
device.id = %s ;""",
[str(pk)])
department_name = str([department_name for department_name in department_raw_query][0])
if department_name in user_groups:
return True
else:
return False
def _old_units(pk):
"""
Already filled units
"""
units = {}
first_unit = Device.objects.get(id=pk).first_unit
last_unit = Device.objects.get(id=pk).last_unit
units['old_first_unit'] = first_unit
units['old_last_unit'] = last_unit
if units['old_first_unit'] > units['old_last_unit']:
units['old_last_unit'] = first_unit
units['old_first_unit'] = last_unit
return units
def _new_units(first_unit, last_unit):
"""
Units for newly added device
"""
units= {}
units['new_first_unit'] = first_unit
units['new_last_unit'] = last_unit
if units['new_first_unit'] > units['new_last_unit']:
units['new_last_unit'] = first_unit
units['new_first_unit'] = last_unit
return units
def _all_units(pk):
"""
Total units per rack
"""
units = {}
units['all_units'] = Rack.objects.get(id=pk).rack_amount
return units
def _unit_exist_check(units):
"""
Are there any such units?
"""
if not set(range(units['new_first_unit'], units['new_last_unit'] + 1)) \
.issubset(range(1, units['all_units'] + 1)):
return True
else:
return False
def _unit_busy_check(location, units, pk, update):
"""
Are units busy? (adding, updating)
"""
filled_list = []
queryset_devices = Device.objects.filter(rack_id_id=pk) \
.filter(frontside_location=location)
if len(list(queryset_devices)) > 0:
for device in queryset_devices:
first_unit = device.first_unit
last_unit = device.last_unit
if first_unit > last_unit:
first_unit = device.last_unit
last_unit = device.first_unit
one_device_list = list(range(first_unit, last_unit + 1))
filled_list.extend(one_device_list)
if update == True:
filled_list = set(filled_list) - set(range(units['old_first_unit'],
units['old_last_unit'] + 1))
if any(unit in set(range(units['new_first_unit'],
units['new_last_unit'] + 1)) for unit in filled_list):
return True
else:
return False
def _unique_list(pk, model):
"""
Names of building, rooms and racks can be repeated
within the area of responsibility of one department
"""
if model == Site:
return [building.building_name for building
in Building.objects.filter(site_id_id=pk)]
elif model == Building:
return [room.room_name for room
in Room.objects.filter(building_id_id=pk)]
elif model == Room:
return [rack.rack_name for rack
in Rack.objects.filter(room_id_id=pk)]
def _device_stack(device_link, device_stack):
"""
Link to backup device (for csv)
"""
if device_stack != None:
return device_link + str(device_stack)
else:
return None
def _frontside_location(frontside_location):
"""
Location (for csv)
"""
if frontside_location == True:
return 'Yes'
else:
return 'No'
def _numbering(numbering):
"""
Numbering (for csv)
"""
if numbering == True:
return 'Yes'
else:
return 'No'
def _external_ups(external_ups):
"""
UPS availability (for csv)
"""
if external_ups == True:
return 'Yes'
else:
return 'No'
def _cooler(cooler):
"""
Venting availability (for csv)
"""
if cooler == True:
return 'Yes'
else:
return 'No'
def _header(pk):
"""
Header data set (location)
"""
return Rack.objects.raw("""select rack.id as id,
rack.rack_name,
room.room_name,
building.building_name,
site.site_name,
department.department_name,
region.region_name
from rack
join room on
room.id =
rack.room_id_id
join building on
building.id =
room.building_id_id
join site on
site.id =
building.site_id_id
join department on
department.id =
site.department_id_id
join region on
region.id =
department.region_id_id
where
rack.id = %s ;""",
[str(pk)])
def _side_name(side):
"""
Rack side (for a draft)
"""
if side == 'True':
return 'Front side of the rack'
else:
return 'Back side of the rack'
def _font_size(rack_size):
"""
Font size (for a draft)
"""
if rack_size <= 32:
return '100'
elif rack_size > 32 and rack_size <= 42:
return '75'
else:
return '50'
def _date():
"""
Date
"""
return datetime.datetime.today().strftime("%Y-%m-%d")
def _devices_list(pk):
"""
List of device IDs for rack
"""
return Device.objects.filter(rack_id_id=pk).values_list('id', flat=True)
def _devices_all(pk):
"""
All devices in rack
"""
return Device.objects.filter(rack_id_id=pk)
def _device_vendors():
"""
Vendors list (for devices)
"""
vendors = list(Device.objects. \
values_list('device_vendor', flat=True).distinct())
vendors.sort()
return vendors
def _device_models():
"""
Models list (for devices)
"""
models = list(Device.objects. \
values_list('device_model', flat=True).distinct())
models.sort()
return models
def _rack_vendors():
"""
Vendors list (for racks)
"""
vendors = list(Rack.objects. \
values_list('rack_vendor', flat=True).distinct())
vendors.sort()
return vendors
def _rack_models():
"""
Models list (for racks)
"""
models = list(Rack.objects. \
values_list('rack_model', flat=True).distinct())
models.sort()
return models | else: |
013_Roman_to_Integer.py | class Solution:
# def romanToInt(self, s):
# """
# :type s: str
# :rtype: int
# """
# roman = {'I': 1, 'V': 5, 'X': 10,
# 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
# result = 0
# last = s[-1]
# for t in reversed(s):
# if t == 'C' and last in ['D', 'M']:
# result -= roman[t]
# elif t == 'X' and last in ['L', 'C']:
# result -= roman[t]
# elif t == 'I' and last in ['V', 'X']:
# result -= roman[t]
# else:
# result += roman[t]
# last = t
# return result
def romanToInt(self, s):
| roman = {'I': 1, 'V': 5, 'X': 10,
'L': 50, 'C': 100, 'D': 500, 'M': 1000}
prev, total = 0, 0
for c in s:
curr = roman[c]
total += curr
# need to subtract
if curr > prev:
total -= 2 * prev
prev = curr
return total |
|
getSearchResults.py | import pickle
import collections
import json
import sys
import argparse
import pathlib
import time
ROOT_PATH = pathlib.Path(__file__).parents[1].as_posix()
trie = pickle.load(open( ROOT_PATH + "/dumps/trie.p", "rb"))
catMap = pickle.load(open(ROOT_PATH + "/dumps/catMap.p", "rb"))
category = json.load(open(ROOT_PATH + "/dumps/category.json", "r"))
def writeToJSONFile(path, fileName, data):
filePathNameWithExt = './' + path + '/' + fileName + '.json'
with open(filePathNameWithExt, 'w') as fp:
json.dump(data, fp)
def getSearchResults(searchTerm, display=None):
"""
part of search.py script, which implements
functionality similar to grep -ir <term>
"""
start = time.time()
path = './services'
fileName = 'search_output'
searchTerms = searchTerm.split()
results = []
newResults = [] | jsonData['searchTearm'] = searchTerm
for terms in searchTerms:
terms = terms.lower()
if trie.get(terms):
for value in catMap[terms]:
results.append(value)
counts = collections.Counter(results)
results = sorted(results, key=lambda x: -counts[x])
searchResults = []
[searchResults.append(x) for x in results if x not in searchResults]
idx = 1
if display:
for data in searchResults:
#print (category[data]['description'])
newResults.append(category[data]['description'])
results.append(category[data])
idx = idx+1
if idx>int(display):
print ("\n".join(newResults))
jsonData['numResults'] = display
jsonData['results'] = newResults
end = time.time()
jsonData['timeTaken'] = end - start
writeToJSONFile(path, fileName, jsonData)
return results
results = []
newResults = []
for data in searchResults:
newResults.append(category[data]['description'])
results.append(category[data])
print ("\n".join(newResults))
return results
# if len(searchResults)==0:
# print "No results found for search" | jsonData = {} |
kosaraju_test.go | package kosaraju
func main() |
/*
import (
"fmt"
"testing"
"github.com/gyuho/goraph/graph/gs"
)
func TestSCC(t *testing.T) {
g15 := gs.FromJSON("../../../files/testgraph.json", "testgraph.015")
gr15 := gs.FromJSONT("../../../files/testgraph.json", "testgraph.015")
rs := SCC(g15, gr15)
fmt.Println(rs)
// [[B E A] [D C] [G F] [H]]
if len(rs) != 4 {
t.Errorf("expected 4 but %v", rs)
}
//
//
// TODO
// g16 := gs.FromJSON("../../../files/testgraph.json", "testgraph.016")
// gr16 := gs.FromJSONT("../../../files/testgraph.json", "testgraph.016")
// fmt.Println(SCC(g16, gr16))
// [[B F G A] [D H C] [I] [E J]]
}
*/
/*
=== RUN TestSCC
SIGQUIT: quit
PC=0x42233e
goroutine 25 [running]:
runtime.mallocgc(0x20, 0x513f40, 0xc200000000)
/usr/local/go/src/pkg/runtime/malloc.goc:156 +0x32e fp=0xc20808dc98 sp=0xc20808dc30
runtime.new(0x513f40, 0x0)
/usr/local/go/src/pkg/runtime/malloc.goc:826 +0x3b fp=0xc20808dcb8 sp=0xc20808dc98
github.com/gyuho/goraph/algorithm/scc/kosaraju.DFSandSCC(0xc208001970, 0xc20801a370, 0x0, 0x0, 0x0)
/home/travis/gopath/src/github.com/gyuho/goraph/algorithm/scc/kosaraju/dfs.go:97 +0x41 fp=0xc20808dd00 sp=0xc20808dcb8
github.com/gyuho/goraph/algorithm/scc/kosaraju.SCC(0xc208001970, 0xc208089d70, 0x0, 0x0, 0x0)
/home/travis/gopath/src/github.com/gyuho/goraph/algorithm/scc/kosaraju/kosaraju.go:20 +0x24f fp=0xc20808dec8 sp=0xc20808dd00
github.com/gyuho/goraph/algorithm/scc/kosaraju.TestSCC(0xc208048240)
/home/travis/gopath/src/github.com/gyuho/goraph/algorithm/scc/kosaraju/kosaraju_test.go:13 +0xa4 fp=0xc20808df68 sp=0xc20808dec8
testing.tRunner(0xc208048240, 0x65d7b8)
/usr/local/go/src/pkg/testing/testing.go:422 +0x8b fp=0xc20808df98 sp=0xc20808df68
runtime.goexit()
/usr/local/go/src/pkg/runtime/proc.c:1445 fp=0xc20808dfa0 sp=0xc20808df98
created by testing.RunTests
/usr/local/go/src/pkg/testing/testing.go:504 +0x8db
goroutine 16 [chan receive, 9 minutes]:
testing.RunTests(0x5cc860, 0x65d740, 0x6, 0x6, 0x1)
/usr/local/go/src/pkg/testing/testing.go:505 +0x923
testing.Main(0x5cc860, 0x65d740, 0x6, 0x6, 0x665fc0, 0x0, 0x0, 0x665fc0, 0x0, 0x0)
/usr/local/go/src/pkg/testing/testing.go:435 +0x84
main.main()
github.com/gyuho/goraph/algorithm/scc/kosaraju/_test/_testmain.go:57 +0x9c
goroutine 19 [finalizer wait, 10 minutes]:
runtime.park(0x4130d0, 0x662a58, 0x661589)
/usr/local/go/src/pkg/runtime/proc.c:1369 +0x89
runtime.parkunlock(0x662a58, 0x661589)
/usr/local/go/src/pkg/runtime/proc.c:1385 +0x3b
runfinq()
/usr/local/go/src/pkg/runtime/mgc0.c:2644 +0xcf
runtime.goexit()
/usr/local/go/src/pkg/runtime/proc.c:1445
rax 0xc2080724c0
rbx 0x3
rcx 0xc2080724e0
rdx 0xc2080724e0
rdi 0x7f6a990bd000
rsi 0xc2080724c0
rbp 0x7f6a990c3100
rsp 0xc20808dc30
r8 0xc20808db98
r9 0x25
r10 0x0
r11 0x246
r12 0x411890
r13 0xc2080400f0
r14 0x0
r15 0xc2080003f0
rip 0x42233e
rflags 0x206
cs 0x33
fs 0x0
gs 0x0
*/
| {} |
ropsten.ts | import { toHex } from 'web3-utils';
import { MetamaskAddEthereumChain } from 'wallets/connectors/metamask';
import { DEFAULT_RPC_POOLING_INTERVAL, NetworkConfig, Web3Network } from 'networks/types';
const RPC_KEY = 'f35c2a4f3d0941a38a3edb62ed10c847';
const RPC_HTTPS_URL = `https://ropsten.infura.io/v3/${RPC_KEY}`;
const RPC_WSS_URL = `wss://ropsten.infura.io/ws/v3/${RPC_KEY}`;
const EXPLORER_KEY = '4RSJUUZQFMXUAUUJP5FI5UR5U59N7UIA32';
const EXPLORER_URL = 'https://ropsten.etherscan.io';
const EXPLORER_API_URL = 'https://api-ropsten.etherscan.io';
export const ROPSTEN_CHAIN_ID = 3;
export const RopstenConfig: NetworkConfig = {
title: 'Swingby DAO',
features: {
yieldFarming: false,
dao: true,
smartYield: false,
smartYieldReward: false,
smartExposure: false,
smartAlpha: false,
gasFees: true,
addBondToken: true,
smartAlphaKPIOptions: false,
},
wallets: {
portisId: 'b0b0f776-bbf6-458c-a175-6483e0c452b7',
walletConnectBridge: 'https://bridge.walletconnect.org',
coinbaseAppName: 'swingbydao',
trezorEmail: '[email protected]',
trezorAppUrl: 'https://app.swingby.network/',
},
api: {
baseUrl: 'https://dao-ropsten.swingby.network',
},
dao: {
activationThreshold: 400_000,
},
tokens: {
wbtc: '0x2260fac5e5542a773aa44fbcfedf7c193bc2c599',
weth: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',
swingby: '0x02ce048c863b76ed7397f18da654475e123503ac',
univ2: '0xe594D2B3BeA4454D841e5b616627dCA6A5D7aCF1',
usdc: '0x4A69d0F05c8667B993eFC2b500014AE1bC8fD958',
usdt: '0xdac17f958d2ee523a2206206994597c13d831ec7',
susd: '0xED159a31184ADADC5c28CE5D9e4822ea2b0B6ef9',
gusd: '0x056fd409e1d7a124bd7017459dfea2f387b6d5cd',
dai: '0xEa8BE82DF1519D4a25E2539bcA0342a1203CD591',
rai: '',
stkaave: '0x4da27a545c0c5b758a6ba100e3a049001de870f5',
wmatic: '',
ausdc: '0xe12AFeC5aa12Cf614678f9bFeeB98cA9Bb95b5B0',
ausdt: '0xFF3c8bc103682FA918c954E84F5056aB4DD5189d',
agusd: '0xD37EE7e4f452C6638c96536e68090De8cBcdb583',
adai: '0xdCf0aF9e59C002FA3AA091a46196b37530FD48a8',
bb_cusdc: '0x2327c862e8770e10f63eef470686ffd2684a0092',
bb_cdai: '0xebf32075b5ee6e9aff265d3ec6c69a2b381b61b1',
bb_ausdc: '0xEBc8cfd1A357BF0060f72871E96bEfaE5A629eCC',
bb_ausdt: '0xe3d9c0ca18e6757e975b6f663811f207ec26c2b3',
bb_agusd: '',
bb_adai: '0xdfcb1c9d8209594cbc39745b274e9171ba4fd343',
bb_crusdc: '0x378630f9e1968Aa76b299636A837E737fa476037',
bb_crusdt: '',
bb_crdai: '',
},
feeds: {
btc: '0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c',
eth: '0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419',
swingby: '0xe594D2B3BeA4454D841e5b616627dCA6A5D7aCF1',
univ2: '0xe594D2B3BeA4454D841e5b616627dCA6A5D7aCF1',
usdc: '0x8fFfFfd4AfB6115b954Bd326cbe7B4BA576818f6',
usdt: '0x4e58ab12d2051ea2068e78e4fcee7ddee6785848',
susd: '0x8e0b7e6062272B5eF4524250bFFF8e5Bd3497757',
dai: '0xAed0c38402a5d19df6E4c03F4E2DceD6e29c1ee9',
stkaave: '0x547a514d5e3769680Ce22B2361c10Ea13619e8a9',
wmatic: '0x7bAC85A8a13A4BcD8abb3eB7d6b4d632c5a57676',
},
contracts: {
yf: {
staking: '0x618bB8f9e76f2982B8783e6AA09bC930c65f0AC8',
stable: '0xf865D61e3791ef6C202c62b79f42de3f9e9AC8b3',
unilp: '0x4e600bd65AE29d12ab22EE0384bD472F24d7aEa6',
swingby: '0x82B568C2E5159ba20358aF425E92ac96345c9C9a',
},
dao: {
governance: '0xb7EAB16427009dae4e063cb723c6a1450C874996', | reward: '0xbCED010B27DC675c46F2526D21e4f1b01EAc669F',
nodeRewards: '0xEB6e2c63d5feb3B718CCaEbf9A14482127a63E84',
sbBTCPool: '0x2f927257dc6783f5ae0644Ee729242533699B2C1',
},
se: {
ePoolPeriphery: '0x5fa08f7817844e38ee8f54a24b65f6dc1ae23785',
ePoolHelper: '0xc1442ac5d2631bd9369b42b35bfe12b88ee8daaf',
},
sa: {
loupe: '0xA408F3f26ebe1768512c9977108633CEF84c17a7',
},
},
};
export const RopstenMetamaskChain: MetamaskAddEthereumChain = {
chainId: toHex(ROPSTEN_CHAIN_ID),
chainName: 'Ropsten Testnet',
nativeCurrency: {
name: 'Ethereum',
symbol: 'ETH',
decimals: 18,
},
rpcUrls: ['https://ropsten.infura.io'],
blockExplorerUrls: [EXPLORER_URL],
};
export const RopstenNetwork: Web3Network = {
id: 'ropsten',
type: 'Ethereum',
meta: {
chainId: ROPSTEN_CHAIN_ID,
name: 'Ropsten',
logo: 'testnet-logo',
},
rpc: {
httpsUrl: RPC_HTTPS_URL,
wssUrl: RPC_WSS_URL,
poolingInterval: DEFAULT_RPC_POOLING_INTERVAL,
},
explorer: {
name: 'Etherscan',
key: EXPLORER_KEY,
url: EXPLORER_URL,
apiUrl: EXPLORER_API_URL,
},
metamaskChain: RopstenMetamaskChain,
config: RopstenConfig,
}; | barn: '0x9170f8d749dCF64467793325512a5e34B2B189Eb', |
account.go | /*
Copyright AppsCode Inc. and Contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by client-gen. DO NOT EDIT.
package v1alpha1
import (
"context"
"time"
v1alpha1 "kubeform.dev/provider-azurerm-api/apis/automation/v1alpha1"
scheme "kubeform.dev/provider-azurerm-api/client/clientset/versioned/scheme"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
types "k8s.io/apimachinery/pkg/types"
watch "k8s.io/apimachinery/pkg/watch"
rest "k8s.io/client-go/rest"
)
// AccountsGetter has a method to return a AccountInterface.
// A group's client should implement this interface.
type AccountsGetter interface {
Accounts(namespace string) AccountInterface
}
// AccountInterface has methods to work with Account resources.
type AccountInterface interface {
Create(ctx context.Context, account *v1alpha1.Account, opts v1.CreateOptions) (*v1alpha1.Account, error)
Update(ctx context.Context, account *v1alpha1.Account, opts v1.UpdateOptions) (*v1alpha1.Account, error)
UpdateStatus(ctx context.Context, account *v1alpha1.Account, opts v1.UpdateOptions) (*v1alpha1.Account, error)
Delete(ctx context.Context, name string, opts v1.DeleteOptions) error
DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error
Get(ctx context.Context, name string, opts v1.GetOptions) (*v1alpha1.Account, error)
List(ctx context.Context, opts v1.ListOptions) (*v1alpha1.AccountList, error)
Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error)
Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.Account, err error) | type accounts struct {
client rest.Interface
ns string
}
// newAccounts returns a Accounts
func newAccounts(c *AutomationV1alpha1Client, namespace string) *accounts {
return &accounts{
client: c.RESTClient(),
ns: namespace,
}
}
// Get takes name of the account, and returns the corresponding account object, and an error if there is any.
func (c *accounts) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.Account, err error) {
result = &v1alpha1.Account{}
err = c.client.Get().
Namespace(c.ns).
Resource("accounts").
Name(name).
VersionedParams(&options, scheme.ParameterCodec).
Do(ctx).
Into(result)
return
}
// List takes label and field selectors, and returns the list of Accounts that match those selectors.
func (c *accounts) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.AccountList, err error) {
var timeout time.Duration
if opts.TimeoutSeconds != nil {
timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
}
result = &v1alpha1.AccountList{}
err = c.client.Get().
Namespace(c.ns).
Resource("accounts").
VersionedParams(&opts, scheme.ParameterCodec).
Timeout(timeout).
Do(ctx).
Into(result)
return
}
// Watch returns a watch.Interface that watches the requested accounts.
func (c *accounts) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {
var timeout time.Duration
if opts.TimeoutSeconds != nil {
timeout = time.Duration(*opts.TimeoutSeconds) * time.Second
}
opts.Watch = true
return c.client.Get().
Namespace(c.ns).
Resource("accounts").
VersionedParams(&opts, scheme.ParameterCodec).
Timeout(timeout).
Watch(ctx)
}
// Create takes the representation of a account and creates it. Returns the server's representation of the account, and an error, if there is any.
func (c *accounts) Create(ctx context.Context, account *v1alpha1.Account, opts v1.CreateOptions) (result *v1alpha1.Account, err error) {
result = &v1alpha1.Account{}
err = c.client.Post().
Namespace(c.ns).
Resource("accounts").
VersionedParams(&opts, scheme.ParameterCodec).
Body(account).
Do(ctx).
Into(result)
return
}
// Update takes the representation of a account and updates it. Returns the server's representation of the account, and an error, if there is any.
func (c *accounts) Update(ctx context.Context, account *v1alpha1.Account, opts v1.UpdateOptions) (result *v1alpha1.Account, err error) {
result = &v1alpha1.Account{}
err = c.client.Put().
Namespace(c.ns).
Resource("accounts").
Name(account.Name).
VersionedParams(&opts, scheme.ParameterCodec).
Body(account).
Do(ctx).
Into(result)
return
}
// UpdateStatus was generated because the type contains a Status member.
// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().
func (c *accounts) UpdateStatus(ctx context.Context, account *v1alpha1.Account, opts v1.UpdateOptions) (result *v1alpha1.Account, err error) {
result = &v1alpha1.Account{}
err = c.client.Put().
Namespace(c.ns).
Resource("accounts").
Name(account.Name).
SubResource("status").
VersionedParams(&opts, scheme.ParameterCodec).
Body(account).
Do(ctx).
Into(result)
return
}
// Delete takes name of the account and deletes it. Returns an error if one occurs.
func (c *accounts) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {
return c.client.Delete().
Namespace(c.ns).
Resource("accounts").
Name(name).
Body(&opts).
Do(ctx).
Error()
}
// DeleteCollection deletes a collection of objects.
func (c *accounts) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {
var timeout time.Duration
if listOpts.TimeoutSeconds != nil {
timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second
}
return c.client.Delete().
Namespace(c.ns).
Resource("accounts").
VersionedParams(&listOpts, scheme.ParameterCodec).
Timeout(timeout).
Body(&opts).
Do(ctx).
Error()
}
// Patch applies the patch and returns the patched account.
func (c *accounts) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.Account, err error) {
result = &v1alpha1.Account{}
err = c.client.Patch(pt).
Namespace(c.ns).
Resource("accounts").
Name(name).
SubResource(subresources...).
VersionedParams(&opts, scheme.ParameterCodec).
Body(data).
Do(ctx).
Into(result)
return
} | AccountExpansion
}
// accounts implements AccountInterface |
app.js | import barba from '@barba/core';
import barbaCss from '@barba/css';
// tell Barba to use the css plugin
barba.use(barbaCss);
const body = document.querySelector('body');
var choice;
var aiga;
var myname;
var age;
var experience;
var citydata;
// gloabl hook
barba.hooks.before((data)=> {
const background = data.current.container.dataset.background;
body.style.setProperty('background', background);
})
barba.init({
sync: true,
views: [
{
namespace: "home",
beforeEnter({next}){
let script = document.createElement('script');
script.src = "js/home.js";
next.container.appendChild(script);
}
},
{
namespace: "dawn",
beforeEnter({next}){
let script = document.createElement('script');
script.src = "js/dawn.js";
next.container.appendChild(script);
}
},
{
namespace: "sunrise",
beforeEnter({next}){
let script = document.createElement('script');
script.src = "js/sunrise.js";
next.container.appendChild(script);
}
},
{
namespace: "morning",
beforeEnter({next}){
let script = document.createElement('script');
script.src = "js/morning.js";
next.container.appendChild(script);
}
},
{ | script.src = "js/midday.js";
next.container.appendChild(script);
}
},
{
namespace: "sunset",
beforeEnter({next}){
let script = document.createElement('script');
script.src = "js/sunset.js";
next.container.appendChild(script);
}
},
{
namespace: "night",
beforeEnter({next}){
let script = document.createElement('script');
script.src = "js/night.js";
next.container.appendChild(script);
}
},
{
namespace: "gallery",
beforeEnter({next}){
let script = document.createElement('script');
script.src = "js/gallery.js";
next.container.appendChild(script);
}
}
],
transitions: [
{
name: "home",
beforeOnce(){},
once() {},
afterOnce() {}
}, {
// name: 'dawn',
to: {
namespace: ['home','dawn', 'sunrise','morning','midday','sunset','night', 'gallery']
},
leave() {},
enter() {}
}
]
}); | namespace: "midday",
beforeEnter({next}){
let script = document.createElement('script'); |
pgm16_10.py | #
# This file contains the Python code from Program 16.10 of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Python"
# by Bruno R. Preiss.
#
# Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved.
#
# http://www.brpreiss.com/books/opus7/programs/pgm16_10.txt
#
class Graph(Container):
def breadthFirstTraversal(self, visitor, start):
|
# ...
| assert isinstance(visitor, Visitor)
enqueued = Array(self._numberOfVertices)
for v in xrange(self._numberOfVertices):
enqueued[v] = False
queue = QueueAsLinkedList()
queue.enqueue(self[start])
enqueued[start] = True
while not queue.isEmpty and not visitor.isDone:
v = queue.dequeue()
visitor.visit(v)
for to in v.successors:
if not enqueued[to.number]:
queue.enqueue(to)
enqueued[to.number] = True |
code.js | import PropTypes from 'prop-types';
import clsx from 'clsx'; | }
foo.propTypes = {
position: PropTypes.oneOf(['top', 'bottom']).isRequired,
}; |
function foo(props) {
const { position: p } = props;
const x = clsx(p === 'top' && classes.x, p === 'bottom' && classes.y); |
goodbye.go | package goodbye
| } | func Goodbye() string {
return "Goodbye" |
test_lua.py | import json
import os
import sys
from ..functional_test import TestCase
class LuaTest(TestCase):
def test_satisfy_from_source(self):
|
if sys.platform != 'win32':
def test_satisfy_with_make(self):
with open(os.path.join(self.path(), 'needs.json'), 'w') as needs_file:
needs_file.write(json.dumps({
'libraries': {
'lua': {
'download': 'http://www.lua.org/ftp/lua-5.2.1.tar.gz',
'checksum': '6bb1b0a39b6a5484b71a83323c690154f86b2021',
'project': {
'make-targets': 'generic',
'make-prefix-arg': 'INSTALL_TOP',
}
}
}
}))
self.assertEqual(self.satisfy(), 0)
self.assertTrue(os.path.isfile(os.path.join(self.build_directory('lua'), 'include', 'lua.h')))
self.assertTrue(os.path.isfile(os.path.join(self.build_directory('lua'), 'lib', 'liblua.a')))
| with open(os.path.join(self.path(), 'needs.json'), 'w') as needs_file:
needs_file.write(json.dumps({
'libraries': {
'lua': {
'download': 'http://www.lua.org/ftp/lua-5.2.1.tar.gz',
'checksum': '6bb1b0a39b6a5484b71a83323c690154f86b2021',
'project': {
'exclude': ['lua.c', 'luac.c']
}
}
}
}))
self.assertEqual(self.satisfy(), 0)
self.assertTrue(os.path.isfile(os.path.join(self.build_directory('lua'), 'include', 'lua.h')))
self.assertTrue(os.path.isfile(os.path.join(self.build_directory('lua'), 'lib', 'lua.lib' if sys.platform == 'win32' else 'liblua.a'))) |
main.py | import robin_stocks as r
import pandas as pd
import numpy as np
import ta as ta
from pandas.plotting import register_matplotlib_converters
from ta import *
from misc import *
from tradingstats import *
#Log in to Robinhood
login = r.login('YOUR_EMAIL','YOUR_PASSWORD')
#Safe divide by zero division function
def safe_division(n, d):
return n / d if d else 0
def get_watchlist_symbols():
"""
Returns: the symbol for each stock in your watchlist as a list of strings
"""
my_list_names = []
symbols = []
for name in r.get_all_watchlists(info='name'):
my_list_names.append(name)
for name in my_list_names:
list = r.get_watchlist_by_name(name)
for item in list:
instrument_data = r.get_instrument_by_url(item.get('instrument'))
symbol = instrument_data['symbol']
symbols.append(symbol)
return symbols
def get_portfolio_symbols():
|
def get_position_creation_date(symbol, holdings_data):
"""Returns the time at which we bought a certain stock in our portfolio
Args:
symbol(str): Symbol of the stock that we are trying to figure out when it was bought
holdings_data(dict): dict returned by r.get_open_stock_positions()
Returns:
A string containing the date and time the stock was bought, or "Not found" otherwise
"""
instrument = r.get_instruments_by_symbols(symbol)
url = instrument[0].get('url')
for dict in holdings_data:
if(dict.get('instrument') == url):
return dict.get('created_at')
return "Not found"
def get_modified_holdings():
""" Retrieves the same dictionary as r.build_holdings, but includes data about
when the stock was purchased, which is useful for the read_trade_history() method
in tradingstats.py
Returns:
the same dict from r.build_holdings, but with an extra key-value pair for each
position you have, which is 'bought_at': (the time the stock was purchased)
"""
holdings = r.build_holdings()
holdings_data = r.get_open_stock_positions()
for symbol, dict in holdings.items():
bought_at = get_position_creation_date(symbol, holdings_data)
bought_at = str(pd.to_datetime(bought_at))
holdings[symbol].update({'bought_at': bought_at})
return holdings
def get_last_crossing(df, days, symbol="", direction=""):
"""Searches for a crossing between two indicators for a given stock
Args:
df(pandas.core.frame.DataFrame): Pandas dataframe with columns containing the stock's prices, both indicators, and the dates
days(int): Specifies the maximum number of days that the cross can occur by
symbol(str): Symbol of the stock we're querying. Optional, used for printing purposes
direction(str): "above" if we are searching for an upwards cross, "below" if we are searching for a downwaords cross. Optional, used for printing purposes
Returns:
1 if the short-term indicator crosses above the long-term one
0 if there is no cross between the indicators
-1 if the short-term indicator crosses below the long-term one
"""
prices = df.loc[:,"Price"]
shortTerm = df.loc[:,"Indicator1"]
LongTerm = df.loc[:,"Indicator2"]
dates = df.loc[:,"Dates"]
lastIndex = prices.size - 1
index = lastIndex
found = index
recentDiff = (shortTerm.at[index] - LongTerm.at[index]) >= 0
if((direction == "above" and not recentDiff) or (direction == "below" and recentDiff)):
return 0
index -= 1
while(index >= 0 and found == lastIndex and not np.isnan(shortTerm.at[index]) and not np.isnan(LongTerm.at[index]) \
and ((pd.Timestamp("now", tz='UTC') - dates.at[index]) <= pd.Timedelta(str(days) + " days"))):
if(recentDiff):
if((shortTerm.at[index] - LongTerm.at[index]) < 0):
found = index
else:
if((shortTerm.at[index] - LongTerm.at[index]) > 0):
found = index
index -= 1
if(found != lastIndex):
if((direction == "above" and recentDiff) or (direction == "below" and not recentDiff)):
print(symbol + ": Short SMA crossed" + (" ABOVE " if recentDiff else " BELOW ") + "Long SMA at " + str(dates.at[found]) \
+", which was " + str(pd.Timestamp("now", tz='UTC') - dates.at[found]) + " ago", ", price at cross: " + str(prices.at[found]) \
+ ", current price: " + str(prices.at[lastIndex]))
return (1 if recentDiff else -1)
else:
return 0
def five_year_check(stockTicker):
"""Figure out if a stock has risen or been created within the last five years.
Args:
stockTicker(str): Symbol of the stock we're querying
Returns:
True if the stock's current price is higher than it was five years ago, or the stock IPO'd within the last five years
False otherwise
"""
instrument = r.get_instruments_by_symbols(stockTicker)
list_date = instrument[0].get("list_date")
if ((pd.Timestamp("now") - pd.to_datetime(list_date)) < pd.Timedelta("5 Y")):
return True
fiveyear = r.get_historicals(stockTicker,span='5year',bounds='regular')
closingPrices = []
for item in fiveyear:
closingPrices.append(float(item['close_price']))
recent_price = closingPrices[len(closingPrices) - 1]
oldest_price = closingPrices[0]
return (recent_price > oldest_price)
def golden_cross(stockTicker, n1, n2, days, direction=""):
"""Determine if a golden/death cross has occured for a specified stock in the last X trading days
Args:
stockTicker(str): Symbol of the stock we're querying
n1(int): Specifies the short-term indicator as an X-day moving average.
n2(int): Specifies the long-term indicator as an X-day moving average.
(n1 should be smaller than n2 to produce meaningful results, e.g n1=50, n2=200)
days(int): Specifies the maximum number of days that the cross can occur by
direction(str): "above" if we are searching for an upwards cross, "below" if we are searching for a downwaords cross. Optional, used for printing purposes
Returns:
1 if the short-term indicator crosses above the long-term one
0 if there is no cross between the indicators
-1 if the short-term indicator crosses below the long-term one
False if direction == "above" and five_year_check(stockTicker) returns False, meaning that we're considering whether to
buy the stock but it hasn't risen overall in the last five years, suggesting it contains fundamental issues
"""
if(direction == "above" and not five_year_check(stockTicker)):
return False
history = r.get_historicals(stockTicker,span='year',bounds='regular')
closingPrices = []
dates = []
for item in history:
closingPrices.append(float(item['close_price']))
dates.append(item['begins_at'])
price = pd.Series(closingPrices)
dates = pd.Series(dates)
dates = pd.to_datetime(dates)
sma1 = ta.volatility.bollinger_mavg(price, n=int(n1), fillna=False)
sma2 = ta.volatility.bollinger_mavg(price, n=int(n2), fillna=False)
series = [price.rename("Price"), sma1.rename("Indicator1"), sma2.rename("Indicator2"), dates.rename("Dates")]
df = pd.concat(series, axis=1)
cross = get_last_crossing(df, days, symbol=stockTicker, direction=direction)
# if(cross):
# show_plot(price, sma1, sma2, dates, symbol=stockTicker, label1=str(n1)+" day SMA", label2=str(n2)+" day SMA")
return cross
def sell_holdings(symbol, holdings_data):
""" Place an order to sell all holdings of a stock.
Args:
symbol(str): Symbol of the stock we want to sell
holdings_data(dict): dict obtained from get_modified_holdings() method
"""
shares_owned = int(float(holdings_data[symbol].get("quantity")))
r.order_sell_market(symbol, shares_owned)
print("####### Selling " + str(shares_owned) + " shares of " + symbol + " #######")
def buy_holdings(potential_buys, profile_data, holdings_data):
""" Places orders to buy holdings of stocks. This method will try to order
an appropriate amount of shares such that your holdings of the stock will
roughly match the average for the rest of your portfoilio. If the share
price is too high considering the rest of your holdings and the amount of
buying power in your account, it will not order any shares.
Args:
potential_buys(list): List of strings, the strings are the symbols of stocks we want to buy
symbol(str): Symbol of the stock we want to sell
holdings_data(dict): dict obtained from r.build_holdings() or get_modified_holdings() method
"""
cash = float(profile_data.get('cash'))
portfolio_value = float(profile_data.get('equity')) - cash
ideal_position_size = (safe_division(portfolio_value, len(holdings_data))+cash/len(potential_buys))/(2 * len(potential_buys))
prices = r.get_latest_price(potential_buys)
for i in range(0, len(potential_buys)):
stock_price = float(prices[i])
if(ideal_position_size < stock_price < ideal_position_size*1.5):
num_shares = int(ideal_position_size*1.5/stock_price)
elif (stock_price < ideal_position_size):
num_shares = int(ideal_position_size/stock_price)
else:
print("####### Tried buying shares of " + potential_buys[i] + ", but not enough buying power to do so#######")
break
print("####### Buying " + str(num_shares) + " shares of " + potential_buys[i] + " #######")
r.order_buy_market(potential_buys[i], num_shares)
def scan_stocks():
""" The main method. Sells stocks in your portfolio if their 50 day moving average crosses
below the 200 day, and buys stocks in your watchlist if the opposite happens.
###############################################################################################
WARNING: Comment out the sell_holdings and buy_holdings lines if you don't actually want to execute the trade.
###############################################################################################
If you sell a stock, this updates tradehistory.txt with information about the position,
how much you've earned/lost, etc.
"""
print("----- Starting scan... -----\n")
register_matplotlib_converters()
watchlist_symbols = get_watchlist_symbols()
portfolio_symbols = get_portfolio_symbols()
holdings_data = get_modified_holdings()
potential_buys = []
sells = []
print("Current Portfolio: " + str(portfolio_symbols) + "\n")
print("Current Watchlist: " + str(watchlist_symbols) + "\n")
print("----- Scanning portfolio for stocks to sell -----\n")
for symbol in portfolio_symbols:
cross = golden_cross(symbol, n1=50, n2=200, days=30, direction="below")
if(cross == -1):
sell_holdings(symbol, holdings_data)
sells.append(symbol)
profile_data = r.build_user_profile()
print("\n----- Scanning watchlist for stocks to buy -----\n")
for symbol in watchlist_symbols:
if(symbol not in portfolio_symbols):
cross = golden_cross(symbol, n1=50, n2=200, days=10, direction="above")
if(cross == 1):
potential_buys.append(symbol)
if(len(potential_buys) > 0):
buy_holdings(potential_buys, profile_data, holdings_data)
if(len(sells) > 0):
update_trade_history(sells, holdings_data, "tradehistory.txt")
print("----- Scan over -----\n")
#execute the scan
scan_stocks()
| """
Returns: the symbol for each stock in your portfolio as a list of strings
"""
symbols = []
holdings_data = r.get_open_stock_positions()
for item in holdings_data:
if not item:
continue
instrument_data = r.get_instrument_by_url(item.get('instrument'))
symbol = instrument_data['symbol']
symbols.append(symbol)
return symbols |
git_client_base.py | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from msrest import Serializer, Deserializer
from ...client import Client
from . import models
class GitClientBase(Client):
"""Git
:param str base_url: Service URL
:param Authentication creds: Authenticated credentials.
"""
def __init__(self, base_url=None, creds=None):
super(GitClientBase, self).__init__(base_url, creds)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
resource_area_identifier = '4e080c62-fa21-4fbc-8fef-2a10a2b38049'
def create_annotated_tag(self, tag_object, project, repository_id):
"""CreateAnnotatedTag.
[Preview API] Create an annotated tag.
:param :class:`<GitAnnotatedTag> <azure.devops.v5_0.git.models.GitAnnotatedTag>` tag_object: Object containing details of tag to be created.
:param str project: Project ID or project name
:param str repository_id: ID or name of the repository.
:rtype: :class:`<GitAnnotatedTag> <azure.devops.v5_0.git.models.GitAnnotatedTag>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
content = self._serialize.body(tag_object, 'GitAnnotatedTag')
response = self._send(http_method='POST',
location_id='5e8a8081-3851-4626-b677-9891cc04102e',
version='5.0-preview.1',
route_values=route_values,
content=content)
return self._deserialize('GitAnnotatedTag', response)
def get_annotated_tag(self, project, repository_id, object_id):
"""GetAnnotatedTag.
[Preview API] Get an annotated tag.
:param str project: Project ID or project name
:param str repository_id: ID or name of the repository.
:param str object_id: ObjectId (Sha1Id) of tag to get.
:rtype: :class:`<GitAnnotatedTag> <azure.devops.v5_0.git.models.GitAnnotatedTag>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if object_id is not None:
route_values['objectId'] = self._serialize.url('object_id', object_id, 'str')
response = self._send(http_method='GET',
location_id='5e8a8081-3851-4626-b677-9891cc04102e',
version='5.0-preview.1',
route_values=route_values)
return self._deserialize('GitAnnotatedTag', response)
def get_blob(self, repository_id, sha1, project=None, download=None, file_name=None, resolve_lfs=None):
"""GetBlob.
Get a single blob.
:param str repository_id: The name or ID of the repository.
:param str sha1: SHA1 hash of the file. You can get the SHA1 of a file using the "Git/Items/Get Item" endpoint.
:param str project: Project ID or project name
:param bool download: If true, prompt for a download rather than rendering in a browser. Note: this value defaults to true if $format is zip
:param str file_name: Provide a fileName to use for a download.
:param bool resolve_lfs: If true, try to resolve a blob to its LFS contents, if it's an LFS pointer file. Only compatible with octet-stream Accept headers or $format types
:rtype: :class:`<GitBlobRef> <azure.devops.v5_0.git.models.GitBlobRef>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if sha1 is not None:
route_values['sha1'] = self._serialize.url('sha1', sha1, 'str')
query_parameters = {}
if download is not None:
query_parameters['download'] = self._serialize.query('download', download, 'bool')
if file_name is not None:
query_parameters['fileName'] = self._serialize.query('file_name', file_name, 'str')
if resolve_lfs is not None:
query_parameters['resolveLfs'] = self._serialize.query('resolve_lfs', resolve_lfs, 'bool')
response = self._send(http_method='GET',
location_id='7b28e929-2c99-405d-9c5c-6167a06e6816',
version='5.0',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('GitBlobRef', response)
def get_blob_content(self, repository_id, sha1, project=None, download=None, file_name=None, resolve_lfs=None, **kwargs):
"""GetBlobContent.
Get a single blob.
:param str repository_id: The name or ID of the repository.
:param str sha1: SHA1 hash of the file. You can get the SHA1 of a file using the "Git/Items/Get Item" endpoint.
:param str project: Project ID or project name
:param bool download: If true, prompt for a download rather than rendering in a browser. Note: this value defaults to true if $format is zip
:param str file_name: Provide a fileName to use for a download.
:param bool resolve_lfs: If true, try to resolve a blob to its LFS contents, if it's an LFS pointer file. Only compatible with octet-stream Accept headers or $format types
:rtype: object
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if sha1 is not None:
route_values['sha1'] = self._serialize.url('sha1', sha1, 'str')
query_parameters = {}
if download is not None:
query_parameters['download'] = self._serialize.query('download', download, 'bool')
if file_name is not None:
query_parameters['fileName'] = self._serialize.query('file_name', file_name, 'str')
if resolve_lfs is not None:
query_parameters['resolveLfs'] = self._serialize.query('resolve_lfs', resolve_lfs, 'bool')
response = self._send(http_method='GET',
location_id='7b28e929-2c99-405d-9c5c-6167a06e6816',
version='5.0',
route_values=route_values,
query_parameters=query_parameters,
accept_media_type='application/octet-stream')
if "callback" in kwargs:
callback = kwargs["callback"]
else:
callback = None
return self._client.stream_download(response, callback=callback)
def get_blobs_zip(self, blob_ids, repository_id, project=None, filename=None, **kwargs):
"""GetBlobsZip.
Gets one or more blobs in a zip file download.
:param [str] blob_ids: Blob IDs (SHA1 hashes) to be returned in the zip file.
:param str repository_id: The name or ID of the repository.
:param str project: Project ID or project name
:param str filename:
:rtype: object
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if filename is not None:
query_parameters['filename'] = self._serialize.query('filename', filename, 'str')
content = self._serialize.body(blob_ids, '[str]')
response = self._send(http_method='POST',
location_id='7b28e929-2c99-405d-9c5c-6167a06e6816',
version='5.0',
route_values=route_values,
query_parameters=query_parameters,
content=content,
accept_media_type='application/zip')
if "callback" in kwargs:
callback = kwargs["callback"]
else:
callback = None
return self._client.stream_download(response, callback=callback)
def get_blob_zip(self, repository_id, sha1, project=None, download=None, file_name=None, resolve_lfs=None, **kwargs):
"""GetBlobZip.
Get a single blob.
:param str repository_id: The name or ID of the repository.
:param str sha1: SHA1 hash of the file. You can get the SHA1 of a file using the "Git/Items/Get Item" endpoint.
:param str project: Project ID or project name
:param bool download: If true, prompt for a download rather than rendering in a browser. Note: this value defaults to true if $format is zip
:param str file_name: Provide a fileName to use for a download.
:param bool resolve_lfs: If true, try to resolve a blob to its LFS contents, if it's an LFS pointer file. Only compatible with octet-stream Accept headers or $format types
:rtype: object
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if sha1 is not None:
route_values['sha1'] = self._serialize.url('sha1', sha1, 'str')
query_parameters = {}
if download is not None:
query_parameters['download'] = self._serialize.query('download', download, 'bool')
if file_name is not None:
query_parameters['fileName'] = self._serialize.query('file_name', file_name, 'str')
if resolve_lfs is not None:
query_parameters['resolveLfs'] = self._serialize.query('resolve_lfs', resolve_lfs, 'bool')
response = self._send(http_method='GET',
location_id='7b28e929-2c99-405d-9c5c-6167a06e6816',
version='5.0',
route_values=route_values,
query_parameters=query_parameters,
accept_media_type='application/zip')
if "callback" in kwargs:
callback = kwargs["callback"]
else:
callback = None
return self._client.stream_download(response, callback=callback)
def get_branch(self, repository_id, name, project=None, base_version_descriptor=None):
"""GetBranch.
Retrieve statistics about a single branch.
:param str repository_id: The name or ID of the repository.
:param str name: Name of the branch.
:param str project: Project ID or project name
:param :class:`<GitVersionDescriptor> <azure.devops.v5_0.git.models.GitVersionDescriptor>` base_version_descriptor: Identifies the commit or branch to use as the base.
:rtype: :class:`<GitBranchStats> <azure.devops.v5_0.git.models.GitBranchStats>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if name is not None:
query_parameters['name'] = self._serialize.query('name', name, 'str')
if base_version_descriptor is not None:
if base_version_descriptor.version_type is not None:
query_parameters['baseVersionDescriptor.versionType'] = base_version_descriptor.version_type
if base_version_descriptor.version is not None:
query_parameters['baseVersionDescriptor.version'] = base_version_descriptor.version
if base_version_descriptor.version_options is not None:
query_parameters['baseVersionDescriptor.versionOptions'] = base_version_descriptor.version_options
response = self._send(http_method='GET',
location_id='d5b216de-d8d5-4d32-ae76-51df755b16d3',
version='5.0',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('GitBranchStats', response)
def get_branches(self, repository_id, project=None, base_version_descriptor=None):
"""GetBranches.
Retrieve statistics about all branches within a repository.
:param str repository_id: The name or ID of the repository.
:param str project: Project ID or project name
:param :class:`<GitVersionDescriptor> <azure.devops.v5_0.git.models.GitVersionDescriptor>` base_version_descriptor: Identifies the commit or branch to use as the base.
:rtype: [GitBranchStats]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if base_version_descriptor is not None:
if base_version_descriptor.version_type is not None:
query_parameters['baseVersionDescriptor.versionType'] = base_version_descriptor.version_type
if base_version_descriptor.version is not None:
query_parameters['baseVersionDescriptor.version'] = base_version_descriptor.version
if base_version_descriptor.version_options is not None:
query_parameters['baseVersionDescriptor.versionOptions'] = base_version_descriptor.version_options
response = self._send(http_method='GET',
location_id='d5b216de-d8d5-4d32-ae76-51df755b16d3',
version='5.0',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitBranchStats]', self._unwrap_collection(response))
def get_changes(self, commit_id, repository_id, project=None, top=None, skip=None):
"""GetChanges.
Retrieve changes for a particular commit.
:param str commit_id: The id of the commit.
:param str repository_id: The id or friendly name of the repository. To use the friendly name, projectId must also be specified.
:param str project: Project ID or project name
:param int top: The maximum number of changes to return.
:param int skip: The number of changes to skip.
:rtype: :class:`<GitCommitChanges> <azure.devops.v5_0.git.models.GitCommitChanges>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if commit_id is not None:
route_values['commitId'] = self._serialize.url('commit_id', commit_id, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if top is not None:
query_parameters['top'] = self._serialize.query('top', top, 'int')
if skip is not None:
query_parameters['skip'] = self._serialize.query('skip', skip, 'int')
response = self._send(http_method='GET',
location_id='5bf884f5-3e07-42e9-afb8-1b872267bf16',
version='5.0',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('GitCommitChanges', response)
def create_cherry_pick(self, cherry_pick_to_create, project, repository_id):
"""CreateCherryPick.
[Preview API] Cherry pick a specific commit or commits that are associated to a pull request into a new branch.
:param :class:`<GitAsyncRefOperationParameters> <azure.devops.v5_0.git.models.GitAsyncRefOperationParameters>` cherry_pick_to_create:
:param str project: Project ID or project name
:param str repository_id: ID of the repository.
:rtype: :class:`<GitCherryPick> <azure.devops.v5_0.git.models.GitCherryPick>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
content = self._serialize.body(cherry_pick_to_create, 'GitAsyncRefOperationParameters')
response = self._send(http_method='POST',
location_id='033bad68-9a14-43d1-90e0-59cb8856fef6',
version='5.0-preview.1',
route_values=route_values,
content=content)
return self._deserialize('GitCherryPick', response)
def get_cherry_pick(self, project, cherry_pick_id, repository_id):
"""GetCherryPick.
[Preview API] Retrieve information about a cherry pick by cherry pick Id.
:param str project: Project ID or project name
:param int cherry_pick_id: ID of the cherry pick.
:param str repository_id: ID of the repository.
:rtype: :class:`<GitCherryPick> <azure.devops.v5_0.git.models.GitCherryPick>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if cherry_pick_id is not None:
route_values['cherryPickId'] = self._serialize.url('cherry_pick_id', cherry_pick_id, 'int')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
response = self._send(http_method='GET',
location_id='033bad68-9a14-43d1-90e0-59cb8856fef6',
version='5.0-preview.1',
route_values=route_values)
return self._deserialize('GitCherryPick', response)
def get_cherry_pick_for_ref_name(self, project, repository_id, ref_name):
"""GetCherryPickForRefName.
[Preview API] Retrieve information about a cherry pick for a specific branch.
:param str project: Project ID or project name
:param str repository_id: ID of the repository.
:param str ref_name: The GitAsyncRefOperationParameters generatedRefName used for the cherry pick operation.
:rtype: :class:`<GitCherryPick> <azure.devops.v5_0.git.models.GitCherryPick>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if ref_name is not None:
query_parameters['refName'] = self._serialize.query('ref_name', ref_name, 'str')
response = self._send(http_method='GET',
location_id='033bad68-9a14-43d1-90e0-59cb8856fef6',
version='5.0-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('GitCherryPick', response)
def get_commit_diffs(self, repository_id, project=None, diff_common_commit=None, top=None, skip=None, base_version_descriptor=None, target_version_descriptor=None):
"""GetCommitDiffs.
Find the closest common commit (the merge base) between base and target commits, and get the diff between either the base and target commits or common and target commits.
:param str repository_id: The name or ID of the repository.
:param str project: Project ID or project name
:param bool diff_common_commit: If true, diff between common and target commits. If false, diff between base and target commits.
:param int top: Maximum number of changes to return. Defaults to 100.
:param int skip: Number of changes to skip
:param :class:`<GitBaseVersionDescriptor> <azure.devops.v5_0.git.models.GitBaseVersionDescriptor>` base_version_descriptor: Descriptor for base commit.
:param :class:`<GitTargetVersionDescriptor> <azure.devops.v5_0.git.models.GitTargetVersionDescriptor>` target_version_descriptor: Descriptor for target commit.
:rtype: :class:`<GitCommitDiffs> <azure.devops.v5_0.git.models.GitCommitDiffs>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if diff_common_commit is not None:
query_parameters['diffCommonCommit'] = self._serialize.query('diff_common_commit', diff_common_commit, 'bool')
if top is not None:
query_parameters['$top'] = self._serialize.query('top', top, 'int')
if skip is not None:
query_parameters['$skip'] = self._serialize.query('skip', skip, 'int')
if base_version_descriptor is not None:
if base_version_descriptor.base_version_type is not None:
query_parameters['baseVersionType'] = base_version_descriptor.base_version_type
if base_version_descriptor.base_version is not None:
query_parameters['baseVersion'] = base_version_descriptor.base_version
if base_version_descriptor.base_version_options is not None:
query_parameters['baseVersionOptions'] = base_version_descriptor.base_version_options
if target_version_descriptor is not None:
if target_version_descriptor.target_version_type is not None:
query_parameters['targetVersionType'] = target_version_descriptor.target_version_type
if target_version_descriptor.target_version is not None:
query_parameters['targetVersion'] = target_version_descriptor.target_version
if target_version_descriptor.target_version_options is not None:
query_parameters['targetVersionOptions'] = target_version_descriptor.target_version_options
response = self._send(http_method='GET',
location_id='615588d5-c0c7-4b88-88f8-e625306446e8',
version='5.0',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('GitCommitDiffs', response)
def get_commit(self, commit_id, repository_id, project=None, change_count=None):
"""GetCommit.
Retrieve a particular commit.
:param str commit_id: The id of the commit.
:param str repository_id: The id or friendly name of the repository. To use the friendly name, projectId must also be specified.
:param str project: Project ID or project name
:param int change_count: The number of changes to include in the result.
:rtype: :class:`<GitCommit> <azure.devops.v5_0.git.models.GitCommit>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if commit_id is not None:
route_values['commitId'] = self._serialize.url('commit_id', commit_id, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if change_count is not None:
query_parameters['changeCount'] = self._serialize.query('change_count', change_count, 'int')
response = self._send(http_method='GET',
location_id='c2570c3b-5b3f-41b8-98bf-5407bfde8d58',
version='5.0',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('GitCommit', response)
def get_commits(self, repository_id, search_criteria, project=None, skip=None, top=None):
"""GetCommits.
Retrieve git commits for a project
:param str repository_id: The id or friendly name of the repository. To use the friendly name, projectId must also be specified.
:param :class:`<GitQueryCommitsCriteria> <azure.devops.v5_0.git.models.GitQueryCommitsCriteria>` search_criteria:
:param str project: Project ID or project name
:param int skip:
:param int top:
:rtype: [GitCommitRef]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if search_criteria is not None:
if search_criteria.ids is not None:
query_parameters['searchCriteria.ids'] = search_criteria.ids
if search_criteria.from_date is not None:
query_parameters['searchCriteria.fromDate'] = search_criteria.from_date
if search_criteria.to_date is not None:
query_parameters['searchCriteria.toDate'] = search_criteria.to_date
if search_criteria.item_version is not None:
if search_criteria.item_version.version_type is not None:
query_parameters['searchCriteria.itemVersion.versionType'] = search_criteria.item_version.version_type
if search_criteria.item_version.version is not None:
query_parameters['searchCriteria.itemVersion.version'] = search_criteria.item_version.version
if search_criteria.item_version.version_options is not None:
query_parameters['searchCriteria.itemVersion.versionOptions'] = search_criteria.item_version.version_options
if search_criteria.compare_version is not None:
if search_criteria.compare_version.version_type is not None:
query_parameters['searchCriteria.compareVersion.versionType'] = search_criteria.compare_version.version_type
if search_criteria.compare_version.version is not None:
query_parameters['searchCriteria.compareVersion.version'] = search_criteria.compare_version.version
if search_criteria.compare_version.version_options is not None:
query_parameters['searchCriteria.compareVersion.versionOptions'] = search_criteria.compare_version.version_options
if search_criteria.from_commit_id is not None:
query_parameters['searchCriteria.fromCommitId'] = search_criteria.from_commit_id
if search_criteria.to_commit_id is not None:
query_parameters['searchCriteria.toCommitId'] = search_criteria.to_commit_id
if search_criteria.user is not None:
query_parameters['searchCriteria.user'] = search_criteria.user
if search_criteria.author is not None:
query_parameters['searchCriteria.author'] = search_criteria.author
if search_criteria.item_path is not None:
query_parameters['searchCriteria.itemPath'] = search_criteria.item_path
if search_criteria.exclude_deletes is not None:
query_parameters['searchCriteria.excludeDeletes'] = search_criteria.exclude_deletes
if search_criteria.skip is not None:
query_parameters['searchCriteria.$skip'] = search_criteria.skip
if search_criteria.top is not None:
query_parameters['searchCriteria.$top'] = search_criteria.top
if search_criteria.include_links is not None:
query_parameters['searchCriteria.includeLinks'] = search_criteria.include_links
if search_criteria.include_work_items is not None:
query_parameters['searchCriteria.includeWorkItems'] = search_criteria.include_work_items
if search_criteria.include_user_image_url is not None:
query_parameters['searchCriteria.includeUserImageUrl'] = search_criteria.include_user_image_url
if search_criteria.include_push_data is not None:
query_parameters['searchCriteria.includePushData'] = search_criteria.include_push_data
if search_criteria.history_mode is not None:
query_parameters['searchCriteria.historyMode'] = search_criteria.history_mode
if skip is not None:
query_parameters['$skip'] = self._serialize.query('skip', skip, 'int')
if top is not None:
query_parameters['$top'] = self._serialize.query('top', top, 'int')
response = self._send(http_method='GET',
location_id='c2570c3b-5b3f-41b8-98bf-5407bfde8d58',
version='5.0',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitCommitRef]', self._unwrap_collection(response))
def get_push_commits(self, repository_id, push_id, project=None, top=None, skip=None, include_links=None):
"""GetPushCommits.
Retrieve a list of commits associated with a particular push.
:param str repository_id: The id or friendly name of the repository. To use the friendly name, projectId must also be specified.
:param int push_id: The id of the push.
:param str project: Project ID or project name
:param int top: The maximum number of commits to return ("get the top x commits").
:param int skip: The number of commits to skip.
:param bool include_links: Set to false to avoid including REST Url links for resources. Defaults to true.
:rtype: [GitCommitRef]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if push_id is not None:
query_parameters['pushId'] = self._serialize.query('push_id', push_id, 'int')
if top is not None:
query_parameters['top'] = self._serialize.query('top', top, 'int')
if skip is not None:
query_parameters['skip'] = self._serialize.query('skip', skip, 'int')
if include_links is not None:
query_parameters['includeLinks'] = self._serialize.query('include_links', include_links, 'bool')
response = self._send(http_method='GET',
location_id='c2570c3b-5b3f-41b8-98bf-5407bfde8d58',
version='5.0',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitCommitRef]', self._unwrap_collection(response))
def get_commits_batch(self, search_criteria, repository_id, project=None, skip=None, top=None, include_statuses=None):
"""GetCommitsBatch.
Retrieve git commits for a project matching the search criteria
:param :class:`<GitQueryCommitsCriteria> <azure.devops.v5_0.git.models.GitQueryCommitsCriteria>` search_criteria: Search options
:param str repository_id: The name or ID of the repository.
:param str project: Project ID or project name
:param int skip: Number of commits to skip.
:param int top: Maximum number of commits to return.
:param bool include_statuses: True to include additional commit status information.
:rtype: [GitCommitRef]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if skip is not None:
query_parameters['$skip'] = self._serialize.query('skip', skip, 'int')
if top is not None:
query_parameters['$top'] = self._serialize.query('top', top, 'int')
if include_statuses is not None:
query_parameters['includeStatuses'] = self._serialize.query('include_statuses', include_statuses, 'bool')
content = self._serialize.body(search_criteria, 'GitQueryCommitsCriteria')
response = self._send(http_method='POST',
location_id='6400dfb2-0bcb-462b-b992-5a57f8f1416c',
version='5.0',
route_values=route_values,
query_parameters=query_parameters,
content=content)
return self._deserialize('[GitCommitRef]', self._unwrap_collection(response))
def get_deleted_repositories(self, project):
"""GetDeletedRepositories.
[Preview API] Retrieve deleted git repositories.
:param str project: Project ID or project name
:rtype: [GitDeletedRepository]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
response = self._send(http_method='GET',
location_id='2b6869c4-cb25-42b5-b7a3-0d3e6be0a11a',
version='5.0-preview.1',
route_values=route_values)
return self._deserialize('[GitDeletedRepository]', self._unwrap_collection(response))
def get_forks(self, repository_name_or_id, collection_id, project=None, include_links=None):
"""GetForks.
[Preview API] Retrieve all forks of a repository in the collection.
:param str repository_name_or_id: The name or ID of the repository.
:param str collection_id: Team project collection ID.
:param str project: Project ID or project name
:param bool include_links: True to include links.
:rtype: [GitRepositoryRef]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_name_or_id is not None:
route_values['repositoryNameOrId'] = self._serialize.url('repository_name_or_id', repository_name_or_id, 'str')
if collection_id is not None:
route_values['collectionId'] = self._serialize.url('collection_id', collection_id, 'str')
query_parameters = {}
if include_links is not None:
query_parameters['includeLinks'] = self._serialize.query('include_links', include_links, 'bool')
response = self._send(http_method='GET',
location_id='158c0340-bf6f-489c-9625-d572a1480d57',
version='5.0-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitRepositoryRef]', self._unwrap_collection(response))
def create_fork_sync_request(self, sync_params, repository_name_or_id, project=None, include_links=None):
"""CreateForkSyncRequest.
[Preview API] Request that another repository's refs be fetched into this one.
:param :class:`<GitForkSyncRequestParameters> <azure.devops.v5_0.git.models.GitForkSyncRequestParameters>` sync_params: Source repository and ref mapping.
:param str repository_name_or_id: The name or ID of the repository.
:param str project: Project ID or project name
:param bool include_links: True to include links
:rtype: :class:`<GitForkSyncRequest> <azure.devops.v5_0.git.models.GitForkSyncRequest>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_name_or_id is not None:
route_values['repositoryNameOrId'] = self._serialize.url('repository_name_or_id', repository_name_or_id, 'str')
query_parameters = {}
if include_links is not None:
query_parameters['includeLinks'] = self._serialize.query('include_links', include_links, 'bool')
content = self._serialize.body(sync_params, 'GitForkSyncRequestParameters')
response = self._send(http_method='POST',
location_id='1703f858-b9d1-46af-ab62-483e9e1055b5',
version='5.0-preview.1',
route_values=route_values,
query_parameters=query_parameters,
content=content)
return self._deserialize('GitForkSyncRequest', response)
def get_fork_sync_request(self, repository_name_or_id, fork_sync_operation_id, project=None, include_links=None):
"""GetForkSyncRequest.
[Preview API] Get a specific fork sync operation's details.
:param str repository_name_or_id: The name or ID of the repository.
:param int fork_sync_operation_id: OperationId of the sync request.
:param str project: Project ID or project name
:param bool include_links: True to include links.
:rtype: :class:`<GitForkSyncRequest> <azure.devops.v5_0.git.models.GitForkSyncRequest>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_name_or_id is not None:
route_values['repositoryNameOrId'] = self._serialize.url('repository_name_or_id', repository_name_or_id, 'str')
if fork_sync_operation_id is not None:
route_values['forkSyncOperationId'] = self._serialize.url('fork_sync_operation_id', fork_sync_operation_id, 'int')
query_parameters = {}
if include_links is not None:
query_parameters['includeLinks'] = self._serialize.query('include_links', include_links, 'bool')
response = self._send(http_method='GET',
location_id='1703f858-b9d1-46af-ab62-483e9e1055b5',
version='5.0-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('GitForkSyncRequest', response)
def get_fork_sync_requests(self, repository_name_or_id, project=None, include_abandoned=None, include_links=None):
"""GetForkSyncRequests.
[Preview API] Retrieve all requested fork sync operations on this repository.
:param str repository_name_or_id: The name or ID of the repository.
:param str project: Project ID or project name
:param bool include_abandoned: True to include abandoned requests.
:param bool include_links: True to include links.
:rtype: [GitForkSyncRequest]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_name_or_id is not None:
route_values['repositoryNameOrId'] = self._serialize.url('repository_name_or_id', repository_name_or_id, 'str')
query_parameters = {}
if include_abandoned is not None:
query_parameters['includeAbandoned'] = self._serialize.query('include_abandoned', include_abandoned, 'bool')
if include_links is not None:
query_parameters['includeLinks'] = self._serialize.query('include_links', include_links, 'bool')
response = self._send(http_method='GET',
location_id='1703f858-b9d1-46af-ab62-483e9e1055b5',
version='5.0-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitForkSyncRequest]', self._unwrap_collection(response))
def create_import_request(self, import_request, project, repository_id):
"""CreateImportRequest.
[Preview API] Create an import request.
:param :class:`<GitImportRequest> <azure.devops.v5_0.git.models.GitImportRequest>` import_request: The import request to create.
:param str project: Project ID or project name
:param str repository_id: The name or ID of the repository.
:rtype: :class:`<GitImportRequest> <azure.devops.v5_0.git.models.GitImportRequest>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
content = self._serialize.body(import_request, 'GitImportRequest')
response = self._send(http_method='POST',
location_id='01828ddc-3600-4a41-8633-99b3a73a0eb3',
version='5.0-preview.1',
route_values=route_values,
content=content)
return self._deserialize('GitImportRequest', response)
def get_import_request(self, project, repository_id, import_request_id):
"""GetImportRequest.
[Preview API] Retrieve a particular import request.
:param str project: Project ID or project name
:param str repository_id: The name or ID of the repository.
:param int import_request_id: The unique identifier for the import request.
:rtype: :class:`<GitImportRequest> <azure.devops.v5_0.git.models.GitImportRequest>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if import_request_id is not None:
route_values['importRequestId'] = self._serialize.url('import_request_id', import_request_id, 'int')
response = self._send(http_method='GET',
location_id='01828ddc-3600-4a41-8633-99b3a73a0eb3',
version='5.0-preview.1',
route_values=route_values)
return self._deserialize('GitImportRequest', response)
def query_import_requests(self, project, repository_id, include_abandoned=None):
"""QueryImportRequests.
[Preview API] Retrieve import requests for a repository.
:param str project: Project ID or project name
:param str repository_id: The name or ID of the repository.
:param bool include_abandoned: True to include abandoned import requests in the results.
:rtype: [GitImportRequest]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if include_abandoned is not None:
query_parameters['includeAbandoned'] = self._serialize.query('include_abandoned', include_abandoned, 'bool')
response = self._send(http_method='GET',
location_id='01828ddc-3600-4a41-8633-99b3a73a0eb3',
version='5.0-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitImportRequest]', self._unwrap_collection(response))
def update_import_request(self, import_request_to_update, project, repository_id, import_request_id):
"""UpdateImportRequest.
[Preview API] Retry or abandon a failed import request.
:param :class:`<GitImportRequest> <azure.devops.v5_0.git.models.GitImportRequest>` import_request_to_update: The updated version of the import request. Currently, the only change allowed is setting the Status to Queued or Abandoned.
:param str project: Project ID or project name
:param str repository_id: The name or ID of the repository.
:param int import_request_id: The unique identifier for the import request to update.
:rtype: :class:`<GitImportRequest> <azure.devops.v5_0.git.models.GitImportRequest>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if import_request_id is not None:
route_values['importRequestId'] = self._serialize.url('import_request_id', import_request_id, 'int')
content = self._serialize.body(import_request_to_update, 'GitImportRequest')
response = self._send(http_method='PATCH',
location_id='01828ddc-3600-4a41-8633-99b3a73a0eb3',
version='5.0-preview.1',
route_values=route_values,
content=content)
return self._deserialize('GitImportRequest', response)
def get_item(self, repository_id, path, project=None, scope_path=None, recursion_level=None, include_content_metadata=None, latest_processed_change=None, download=None, version_descriptor=None, include_content=None, resolve_lfs=None):
"""GetItem.
Get Item Metadata and/or Content for a single item. The download parameter is to indicate whether the content should be available as a download or just sent as a stream in the response. Doesn't apply to zipped content, which is always returned as a download.
:param str repository_id: The name or ID of the repository.
:param str path: The item path.
:param str project: Project ID or project name
:param str scope_path: The path scope. The default is null.
:param str recursion_level: The recursion level of this request. The default is 'none', no recursion.
:param bool include_content_metadata: Set to true to include content metadata. Default is false.
:param bool latest_processed_change: Set to true to include the lastest changes. Default is false.
:param bool download: Set to true to download the response as a file. Default is false.
:param :class:`<GitVersionDescriptor> <azure.devops.v5_0.git.models.GitVersionDescriptor>` version_descriptor: Version descriptor. Default is null.
:param bool include_content: Set to true to include item content when requesting json. Default is false.
:param bool resolve_lfs: Set to true to resolve Git LFS pointer files to return actual content from Git LFS. Default is false.
:rtype: :class:`<GitItem> <azure.devops.v5_0.git.models.GitItem>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if path is not None:
query_parameters['path'] = self._serialize.query('path', path, 'str')
if scope_path is not None:
query_parameters['scopePath'] = self._serialize.query('scope_path', scope_path, 'str')
if recursion_level is not None:
query_parameters['recursionLevel'] = self._serialize.query('recursion_level', recursion_level, 'str')
if include_content_metadata is not None:
query_parameters['includeContentMetadata'] = self._serialize.query('include_content_metadata', include_content_metadata, 'bool')
if latest_processed_change is not None:
query_parameters['latestProcessedChange'] = self._serialize.query('latest_processed_change', latest_processed_change, 'bool')
if download is not None:
query_parameters['download'] = self._serialize.query('download', download, 'bool')
if version_descriptor is not None:
if version_descriptor.version_type is not None:
query_parameters['versionDescriptor.versionType'] = version_descriptor.version_type
if version_descriptor.version is not None:
query_parameters['versionDescriptor.version'] = version_descriptor.version
if version_descriptor.version_options is not None:
query_parameters['versionDescriptor.versionOptions'] = version_descriptor.version_options
if include_content is not None:
query_parameters['includeContent'] = self._serialize.query('include_content', include_content, 'bool')
if resolve_lfs is not None:
query_parameters['resolveLfs'] = self._serialize.query('resolve_lfs', resolve_lfs, 'bool')
response = self._send(http_method='GET',
location_id='fb93c0db-47ed-4a31-8c20-47552878fb44',
version='5.0',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('GitItem', response)
def get_item_content(self, repository_id, path, project=None, scope_path=None, recursion_level=None, include_content_metadata=None, latest_processed_change=None, download=None, version_descriptor=None, include_content=None, resolve_lfs=None, **kwargs):
"""GetItemContent.
Get Item Metadata and/or Content for a single item. The download parameter is to indicate whether the content should be available as a download or just sent as a stream in the response. Doesn't apply to zipped content, which is always returned as a download.
:param str repository_id: The name or ID of the repository.
:param str path: The item path.
:param str project: Project ID or project name
:param str scope_path: The path scope. The default is null.
:param str recursion_level: The recursion level of this request. The default is 'none', no recursion.
:param bool include_content_metadata: Set to true to include content metadata. Default is false.
:param bool latest_processed_change: Set to true to include the lastest changes. Default is false.
:param bool download: Set to true to download the response as a file. Default is false.
:param :class:`<GitVersionDescriptor> <azure.devops.v5_0.git.models.GitVersionDescriptor>` version_descriptor: Version descriptor. Default is null.
:param bool include_content: Set to true to include item content when requesting json. Default is false.
:param bool resolve_lfs: Set to true to resolve Git LFS pointer files to return actual content from Git LFS. Default is false.
:rtype: object
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if path is not None:
query_parameters['path'] = self._serialize.query('path', path, 'str')
if scope_path is not None:
query_parameters['scopePath'] = self._serialize.query('scope_path', scope_path, 'str')
if recursion_level is not None:
query_parameters['recursionLevel'] = self._serialize.query('recursion_level', recursion_level, 'str')
if include_content_metadata is not None:
query_parameters['includeContentMetadata'] = self._serialize.query('include_content_metadata', include_content_metadata, 'bool')
if latest_processed_change is not None:
query_parameters['latestProcessedChange'] = self._serialize.query('latest_processed_change', latest_processed_change, 'bool')
if download is not None:
query_parameters['download'] = self._serialize.query('download', download, 'bool')
if version_descriptor is not None:
if version_descriptor.version_type is not None:
query_parameters['versionDescriptor.versionType'] = version_descriptor.version_type
if version_descriptor.version is not None:
query_parameters['versionDescriptor.version'] = version_descriptor.version
if version_descriptor.version_options is not None:
query_parameters['versionDescriptor.versionOptions'] = version_descriptor.version_options
if include_content is not None:
query_parameters['includeContent'] = self._serialize.query('include_content', include_content, 'bool')
if resolve_lfs is not None:
query_parameters['resolveLfs'] = self._serialize.query('resolve_lfs', resolve_lfs, 'bool')
response = self._send(http_method='GET', | location_id='fb93c0db-47ed-4a31-8c20-47552878fb44',
version='5.0',
route_values=route_values,
query_parameters=query_parameters,
accept_media_type='application/octet-stream')
if "callback" in kwargs:
callback = kwargs["callback"]
else:
callback = None
return self._client.stream_download(response, callback=callback)
def get_items(self, repository_id, project=None, scope_path=None, recursion_level=None, include_content_metadata=None, latest_processed_change=None, download=None, include_links=None, version_descriptor=None):
"""GetItems.
Get Item Metadata and/or Content for a collection of items. The download parameter is to indicate whether the content should be available as a download or just sent as a stream in the response. Doesn't apply to zipped content which is always returned as a download.
:param str repository_id: The name or ID of the repository.
:param str project: Project ID or project name
:param str scope_path: The path scope. The default is null.
:param str recursion_level: The recursion level of this request. The default is 'none', no recursion.
:param bool include_content_metadata: Set to true to include content metadata. Default is false.
:param bool latest_processed_change: Set to true to include the lastest changes. Default is false.
:param bool download: Set to true to download the response as a file. Default is false.
:param bool include_links: Set to true to include links to items. Default is false.
:param :class:`<GitVersionDescriptor> <azure.devops.v5_0.git.models.GitVersionDescriptor>` version_descriptor: Version descriptor. Default is null.
:rtype: [GitItem]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if scope_path is not None:
query_parameters['scopePath'] = self._serialize.query('scope_path', scope_path, 'str')
if recursion_level is not None:
query_parameters['recursionLevel'] = self._serialize.query('recursion_level', recursion_level, 'str')
if include_content_metadata is not None:
query_parameters['includeContentMetadata'] = self._serialize.query('include_content_metadata', include_content_metadata, 'bool')
if latest_processed_change is not None:
query_parameters['latestProcessedChange'] = self._serialize.query('latest_processed_change', latest_processed_change, 'bool')
if download is not None:
query_parameters['download'] = self._serialize.query('download', download, 'bool')
if include_links is not None:
query_parameters['includeLinks'] = self._serialize.query('include_links', include_links, 'bool')
if version_descriptor is not None:
if version_descriptor.version_type is not None:
query_parameters['versionDescriptor.versionType'] = version_descriptor.version_type
if version_descriptor.version is not None:
query_parameters['versionDescriptor.version'] = version_descriptor.version
if version_descriptor.version_options is not None:
query_parameters['versionDescriptor.versionOptions'] = version_descriptor.version_options
response = self._send(http_method='GET',
location_id='fb93c0db-47ed-4a31-8c20-47552878fb44',
version='5.0',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitItem]', self._unwrap_collection(response))
def get_item_text(self, repository_id, path, project=None, scope_path=None, recursion_level=None, include_content_metadata=None, latest_processed_change=None, download=None, version_descriptor=None, include_content=None, resolve_lfs=None, **kwargs):
"""GetItemText.
Get Item Metadata and/or Content for a single item. The download parameter is to indicate whether the content should be available as a download or just sent as a stream in the response. Doesn't apply to zipped content, which is always returned as a download.
:param str repository_id: The name or ID of the repository.
:param str path: The item path.
:param str project: Project ID or project name
:param str scope_path: The path scope. The default is null.
:param str recursion_level: The recursion level of this request. The default is 'none', no recursion.
:param bool include_content_metadata: Set to true to include content metadata. Default is false.
:param bool latest_processed_change: Set to true to include the lastest changes. Default is false.
:param bool download: Set to true to download the response as a file. Default is false.
:param :class:`<GitVersionDescriptor> <azure.devops.v5_0.git.models.GitVersionDescriptor>` version_descriptor: Version descriptor. Default is null.
:param bool include_content: Set to true to include item content when requesting json. Default is false.
:param bool resolve_lfs: Set to true to resolve Git LFS pointer files to return actual content from Git LFS. Default is false.
:rtype: object
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if path is not None:
query_parameters['path'] = self._serialize.query('path', path, 'str')
if scope_path is not None:
query_parameters['scopePath'] = self._serialize.query('scope_path', scope_path, 'str')
if recursion_level is not None:
query_parameters['recursionLevel'] = self._serialize.query('recursion_level', recursion_level, 'str')
if include_content_metadata is not None:
query_parameters['includeContentMetadata'] = self._serialize.query('include_content_metadata', include_content_metadata, 'bool')
if latest_processed_change is not None:
query_parameters['latestProcessedChange'] = self._serialize.query('latest_processed_change', latest_processed_change, 'bool')
if download is not None:
query_parameters['download'] = self._serialize.query('download', download, 'bool')
if version_descriptor is not None:
if version_descriptor.version_type is not None:
query_parameters['versionDescriptor.versionType'] = version_descriptor.version_type
if version_descriptor.version is not None:
query_parameters['versionDescriptor.version'] = version_descriptor.version
if version_descriptor.version_options is not None:
query_parameters['versionDescriptor.versionOptions'] = version_descriptor.version_options
if include_content is not None:
query_parameters['includeContent'] = self._serialize.query('include_content', include_content, 'bool')
if resolve_lfs is not None:
query_parameters['resolveLfs'] = self._serialize.query('resolve_lfs', resolve_lfs, 'bool')
response = self._send(http_method='GET',
location_id='fb93c0db-47ed-4a31-8c20-47552878fb44',
version='5.0',
route_values=route_values,
query_parameters=query_parameters,
accept_media_type='text/plain')
if "callback" in kwargs:
callback = kwargs["callback"]
else:
callback = None
return self._client.stream_download(response, callback=callback)
def get_item_zip(self, repository_id, path, project=None, scope_path=None, recursion_level=None, include_content_metadata=None, latest_processed_change=None, download=None, version_descriptor=None, include_content=None, resolve_lfs=None, **kwargs):
"""GetItemZip.
Get Item Metadata and/or Content for a single item. The download parameter is to indicate whether the content should be available as a download or just sent as a stream in the response. Doesn't apply to zipped content, which is always returned as a download.
:param str repository_id: The name or ID of the repository.
:param str path: The item path.
:param str project: Project ID or project name
:param str scope_path: The path scope. The default is null.
:param str recursion_level: The recursion level of this request. The default is 'none', no recursion.
:param bool include_content_metadata: Set to true to include content metadata. Default is false.
:param bool latest_processed_change: Set to true to include the lastest changes. Default is false.
:param bool download: Set to true to download the response as a file. Default is false.
:param :class:`<GitVersionDescriptor> <azure.devops.v5_0.git.models.GitVersionDescriptor>` version_descriptor: Version descriptor. Default is null.
:param bool include_content: Set to true to include item content when requesting json. Default is false.
:param bool resolve_lfs: Set to true to resolve Git LFS pointer files to return actual content from Git LFS. Default is false.
:rtype: object
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if path is not None:
query_parameters['path'] = self._serialize.query('path', path, 'str')
if scope_path is not None:
query_parameters['scopePath'] = self._serialize.query('scope_path', scope_path, 'str')
if recursion_level is not None:
query_parameters['recursionLevel'] = self._serialize.query('recursion_level', recursion_level, 'str')
if include_content_metadata is not None:
query_parameters['includeContentMetadata'] = self._serialize.query('include_content_metadata', include_content_metadata, 'bool')
if latest_processed_change is not None:
query_parameters['latestProcessedChange'] = self._serialize.query('latest_processed_change', latest_processed_change, 'bool')
if download is not None:
query_parameters['download'] = self._serialize.query('download', download, 'bool')
if version_descriptor is not None:
if version_descriptor.version_type is not None:
query_parameters['versionDescriptor.versionType'] = version_descriptor.version_type
if version_descriptor.version is not None:
query_parameters['versionDescriptor.version'] = version_descriptor.version
if version_descriptor.version_options is not None:
query_parameters['versionDescriptor.versionOptions'] = version_descriptor.version_options
if include_content is not None:
query_parameters['includeContent'] = self._serialize.query('include_content', include_content, 'bool')
if resolve_lfs is not None:
query_parameters['resolveLfs'] = self._serialize.query('resolve_lfs', resolve_lfs, 'bool')
response = self._send(http_method='GET',
location_id='fb93c0db-47ed-4a31-8c20-47552878fb44',
version='5.0',
route_values=route_values,
query_parameters=query_parameters,
accept_media_type='application/zip')
if "callback" in kwargs:
callback = kwargs["callback"]
else:
callback = None
return self._client.stream_download(response, callback=callback)
def get_items_batch(self, request_data, repository_id, project=None):
"""GetItemsBatch.
Post for retrieving a creating a batch out of a set of items in a repo / project given a list of paths or a long path
:param :class:`<GitItemRequestData> <azure.devops.v5_0.git.models.GitItemRequestData>` request_data: Request data attributes: ItemDescriptors, IncludeContentMetadata, LatestProcessedChange, IncludeLinks. ItemDescriptors: Collection of items to fetch, including path, version, and recursion level. IncludeContentMetadata: Whether to include metadata for all items LatestProcessedChange: Whether to include shallow ref to commit that last changed each item. IncludeLinks: Whether to include the _links field on the shallow references.
:param str repository_id: The name or ID of the repository
:param str project: Project ID or project name
:rtype: [[GitItem]]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
content = self._serialize.body(request_data, 'GitItemRequestData')
response = self._send(http_method='POST',
location_id='630fd2e4-fb88-4f85-ad21-13f3fd1fbca9',
version='5.0',
route_values=route_values,
content=content)
return self._deserialize('[[GitItem]]', self._unwrap_collection(response))
def get_merge_bases(self, repository_name_or_id, commit_id, other_commit_id, project=None, other_collection_id=None, other_repository_id=None):
"""GetMergeBases.
[Preview API] Find the merge bases of two commits, optionally across forks. If otherRepositoryId is not specified, the merge bases will only be calculated within the context of the local repositoryNameOrId.
:param str repository_name_or_id: ID or name of the local repository.
:param str commit_id: First commit, usually the tip of the target branch of the potential merge.
:param str other_commit_id: Other commit, usually the tip of the source branch of the potential merge.
:param str project: Project ID or project name
:param str other_collection_id: The collection ID where otherCommitId lives.
:param str other_repository_id: The repository ID where otherCommitId lives.
:rtype: [GitCommitRef]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_name_or_id is not None:
route_values['repositoryNameOrId'] = self._serialize.url('repository_name_or_id', repository_name_or_id, 'str')
if commit_id is not None:
route_values['commitId'] = self._serialize.url('commit_id', commit_id, 'str')
query_parameters = {}
if other_commit_id is not None:
query_parameters['otherCommitId'] = self._serialize.query('other_commit_id', other_commit_id, 'str')
if other_collection_id is not None:
query_parameters['otherCollectionId'] = self._serialize.query('other_collection_id', other_collection_id, 'str')
if other_repository_id is not None:
query_parameters['otherRepositoryId'] = self._serialize.query('other_repository_id', other_repository_id, 'str')
response = self._send(http_method='GET',
location_id='7cf2abb6-c964-4f7e-9872-f78c66e72e9c',
version='5.0-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitCommitRef]', self._unwrap_collection(response))
def create_attachment(self, upload_stream, file_name, repository_id, pull_request_id, project=None, **kwargs):
"""CreateAttachment.
[Preview API] Attach a new file to a pull request.
:param object upload_stream: Stream to upload
:param str file_name: The name of the file.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:rtype: :class:`<Attachment> <azure.devops.v5_0.git.models.Attachment>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if file_name is not None:
route_values['fileName'] = self._serialize.url('file_name', file_name, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if "callback" in kwargs:
callback = kwargs["callback"]
else:
callback = None
content = self._client.stream_upload(upload_stream, callback=callback)
response = self._send(http_method='POST',
location_id='965d9361-878b-413b-a494-45d5b5fd8ab7',
version='5.0-preview.1',
route_values=route_values,
content=content,
media_type='application/octet-stream')
return self._deserialize('Attachment', response)
def delete_attachment(self, file_name, repository_id, pull_request_id, project=None):
"""DeleteAttachment.
[Preview API] Delete a pull request attachment.
:param str file_name: The name of the attachment to delete.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if file_name is not None:
route_values['fileName'] = self._serialize.url('file_name', file_name, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
self._send(http_method='DELETE',
location_id='965d9361-878b-413b-a494-45d5b5fd8ab7',
version='5.0-preview.1',
route_values=route_values)
def get_attachment_content(self, file_name, repository_id, pull_request_id, project=None, **kwargs):
"""GetAttachmentContent.
[Preview API] Get the file content of a pull request attachment.
:param str file_name: The name of the attachment.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:rtype: object
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if file_name is not None:
route_values['fileName'] = self._serialize.url('file_name', file_name, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
response = self._send(http_method='GET',
location_id='965d9361-878b-413b-a494-45d5b5fd8ab7',
version='5.0-preview.1',
route_values=route_values,
accept_media_type='application/octet-stream')
if "callback" in kwargs:
callback = kwargs["callback"]
else:
callback = None
return self._client.stream_download(response, callback=callback)
def get_attachments(self, repository_id, pull_request_id, project=None):
"""GetAttachments.
[Preview API] Get a list of files attached to a given pull request.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:rtype: [Attachment]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
response = self._send(http_method='GET',
location_id='965d9361-878b-413b-a494-45d5b5fd8ab7',
version='5.0-preview.1',
route_values=route_values)
return self._deserialize('[Attachment]', self._unwrap_collection(response))
def get_attachment_zip(self, file_name, repository_id, pull_request_id, project=None, **kwargs):
"""GetAttachmentZip.
[Preview API] Get the file content of a pull request attachment.
:param str file_name: The name of the attachment.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:rtype: object
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if file_name is not None:
route_values['fileName'] = self._serialize.url('file_name', file_name, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
response = self._send(http_method='GET',
location_id='965d9361-878b-413b-a494-45d5b5fd8ab7',
version='5.0-preview.1',
route_values=route_values,
accept_media_type='application/zip')
if "callback" in kwargs:
callback = kwargs["callback"]
else:
callback = None
return self._client.stream_download(response, callback=callback)
def create_like(self, repository_id, pull_request_id, thread_id, comment_id, project=None):
"""CreateLike.
[Preview API] Add a like on a comment.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:param int thread_id: The ID of the thread that contains the comment.
:param int comment_id: The ID of the comment.
:param str project: Project ID or project name
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if thread_id is not None:
route_values['threadId'] = self._serialize.url('thread_id', thread_id, 'int')
if comment_id is not None:
route_values['commentId'] = self._serialize.url('comment_id', comment_id, 'int')
self._send(http_method='POST',
location_id='5f2e2851-1389-425b-a00b-fb2adb3ef31b',
version='5.0-preview.1',
route_values=route_values)
def delete_like(self, repository_id, pull_request_id, thread_id, comment_id, project=None):
"""DeleteLike.
[Preview API] Delete a like on a comment.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:param int thread_id: The ID of the thread that contains the comment.
:param int comment_id: The ID of the comment.
:param str project: Project ID or project name
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if thread_id is not None:
route_values['threadId'] = self._serialize.url('thread_id', thread_id, 'int')
if comment_id is not None:
route_values['commentId'] = self._serialize.url('comment_id', comment_id, 'int')
self._send(http_method='DELETE',
location_id='5f2e2851-1389-425b-a00b-fb2adb3ef31b',
version='5.0-preview.1',
route_values=route_values)
def get_likes(self, repository_id, pull_request_id, thread_id, comment_id, project=None):
"""GetLikes.
[Preview API] Get likes for a comment.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:param int thread_id: The ID of the thread that contains the comment.
:param int comment_id: The ID of the comment.
:param str project: Project ID or project name
:rtype: [IdentityRef]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if thread_id is not None:
route_values['threadId'] = self._serialize.url('thread_id', thread_id, 'int')
if comment_id is not None:
route_values['commentId'] = self._serialize.url('comment_id', comment_id, 'int')
response = self._send(http_method='GET',
location_id='5f2e2851-1389-425b-a00b-fb2adb3ef31b',
version='5.0-preview.1',
route_values=route_values)
return self._deserialize('[IdentityRef]', self._unwrap_collection(response))
def get_pull_request_iteration_commits(self, repository_id, pull_request_id, iteration_id, project=None):
"""GetPullRequestIterationCommits.
Get the commits for the specified iteration of a pull request.
:param str repository_id: ID or name of the repository.
:param int pull_request_id: ID of the pull request.
:param int iteration_id: ID of the iteration from which to get the commits.
:param str project: Project ID or project name
:rtype: [GitCommitRef]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if iteration_id is not None:
route_values['iterationId'] = self._serialize.url('iteration_id', iteration_id, 'int')
response = self._send(http_method='GET',
location_id='e7ea0883-095f-4926-b5fb-f24691c26fb9',
version='5.0',
route_values=route_values)
return self._deserialize('[GitCommitRef]', self._unwrap_collection(response))
def get_pull_request_commits(self, repository_id, pull_request_id, project=None):
"""GetPullRequestCommits.
Get the commits for the specified pull request.
:param str repository_id: ID or name of the repository.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:rtype: [GitCommitRef]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
response = self._send(http_method='GET',
location_id='52823034-34a8-4576-922c-8d8b77e9e4c4',
version='5.0',
route_values=route_values)
return self._deserialize('[GitCommitRef]', self._unwrap_collection(response))
def get_pull_request_iteration_changes(self, repository_id, pull_request_id, iteration_id, project=None, top=None, skip=None, compare_to=None):
"""GetPullRequestIterationChanges.
Retrieve the changes made in a pull request between two iterations.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:param int iteration_id: ID of the pull request iteration. <br /> Iteration IDs are zero-based with zero indicating the common commit between the source and target branches. Iteration one is the head of the source branch at the time the pull request is created and subsequent iterations are created when there are pushes to the source branch.
:param str project: Project ID or project name
:param int top: Optional. The number of changes to retrieve. The default value is 100 and the maximum value is 2000.
:param int skip: Optional. The number of changes to ignore. For example, to retrieve changes 101-150, set top 50 and skip to 100.
:param int compare_to: ID of the pull request iteration to compare against. The default value is zero which indicates the comparison is made against the common commit between the source and target branches
:rtype: :class:`<GitPullRequestIterationChanges> <azure.devops.v5_0.git.models.GitPullRequestIterationChanges>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if iteration_id is not None:
route_values['iterationId'] = self._serialize.url('iteration_id', iteration_id, 'int')
query_parameters = {}
if top is not None:
query_parameters['$top'] = self._serialize.query('top', top, 'int')
if skip is not None:
query_parameters['$skip'] = self._serialize.query('skip', skip, 'int')
if compare_to is not None:
query_parameters['$compareTo'] = self._serialize.query('compare_to', compare_to, 'int')
response = self._send(http_method='GET',
location_id='4216bdcf-b6b1-4d59-8b82-c34cc183fc8b',
version='5.0',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('GitPullRequestIterationChanges', response)
def get_pull_request_iteration(self, repository_id, pull_request_id, iteration_id, project=None):
"""GetPullRequestIteration.
Get the specified iteration for a pull request.
:param str repository_id: ID or name of the repository.
:param int pull_request_id: ID of the pull request.
:param int iteration_id: ID of the pull request iteration to return.
:param str project: Project ID or project name
:rtype: :class:`<GitPullRequestIteration> <azure.devops.v5_0.git.models.GitPullRequestIteration>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if iteration_id is not None:
route_values['iterationId'] = self._serialize.url('iteration_id', iteration_id, 'int')
response = self._send(http_method='GET',
location_id='d43911ee-6958-46b0-a42b-8445b8a0d004',
version='5.0',
route_values=route_values)
return self._deserialize('GitPullRequestIteration', response)
def get_pull_request_iterations(self, repository_id, pull_request_id, project=None, include_commits=None):
"""GetPullRequestIterations.
Get the list of iterations for the specified pull request.
:param str repository_id: ID or name of the repository.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:param bool include_commits: If true, include the commits associated with each iteration in the response.
:rtype: [GitPullRequestIteration]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
query_parameters = {}
if include_commits is not None:
query_parameters['includeCommits'] = self._serialize.query('include_commits', include_commits, 'bool')
response = self._send(http_method='GET',
location_id='d43911ee-6958-46b0-a42b-8445b8a0d004',
version='5.0',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitPullRequestIteration]', self._unwrap_collection(response))
def create_pull_request_iteration_status(self, status, repository_id, pull_request_id, iteration_id, project=None):
"""CreatePullRequestIterationStatus.
[Preview API] Create a pull request status on the iteration. This operation will have the same result as Create status on pull request with specified iteration ID in the request body.
:param :class:`<GitPullRequestStatus> <azure.devops.v5_0.git.models.GitPullRequestStatus>` status: Pull request status to create.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param int iteration_id: ID of the pull request iteration.
:param str project: Project ID or project name
:rtype: :class:`<GitPullRequestStatus> <azure.devops.v5_0.git.models.GitPullRequestStatus>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if iteration_id is not None:
route_values['iterationId'] = self._serialize.url('iteration_id', iteration_id, 'int')
content = self._serialize.body(status, 'GitPullRequestStatus')
response = self._send(http_method='POST',
location_id='75cf11c5-979f-4038-a76e-058a06adf2bf',
version='5.0-preview.1',
route_values=route_values,
content=content)
return self._deserialize('GitPullRequestStatus', response)
def delete_pull_request_iteration_status(self, repository_id, pull_request_id, iteration_id, status_id, project=None):
"""DeletePullRequestIterationStatus.
[Preview API] Delete pull request iteration status.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param int iteration_id: ID of the pull request iteration.
:param int status_id: ID of the pull request status.
:param str project: Project ID or project name
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if iteration_id is not None:
route_values['iterationId'] = self._serialize.url('iteration_id', iteration_id, 'int')
if status_id is not None:
route_values['statusId'] = self._serialize.url('status_id', status_id, 'int')
self._send(http_method='DELETE',
location_id='75cf11c5-979f-4038-a76e-058a06adf2bf',
version='5.0-preview.1',
route_values=route_values)
def get_pull_request_iteration_status(self, repository_id, pull_request_id, iteration_id, status_id, project=None):
"""GetPullRequestIterationStatus.
[Preview API] Get the specific pull request iteration status by ID. The status ID is unique within the pull request across all iterations.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param int iteration_id: ID of the pull request iteration.
:param int status_id: ID of the pull request status.
:param str project: Project ID or project name
:rtype: :class:`<GitPullRequestStatus> <azure.devops.v5_0.git.models.GitPullRequestStatus>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if iteration_id is not None:
route_values['iterationId'] = self._serialize.url('iteration_id', iteration_id, 'int')
if status_id is not None:
route_values['statusId'] = self._serialize.url('status_id', status_id, 'int')
response = self._send(http_method='GET',
location_id='75cf11c5-979f-4038-a76e-058a06adf2bf',
version='5.0-preview.1',
route_values=route_values)
return self._deserialize('GitPullRequestStatus', response)
def get_pull_request_iteration_statuses(self, repository_id, pull_request_id, iteration_id, project=None):
"""GetPullRequestIterationStatuses.
[Preview API] Get all the statuses associated with a pull request iteration.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param int iteration_id: ID of the pull request iteration.
:param str project: Project ID or project name
:rtype: [GitPullRequestStatus]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if iteration_id is not None:
route_values['iterationId'] = self._serialize.url('iteration_id', iteration_id, 'int')
response = self._send(http_method='GET',
location_id='75cf11c5-979f-4038-a76e-058a06adf2bf',
version='5.0-preview.1',
route_values=route_values)
return self._deserialize('[GitPullRequestStatus]', self._unwrap_collection(response))
def update_pull_request_iteration_statuses(self, patch_document, repository_id, pull_request_id, iteration_id, project=None):
"""UpdatePullRequestIterationStatuses.
[Preview API] Update pull request iteration statuses collection. The only supported operation type is `remove`.
:param :class:`<[JsonPatchOperation]> <azure.devops.v5_0.git.models.[JsonPatchOperation]>` patch_document: Operations to apply to the pull request statuses in JSON Patch format.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param int iteration_id: ID of the pull request iteration.
:param str project: Project ID or project name
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if iteration_id is not None:
route_values['iterationId'] = self._serialize.url('iteration_id', iteration_id, 'int')
content = self._serialize.body(patch_document, '[JsonPatchOperation]')
self._send(http_method='PATCH',
location_id='75cf11c5-979f-4038-a76e-058a06adf2bf',
version='5.0-preview.1',
route_values=route_values,
content=content,
media_type='application/json-patch+json')
def create_pull_request_label(self, label, repository_id, pull_request_id, project=None, project_id=None):
"""CreatePullRequestLabel.
[Preview API] Create a label for a specified pull request. The only required field is the name of the new label.
:param :class:`<WebApiCreateTagRequestData> <azure.devops.v5_0.git.models.WebApiCreateTagRequestData>` label: Label to assign to the pull request.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:param str project_id: Project ID or project name.
:rtype: :class:`<WebApiTagDefinition> <azure.devops.v5_0.git.models.WebApiTagDefinition>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
query_parameters = {}
if project_id is not None:
query_parameters['projectId'] = self._serialize.query('project_id', project_id, 'str')
content = self._serialize.body(label, 'WebApiCreateTagRequestData')
response = self._send(http_method='POST',
location_id='f22387e3-984e-4c52-9c6d-fbb8f14c812d',
version='5.0-preview.1',
route_values=route_values,
query_parameters=query_parameters,
content=content)
return self._deserialize('WebApiTagDefinition', response)
def delete_pull_request_labels(self, repository_id, pull_request_id, label_id_or_name, project=None, project_id=None):
"""DeletePullRequestLabels.
[Preview API] Removes a label from the set of those assigned to the pull request.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param str label_id_or_name: The name or ID of the label requested.
:param str project: Project ID or project name
:param str project_id: Project ID or project name.
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if label_id_or_name is not None:
route_values['labelIdOrName'] = self._serialize.url('label_id_or_name', label_id_or_name, 'str')
query_parameters = {}
if project_id is not None:
query_parameters['projectId'] = self._serialize.query('project_id', project_id, 'str')
self._send(http_method='DELETE',
location_id='f22387e3-984e-4c52-9c6d-fbb8f14c812d',
version='5.0-preview.1',
route_values=route_values,
query_parameters=query_parameters)
def get_pull_request_label(self, repository_id, pull_request_id, label_id_or_name, project=None, project_id=None):
"""GetPullRequestLabel.
[Preview API] Retrieves a single label that has been assigned to a pull request.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param str label_id_or_name: The name or ID of the label requested.
:param str project: Project ID or project name
:param str project_id: Project ID or project name.
:rtype: :class:`<WebApiTagDefinition> <azure.devops.v5_0.git.models.WebApiTagDefinition>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if label_id_or_name is not None:
route_values['labelIdOrName'] = self._serialize.url('label_id_or_name', label_id_or_name, 'str')
query_parameters = {}
if project_id is not None:
query_parameters['projectId'] = self._serialize.query('project_id', project_id, 'str')
response = self._send(http_method='GET',
location_id='f22387e3-984e-4c52-9c6d-fbb8f14c812d',
version='5.0-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('WebApiTagDefinition', response)
def get_pull_request_labels(self, repository_id, pull_request_id, project=None, project_id=None):
"""GetPullRequestLabels.
[Preview API] Get all the labels assigned to a pull request.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:param str project_id: Project ID or project name.
:rtype: [WebApiTagDefinition]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
query_parameters = {}
if project_id is not None:
query_parameters['projectId'] = self._serialize.query('project_id', project_id, 'str')
response = self._send(http_method='GET',
location_id='f22387e3-984e-4c52-9c6d-fbb8f14c812d',
version='5.0-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[WebApiTagDefinition]', self._unwrap_collection(response))
def get_pull_request_properties(self, repository_id, pull_request_id, project=None):
"""GetPullRequestProperties.
[Preview API] Get external properties of the pull request.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:rtype: :class:`<object> <azure.devops.v5_0.git.models.object>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
response = self._send(http_method='GET',
location_id='48a52185-5b9e-4736-9dc1-bb1e2feac80b',
version='5.0-preview.1',
route_values=route_values)
return self._deserialize('object', response)
def update_pull_request_properties(self, patch_document, repository_id, pull_request_id, project=None):
"""UpdatePullRequestProperties.
[Preview API] Create or update pull request external properties. The patch operation can be `add`, `replace` or `remove`. For `add` operation, the path can be empty. If the path is empty, the value must be a list of key value pairs. For `replace` operation, the path cannot be empty. If the path does not exist, the property will be added to the collection. For `remove` operation, the path cannot be empty. If the path does not exist, no action will be performed.
:param :class:`<[JsonPatchOperation]> <azure.devops.v5_0.git.models.[JsonPatchOperation]>` patch_document: Properties to add, replace or remove in JSON Patch format.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:rtype: :class:`<object> <azure.devops.v5_0.git.models.object>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
content = self._serialize.body(patch_document, '[JsonPatchOperation]')
response = self._send(http_method='PATCH',
location_id='48a52185-5b9e-4736-9dc1-bb1e2feac80b',
version='5.0-preview.1',
route_values=route_values,
content=content,
media_type='application/json-patch+json')
return self._deserialize('object', response)
def get_pull_request_query(self, queries, repository_id, project=None):
"""GetPullRequestQuery.
This API is used to find what pull requests are related to a given commit. It can be used to either find the pull request that created a particular merge commit or it can be used to find all pull requests that have ever merged a particular commit. The input is a list of queries which each contain a list of commits. For each commit that you search against, you will get back a dictionary of commit -> pull requests.
:param :class:`<GitPullRequestQuery> <azure.devops.v5_0.git.models.GitPullRequestQuery>` queries: The list of queries to perform.
:param str repository_id: ID of the repository.
:param str project: Project ID or project name
:rtype: :class:`<GitPullRequestQuery> <azure.devops.v5_0.git.models.GitPullRequestQuery>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
content = self._serialize.body(queries, 'GitPullRequestQuery')
response = self._send(http_method='POST',
location_id='b3a6eebe-9cf0-49ea-b6cb-1a4c5f5007b0',
version='5.0',
route_values=route_values,
content=content)
return self._deserialize('GitPullRequestQuery', response)
def create_pull_request_reviewer(self, reviewer, repository_id, pull_request_id, reviewer_id, project=None):
"""CreatePullRequestReviewer.
Add a reviewer to a pull request or cast a vote.
:param :class:`<IdentityRefWithVote> <azure.devops.v5_0.git.models.IdentityRefWithVote>` reviewer: Reviewer's vote.<br />If the reviewer's ID is included here, it must match the reviewerID parameter.<br />Reviewers can set their own vote with this method. When adding other reviewers, vote must be set to zero.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param str reviewer_id: ID of the reviewer.
:param str project: Project ID or project name
:rtype: :class:`<IdentityRefWithVote> <azure.devops.v5_0.git.models.IdentityRefWithVote>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if reviewer_id is not None:
route_values['reviewerId'] = self._serialize.url('reviewer_id', reviewer_id, 'str')
content = self._serialize.body(reviewer, 'IdentityRefWithVote')
response = self._send(http_method='PUT',
location_id='4b6702c7-aa35-4b89-9c96-b9abf6d3e540',
version='5.0',
route_values=route_values,
content=content)
return self._deserialize('IdentityRefWithVote', response)
def create_pull_request_reviewers(self, reviewers, repository_id, pull_request_id, project=None):
"""CreatePullRequestReviewers.
Add reviewers to a pull request.
:param [IdentityRef] reviewers: Reviewers to add to the pull request.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:rtype: [IdentityRefWithVote]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
content = self._serialize.body(reviewers, '[IdentityRef]')
response = self._send(http_method='POST',
location_id='4b6702c7-aa35-4b89-9c96-b9abf6d3e540',
version='5.0',
route_values=route_values,
content=content)
return self._deserialize('[IdentityRefWithVote]', self._unwrap_collection(response))
def delete_pull_request_reviewer(self, repository_id, pull_request_id, reviewer_id, project=None):
"""DeletePullRequestReviewer.
Remove a reviewer from a pull request.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param str reviewer_id: ID of the reviewer to remove.
:param str project: Project ID or project name
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if reviewer_id is not None:
route_values['reviewerId'] = self._serialize.url('reviewer_id', reviewer_id, 'str')
self._send(http_method='DELETE',
location_id='4b6702c7-aa35-4b89-9c96-b9abf6d3e540',
version='5.0',
route_values=route_values)
def get_pull_request_reviewer(self, repository_id, pull_request_id, reviewer_id, project=None):
"""GetPullRequestReviewer.
Retrieve information about a particular reviewer on a pull request
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param str reviewer_id: ID of the reviewer.
:param str project: Project ID or project name
:rtype: :class:`<IdentityRefWithVote> <azure.devops.v5_0.git.models.IdentityRefWithVote>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if reviewer_id is not None:
route_values['reviewerId'] = self._serialize.url('reviewer_id', reviewer_id, 'str')
response = self._send(http_method='GET',
location_id='4b6702c7-aa35-4b89-9c96-b9abf6d3e540',
version='5.0',
route_values=route_values)
return self._deserialize('IdentityRefWithVote', response)
def get_pull_request_reviewers(self, repository_id, pull_request_id, project=None):
"""GetPullRequestReviewers.
Retrieve the reviewers for a pull request
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:rtype: [IdentityRefWithVote]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
response = self._send(http_method='GET',
location_id='4b6702c7-aa35-4b89-9c96-b9abf6d3e540',
version='5.0',
route_values=route_values)
return self._deserialize('[IdentityRefWithVote]', self._unwrap_collection(response))
def update_pull_request_reviewers(self, patch_votes, repository_id, pull_request_id, project=None):
"""UpdatePullRequestReviewers.
Reset the votes of multiple reviewers on a pull request. NOTE: This endpoint only supports updating votes, but does not support updating required reviewers (use policy) or display names.
:param [IdentityRefWithVote] patch_votes: IDs of the reviewers whose votes will be reset to zero
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request
:param str project: Project ID or project name
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
content = self._serialize.body(patch_votes, '[IdentityRefWithVote]')
self._send(http_method='PATCH',
location_id='4b6702c7-aa35-4b89-9c96-b9abf6d3e540',
version='5.0',
route_values=route_values,
content=content)
def get_pull_request_by_id(self, pull_request_id, project=None):
"""GetPullRequestById.
Retrieve a pull request.
:param int pull_request_id: The ID of the pull request to retrieve.
:param str project: Project ID or project name
:rtype: :class:`<GitPullRequest> <azure.devops.v5_0.git.models.GitPullRequest>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
response = self._send(http_method='GET',
location_id='01a46dea-7d46-4d40-bc84-319e7c260d99',
version='5.0',
route_values=route_values)
return self._deserialize('GitPullRequest', response)
def get_pull_requests_by_project(self, project, search_criteria, max_comment_length=None, skip=None, top=None):
"""GetPullRequestsByProject.
Retrieve all pull requests matching a specified criteria.
:param str project: Project ID or project name
:param :class:`<GitPullRequestSearchCriteria> <azure.devops.v5_0.git.models.GitPullRequestSearchCriteria>` search_criteria: Pull requests will be returned that match this search criteria.
:param int max_comment_length: Not used.
:param int skip: The number of pull requests to ignore. For example, to retrieve results 101-150, set top to 50 and skip to 100.
:param int top: The number of pull requests to retrieve.
:rtype: [GitPullRequest]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
query_parameters = {}
if search_criteria is not None:
if search_criteria.repository_id is not None:
query_parameters['searchCriteria.repositoryId'] = search_criteria.repository_id
if search_criteria.creator_id is not None:
query_parameters['searchCriteria.creatorId'] = search_criteria.creator_id
if search_criteria.reviewer_id is not None:
query_parameters['searchCriteria.reviewerId'] = search_criteria.reviewer_id
if search_criteria.status is not None:
query_parameters['searchCriteria.status'] = search_criteria.status
if search_criteria.target_ref_name is not None:
query_parameters['searchCriteria.targetRefName'] = search_criteria.target_ref_name
if search_criteria.source_repository_id is not None:
query_parameters['searchCriteria.sourceRepositoryId'] = search_criteria.source_repository_id
if search_criteria.source_ref_name is not None:
query_parameters['searchCriteria.sourceRefName'] = search_criteria.source_ref_name
if search_criteria.include_links is not None:
query_parameters['searchCriteria.includeLinks'] = search_criteria.include_links
if max_comment_length is not None:
query_parameters['maxCommentLength'] = self._serialize.query('max_comment_length', max_comment_length, 'int')
if skip is not None:
query_parameters['$skip'] = self._serialize.query('skip', skip, 'int')
if top is not None:
query_parameters['$top'] = self._serialize.query('top', top, 'int')
response = self._send(http_method='GET',
location_id='a5d28130-9cd2-40fa-9f08-902e7daa9efb',
version='5.0',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitPullRequest]', self._unwrap_collection(response))
def create_pull_request(self, git_pull_request_to_create, repository_id, project=None, supports_iterations=None):
"""CreatePullRequest.
Create a pull request.
:param :class:`<GitPullRequest> <azure.devops.v5_0.git.models.GitPullRequest>` git_pull_request_to_create: The pull request to create.
:param str repository_id: The repository ID of the pull request's target branch.
:param str project: Project ID or project name
:param bool supports_iterations: If true, subsequent pushes to the pull request will be individually reviewable. Set this to false for large pull requests for performance reasons if this functionality is not needed.
:rtype: :class:`<GitPullRequest> <azure.devops.v5_0.git.models.GitPullRequest>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if supports_iterations is not None:
query_parameters['supportsIterations'] = self._serialize.query('supports_iterations', supports_iterations, 'bool')
content = self._serialize.body(git_pull_request_to_create, 'GitPullRequest')
response = self._send(http_method='POST',
location_id='9946fd70-0d40-406e-b686-b4744cbbcc37',
version='5.0',
route_values=route_values,
query_parameters=query_parameters,
content=content)
return self._deserialize('GitPullRequest', response)
def get_pull_request(self, repository_id, pull_request_id, project=None, max_comment_length=None, skip=None, top=None, include_commits=None, include_work_item_refs=None):
"""GetPullRequest.
Retrieve a pull request.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: The ID of the pull request to retrieve.
:param str project: Project ID or project name
:param int max_comment_length: Not used.
:param int skip: Not used.
:param int top: Not used.
:param bool include_commits: If true, the pull request will be returned with the associated commits.
:param bool include_work_item_refs: If true, the pull request will be returned with the associated work item references.
:rtype: :class:`<GitPullRequest> <azure.devops.v5_0.git.models.GitPullRequest>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
query_parameters = {}
if max_comment_length is not None:
query_parameters['maxCommentLength'] = self._serialize.query('max_comment_length', max_comment_length, 'int')
if skip is not None:
query_parameters['$skip'] = self._serialize.query('skip', skip, 'int')
if top is not None:
query_parameters['$top'] = self._serialize.query('top', top, 'int')
if include_commits is not None:
query_parameters['includeCommits'] = self._serialize.query('include_commits', include_commits, 'bool')
if include_work_item_refs is not None:
query_parameters['includeWorkItemRefs'] = self._serialize.query('include_work_item_refs', include_work_item_refs, 'bool')
response = self._send(http_method='GET',
location_id='9946fd70-0d40-406e-b686-b4744cbbcc37',
version='5.0',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('GitPullRequest', response)
def get_pull_requests(self, repository_id, search_criteria, project=None, max_comment_length=None, skip=None, top=None):
"""GetPullRequests.
Retrieve all pull requests matching a specified criteria.
:param str repository_id: The repository ID of the pull request's target branch.
:param :class:`<GitPullRequestSearchCriteria> <azure.devops.v5_0.git.models.GitPullRequestSearchCriteria>` search_criteria: Pull requests will be returned that match this search criteria.
:param str project: Project ID or project name
:param int max_comment_length: Not used.
:param int skip: The number of pull requests to ignore. For example, to retrieve results 101-150, set top to 50 and skip to 100.
:param int top: The number of pull requests to retrieve.
:rtype: [GitPullRequest]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if search_criteria is not None:
if search_criteria.repository_id is not None:
query_parameters['searchCriteria.repositoryId'] = search_criteria.repository_id
if search_criteria.creator_id is not None:
query_parameters['searchCriteria.creatorId'] = search_criteria.creator_id
if search_criteria.reviewer_id is not None:
query_parameters['searchCriteria.reviewerId'] = search_criteria.reviewer_id
if search_criteria.status is not None:
query_parameters['searchCriteria.status'] = search_criteria.status
if search_criteria.target_ref_name is not None:
query_parameters['searchCriteria.targetRefName'] = search_criteria.target_ref_name
if search_criteria.source_repository_id is not None:
query_parameters['searchCriteria.sourceRepositoryId'] = search_criteria.source_repository_id
if search_criteria.source_ref_name is not None:
query_parameters['searchCriteria.sourceRefName'] = search_criteria.source_ref_name
if search_criteria.include_links is not None:
query_parameters['searchCriteria.includeLinks'] = search_criteria.include_links
if max_comment_length is not None:
query_parameters['maxCommentLength'] = self._serialize.query('max_comment_length', max_comment_length, 'int')
if skip is not None:
query_parameters['$skip'] = self._serialize.query('skip', skip, 'int')
if top is not None:
query_parameters['$top'] = self._serialize.query('top', top, 'int')
response = self._send(http_method='GET',
location_id='9946fd70-0d40-406e-b686-b4744cbbcc37',
version='5.0',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitPullRequest]', self._unwrap_collection(response))
def update_pull_request(self, git_pull_request_to_update, repository_id, pull_request_id, project=None):
"""UpdatePullRequest.
Update a pull request.
:param :class:`<GitPullRequest> <azure.devops.v5_0.git.models.GitPullRequest>` git_pull_request_to_update: The pull request content to update.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: The ID of the pull request to retrieve.
:param str project: Project ID or project name
:rtype: :class:`<GitPullRequest> <azure.devops.v5_0.git.models.GitPullRequest>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
content = self._serialize.body(git_pull_request_to_update, 'GitPullRequest')
response = self._send(http_method='PATCH',
location_id='9946fd70-0d40-406e-b686-b4744cbbcc37',
version='5.0',
route_values=route_values,
content=content)
return self._deserialize('GitPullRequest', response)
def share_pull_request(self, user_message, repository_id, pull_request_id, project=None):
"""SharePullRequest.
[Preview API] Sends an e-mail notification about a specific pull request to a set of recipients
:param :class:`<ShareNotificationContext> <azure.devops.v5_0.git.models.ShareNotificationContext>` user_message:
:param str repository_id: ID of the git repository.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
content = self._serialize.body(user_message, 'ShareNotificationContext')
self._send(http_method='POST',
location_id='696f3a82-47c9-487f-9117-b9d00972ca84',
version='5.0-preview.1',
route_values=route_values,
content=content)
def create_pull_request_status(self, status, repository_id, pull_request_id, project=None):
"""CreatePullRequestStatus.
[Preview API] Create a pull request status.
:param :class:`<GitPullRequestStatus> <azure.devops.v5_0.git.models.GitPullRequestStatus>` status: Pull request status to create.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:rtype: :class:`<GitPullRequestStatus> <azure.devops.v5_0.git.models.GitPullRequestStatus>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
content = self._serialize.body(status, 'GitPullRequestStatus')
response = self._send(http_method='POST',
location_id='b5f6bb4f-8d1e-4d79-8d11-4c9172c99c35',
version='5.0-preview.1',
route_values=route_values,
content=content)
return self._deserialize('GitPullRequestStatus', response)
def delete_pull_request_status(self, repository_id, pull_request_id, status_id, project=None):
"""DeletePullRequestStatus.
[Preview API] Delete pull request status.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param int status_id: ID of the pull request status.
:param str project: Project ID or project name
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if status_id is not None:
route_values['statusId'] = self._serialize.url('status_id', status_id, 'int')
self._send(http_method='DELETE',
location_id='b5f6bb4f-8d1e-4d79-8d11-4c9172c99c35',
version='5.0-preview.1',
route_values=route_values)
def get_pull_request_status(self, repository_id, pull_request_id, status_id, project=None):
"""GetPullRequestStatus.
[Preview API] Get the specific pull request status by ID. The status ID is unique within the pull request across all iterations.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param int status_id: ID of the pull request status.
:param str project: Project ID or project name
:rtype: :class:`<GitPullRequestStatus> <azure.devops.v5_0.git.models.GitPullRequestStatus>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if status_id is not None:
route_values['statusId'] = self._serialize.url('status_id', status_id, 'int')
response = self._send(http_method='GET',
location_id='b5f6bb4f-8d1e-4d79-8d11-4c9172c99c35',
version='5.0-preview.1',
route_values=route_values)
return self._deserialize('GitPullRequestStatus', response)
def get_pull_request_statuses(self, repository_id, pull_request_id, project=None):
"""GetPullRequestStatuses.
[Preview API] Get all the statuses associated with a pull request.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:rtype: [GitPullRequestStatus]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
response = self._send(http_method='GET',
location_id='b5f6bb4f-8d1e-4d79-8d11-4c9172c99c35',
version='5.0-preview.1',
route_values=route_values)
return self._deserialize('[GitPullRequestStatus]', self._unwrap_collection(response))
def update_pull_request_statuses(self, patch_document, repository_id, pull_request_id, project=None):
"""UpdatePullRequestStatuses.
[Preview API] Update pull request statuses collection. The only supported operation type is `remove`.
:param :class:`<[JsonPatchOperation]> <azure.devops.v5_0.git.models.[JsonPatchOperation]>` patch_document: Operations to apply to the pull request statuses in JSON Patch format.
:param str repository_id: The repository ID of the pull request’s target branch.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
content = self._serialize.body(patch_document, '[JsonPatchOperation]')
self._send(http_method='PATCH',
location_id='b5f6bb4f-8d1e-4d79-8d11-4c9172c99c35',
version='5.0-preview.1',
route_values=route_values,
content=content,
media_type='application/json-patch+json')
def create_comment(self, comment, repository_id, pull_request_id, thread_id, project=None):
"""CreateComment.
Create a comment on a specific thread in a pull request.
:param :class:`<Comment> <azure.devops.v5_0.git.models.Comment>` comment: The comment to create.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:param int thread_id: ID of the thread that the desired comment is in.
:param str project: Project ID or project name
:rtype: :class:`<Comment> <azure.devops.v5_0.git.models.Comment>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if thread_id is not None:
route_values['threadId'] = self._serialize.url('thread_id', thread_id, 'int')
content = self._serialize.body(comment, 'Comment')
response = self._send(http_method='POST',
location_id='965a3ec7-5ed8-455a-bdcb-835a5ea7fe7b',
version='5.0',
route_values=route_values,
content=content)
return self._deserialize('Comment', response)
def delete_comment(self, repository_id, pull_request_id, thread_id, comment_id, project=None):
"""DeleteComment.
Delete a comment associated with a specific thread in a pull request.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:param int thread_id: ID of the thread that the desired comment is in.
:param int comment_id: ID of the comment.
:param str project: Project ID or project name
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if thread_id is not None:
route_values['threadId'] = self._serialize.url('thread_id', thread_id, 'int')
if comment_id is not None:
route_values['commentId'] = self._serialize.url('comment_id', comment_id, 'int')
self._send(http_method='DELETE',
location_id='965a3ec7-5ed8-455a-bdcb-835a5ea7fe7b',
version='5.0',
route_values=route_values)
def get_comment(self, repository_id, pull_request_id, thread_id, comment_id, project=None):
"""GetComment.
Retrieve a comment associated with a specific thread in a pull request.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:param int thread_id: ID of the thread that the desired comment is in.
:param int comment_id: ID of the comment.
:param str project: Project ID or project name
:rtype: :class:`<Comment> <azure.devops.v5_0.git.models.Comment>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if thread_id is not None:
route_values['threadId'] = self._serialize.url('thread_id', thread_id, 'int')
if comment_id is not None:
route_values['commentId'] = self._serialize.url('comment_id', comment_id, 'int')
response = self._send(http_method='GET',
location_id='965a3ec7-5ed8-455a-bdcb-835a5ea7fe7b',
version='5.0',
route_values=route_values)
return self._deserialize('Comment', response)
def get_comments(self, repository_id, pull_request_id, thread_id, project=None):
"""GetComments.
Retrieve all comments associated with a specific thread in a pull request.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:param int thread_id: ID of the thread.
:param str project: Project ID or project name
:rtype: [Comment]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if thread_id is not None:
route_values['threadId'] = self._serialize.url('thread_id', thread_id, 'int')
response = self._send(http_method='GET',
location_id='965a3ec7-5ed8-455a-bdcb-835a5ea7fe7b',
version='5.0',
route_values=route_values)
return self._deserialize('[Comment]', self._unwrap_collection(response))
def update_comment(self, comment, repository_id, pull_request_id, thread_id, comment_id, project=None):
"""UpdateComment.
Update a comment associated with a specific thread in a pull request.
:param :class:`<Comment> <azure.devops.v5_0.git.models.Comment>` comment: The comment content that should be updated.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:param int thread_id: ID of the thread that the desired comment is in.
:param int comment_id: ID of the comment to update.
:param str project: Project ID or project name
:rtype: :class:`<Comment> <azure.devops.v5_0.git.models.Comment>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if thread_id is not None:
route_values['threadId'] = self._serialize.url('thread_id', thread_id, 'int')
if comment_id is not None:
route_values['commentId'] = self._serialize.url('comment_id', comment_id, 'int')
content = self._serialize.body(comment, 'Comment')
response = self._send(http_method='PATCH',
location_id='965a3ec7-5ed8-455a-bdcb-835a5ea7fe7b',
version='5.0',
route_values=route_values,
content=content)
return self._deserialize('Comment', response)
def create_thread(self, comment_thread, repository_id, pull_request_id, project=None):
"""CreateThread.
Create a thread in a pull request.
:param :class:`<GitPullRequestCommentThread> <azure.devops.v5_0.git.models.GitPullRequestCommentThread>` comment_thread: The thread to create. Thread must contain at least one comment.
:param str repository_id: Repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:rtype: :class:`<GitPullRequestCommentThread> <azure.devops.v5_0.git.models.GitPullRequestCommentThread>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
content = self._serialize.body(comment_thread, 'GitPullRequestCommentThread')
response = self._send(http_method='POST',
location_id='ab6e2e5d-a0b7-4153-b64a-a4efe0d49449',
version='5.0',
route_values=route_values,
content=content)
return self._deserialize('GitPullRequestCommentThread', response)
def get_pull_request_thread(self, repository_id, pull_request_id, thread_id, project=None, iteration=None, base_iteration=None):
"""GetPullRequestThread.
Retrieve a thread in a pull request.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:param int thread_id: ID of the thread.
:param str project: Project ID or project name
:param int iteration: If specified, thread position will be tracked using this iteration as the right side of the diff.
:param int base_iteration: If specified, thread position will be tracked using this iteration as the left side of the diff.
:rtype: :class:`<GitPullRequestCommentThread> <azure.devops.v5_0.git.models.GitPullRequestCommentThread>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if thread_id is not None:
route_values['threadId'] = self._serialize.url('thread_id', thread_id, 'int')
query_parameters = {}
if iteration is not None:
query_parameters['$iteration'] = self._serialize.query('iteration', iteration, 'int')
if base_iteration is not None:
query_parameters['$baseIteration'] = self._serialize.query('base_iteration', base_iteration, 'int')
response = self._send(http_method='GET',
location_id='ab6e2e5d-a0b7-4153-b64a-a4efe0d49449',
version='5.0',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('GitPullRequestCommentThread', response)
def get_threads(self, repository_id, pull_request_id, project=None, iteration=None, base_iteration=None):
"""GetThreads.
Retrieve all threads in a pull request.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:param int iteration: If specified, thread positions will be tracked using this iteration as the right side of the diff.
:param int base_iteration: If specified, thread positions will be tracked using this iteration as the left side of the diff.
:rtype: [GitPullRequestCommentThread]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
query_parameters = {}
if iteration is not None:
query_parameters['$iteration'] = self._serialize.query('iteration', iteration, 'int')
if base_iteration is not None:
query_parameters['$baseIteration'] = self._serialize.query('base_iteration', base_iteration, 'int')
response = self._send(http_method='GET',
location_id='ab6e2e5d-a0b7-4153-b64a-a4efe0d49449',
version='5.0',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitPullRequestCommentThread]', self._unwrap_collection(response))
def update_thread(self, comment_thread, repository_id, pull_request_id, thread_id, project=None):
"""UpdateThread.
Update a thread in a pull request.
:param :class:`<GitPullRequestCommentThread> <azure.devops.v5_0.git.models.GitPullRequestCommentThread>` comment_thread: The thread content that should be updated.
:param str repository_id: The repository ID of the pull request's target branch.
:param int pull_request_id: ID of the pull request.
:param int thread_id: ID of the thread to update.
:param str project: Project ID or project name
:rtype: :class:`<GitPullRequestCommentThread> <azure.devops.v5_0.git.models.GitPullRequestCommentThread>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
if thread_id is not None:
route_values['threadId'] = self._serialize.url('thread_id', thread_id, 'int')
content = self._serialize.body(comment_thread, 'GitPullRequestCommentThread')
response = self._send(http_method='PATCH',
location_id='ab6e2e5d-a0b7-4153-b64a-a4efe0d49449',
version='5.0',
route_values=route_values,
content=content)
return self._deserialize('GitPullRequestCommentThread', response)
def get_pull_request_work_item_refs(self, repository_id, pull_request_id, project=None):
"""GetPullRequestWorkItemRefs.
Retrieve a list of work items associated with a pull request.
:param str repository_id: ID or name of the repository.
:param int pull_request_id: ID of the pull request.
:param str project: Project ID or project name
:rtype: [ResourceRef]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if pull_request_id is not None:
route_values['pullRequestId'] = self._serialize.url('pull_request_id', pull_request_id, 'int')
response = self._send(http_method='GET',
location_id='0a637fcc-5370-4ce8-b0e8-98091f5f9482',
version='5.0',
route_values=route_values)
return self._deserialize('[ResourceRef]', self._unwrap_collection(response))
def create_push(self, push, repository_id, project=None):
"""CreatePush.
Push changes to the repository.
:param :class:`<GitPush> <azure.devops.v5_0.git.models.GitPush>` push:
:param str repository_id: The name or ID of the repository.
:param str project: Project ID or project name
:rtype: :class:`<GitPush> <azure.devops.v5_0.git.models.GitPush>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
content = self._serialize.body(push, 'GitPush')
response = self._send(http_method='POST',
location_id='ea98d07b-3c87-4971-8ede-a613694ffb55',
version='5.0',
route_values=route_values,
content=content)
return self._deserialize('GitPush', response)
def get_push(self, repository_id, push_id, project=None, include_commits=None, include_ref_updates=None):
"""GetPush.
Retrieves a particular push.
:param str repository_id: The name or ID of the repository.
:param int push_id: ID of the push.
:param str project: Project ID or project name
:param int include_commits: The number of commits to include in the result.
:param bool include_ref_updates: If true, include the list of refs that were updated by the push.
:rtype: :class:`<GitPush> <azure.devops.v5_0.git.models.GitPush>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if push_id is not None:
route_values['pushId'] = self._serialize.url('push_id', push_id, 'int')
query_parameters = {}
if include_commits is not None:
query_parameters['includeCommits'] = self._serialize.query('include_commits', include_commits, 'int')
if include_ref_updates is not None:
query_parameters['includeRefUpdates'] = self._serialize.query('include_ref_updates', include_ref_updates, 'bool')
response = self._send(http_method='GET',
location_id='ea98d07b-3c87-4971-8ede-a613694ffb55',
version='5.0',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('GitPush', response)
def get_pushes(self, repository_id, project=None, skip=None, top=None, search_criteria=None):
"""GetPushes.
Retrieves pushes associated with the specified repository.
:param str repository_id: The name or ID of the repository.
:param str project: Project ID or project name
:param int skip: Number of pushes to skip.
:param int top: Number of pushes to return.
:param :class:`<GitPushSearchCriteria> <azure.devops.v5_0.git.models.GitPushSearchCriteria>` search_criteria: Search criteria attributes: fromDate, toDate, pusherId, refName, includeRefUpdates or includeLinks. fromDate: Start date to search from. toDate: End date to search to. pusherId: Identity of the person who submitted the push. refName: Branch name to consider. includeRefUpdates: If true, include the list of refs that were updated by the push. includeLinks: Whether to include the _links field on the shallow references.
:rtype: [GitPush]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if skip is not None:
query_parameters['$skip'] = self._serialize.query('skip', skip, 'int')
if top is not None:
query_parameters['$top'] = self._serialize.query('top', top, 'int')
if search_criteria is not None:
if search_criteria.from_date is not None:
query_parameters['searchCriteria.fromDate'] = search_criteria.from_date
if search_criteria.to_date is not None:
query_parameters['searchCriteria.toDate'] = search_criteria.to_date
if search_criteria.pusher_id is not None:
query_parameters['searchCriteria.pusherId'] = search_criteria.pusher_id
if search_criteria.ref_name is not None:
query_parameters['searchCriteria.refName'] = search_criteria.ref_name
if search_criteria.include_ref_updates is not None:
query_parameters['searchCriteria.includeRefUpdates'] = search_criteria.include_ref_updates
if search_criteria.include_links is not None:
query_parameters['searchCriteria.includeLinks'] = search_criteria.include_links
response = self._send(http_method='GET',
location_id='ea98d07b-3c87-4971-8ede-a613694ffb55',
version='5.0',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitPush]', self._unwrap_collection(response))
def delete_repository_from_recycle_bin(self, project, repository_id):
"""DeleteRepositoryFromRecycleBin.
[Preview API] Destroy (hard delete) a soft-deleted Git repository.
:param str project: Project ID or project name
:param str repository_id: The ID of the repository.
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
self._send(http_method='DELETE',
location_id='a663da97-81db-4eb3-8b83-287670f63073',
version='5.0-preview.1',
route_values=route_values)
def get_recycle_bin_repositories(self, project):
"""GetRecycleBinRepositories.
[Preview API] Retrieve soft-deleted git repositories from the recycle bin.
:param str project: Project ID or project name
:rtype: [GitDeletedRepository]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
response = self._send(http_method='GET',
location_id='a663da97-81db-4eb3-8b83-287670f63073',
version='5.0-preview.1',
route_values=route_values)
return self._deserialize('[GitDeletedRepository]', self._unwrap_collection(response))
def restore_repository_from_recycle_bin(self, repository_details, project, repository_id):
"""RestoreRepositoryFromRecycleBin.
[Preview API] Recover a soft-deleted Git repository. Recently deleted repositories go into a soft-delete state for a period of time before they are hard deleted and become unrecoverable.
:param :class:`<GitRecycleBinRepositoryDetails> <azure.devops.v5_0.git.models.GitRecycleBinRepositoryDetails>` repository_details:
:param str project: Project ID or project name
:param str repository_id: The ID of the repository.
:rtype: :class:`<GitRepository> <azure.devops.v5_0.git.models.GitRepository>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
content = self._serialize.body(repository_details, 'GitRecycleBinRepositoryDetails')
response = self._send(http_method='PATCH',
location_id='a663da97-81db-4eb3-8b83-287670f63073',
version='5.0-preview.1',
route_values=route_values,
content=content)
return self._deserialize('GitRepository', response)
def get_refs(self, repository_id, project=None, filter=None, include_links=None, include_statuses=None, include_my_branches=None, latest_statuses_only=None, peel_tags=None, filter_contains=None):
"""GetRefs.
Queries the provided repository for its refs and returns them.
:param str repository_id: The name or ID of the repository.
:param str project: Project ID or project name
:param str filter: [optional] A filter to apply to the refs (starts with).
:param bool include_links: [optional] Specifies if referenceLinks should be included in the result. default is false.
:param bool include_statuses: [optional] Includes up to the first 1000 commit statuses for each ref. The default value is false.
:param bool include_my_branches: [optional] Includes only branches that the user owns, the branches the user favorites, and the default branch. The default value is false. Cannot be combined with the filter parameter.
:param bool latest_statuses_only: [optional] True to include only the tip commit status for each ref. This option requires `includeStatuses` to be true. The default value is false.
:param bool peel_tags: [optional] Annotated tags will populate the PeeledObjectId property. default is false.
:param str filter_contains: [optional] A filter to apply to the refs (contains).
:rtype: [GitRef]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query('filter', filter, 'str')
if include_links is not None:
query_parameters['includeLinks'] = self._serialize.query('include_links', include_links, 'bool')
if include_statuses is not None:
query_parameters['includeStatuses'] = self._serialize.query('include_statuses', include_statuses, 'bool')
if include_my_branches is not None:
query_parameters['includeMyBranches'] = self._serialize.query('include_my_branches', include_my_branches, 'bool')
if latest_statuses_only is not None:
query_parameters['latestStatusesOnly'] = self._serialize.query('latest_statuses_only', latest_statuses_only, 'bool')
if peel_tags is not None:
query_parameters['peelTags'] = self._serialize.query('peel_tags', peel_tags, 'bool')
if filter_contains is not None:
query_parameters['filterContains'] = self._serialize.query('filter_contains', filter_contains, 'str')
response = self._send(http_method='GET',
location_id='2d874a60-a811-4f62-9c9f-963a6ea0a55b',
version='5.0',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitRef]', self._unwrap_collection(response))
def update_ref(self, new_ref_info, repository_id, filter, project=None, project_id=None):
"""UpdateRef.
Lock or Unlock a branch.
:param :class:`<GitRefUpdate> <azure.devops.v5_0.git.models.GitRefUpdate>` new_ref_info: The ref update action (lock/unlock) to perform
:param str repository_id: The name or ID of the repository.
:param str filter: The name of the branch to lock/unlock
:param str project: Project ID or project name
:param str project_id: ID or name of the team project. Optional if specifying an ID for repository.
:rtype: :class:`<GitRef> <azure.devops.v5_0.git.models.GitRef>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if filter is not None:
query_parameters['filter'] = self._serialize.query('filter', filter, 'str')
if project_id is not None:
query_parameters['projectId'] = self._serialize.query('project_id', project_id, 'str')
content = self._serialize.body(new_ref_info, 'GitRefUpdate')
response = self._send(http_method='PATCH',
location_id='2d874a60-a811-4f62-9c9f-963a6ea0a55b',
version='5.0',
route_values=route_values,
query_parameters=query_parameters,
content=content)
return self._deserialize('GitRef', response)
def update_refs(self, ref_updates, repository_id, project=None, project_id=None):
"""UpdateRefs.
Creating, updating, or deleting refs(branches).
:param [GitRefUpdate] ref_updates: List of ref updates to attempt to perform
:param str repository_id: The name or ID of the repository.
:param str project: Project ID or project name
:param str project_id: ID or name of the team project. Optional if specifying an ID for repository.
:rtype: [GitRefUpdateResult]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if project_id is not None:
query_parameters['projectId'] = self._serialize.query('project_id', project_id, 'str')
content = self._serialize.body(ref_updates, '[GitRefUpdate]')
response = self._send(http_method='POST',
location_id='2d874a60-a811-4f62-9c9f-963a6ea0a55b',
version='5.0',
route_values=route_values,
query_parameters=query_parameters,
content=content)
return self._deserialize('[GitRefUpdateResult]', self._unwrap_collection(response))
def create_favorite(self, favorite, project):
"""CreateFavorite.
[Preview API] Creates a ref favorite
:param :class:`<GitRefFavorite> <azure.devops.v5_0.git.models.GitRefFavorite>` favorite: The ref favorite to create.
:param str project: Project ID or project name
:rtype: :class:`<GitRefFavorite> <azure.devops.v5_0.git.models.GitRefFavorite>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
content = self._serialize.body(favorite, 'GitRefFavorite')
response = self._send(http_method='POST',
location_id='876f70af-5792-485a-a1c7-d0a7b2f42bbb',
version='5.0-preview.1',
route_values=route_values,
content=content)
return self._deserialize('GitRefFavorite', response)
def delete_ref_favorite(self, project, favorite_id):
"""DeleteRefFavorite.
[Preview API] Deletes the refs favorite specified
:param str project: Project ID or project name
:param int favorite_id: The Id of the ref favorite to delete.
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if favorite_id is not None:
route_values['favoriteId'] = self._serialize.url('favorite_id', favorite_id, 'int')
self._send(http_method='DELETE',
location_id='876f70af-5792-485a-a1c7-d0a7b2f42bbb',
version='5.0-preview.1',
route_values=route_values)
def get_ref_favorite(self, project, favorite_id):
"""GetRefFavorite.
[Preview API] Gets the refs favorite for a favorite Id.
:param str project: Project ID or project name
:param int favorite_id: The Id of the requested ref favorite.
:rtype: :class:`<GitRefFavorite> <azure.devops.v5_0.git.models.GitRefFavorite>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if favorite_id is not None:
route_values['favoriteId'] = self._serialize.url('favorite_id', favorite_id, 'int')
response = self._send(http_method='GET',
location_id='876f70af-5792-485a-a1c7-d0a7b2f42bbb',
version='5.0-preview.1',
route_values=route_values)
return self._deserialize('GitRefFavorite', response)
def get_ref_favorites(self, project, repository_id=None, identity_id=None):
"""GetRefFavorites.
[Preview API] Gets the refs favorites for a repo and an identity.
:param str project: Project ID or project name
:param str repository_id: The id of the repository.
:param str identity_id: The id of the identity whose favorites are to be retrieved. If null, the requesting identity is used.
:rtype: [GitRefFavorite]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
query_parameters = {}
if repository_id is not None:
query_parameters['repositoryId'] = self._serialize.query('repository_id', repository_id, 'str')
if identity_id is not None:
query_parameters['identityId'] = self._serialize.query('identity_id', identity_id, 'str')
response = self._send(http_method='GET',
location_id='876f70af-5792-485a-a1c7-d0a7b2f42bbb',
version='5.0-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitRefFavorite]', self._unwrap_collection(response))
def create_repository(self, git_repository_to_create, project=None, source_ref=None):
"""CreateRepository.
Create a git repository in a team project.
:param :class:`<GitRepositoryCreateOptions> <azure.devops.v5_0.git.models.GitRepositoryCreateOptions>` git_repository_to_create: Specify the repo name, team project and/or parent repository. Team project information can be ommitted from gitRepositoryToCreate if the request is project-scoped (i.e., includes project Id).
:param str project: Project ID or project name
:param str source_ref: [optional] Specify the source refs to use while creating a fork repo
:rtype: :class:`<GitRepository> <azure.devops.v5_0.git.models.GitRepository>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
query_parameters = {}
if source_ref is not None:
query_parameters['sourceRef'] = self._serialize.query('source_ref', source_ref, 'str')
content = self._serialize.body(git_repository_to_create, 'GitRepositoryCreateOptions')
response = self._send(http_method='POST',
location_id='225f7195-f9c7-4d14-ab28-a83f7ff77e1f',
version='5.0',
route_values=route_values,
query_parameters=query_parameters,
content=content)
return self._deserialize('GitRepository', response)
def delete_repository(self, repository_id, project=None):
"""DeleteRepository.
Delete a git repository
:param str repository_id: The name or ID of the repository.
:param str project: Project ID or project name
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
self._send(http_method='DELETE',
location_id='225f7195-f9c7-4d14-ab28-a83f7ff77e1f',
version='5.0',
route_values=route_values)
def get_repositories(self, project=None, include_links=None, include_all_urls=None, include_hidden=None):
"""GetRepositories.
Retrieve git repositories.
:param str project: Project ID or project name
:param bool include_links: [optional] True to include reference links. The default value is false.
:param bool include_all_urls: [optional] True to include all remote URLs. The default value is false.
:param bool include_hidden: [optional] True to include hidden repositories. The default value is false.
:rtype: [GitRepository]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
query_parameters = {}
if include_links is not None:
query_parameters['includeLinks'] = self._serialize.query('include_links', include_links, 'bool')
if include_all_urls is not None:
query_parameters['includeAllUrls'] = self._serialize.query('include_all_urls', include_all_urls, 'bool')
if include_hidden is not None:
query_parameters['includeHidden'] = self._serialize.query('include_hidden', include_hidden, 'bool')
response = self._send(http_method='GET',
location_id='225f7195-f9c7-4d14-ab28-a83f7ff77e1f',
version='5.0',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitRepository]', self._unwrap_collection(response))
def get_repository(self, repository_id, project=None):
"""GetRepository.
Retrieve a git repository.
:param str repository_id: The name or ID of the repository.
:param str project: Project ID or project name
:rtype: :class:`<GitRepository> <azure.devops.v5_0.git.models.GitRepository>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
response = self._send(http_method='GET',
location_id='225f7195-f9c7-4d14-ab28-a83f7ff77e1f',
version='5.0',
route_values=route_values)
return self._deserialize('GitRepository', response)
def get_repository_with_parent(self, repository_id, include_parent, project=None):
"""GetRepositoryWithParent.
Retrieve a git repository.
:param str repository_id: The name or ID of the repository.
:param bool include_parent: True to include parent repository. Only available in authenticated calls.
:param str project: Project ID or project name
:rtype: :class:`<GitRepository> <azure.devops.v5_0.git.models.GitRepository>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if include_parent is not None:
query_parameters['includeParent'] = self._serialize.query('include_parent', include_parent, 'bool')
response = self._send(http_method='GET',
location_id='225f7195-f9c7-4d14-ab28-a83f7ff77e1f',
version='5.0',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('GitRepository', response)
def update_repository(self, new_repository_info, repository_id, project=None):
"""UpdateRepository.
Updates the Git repository with either a new repo name or a new default branch.
:param :class:`<GitRepository> <azure.devops.v5_0.git.models.GitRepository>` new_repository_info: Specify a new repo name or a new default branch of the repository
:param str repository_id: The name or ID of the repository.
:param str project: Project ID or project name
:rtype: :class:`<GitRepository> <azure.devops.v5_0.git.models.GitRepository>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
content = self._serialize.body(new_repository_info, 'GitRepository')
response = self._send(http_method='PATCH',
location_id='225f7195-f9c7-4d14-ab28-a83f7ff77e1f',
version='5.0',
route_values=route_values,
content=content)
return self._deserialize('GitRepository', response)
def create_revert(self, revert_to_create, project, repository_id):
"""CreateRevert.
[Preview API] Starts the operation to create a new branch which reverts changes introduced by either a specific commit or commits that are associated to a pull request.
:param :class:`<GitAsyncRefOperationParameters> <azure.devops.v5_0.git.models.GitAsyncRefOperationParameters>` revert_to_create:
:param str project: Project ID or project name
:param str repository_id: ID of the repository.
:rtype: :class:`<GitRevert> <azure.devops.v5_0.git.models.GitRevert>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
content = self._serialize.body(revert_to_create, 'GitAsyncRefOperationParameters')
response = self._send(http_method='POST',
location_id='bc866058-5449-4715-9cf1-a510b6ff193c',
version='5.0-preview.1',
route_values=route_values,
content=content)
return self._deserialize('GitRevert', response)
def get_revert(self, project, revert_id, repository_id):
"""GetRevert.
[Preview API] Retrieve information about a revert operation by revert Id.
:param str project: Project ID or project name
:param int revert_id: ID of the revert operation.
:param str repository_id: ID of the repository.
:rtype: :class:`<GitRevert> <azure.devops.v5_0.git.models.GitRevert>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if revert_id is not None:
route_values['revertId'] = self._serialize.url('revert_id', revert_id, 'int')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
response = self._send(http_method='GET',
location_id='bc866058-5449-4715-9cf1-a510b6ff193c',
version='5.0-preview.1',
route_values=route_values)
return self._deserialize('GitRevert', response)
def get_revert_for_ref_name(self, project, repository_id, ref_name):
"""GetRevertForRefName.
[Preview API] Retrieve information about a revert operation for a specific branch.
:param str project: Project ID or project name
:param str repository_id: ID of the repository.
:param str ref_name: The GitAsyncRefOperationParameters generatedRefName used for the revert operation.
:rtype: :class:`<GitRevert> <azure.devops.v5_0.git.models.GitRevert>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if ref_name is not None:
query_parameters['refName'] = self._serialize.query('ref_name', ref_name, 'str')
response = self._send(http_method='GET',
location_id='bc866058-5449-4715-9cf1-a510b6ff193c',
version='5.0-preview.1',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('GitRevert', response)
def create_commit_status(self, git_commit_status_to_create, commit_id, repository_id, project=None):
"""CreateCommitStatus.
Create Git commit status.
:param :class:`<GitStatus> <azure.devops.v5_0.git.models.GitStatus>` git_commit_status_to_create: Git commit status object to create.
:param str commit_id: ID of the Git commit.
:param str repository_id: ID of the repository.
:param str project: Project ID or project name
:rtype: :class:`<GitStatus> <azure.devops.v5_0.git.models.GitStatus>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if commit_id is not None:
route_values['commitId'] = self._serialize.url('commit_id', commit_id, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
content = self._serialize.body(git_commit_status_to_create, 'GitStatus')
response = self._send(http_method='POST',
location_id='428dd4fb-fda5-4722-af02-9313b80305da',
version='5.0',
route_values=route_values,
content=content)
return self._deserialize('GitStatus', response)
def get_statuses(self, commit_id, repository_id, project=None, top=None, skip=None, latest_only=None):
"""GetStatuses.
Get statuses associated with the Git commit.
:param str commit_id: ID of the Git commit.
:param str repository_id: ID of the repository.
:param str project: Project ID or project name
:param int top: Optional. The number of statuses to retrieve. Default is 1000.
:param int skip: Optional. The number of statuses to ignore. Default is 0. For example, to retrieve results 101-150, set top to 50 and skip to 100.
:param bool latest_only: The flag indicates whether to get only latest statuses grouped by `Context.Name` and `Context.Genre`.
:rtype: [GitStatus]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if commit_id is not None:
route_values['commitId'] = self._serialize.url('commit_id', commit_id, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
query_parameters = {}
if top is not None:
query_parameters['top'] = self._serialize.query('top', top, 'int')
if skip is not None:
query_parameters['skip'] = self._serialize.query('skip', skip, 'int')
if latest_only is not None:
query_parameters['latestOnly'] = self._serialize.query('latest_only', latest_only, 'bool')
response = self._send(http_method='GET',
location_id='428dd4fb-fda5-4722-af02-9313b80305da',
version='5.0',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('[GitStatus]', self._unwrap_collection(response))
def get_suggestions(self, repository_id, project=None):
"""GetSuggestions.
[Preview API] Retrieve a pull request suggestion for a particular repository or team project.
:param str repository_id: ID of the git repository.
:param str project: Project ID or project name
:rtype: [GitSuggestion]
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
response = self._send(http_method='GET',
location_id='9393b4fb-4445-4919-972b-9ad16f442d83',
version='5.0-preview.1',
route_values=route_values)
return self._deserialize('[GitSuggestion]', self._unwrap_collection(response))
def get_tree(self, repository_id, sha1, project=None, project_id=None, recursive=None, file_name=None):
"""GetTree.
The Tree endpoint returns the collection of objects underneath the specified tree. Trees are folders in a Git repository.
:param str repository_id: Repository Id.
:param str sha1: SHA1 hash of the tree object.
:param str project: Project ID or project name
:param str project_id: Project Id.
:param bool recursive: Search recursively. Include trees underneath this tree. Default is false.
:param str file_name: Name to use if a .zip file is returned. Default is the object ID.
:rtype: :class:`<GitTreeRef> <azure.devops.v5_0.git.models.GitTreeRef>`
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if sha1 is not None:
route_values['sha1'] = self._serialize.url('sha1', sha1, 'str')
query_parameters = {}
if project_id is not None:
query_parameters['projectId'] = self._serialize.query('project_id', project_id, 'str')
if recursive is not None:
query_parameters['recursive'] = self._serialize.query('recursive', recursive, 'bool')
if file_name is not None:
query_parameters['fileName'] = self._serialize.query('file_name', file_name, 'str')
response = self._send(http_method='GET',
location_id='729f6437-6f92-44ec-8bee-273a7111063c',
version='5.0',
route_values=route_values,
query_parameters=query_parameters)
return self._deserialize('GitTreeRef', response)
def get_tree_zip(self, repository_id, sha1, project=None, project_id=None, recursive=None, file_name=None, **kwargs):
"""GetTreeZip.
The Tree endpoint returns the collection of objects underneath the specified tree. Trees are folders in a Git repository.
:param str repository_id: Repository Id.
:param str sha1: SHA1 hash of the tree object.
:param str project: Project ID or project name
:param str project_id: Project Id.
:param bool recursive: Search recursively. Include trees underneath this tree. Default is false.
:param str file_name: Name to use if a .zip file is returned. Default is the object ID.
:rtype: object
"""
route_values = {}
if project is not None:
route_values['project'] = self._serialize.url('project', project, 'str')
if repository_id is not None:
route_values['repositoryId'] = self._serialize.url('repository_id', repository_id, 'str')
if sha1 is not None:
route_values['sha1'] = self._serialize.url('sha1', sha1, 'str')
query_parameters = {}
if project_id is not None:
query_parameters['projectId'] = self._serialize.query('project_id', project_id, 'str')
if recursive is not None:
query_parameters['recursive'] = self._serialize.query('recursive', recursive, 'bool')
if file_name is not None:
query_parameters['fileName'] = self._serialize.query('file_name', file_name, 'str')
response = self._send(http_method='GET',
location_id='729f6437-6f92-44ec-8bee-273a7111063c',
version='5.0',
route_values=route_values,
query_parameters=query_parameters,
accept_media_type='application/zip')
if "callback" in kwargs:
callback = kwargs["callback"]
else:
callback = None
return self._client.stream_download(response, callback=callback) | |
Image.tsx | /*
* Copyright (C) 2005-2022 SplendidCRM Software, Inc.
* MIT License
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*/
// 1. React and fabric.
import * as React from 'react';
// 2. Store and Types.
// 3. Scripts.
import Sql from '../scripts/Sql';
| interface IImageProps
{
row : any;
layout: any;
}
class Image extends React.PureComponent<IImageProps>
{
public render()
{
const { layout, row } = this.props;
let DATA_FIELD = Sql.ToString(layout.DATA_FIELD);
if ( layout == null )
{
return (<div>layout prop is null</div>);
}
else if ( Sql.IsEmptyString(DATA_FIELD) )
{
return (<div>DATA_FIELD is empty for FIELD_INDEX { layout.FIELD_INDEX }</div>);
}
else
{
// 11/03/2018 Paul. Image not supported at this time.
return null;
}
}
}
export default Image; | // 4. Components and Views.
|
commands.go | package redis
import (
"errors"
"io"
"time"
"github.com/hustfisher/redis/internal"
)
// SlotStatusMigrating SlotStatusStable status for cmd SlotsSetSlot
const (
SlotStatusMigrating = "migrating"
SlotStatusStable = "stable"
)
func usePrecise(dur time.Duration) bool {
return dur < time.Second || dur%time.Second != 0
}
func formatMs(dur time.Duration) int64 {
if dur > 0 && dur < time.Millisecond {
internal.Logger.Printf(
"specified duration is %s, but minimal supported value is %s",
dur, time.Millisecond,
)
}
return int64(dur / time.Millisecond)
}
func formatSec(dur time.Duration) int64 {
if dur > 0 && dur < time.Second {
internal.Logger.Printf(
"specified duration is %s, but minimal supported value is %s",
dur, time.Second,
)
}
return int64(dur / time.Second)
}
func appendArgs(dst, src []interface{}) []interface{} {
if len(src) == 1 {
if ss, ok := src[0].([]string); ok {
for _, s := range ss {
dst = append(dst, s)
}
return dst
}
}
for _, v := range src {
dst = append(dst, v)
}
return dst
}
type Cmdable interface {
Pipeline() Pipeliner
Pipelined(fn func(Pipeliner) error) ([]Cmder, error)
TxPipelined(fn func(Pipeliner) error) ([]Cmder, error)
TxPipeline() Pipeliner
Command() *CommandsInfoCmd
ClientGetName() *StringCmd
Echo(message interface{}) *StringCmd
Ping() *StatusCmd
Quit() *StatusCmd
Del(keys ...string) *IntCmd
Unlink(keys ...string) *IntCmd
Dump(key string) *StringCmd
Exists(keys ...string) *IntCmd
Expire(key string, expiration time.Duration) *BoolCmd
ExpireAt(key string, tm time.Time) *BoolCmd
Keys(pattern string) *StringSliceCmd
Migrate(host, port, key string, db int, timeout time.Duration) *StatusCmd
Move(key string, db int) *BoolCmd
ObjectRefCount(key string) *IntCmd
ObjectEncoding(key string) *StringCmd
ObjectIdleTime(key string) *DurationCmd
Persist(key string) *BoolCmd
PExpire(key string, expiration time.Duration) *BoolCmd
PExpireAt(key string, tm time.Time) *BoolCmd
PTTL(key string) *DurationCmd
RandomKey() *StringCmd
Rename(key, newkey string) *StatusCmd
RenameNX(key, newkey string) *BoolCmd
Restore(key string, ttl time.Duration, value string) *StatusCmd
RestoreReplace(key string, ttl time.Duration, value string) *StatusCmd
Sort(key string, sort *Sort) *StringSliceCmd
SortStore(key, store string, sort *Sort) *IntCmd
SortInterfaces(key string, sort *Sort) *SliceCmd
Touch(keys ...string) *IntCmd
TTL(key string) *DurationCmd
Type(key string) *StatusCmd
Scan(cursor uint64, match string, count int64) *ScanCmd
SScan(key string, cursor uint64, match string, count int64) *ScanCmd
HScan(key string, cursor uint64, match string, count int64) *ScanCmd
ZScan(key string, cursor uint64, match string, count int64) *ScanCmd
Append(key, value string) *IntCmd
BitCount(key string, bitCount *BitCount) *IntCmd
BitOpAnd(destKey string, keys ...string) *IntCmd
BitOpOr(destKey string, keys ...string) *IntCmd
BitOpXor(destKey string, keys ...string) *IntCmd
BitOpNot(destKey string, key string) *IntCmd
BitPos(key string, bit int64, pos ...int64) *IntCmd
BitField(key string, args ...interface{}) *IntSliceCmd
Decr(key string) *IntCmd
DecrBy(key string, decrement int64) *IntCmd
Get(key string) *StringCmd
GetBit(key string, offset int64) *IntCmd
GetRange(key string, start, end int64) *StringCmd
GetSet(key string, value interface{}) *StringCmd
Incr(key string) *IntCmd
IncrBy(key string, value int64) *IntCmd
IncrByFloat(key string, value float64) *FloatCmd
MGet(keys ...string) *SliceCmd
MSet(pairs ...interface{}) *StatusCmd
MSetNX(pairs ...interface{}) *BoolCmd
Set(key string, value interface{}, expiration time.Duration) *StatusCmd
SetBit(key string, offset int64, value int) *IntCmd
SetNX(key string, value interface{}, expiration time.Duration) *BoolCmd
SetXX(key string, value interface{}, expiration time.Duration) *BoolCmd
SetRange(key string, offset int64, value string) *IntCmd
StrLen(key string) *IntCmd
HDel(key string, fields ...string) *IntCmd
HExists(key, field string) *BoolCmd
HGet(key, field string) *StringCmd
HGetAll(key string) *StringStringMapCmd
HIncrBy(key, field string, incr int64) *IntCmd
HIncrByFloat(key, field string, incr float64) *FloatCmd
HKeys(key string) *StringSliceCmd
HLen(key string) *IntCmd
HMGet(key string, fields ...string) *SliceCmd
HMSet(key string, fields map[string]interface{}) *StatusCmd
HSet(key, field string, value interface{}) *BoolCmd
HSetNX(key, field string, value interface{}) *BoolCmd
HVals(key string) *StringSliceCmd
BLPop(timeout time.Duration, keys ...string) *StringSliceCmd
BRPop(timeout time.Duration, keys ...string) *StringSliceCmd
BRPopLPush(source, destination string, timeout time.Duration) *StringCmd
LIndex(key string, index int64) *StringCmd
LInsert(key, op string, pivot, value interface{}) *IntCmd
LInsertBefore(key string, pivot, value interface{}) *IntCmd
LInsertAfter(key string, pivot, value interface{}) *IntCmd
LLen(key string) *IntCmd
LPop(key string) *StringCmd
LPush(key string, values ...interface{}) *IntCmd
LPushX(key string, value interface{}) *IntCmd
LRange(key string, start, stop int64) *StringSliceCmd
LRem(key string, count int64, value interface{}) *IntCmd
LSet(key string, index int64, value interface{}) *StatusCmd
LTrim(key string, start, stop int64) *StatusCmd
RPop(key string) *StringCmd
RPopLPush(source, destination string) *StringCmd
RPush(key string, values ...interface{}) *IntCmd
RPushX(key string, value interface{}) *IntCmd
SAdd(key string, members ...interface{}) *IntCmd
SCard(key string) *IntCmd
SDiff(keys ...string) *StringSliceCmd
SDiffStore(destination string, keys ...string) *IntCmd
SInter(keys ...string) *StringSliceCmd
SInterStore(destination string, keys ...string) *IntCmd
SIsMember(key string, member interface{}) *BoolCmd
SMembers(key string) *StringSliceCmd
SMembersMap(key string) *StringStructMapCmd
SMove(source, destination string, member interface{}) *BoolCmd
SPop(key string) *StringCmd
SPopN(key string, count int64) *StringSliceCmd
SRandMember(key string) *StringCmd
SRandMemberN(key string, count int64) *StringSliceCmd
SRem(key string, members ...interface{}) *IntCmd
SUnion(keys ...string) *StringSliceCmd
SUnionStore(destination string, keys ...string) *IntCmd
XAdd(a *XAddArgs) *StringCmd
XDel(stream string, ids ...string) *IntCmd
XLen(stream string) *IntCmd
XRange(stream, start, stop string) *XMessageSliceCmd
XRangeN(stream, start, stop string, count int64) *XMessageSliceCmd
XRevRange(stream string, start, stop string) *XMessageSliceCmd
XRevRangeN(stream string, start, stop string, count int64) *XMessageSliceCmd
XRead(a *XReadArgs) *XStreamSliceCmd
XReadStreams(streams ...string) *XStreamSliceCmd
XGroupCreate(stream, group, start string) *StatusCmd
XGroupCreateMkStream(stream, group, start string) *StatusCmd
XGroupSetID(stream, group, start string) *StatusCmd
XGroupDestroy(stream, group string) *IntCmd
XGroupDelConsumer(stream, group, consumer string) *IntCmd
XReadGroup(a *XReadGroupArgs) *XStreamSliceCmd
XAck(stream, group string, ids ...string) *IntCmd
XPending(stream, group string) *XPendingCmd
XPendingExt(a *XPendingExtArgs) *XPendingExtCmd
XClaim(a *XClaimArgs) *XMessageSliceCmd
XClaimJustID(a *XClaimArgs) *StringSliceCmd
XTrim(key string, maxLen int64) *IntCmd
XTrimApprox(key string, maxLen int64) *IntCmd
BZPopMax(timeout time.Duration, keys ...string) *ZWithKeyCmd
BZPopMin(timeout time.Duration, keys ...string) *ZWithKeyCmd
ZAdd(key string, members ...*Z) *IntCmd
ZAddNX(key string, members ...*Z) *IntCmd
ZAddXX(key string, members ...*Z) *IntCmd
ZAddCh(key string, members ...*Z) *IntCmd
ZAddNXCh(key string, members ...*Z) *IntCmd
ZAddXXCh(key string, members ...*Z) *IntCmd
ZIncr(key string, member *Z) *FloatCmd
ZIncrNX(key string, member *Z) *FloatCmd
ZIncrXX(key string, member *Z) *FloatCmd
ZCard(key string) *IntCmd
ZCount(key, min, max string) *IntCmd
ZLexCount(key, min, max string) *IntCmd
ZIncrBy(key string, increment float64, member string) *FloatCmd
ZInterStore(destination string, store *ZStore, keys ...string) *IntCmd
ZPopMax(key string, count ...int64) *ZSliceCmd
ZPopMin(key string, count ...int64) *ZSliceCmd
ZRange(key string, start, stop int64) *StringSliceCmd
ZRangeWithScores(key string, start, stop int64) *ZSliceCmd
ZRangeByScore(key string, opt *ZRangeBy) *StringSliceCmd
ZRangeByLex(key string, opt *ZRangeBy) *StringSliceCmd
ZRangeByScoreWithScores(key string, opt *ZRangeBy) *ZSliceCmd
ZRank(key, member string) *IntCmd
ZRem(key string, members ...interface{}) *IntCmd
ZRemRangeByRank(key string, start, stop int64) *IntCmd
ZRemRangeByScore(key, min, max string) *IntCmd
ZRemRangeByLex(key, min, max string) *IntCmd
ZRevRange(key string, start, stop int64) *StringSliceCmd
ZRevRangeWithScores(key string, start, stop int64) *ZSliceCmd
ZRevRangeByScore(key string, opt *ZRangeBy) *StringSliceCmd
ZRevRangeByLex(key string, opt *ZRangeBy) *StringSliceCmd
ZRevRangeByScoreWithScores(key string, opt *ZRangeBy) *ZSliceCmd
ZRevRank(key, member string) *IntCmd
ZScore(key, member string) *FloatCmd
ZUnionStore(dest string, store *ZStore, keys ...string) *IntCmd
PFAdd(key string, els ...interface{}) *IntCmd
PFCount(keys ...string) *IntCmd
PFMerge(dest string, keys ...string) *StatusCmd
BgRewriteAOF() *StatusCmd
BgSave() *StatusCmd
ClientKill(ipPort string) *StatusCmd
ClientKillByFilter(keys ...string) *IntCmd
ClientList() *StringCmd
ClientPause(dur time.Duration) *BoolCmd
ClientID() *IntCmd
ConfigGet(parameter string) *SliceCmd
ConfigResetStat() *StatusCmd
ConfigSet(parameter, value string) *StatusCmd
ConfigRewrite() *StatusCmd
DBSize() *IntCmd
FlushAll() *StatusCmd
FlushAllAsync() *StatusCmd
FlushDB() *StatusCmd
FlushDBAsync() *StatusCmd
Info(section ...string) *StringCmd
LastSave() *IntCmd
Save() *StatusCmd
Shutdown() *StatusCmd
ShutdownSave() *StatusCmd
ShutdownNoSave() *StatusCmd
SlaveOf(host, port string) *StatusCmd
Time() *TimeCmd
Eval(script string, keys []string, args ...interface{}) *Cmd
EvalSha(sha1 string, keys []string, args ...interface{}) *Cmd
ScriptExists(hashes ...string) *BoolSliceCmd
ScriptFlush() *StatusCmd
ScriptKill() *StatusCmd
ScriptLoad(script string) *StringCmd
DebugObject(key string) *StringCmd
Publish(channel string, message interface{}) *IntCmd
PubSubChannels(pattern string) *StringSliceCmd
PubSubNumSub(channels ...string) *StringIntMapCmd
PubSubNumPat() *IntCmd
ClusterSlots() *ClusterSlotsCmd
ClusterNodes() *StringCmd
ClusterMeet(host, port string) *StatusCmd
ClusterForget(nodeID string) *StatusCmd
ClusterReplicate(nodeID string) *StatusCmd
ClusterResetSoft() *StatusCmd
ClusterResetHard() *StatusCmd
ClusterInfo() *StringCmd
ClusterKeySlot(key string) *IntCmd
ClusterGetKeysInSlot(slot int, count int) *StringSliceCmd
ClusterCountFailureReports(nodeID string) *IntCmd
ClusterCountKeysInSlot(slot int) *IntCmd
ClusterDelSlots(slots ...int) *StatusCmd
ClusterDelSlotsRange(min, max int) *StatusCmd
ClusterSaveConfig() *StatusCmd
ClusterSlaves(nodeID string) *StringSliceCmd
ClusterFailover() *StatusCmd
ClusterAddSlots(slots ...int) *StatusCmd
ClusterAddSlotsRange(min, max int) *StatusCmd
GeoAdd(key string, geoLocation ...*GeoLocation) *IntCmd
GeoPos(key string, members ...string) *GeoPosCmd
GeoRadius(key string, longitude, latitude float64, query *GeoRadiusQuery) *GeoLocationCmd
GeoRadiusRO(key string, longitude, latitude float64, query *GeoRadiusQuery) *GeoLocationCmd
GeoRadiusByMember(key, member string, query *GeoRadiusQuery) *GeoLocationCmd
GeoRadiusByMemberRO(key, member string, query *GeoRadiusQuery) *GeoLocationCmd
GeoDist(key string, member1, member2, unit string) *FloatCmd
GeoHash(key string, members ...string) *StringSliceCmd
ReadOnly() *StatusCmd
ReadWrite() *StatusCmd
MemoryUsage(key string, samples ...int) *IntCmd
// used for slots migrate
SlotsSetSlot(slot int, slotStatus string) *StatusCmd
SlotsMgrtSlot(host string, port int, timeoutInMills int, slot int, keyNum int64) *IntSliceCmd
SlotsHashKey(keys ...string) *IntSliceCmd
SlotsInfo(startSlot int, count int) *IntMatrixCmd
SlotsMgrtState(startSlot int, count int) *IntMatrixCmd
}
type StatefulCmdable interface {
Cmdable
Auth(password string) *StatusCmd
Select(index int) *StatusCmd
SwapDB(index1, index2 int) *StatusCmd
ClientSetName(name string) *BoolCmd
}
var _ Cmdable = (*Client)(nil)
var _ Cmdable = (*Tx)(nil)
var _ Cmdable = (*Ring)(nil)
var _ Cmdable = (*ClusterClient)(nil)
type cmdable func(cmd Cmder) error
type statefulCmdable func(cmd Cmder) error
//------------------------------------------------------------------------------
func (c statefulCmdable) Auth(password string) *StatusCmd {
cmd := NewStatusCmd("auth", password)
c(cmd)
return cmd
}
func (c cmdable) Echo(message interface{}) *StringCmd {
cmd := NewStringCmd("echo", message)
c(cmd)
return cmd
}
func (c cmdable) Ping() *StatusCmd {
cmd := NewStatusCmd("ping")
c(cmd)
return cmd
}
func (c cmdable) Wait(numSlaves int, timeout time.Duration) *IntCmd {
cmd := NewIntCmd("wait", numSlaves, int(timeout/time.Millisecond))
c(cmd)
return cmd
}
func (c cmdable) Quit() *StatusCmd {
panic("not implemented")
}
func (c statefulCmdable) Select(index int) *StatusCmd {
cmd := NewStatusCmd("select", index)
c(cmd)
return cmd
}
func (c statefulCmdable) SwapDB(index1, index2 int) *StatusCmd {
cmd := NewStatusCmd("swapdb", index1, index2)
c(cmd)
return cmd
}
//------------------------------------------------------------------------------
func (c cmdable) Command() *CommandsInfoCmd {
cmd := NewCommandsInfoCmd("command")
c(cmd)
return cmd
}
func (c cmdable) Del(keys ...string) *IntCmd {
args := make([]interface{}, 1+len(keys))
args[0] = "del"
for i, key := range keys {
args[1+i] = key
}
cmd := NewIntCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) Unlink(keys ...string) *IntCmd {
args := make([]interface{}, 1+len(keys))
args[0] = "unlink"
for i, key := range keys {
args[1+i] = key
}
cmd := NewIntCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) Dump(key string) *StringCmd {
cmd := NewStringCmd("dump", key)
c(cmd)
return cmd
}
func (c cmdable) Exists(keys ...string) *IntCmd {
args := make([]interface{}, 1+len(keys))
args[0] = "exists"
for i, key := range keys {
args[1+i] = key
}
cmd := NewIntCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) Expire(key string, expiration time.Duration) *BoolCmd {
cmd := NewBoolCmd("expire", key, formatSec(expiration))
c(cmd)
return cmd
}
func (c cmdable) ExpireAt(key string, tm time.Time) *BoolCmd {
cmd := NewBoolCmd("expireat", key, tm.Unix())
c(cmd)
return cmd
}
func (c cmdable) Keys(pattern string) *StringSliceCmd {
cmd := NewStringSliceCmd("keys", pattern)
c(cmd)
return cmd
}
func (c cmdable) Migrate(host, port, key string, db int, timeout time.Duration) *StatusCmd {
cmd := NewStatusCmd(
"migrate",
host,
port,
key,
db,
formatMs(timeout),
)
cmd.setReadTimeout(timeout)
c(cmd)
return cmd
}
func (c cmdable) Move(key string, db int) *BoolCmd {
cmd := NewBoolCmd("move", key, db)
c(cmd)
return cmd
}
func (c cmdable) ObjectRefCount(key string) *IntCmd {
cmd := NewIntCmd("object", "refcount", key)
c(cmd)
return cmd
}
func (c cmdable) ObjectEncoding(key string) *StringCmd {
cmd := NewStringCmd("object", "encoding", key)
c(cmd)
return cmd
}
func (c cmdable) ObjectIdleTime(key string) *DurationCmd {
cmd := NewDurationCmd(time.Second, "object", "idletime", key)
c(cmd)
return cmd
}
func (c cmdable) Persist(key string) *BoolCmd {
cmd := NewBoolCmd("persist", key)
c(cmd)
return cmd
}
func (c cmdable) PExpire(key string, expiration time.Duration) *BoolCmd {
cmd := NewBoolCmd("pexpire", key, formatMs(expiration))
c(cmd)
return cmd
}
func (c cmdable) PExpireAt(key string, tm time.Time) *BoolCmd {
cmd := NewBoolCmd(
"pexpireat",
key,
tm.UnixNano()/int64(time.Millisecond),
)
c(cmd)
return cmd
}
func (c cmdable) PTTL(key string) *DurationCmd {
cmd := NewDurationCmd(time.Millisecond, "pttl", key)
c(cmd)
return cmd
}
func (c cmdable) RandomKey() *StringCmd {
cmd := NewStringCmd("randomkey")
c(cmd)
return cmd
}
func (c cmdable) Rename(key, newkey string) *StatusCmd {
cmd := NewStatusCmd("rename", key, newkey)
c(cmd)
return cmd
}
func (c cmdable) RenameNX(key, newkey string) *BoolCmd {
cmd := NewBoolCmd("renamenx", key, newkey)
c(cmd)
return cmd
}
func (c cmdable) Restore(key string, ttl time.Duration, value string) *StatusCmd {
cmd := NewStatusCmd(
"restore",
key,
formatMs(ttl),
value,
)
c(cmd)
return cmd
}
func (c cmdable) RestoreReplace(key string, ttl time.Duration, value string) *StatusCmd {
cmd := NewStatusCmd(
"restore",
key,
formatMs(ttl),
value,
"replace",
)
c(cmd)
return cmd
}
type Sort struct {
By string
Offset, Count int64
Get []string
Order string
Alpha bool
}
func (sort *Sort) args(key string) []interface{} {
args := []interface{}{"sort", key}
if sort.By != "" {
args = append(args, "by", sort.By)
}
if sort.Offset != 0 || sort.Count != 0 {
args = append(args, "limit", sort.Offset, sort.Count)
}
for _, get := range sort.Get {
args = append(args, "get", get)
}
if sort.Order != "" {
args = append(args, sort.Order)
}
if sort.Alpha {
args = append(args, "alpha")
}
return args
}
func (c cmdable) Sort(key string, sort *Sort) *StringSliceCmd {
cmd := NewStringSliceCmd(sort.args(key)...)
c(cmd)
return cmd
}
func (c cmdable) SortStore(key, store string, sort *Sort) *IntCmd {
args := sort.args(key)
if store != "" {
args = append(args, "store", store)
}
cmd := NewIntCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) SortInterfaces(key string, sort *Sort) *SliceCmd {
cmd := NewSliceCmd(sort.args(key)...)
c(cmd)
return cmd
}
func (c cmdable) Touch(keys ...string) *IntCmd {
args := make([]interface{}, len(keys)+1)
args[0] = "touch"
for i, key := range keys {
args[i+1] = key
}
cmd := NewIntCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) TTL(key string) *DurationCmd {
cmd := NewDurationCmd(time.Second, "ttl", key)
c(cmd)
return cmd
}
func (c cmdable) Type(key string) *StatusCmd {
cmd := NewStatusCmd("type", key)
c(cmd)
return cmd
}
func (c cmdable) Scan(cursor uint64, match string, count int64) *ScanCmd {
args := []interface{}{"scan", cursor}
if match != "" {
args = append(args, "match", match)
}
if count > 0 {
args = append(args, "count", count)
}
cmd := NewScanCmd(c, args...)
c(cmd)
return cmd
}
func (c cmdable) SScan(key string, cursor uint64, match string, count int64) *ScanCmd {
args := []interface{}{"sscan", key, cursor}
if match != "" {
args = append(args, "match", match)
}
if count > 0 {
args = append(args, "count", count)
}
cmd := NewScanCmd(c, args...)
c(cmd)
return cmd
}
func (c cmdable) HScan(key string, cursor uint64, match string, count int64) *ScanCmd {
args := []interface{}{"hscan", key, cursor}
if match != "" {
args = append(args, "match", match)
}
if count > 0 {
args = append(args, "count", count)
}
cmd := NewScanCmd(c, args...)
c(cmd)
return cmd
}
func (c cmdable) ZScan(key string, cursor uint64, match string, count int64) *ScanCmd {
args := []interface{}{"zscan", key, cursor}
if match != "" {
args = append(args, "match", match)
}
if count > 0 {
args = append(args, "count", count)
}
cmd := NewScanCmd(c, args...)
c(cmd)
return cmd
}
//------------------------------------------------------------------------------
func (c cmdable) Append(key, value string) *IntCmd {
cmd := NewIntCmd("append", key, value)
c(cmd)
return cmd
}
type BitCount struct {
Start, End int64
}
func (c cmdable) BitCount(key string, bitCount *BitCount) *IntCmd {
args := []interface{}{"bitcount", key}
if bitCount != nil {
args = append(
args,
bitCount.Start,
bitCount.End,
)
}
cmd := NewIntCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) bitOp(op, destKey string, keys ...string) *IntCmd {
args := make([]interface{}, 3+len(keys))
args[0] = "bitop"
args[1] = op
args[2] = destKey
for i, key := range keys {
args[3+i] = key
}
cmd := NewIntCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) BitOpAnd(destKey string, keys ...string) *IntCmd {
return c.bitOp("and", destKey, keys...)
}
func (c cmdable) BitOpOr(destKey string, keys ...string) *IntCmd {
return c.bitOp("or", destKey, keys...)
}
func (c cmdable) BitOpXor(destKey string, keys ...string) *IntCmd {
return c.bitOp("xor", destKey, keys...)
}
func (c cmdable) BitOpNot(destKey string, key string) *IntCmd {
return c.bitOp("not", destKey, key)
}
func (c cmdable) BitPos(key string, bit int64, pos ...int64) *IntCmd {
args := make([]interface{}, 3+len(pos))
args[0] = "bitpos"
args[1] = key
args[2] = bit
switch len(pos) {
case 0:
case 1:
args[3] = pos[0]
case 2:
args[3] = pos[0]
args[4] = pos[1]
default:
panic("too many arguments")
}
cmd := NewIntCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) BitField(key string, args ...interface{}) *IntSliceCmd {
a := make([]interface{}, 0, 2+len(args))
a = append(a, "bitfield")
a = append(a, key)
a = append(a, args...)
cmd := NewIntSliceCmd(a...)
c(cmd)
return cmd
}
func (c cmdable) Decr(key string) *IntCmd {
cmd := NewIntCmd("decr", key)
c(cmd)
return cmd
}
func (c cmdable) DecrBy(key string, decrement int64) *IntCmd {
cmd := NewIntCmd("decrby", key, decrement)
c(cmd)
return cmd
}
// Redis `GET key` command. It returns redis.Nil error when key does not exist.
func (c cmdable) Get(key string) *StringCmd {
cmd := NewStringCmd("get", key)
c(cmd)
return cmd
}
func (c cmdable) GetBit(key string, offset int64) *IntCmd {
cmd := NewIntCmd("getbit", key, offset)
c(cmd)
return cmd
}
func (c cmdable) GetRange(key string, start, end int64) *StringCmd {
cmd := NewStringCmd("getrange", key, start, end)
c(cmd)
return cmd
}
func (c cmdable) GetSet(key string, value interface{}) *StringCmd {
cmd := NewStringCmd("getset", key, value)
c(cmd)
return cmd
}
func (c cmdable) Incr(key string) *IntCmd {
cmd := NewIntCmd("incr", key)
c(cmd)
return cmd
}
func (c cmdable) IncrBy(key string, value int64) *IntCmd {
cmd := NewIntCmd("incrby", key, value)
c(cmd)
return cmd
}
func (c cmdable) IncrByFloat(key string, value float64) *FloatCmd {
cmd := NewFloatCmd("incrbyfloat", key, value)
c(cmd)
return cmd
}
func (c cmdable) MGet(keys ...string) *SliceCmd {
args := make([]interface{}, 1+len(keys))
args[0] = "mget"
for i, key := range keys {
args[1+i] = key
}
cmd := NewSliceCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) MSet(pairs ...interface{}) *StatusCmd {
args := make([]interface{}, 1, 1+len(pairs))
args[0] = "mset"
args = appendArgs(args, pairs)
cmd := NewStatusCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) MSetNX(pairs ...interface{}) *BoolCmd {
args := make([]interface{}, 1, 1+len(pairs))
args[0] = "msetnx"
args = appendArgs(args, pairs)
cmd := NewBoolCmd(args...)
c(cmd)
return cmd
}
// Redis `SET key value [expiration]` command.
//
// Use expiration for `SETEX`-like behavior.
// Zero expiration means the key has no expiration time.
func (c cmdable) Set(key string, value interface{}, expiration time.Duration) *StatusCmd {
args := make([]interface{}, 3, 4)
args[0] = "set"
args[1] = key
args[2] = value
if expiration > 0 {
if usePrecise(expiration) {
args = append(args, "px", formatMs(expiration))
} else {
args = append(args, "ex", formatSec(expiration))
}
}
cmd := NewStatusCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) SetBit(key string, offset int64, value int) *IntCmd {
cmd := NewIntCmd(
"setbit",
key,
offset,
value,
)
c(cmd)
return cmd
}
// Redis `SET key value [expiration] NX` command.
//
// Zero expiration means the key has no expiration time.
func (c cmdable) SetNX(key string, value interface{}, expiration time.Duration) *BoolCmd {
var cmd *BoolCmd
if expiration == 0 {
// Use old `SETNX` to support old Redis versions.
cmd = NewBoolCmd("setnx", key, value)
} else {
if usePrecise(expiration) {
cmd = NewBoolCmd("set", key, value, "px", formatMs(expiration), "nx")
} else {
cmd = NewBoolCmd("set", key, value, "ex", formatSec(expiration), "nx")
}
}
c(cmd)
return cmd
}
// Redis `SET key value [expiration] XX` command.
//
// Zero expiration means the key has no expiration time.
func (c cmdable) SetXX(key string, value interface{}, expiration time.Duration) *BoolCmd {
var cmd *BoolCmd
if expiration == 0 {
cmd = NewBoolCmd("set", key, value, "xx")
} else {
if usePrecise(expiration) {
cmd = NewBoolCmd("set", key, value, "px", formatMs(expiration), "xx")
} else {
cmd = NewBoolCmd("set", key, value, "ex", formatSec(expiration), "xx")
}
}
c(cmd)
return cmd
}
func (c cmdable) SetRange(key string, offset int64, value string) *IntCmd {
cmd := NewIntCmd("setrange", key, offset, value)
c(cmd)
return cmd
}
func (c cmdable) StrLen(key string) *IntCmd {
cmd := NewIntCmd("strlen", key)
c(cmd)
return cmd
}
//------------------------------------------------------------------------------
func (c cmdable) HDel(key string, fields ...string) *IntCmd {
args := make([]interface{}, 2+len(fields))
args[0] = "hdel"
args[1] = key
for i, field := range fields {
args[2+i] = field
}
cmd := NewIntCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) HExists(key, field string) *BoolCmd {
cmd := NewBoolCmd("hexists", key, field)
c(cmd)
return cmd
}
func (c cmdable) HGet(key, field string) *StringCmd {
cmd := NewStringCmd("hget", key, field)
c(cmd)
return cmd
}
func (c cmdable) HGetAll(key string) *StringStringMapCmd {
cmd := NewStringStringMapCmd("hgetall", key)
c(cmd)
return cmd
}
func (c cmdable) HIncrBy(key, field string, incr int64) *IntCmd {
cmd := NewIntCmd("hincrby", key, field, incr)
c(cmd)
return cmd
}
func (c cmdable) HIncrByFloat(key, field string, incr float64) *FloatCmd {
cmd := NewFloatCmd("hincrbyfloat", key, field, incr)
c(cmd)
return cmd
}
func (c cmdable) HKeys(key string) *StringSliceCmd {
cmd := NewStringSliceCmd("hkeys", key)
c(cmd)
return cmd
}
func (c cmdable) HLen(key string) *IntCmd {
cmd := NewIntCmd("hlen", key)
c(cmd)
return cmd
}
func (c cmdable) HMGet(key string, fields ...string) *SliceCmd {
args := make([]interface{}, 2+len(fields))
args[0] = "hmget"
args[1] = key
for i, field := range fields {
args[2+i] = field
}
cmd := NewSliceCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) HMSet(key string, fields map[string]interface{}) *StatusCmd {
args := make([]interface{}, 2+len(fields)*2)
args[0] = "hmset"
args[1] = key
i := 2
for k, v := range fields {
args[i] = k
args[i+1] = v
i += 2
}
cmd := NewStatusCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) HSet(key, field string, value interface{}) *BoolCmd {
cmd := NewBoolCmd("hset", key, field, value)
c(cmd)
return cmd
}
func (c cmdable) HSetNX(key, field string, value interface{}) *BoolCmd {
cmd := NewBoolCmd("hsetnx", key, field, value)
c(cmd)
return cmd
}
func (c cmdable) HVals(key string) *StringSliceCmd {
cmd := NewStringSliceCmd("hvals", key)
c(cmd)
return cmd
}
//------------------------------------------------------------------------------
func (c cmdable) BLPop(timeout time.Duration, keys ...string) *StringSliceCmd {
args := make([]interface{}, 1+len(keys)+1)
args[0] = "blpop"
for i, key := range keys {
args[1+i] = key
}
args[len(args)-1] = formatSec(timeout)
cmd := NewStringSliceCmd(args...)
cmd.setReadTimeout(timeout)
c(cmd)
return cmd
}
func (c cmdable) BRPop(timeout time.Duration, keys ...string) *StringSliceCmd {
args := make([]interface{}, 1+len(keys)+1)
args[0] = "brpop"
for i, key := range keys {
args[1+i] = key
}
args[len(keys)+1] = formatSec(timeout)
cmd := NewStringSliceCmd(args...)
cmd.setReadTimeout(timeout)
c(cmd)
return cmd
}
func (c cmdable) BRPopLPush(source, destination string, timeout time.Duration) *StringCmd {
cmd := NewStringCmd(
"brpoplpush",
source,
destination,
formatSec(timeout),
)
cmd.setReadTimeout(timeout)
c(cmd)
return cmd
}
func (c cmdable) LIndex(key string, index int64) *StringCmd {
cmd := NewStringCmd("lindex", key, index)
c(cmd)
return cmd
}
func (c cmdable) LInsert(key, op string, pivot, value interface{}) *IntCmd {
cmd := NewIntCmd("linsert", key, op, pivot, value)
c(cmd)
return cmd
}
func (c cmdable) LInsertBefore(key string, pivot, value interface{}) *IntCmd {
cmd := NewIntCmd("linsert", key, "before", pivot, value)
c(cmd)
return cmd
}
func (c cmdable) LInsertAfter(key string, pivot, value interface{}) *IntCmd {
cmd := NewIntCmd("linsert", key, "after", pivot, value)
c(cmd)
return cmd
}
func (c cmdable) LLen(key string) *IntCmd {
cmd := NewIntCmd("llen", key)
c(cmd)
return cmd
}
func (c cmdable) LPop(key string) *StringCmd {
cmd := NewStringCmd("lpop", key)
c(cmd)
return cmd
}
func (c cmdable) LPush(key string, values ...interface{}) *IntCmd {
args := make([]interface{}, 2, 2+len(values))
args[0] = "lpush"
args[1] = key
args = appendArgs(args, values)
cmd := NewIntCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) LPushX(key string, value interface{}) *IntCmd {
cmd := NewIntCmd("lpushx", key, value)
c(cmd)
return cmd
}
func (c cmdable) LRange(key string, start, stop int64) *StringSliceCmd {
cmd := NewStringSliceCmd(
"lrange",
key,
start,
stop,
)
c(cmd)
return cmd
}
func (c cmdable) LRem(key string, count int64, value interface{}) *IntCmd {
cmd := NewIntCmd("lrem", key, count, value)
c(cmd)
return cmd
}
func (c cmdable) LSet(key string, index int64, value interface{}) *StatusCmd {
cmd := NewStatusCmd("lset", key, index, value)
c(cmd)
return cmd
}
func (c cmdable) LTrim(key string, start, stop int64) *StatusCmd {
cmd := NewStatusCmd(
"ltrim",
key,
start,
stop,
)
c(cmd)
return cmd
}
func (c cmdable) RPop(key string) *StringCmd {
cmd := NewStringCmd("rpop", key)
c(cmd)
return cmd
}
func (c cmdable) RPopLPush(source, destination string) *StringCmd {
cmd := NewStringCmd("rpoplpush", source, destination)
c(cmd)
return cmd
}
func (c cmdable) RPush(key string, values ...interface{}) *IntCmd {
args := make([]interface{}, 2, 2+len(values))
args[0] = "rpush"
args[1] = key
args = appendArgs(args, values)
cmd := NewIntCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) RPushX(key string, value interface{}) *IntCmd {
cmd := NewIntCmd("rpushx", key, value)
c(cmd)
return cmd
}
//------------------------------------------------------------------------------
func (c cmdable) SAdd(key string, members ...interface{}) *IntCmd {
args := make([]interface{}, 2, 2+len(members))
args[0] = "sadd"
args[1] = key
args = appendArgs(args, members)
cmd := NewIntCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) SCard(key string) *IntCmd {
cmd := NewIntCmd("scard", key)
c(cmd)
return cmd
}
func (c cmdable) SDiff(keys ...string) *StringSliceCmd {
args := make([]interface{}, 1+len(keys))
args[0] = "sdiff"
for i, key := range keys {
args[1+i] = key
}
cmd := NewStringSliceCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) SDiffStore(destination string, keys ...string) *IntCmd {
args := make([]interface{}, 2+len(keys))
args[0] = "sdiffstore"
args[1] = destination
for i, key := range keys {
args[2+i] = key
}
cmd := NewIntCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) SInter(keys ...string) *StringSliceCmd {
args := make([]interface{}, 1+len(keys))
args[0] = "sinter"
for i, key := range keys {
args[1+i] = key
}
cmd := NewStringSliceCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) SInterStore(destination string, keys ...string) *IntCmd {
args := make([]interface{}, 2+len(keys))
args[0] = "sinterstore"
args[1] = destination
for i, key := range keys {
args[2+i] = key
}
cmd := NewIntCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) SIsMember(key string, member interface{}) *BoolCmd {
cmd := NewBoolCmd("sismember", key, member)
c(cmd)
return cmd
}
// Redis `SMEMBERS key` command output as a slice
func (c cmdable) SMembers(key string) *StringSliceCmd {
cmd := NewStringSliceCmd("smembers", key)
c(cmd)
return cmd
}
// Redis `SMEMBERS key` command output as a map
func (c cmdable) SMembersMap(key string) *StringStructMapCmd {
cmd := NewStringStructMapCmd("smembers", key)
c(cmd)
return cmd
}
func (c cmdable) SMove(source, destination string, member interface{}) *BoolCmd {
cmd := NewBoolCmd("smove", source, destination, member)
c(cmd)
return cmd
}
// Redis `SPOP key` command.
func (c cmdable) SPop(key string) *StringCmd {
cmd := NewStringCmd("spop", key)
c(cmd)
return cmd
}
// Redis `SPOP key count` command.
func (c cmdable) SPopN(key string, count int64) *StringSliceCmd {
cmd := NewStringSliceCmd("spop", key, count)
c(cmd)
return cmd
}
// Redis `SRANDMEMBER key` command.
func (c cmdable) SRandMember(key string) *StringCmd {
cmd := NewStringCmd("srandmember", key)
c(cmd)
return cmd
}
// Redis `SRANDMEMBER key count` command.
func (c cmdable) SRandMemberN(key string, count int64) *StringSliceCmd {
cmd := NewStringSliceCmd("srandmember", key, count)
c(cmd)
return cmd
}
func (c cmdable) SRem(key string, members ...interface{}) *IntCmd {
args := make([]interface{}, 2, 2+len(members))
args[0] = "srem"
args[1] = key
args = appendArgs(args, members)
cmd := NewIntCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) SUnion(keys ...string) *StringSliceCmd {
args := make([]interface{}, 1+len(keys))
args[0] = "sunion"
for i, key := range keys {
args[1+i] = key
}
cmd := NewStringSliceCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) SUnionStore(destination string, keys ...string) *IntCmd {
args := make([]interface{}, 2+len(keys))
args[0] = "sunionstore"
args[1] = destination
for i, key := range keys {
args[2+i] = key
}
cmd := NewIntCmd(args...)
c(cmd)
return cmd
}
//------------------------------------------------------------------------------
type XAddArgs struct {
Stream string
MaxLen int64 // MAXLEN N
MaxLenApprox int64 // MAXLEN ~ N
ID string
Values map[string]interface{}
}
func (c cmdable) XAdd(a *XAddArgs) *StringCmd {
args := make([]interface{}, 0, 6+len(a.Values)*2)
args = append(args, "xadd")
args = append(args, a.Stream)
if a.MaxLen > 0 {
args = append(args, "maxlen", a.MaxLen)
} else if a.MaxLenApprox > 0 {
args = append(args, "maxlen", "~", a.MaxLenApprox)
}
if a.ID != "" {
args = append(args, a.ID)
} else {
args = append(args, "*")
}
for k, v := range a.Values {
args = append(args, k)
args = append(args, v)
}
cmd := NewStringCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) XDel(stream string, ids ...string) *IntCmd {
args := []interface{}{"xdel", stream}
for _, id := range ids {
args = append(args, id)
}
cmd := NewIntCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) XLen(stream string) *IntCmd {
cmd := NewIntCmd("xlen", stream)
c(cmd)
return cmd
}
func (c cmdable) XRange(stream, start, stop string) *XMessageSliceCmd {
cmd := NewXMessageSliceCmd("xrange", stream, start, stop)
c(cmd)
return cmd
}
func (c cmdable) XRangeN(stream, start, stop string, count int64) *XMessageSliceCmd {
cmd := NewXMessageSliceCmd("xrange", stream, start, stop, "count", count)
c(cmd)
return cmd
}
func (c cmdable) XRevRange(stream, start, stop string) *XMessageSliceCmd {
cmd := NewXMessageSliceCmd("xrevrange", stream, start, stop)
c(cmd)
return cmd
}
func (c cmdable) XRevRangeN(stream, start, stop string, count int64) *XMessageSliceCmd {
cmd := NewXMessageSliceCmd("xrevrange", stream, start, stop, "count", count)
c(cmd)
return cmd
}
type XReadArgs struct {
Streams []string
Count int64
Block time.Duration
}
func (c cmdable) XRead(a *XReadArgs) *XStreamSliceCmd {
args := make([]interface{}, 0, 5+len(a.Streams))
args = append(args, "xread")
if a.Count > 0 {
args = append(args, "count")
args = append(args, a.Count)
}
if a.Block >= 0 {
args = append(args, "block")
args = append(args, int64(a.Block/time.Millisecond))
}
args = append(args, "streams")
for _, s := range a.Streams {
args = append(args, s)
}
cmd := NewXStreamSliceCmd(args...)
if a.Block >= 0 {
cmd.setReadTimeout(a.Block)
}
c(cmd)
return cmd
}
func (c cmdable) XReadStreams(streams ...string) *XStreamSliceCmd {
return c.XRead(&XReadArgs{
Streams: streams,
Block: -1,
})
}
func (c cmdable) XGroupCreate(stream, group, start string) *StatusCmd {
cmd := NewStatusCmd("xgroup", "create", stream, group, start)
c(cmd)
return cmd
}
func (c cmdable) XGroupCreateMkStream(stream, group, start string) *StatusCmd {
cmd := NewStatusCmd("xgroup", "create", stream, group, start, "mkstream")
c(cmd)
return cmd
}
func (c cmdable) XGroupSetID(stream, group, start string) *StatusCmd {
cmd := NewStatusCmd("xgroup", "setid", stream, group, start)
c(cmd)
return cmd
}
func (c cmdable) XGroupDestroy(stream, group string) *IntCmd {
cmd := NewIntCmd("xgroup", "destroy", stream, group)
c(cmd)
return cmd
}
func (c cmdable) XGroupDelConsumer(stream, group, consumer string) *IntCmd {
cmd := NewIntCmd("xgroup", "delconsumer", stream, group, consumer)
c(cmd)
return cmd
}
type XReadGroupArgs struct {
Group string
Consumer string
Streams []string // list of streams and ids, e.g. stream1 stream2 id1 id2
Count int64
Block time.Duration
NoAck bool
}
func (c cmdable) XReadGroup(a *XReadGroupArgs) *XStreamSliceCmd {
args := make([]interface{}, 0, 8+len(a.Streams))
args = append(args, "xreadgroup", "group", a.Group, a.Consumer)
if a.Count > 0 {
args = append(args, "count", a.Count) | if a.NoAck {
args = append(args, "noack")
}
args = append(args, "streams")
for _, s := range a.Streams {
args = append(args, s)
}
cmd := NewXStreamSliceCmd(args...)
if a.Block >= 0 {
cmd.setReadTimeout(a.Block)
}
c(cmd)
return cmd
}
func (c cmdable) XAck(stream, group string, ids ...string) *IntCmd {
args := []interface{}{"xack", stream, group}
for _, id := range ids {
args = append(args, id)
}
cmd := NewIntCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) XPending(stream, group string) *XPendingCmd {
cmd := NewXPendingCmd("xpending", stream, group)
c(cmd)
return cmd
}
type XPendingExtArgs struct {
Stream string
Group string
Start string
End string
Count int64
Consumer string
}
func (c cmdable) XPendingExt(a *XPendingExtArgs) *XPendingExtCmd {
args := make([]interface{}, 0, 7)
args = append(args, "xpending", a.Stream, a.Group, a.Start, a.End, a.Count)
if a.Consumer != "" {
args = append(args, a.Consumer)
}
cmd := NewXPendingExtCmd(args...)
c(cmd)
return cmd
}
type XClaimArgs struct {
Stream string
Group string
Consumer string
MinIdle time.Duration
Messages []string
}
func (c cmdable) XClaim(a *XClaimArgs) *XMessageSliceCmd {
args := xClaimArgs(a)
cmd := NewXMessageSliceCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) XClaimJustID(a *XClaimArgs) *StringSliceCmd {
args := xClaimArgs(a)
args = append(args, "justid")
cmd := NewStringSliceCmd(args...)
c(cmd)
return cmd
}
func xClaimArgs(a *XClaimArgs) []interface{} {
args := make([]interface{}, 0, 4+len(a.Messages))
args = append(args,
"xclaim",
a.Stream,
a.Group, a.Consumer,
int64(a.MinIdle/time.Millisecond))
for _, id := range a.Messages {
args = append(args, id)
}
return args
}
func (c cmdable) XTrim(key string, maxLen int64) *IntCmd {
cmd := NewIntCmd("xtrim", key, "maxlen", maxLen)
c(cmd)
return cmd
}
func (c cmdable) XTrimApprox(key string, maxLen int64) *IntCmd {
cmd := NewIntCmd("xtrim", key, "maxlen", "~", maxLen)
c(cmd)
return cmd
}
//------------------------------------------------------------------------------
// Z represents sorted set member.
type Z struct {
Score float64
Member interface{}
}
// ZWithKey represents sorted set member including the name of the key where it was popped.
type ZWithKey struct {
Z
Key string
}
// ZStore is used as an arg to ZInterStore and ZUnionStore.
type ZStore struct {
Weights []float64
// Can be SUM, MIN or MAX.
Aggregate string
}
// Redis `BZPOPMAX key [key ...] timeout` command.
func (c cmdable) BZPopMax(timeout time.Duration, keys ...string) *ZWithKeyCmd {
args := make([]interface{}, 1+len(keys)+1)
args[0] = "bzpopmax"
for i, key := range keys {
args[1+i] = key
}
args[len(args)-1] = formatSec(timeout)
cmd := NewZWithKeyCmd(args...)
cmd.setReadTimeout(timeout)
c(cmd)
return cmd
}
// Redis `BZPOPMIN key [key ...] timeout` command.
func (c cmdable) BZPopMin(timeout time.Duration, keys ...string) *ZWithKeyCmd {
args := make([]interface{}, 1+len(keys)+1)
args[0] = "bzpopmin"
for i, key := range keys {
args[1+i] = key
}
args[len(args)-1] = formatSec(timeout)
cmd := NewZWithKeyCmd(args...)
cmd.setReadTimeout(timeout)
c(cmd)
return cmd
}
func (c cmdable) zAdd(a []interface{}, n int, members ...*Z) *IntCmd {
for i, m := range members {
a[n+2*i] = m.Score
a[n+2*i+1] = m.Member
}
cmd := NewIntCmd(a...)
c(cmd)
return cmd
}
// Redis `ZADD key score member [score member ...]` command.
func (c cmdable) ZAdd(key string, members ...*Z) *IntCmd {
const n = 2
a := make([]interface{}, n+2*len(members))
a[0], a[1] = "zadd", key
return c.zAdd(a, n, members...)
}
// Redis `ZADD key NX score member [score member ...]` command.
func (c cmdable) ZAddNX(key string, members ...*Z) *IntCmd {
const n = 3
a := make([]interface{}, n+2*len(members))
a[0], a[1], a[2] = "zadd", key, "nx"
return c.zAdd(a, n, members...)
}
// Redis `ZADD key XX score member [score member ...]` command.
func (c cmdable) ZAddXX(key string, members ...*Z) *IntCmd {
const n = 3
a := make([]interface{}, n+2*len(members))
a[0], a[1], a[2] = "zadd", key, "xx"
return c.zAdd(a, n, members...)
}
// Redis `ZADD key CH score member [score member ...]` command.
func (c cmdable) ZAddCh(key string, members ...*Z) *IntCmd {
const n = 3
a := make([]interface{}, n+2*len(members))
a[0], a[1], a[2] = "zadd", key, "ch"
return c.zAdd(a, n, members...)
}
// Redis `ZADD key NX CH score member [score member ...]` command.
func (c cmdable) ZAddNXCh(key string, members ...*Z) *IntCmd {
const n = 4
a := make([]interface{}, n+2*len(members))
a[0], a[1], a[2], a[3] = "zadd", key, "nx", "ch"
return c.zAdd(a, n, members...)
}
// Redis `ZADD key XX CH score member [score member ...]` command.
func (c cmdable) ZAddXXCh(key string, members ...*Z) *IntCmd {
const n = 4
a := make([]interface{}, n+2*len(members))
a[0], a[1], a[2], a[3] = "zadd", key, "xx", "ch"
return c.zAdd(a, n, members...)
}
func (c cmdable) zIncr(a []interface{}, n int, members ...*Z) *FloatCmd {
for i, m := range members {
a[n+2*i] = m.Score
a[n+2*i+1] = m.Member
}
cmd := NewFloatCmd(a...)
c(cmd)
return cmd
}
// Redis `ZADD key INCR score member` command.
func (c cmdable) ZIncr(key string, member *Z) *FloatCmd {
const n = 3
a := make([]interface{}, n+2)
a[0], a[1], a[2] = "zadd", key, "incr"
return c.zIncr(a, n, member)
}
// Redis `ZADD key NX INCR score member` command.
func (c cmdable) ZIncrNX(key string, member *Z) *FloatCmd {
const n = 4
a := make([]interface{}, n+2)
a[0], a[1], a[2], a[3] = "zadd", key, "incr", "nx"
return c.zIncr(a, n, member)
}
// Redis `ZADD key XX INCR score member` command.
func (c cmdable) ZIncrXX(key string, member *Z) *FloatCmd {
const n = 4
a := make([]interface{}, n+2)
a[0], a[1], a[2], a[3] = "zadd", key, "incr", "xx"
return c.zIncr(a, n, member)
}
func (c cmdable) ZCard(key string) *IntCmd {
cmd := NewIntCmd("zcard", key)
c(cmd)
return cmd
}
func (c cmdable) ZCount(key, min, max string) *IntCmd {
cmd := NewIntCmd("zcount", key, min, max)
c(cmd)
return cmd
}
func (c cmdable) ZLexCount(key, min, max string) *IntCmd {
cmd := NewIntCmd("zlexcount", key, min, max)
c(cmd)
return cmd
}
func (c cmdable) ZIncrBy(key string, increment float64, member string) *FloatCmd {
cmd := NewFloatCmd("zincrby", key, increment, member)
c(cmd)
return cmd
}
func (c cmdable) ZInterStore(destination string, store *ZStore, keys ...string) *IntCmd {
args := make([]interface{}, 3+len(keys))
args[0] = "zinterstore"
args[1] = destination
args[2] = len(keys)
for i, key := range keys {
args[3+i] = key
}
if len(store.Weights) > 0 {
args = append(args, "weights")
for _, weight := range store.Weights {
args = append(args, weight)
}
}
if store.Aggregate != "" {
args = append(args, "aggregate", store.Aggregate)
}
cmd := NewIntCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) ZPopMax(key string, count ...int64) *ZSliceCmd {
args := []interface{}{
"zpopmax",
key,
}
switch len(count) {
case 0:
break
case 1:
args = append(args, count[0])
default:
panic("too many arguments")
}
cmd := NewZSliceCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) ZPopMin(key string, count ...int64) *ZSliceCmd {
args := []interface{}{
"zpopmin",
key,
}
switch len(count) {
case 0:
break
case 1:
args = append(args, count[0])
default:
panic("too many arguments")
}
cmd := NewZSliceCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) zRange(key string, start, stop int64, withScores bool) *StringSliceCmd {
args := []interface{}{
"zrange",
key,
start,
stop,
}
if withScores {
args = append(args, "withscores")
}
cmd := NewStringSliceCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) ZRange(key string, start, stop int64) *StringSliceCmd {
return c.zRange(key, start, stop, false)
}
func (c cmdable) ZRangeWithScores(key string, start, stop int64) *ZSliceCmd {
cmd := NewZSliceCmd("zrange", key, start, stop, "withscores")
c(cmd)
return cmd
}
type ZRangeBy struct {
Min, Max string
Offset, Count int64
}
func (c cmdable) zRangeBy(zcmd, key string, opt *ZRangeBy, withScores bool) *StringSliceCmd {
args := []interface{}{zcmd, key, opt.Min, opt.Max}
if withScores {
args = append(args, "withscores")
}
if opt.Offset != 0 || opt.Count != 0 {
args = append(
args,
"limit",
opt.Offset,
opt.Count,
)
}
cmd := NewStringSliceCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) ZRangeByScore(key string, opt *ZRangeBy) *StringSliceCmd {
return c.zRangeBy("zrangebyscore", key, opt, false)
}
func (c cmdable) ZRangeByLex(key string, opt *ZRangeBy) *StringSliceCmd {
return c.zRangeBy("zrangebylex", key, opt, false)
}
func (c cmdable) ZRangeByScoreWithScores(key string, opt *ZRangeBy) *ZSliceCmd {
args := []interface{}{"zrangebyscore", key, opt.Min, opt.Max, "withscores"}
if opt.Offset != 0 || opt.Count != 0 {
args = append(
args,
"limit",
opt.Offset,
opt.Count,
)
}
cmd := NewZSliceCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) ZRank(key, member string) *IntCmd {
cmd := NewIntCmd("zrank", key, member)
c(cmd)
return cmd
}
func (c cmdable) ZRem(key string, members ...interface{}) *IntCmd {
args := make([]interface{}, 2, 2+len(members))
args[0] = "zrem"
args[1] = key
args = appendArgs(args, members)
cmd := NewIntCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) ZRemRangeByRank(key string, start, stop int64) *IntCmd {
cmd := NewIntCmd(
"zremrangebyrank",
key,
start,
stop,
)
c(cmd)
return cmd
}
func (c cmdable) ZRemRangeByScore(key, min, max string) *IntCmd {
cmd := NewIntCmd("zremrangebyscore", key, min, max)
c(cmd)
return cmd
}
func (c cmdable) ZRemRangeByLex(key, min, max string) *IntCmd {
cmd := NewIntCmd("zremrangebylex", key, min, max)
c(cmd)
return cmd
}
func (c cmdable) ZRevRange(key string, start, stop int64) *StringSliceCmd {
cmd := NewStringSliceCmd("zrevrange", key, start, stop)
c(cmd)
return cmd
}
func (c cmdable) ZRevRangeWithScores(key string, start, stop int64) *ZSliceCmd {
cmd := NewZSliceCmd("zrevrange", key, start, stop, "withscores")
c(cmd)
return cmd
}
func (c cmdable) zRevRangeBy(zcmd, key string, opt *ZRangeBy) *StringSliceCmd {
args := []interface{}{zcmd, key, opt.Max, opt.Min}
if opt.Offset != 0 || opt.Count != 0 {
args = append(
args,
"limit",
opt.Offset,
opt.Count,
)
}
cmd := NewStringSliceCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) ZRevRangeByScore(key string, opt *ZRangeBy) *StringSliceCmd {
return c.zRevRangeBy("zrevrangebyscore", key, opt)
}
func (c cmdable) ZRevRangeByLex(key string, opt *ZRangeBy) *StringSliceCmd {
return c.zRevRangeBy("zrevrangebylex", key, opt)
}
func (c cmdable) ZRevRangeByScoreWithScores(key string, opt *ZRangeBy) *ZSliceCmd {
args := []interface{}{"zrevrangebyscore", key, opt.Max, opt.Min, "withscores"}
if opt.Offset != 0 || opt.Count != 0 {
args = append(
args,
"limit",
opt.Offset,
opt.Count,
)
}
cmd := NewZSliceCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) ZRevRank(key, member string) *IntCmd {
cmd := NewIntCmd("zrevrank", key, member)
c(cmd)
return cmd
}
func (c cmdable) ZScore(key, member string) *FloatCmd {
cmd := NewFloatCmd("zscore", key, member)
c(cmd)
return cmd
}
// TODO: move keys to ZStore?
func (c cmdable) ZUnionStore(dest string, store *ZStore, keys ...string) *IntCmd {
args := make([]interface{}, 3+len(keys))
args[0] = "zunionstore"
args[1] = dest
args[2] = len(keys)
for i, key := range keys {
args[3+i] = key
}
if len(store.Weights) > 0 {
args = append(args, "weights")
for _, weight := range store.Weights {
args = append(args, weight)
}
}
if store.Aggregate != "" {
args = append(args, "aggregate", store.Aggregate)
}
cmd := NewIntCmd(args...)
c(cmd)
return cmd
}
//------------------------------------------------------------------------------
func (c cmdable) PFAdd(key string, els ...interface{}) *IntCmd {
args := make([]interface{}, 2, 2+len(els))
args[0] = "pfadd"
args[1] = key
args = appendArgs(args, els)
cmd := NewIntCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) PFCount(keys ...string) *IntCmd {
args := make([]interface{}, 1+len(keys))
args[0] = "pfcount"
for i, key := range keys {
args[1+i] = key
}
cmd := NewIntCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) PFMerge(dest string, keys ...string) *StatusCmd {
args := make([]interface{}, 2+len(keys))
args[0] = "pfmerge"
args[1] = dest
for i, key := range keys {
args[2+i] = key
}
cmd := NewStatusCmd(args...)
c(cmd)
return cmd
}
//------------------------------------------------------------------------------
func (c cmdable) BgRewriteAOF() *StatusCmd {
cmd := NewStatusCmd("bgrewriteaof")
c(cmd)
return cmd
}
func (c cmdable) BgSave() *StatusCmd {
cmd := NewStatusCmd("bgsave")
c(cmd)
return cmd
}
func (c cmdable) ClientKill(ipPort string) *StatusCmd {
cmd := NewStatusCmd("client", "kill", ipPort)
c(cmd)
return cmd
}
// ClientKillByFilter is new style synx, while the ClientKill is old
// CLIENT KILL <option> [value] ... <option> [value]
func (c cmdable) ClientKillByFilter(keys ...string) *IntCmd {
args := make([]interface{}, 2+len(keys))
args[0] = "client"
args[1] = "kill"
for i, key := range keys {
args[2+i] = key
}
cmd := NewIntCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) ClientList() *StringCmd {
cmd := NewStringCmd("client", "list")
c(cmd)
return cmd
}
func (c cmdable) ClientPause(dur time.Duration) *BoolCmd {
cmd := NewBoolCmd("client", "pause", formatMs(dur))
c(cmd)
return cmd
}
func (c cmdable) ClientID() *IntCmd {
cmd := NewIntCmd("client", "id")
c(cmd)
return cmd
}
func (c cmdable) ClientUnblock(id int64) *IntCmd {
cmd := NewIntCmd("client", "unblock", id)
c(cmd)
return cmd
}
func (c cmdable) ClientUnblockWithError(id int64) *IntCmd {
cmd := NewIntCmd("client", "unblock", id, "error")
c(cmd)
return cmd
}
// ClientSetName assigns a name to the connection.
func (c statefulCmdable) ClientSetName(name string) *BoolCmd {
cmd := NewBoolCmd("client", "setname", name)
c(cmd)
return cmd
}
// ClientGetName returns the name of the connection.
func (c cmdable) ClientGetName() *StringCmd {
cmd := NewStringCmd("client", "getname")
c(cmd)
return cmd
}
func (c cmdable) ConfigGet(parameter string) *SliceCmd {
cmd := NewSliceCmd("config", "get", parameter)
c(cmd)
return cmd
}
func (c cmdable) ConfigResetStat() *StatusCmd {
cmd := NewStatusCmd("config", "resetstat")
c(cmd)
return cmd
}
func (c cmdable) ConfigSet(parameter, value string) *StatusCmd {
cmd := NewStatusCmd("config", "set", parameter, value)
c(cmd)
return cmd
}
func (c cmdable) ConfigRewrite() *StatusCmd {
cmd := NewStatusCmd("config", "rewrite")
c(cmd)
return cmd
}
// Deperecated. Use DBSize instead.
func (c cmdable) DbSize() *IntCmd {
return c.DBSize()
}
func (c cmdable) DBSize() *IntCmd {
cmd := NewIntCmd("dbsize")
c(cmd)
return cmd
}
func (c cmdable) FlushAll() *StatusCmd {
cmd := NewStatusCmd("flushall")
c(cmd)
return cmd
}
func (c cmdable) FlushAllAsync() *StatusCmd {
cmd := NewStatusCmd("flushall", "async")
c(cmd)
return cmd
}
// Deprecated. Use FlushDB instead.
func (c cmdable) FlushDb() *StatusCmd {
return c.FlushDB()
}
func (c cmdable) FlushDB() *StatusCmd {
cmd := NewStatusCmd("flushdb")
c(cmd)
return cmd
}
func (c cmdable) FlushDBAsync() *StatusCmd {
cmd := NewStatusCmd("flushdb", "async")
c(cmd)
return cmd
}
func (c cmdable) Info(section ...string) *StringCmd {
args := []interface{}{"info"}
if len(section) > 0 {
args = append(args, section[0])
}
cmd := NewStringCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) LastSave() *IntCmd {
cmd := NewIntCmd("lastsave")
c(cmd)
return cmd
}
func (c cmdable) Save() *StatusCmd {
cmd := NewStatusCmd("save")
c(cmd)
return cmd
}
func (c cmdable) shutdown(modifier string) *StatusCmd {
var args []interface{}
if modifier == "" {
args = []interface{}{"shutdown"}
} else {
args = []interface{}{"shutdown", modifier}
}
cmd := NewStatusCmd(args...)
c(cmd)
if err := cmd.Err(); err != nil {
if err == io.EOF {
// Server quit as expected.
cmd.err = nil
}
} else {
// Server did not quit. String reply contains the reason.
cmd.err = errors.New(cmd.val)
cmd.val = ""
}
return cmd
}
func (c cmdable) Shutdown() *StatusCmd {
return c.shutdown("")
}
func (c cmdable) ShutdownSave() *StatusCmd {
return c.shutdown("save")
}
func (c cmdable) ShutdownNoSave() *StatusCmd {
return c.shutdown("nosave")
}
func (c cmdable) SlaveOf(host, port string) *StatusCmd {
cmd := NewStatusCmd("slaveof", host, port)
c(cmd)
return cmd
}
func (c cmdable) SlowLog() {
panic("not implemented")
}
func (c cmdable) Sync() {
panic("not implemented")
}
func (c cmdable) Time() *TimeCmd {
cmd := NewTimeCmd("time")
c(cmd)
return cmd
}
//------------------------------------------------------------------------------
func (c cmdable) Eval(script string, keys []string, args ...interface{}) *Cmd {
cmdArgs := make([]interface{}, 3+len(keys), 3+len(keys)+len(args))
cmdArgs[0] = "eval"
cmdArgs[1] = script
cmdArgs[2] = len(keys)
for i, key := range keys {
cmdArgs[3+i] = key
}
cmdArgs = appendArgs(cmdArgs, args)
cmd := NewCmd(cmdArgs...)
c(cmd)
return cmd
}
func (c cmdable) EvalSha(sha1 string, keys []string, args ...interface{}) *Cmd {
cmdArgs := make([]interface{}, 3+len(keys), 3+len(keys)+len(args))
cmdArgs[0] = "evalsha"
cmdArgs[1] = sha1
cmdArgs[2] = len(keys)
for i, key := range keys {
cmdArgs[3+i] = key
}
cmdArgs = appendArgs(cmdArgs, args)
cmd := NewCmd(cmdArgs...)
c(cmd)
return cmd
}
func (c cmdable) ScriptExists(hashes ...string) *BoolSliceCmd {
args := make([]interface{}, 2+len(hashes))
args[0] = "script"
args[1] = "exists"
for i, hash := range hashes {
args[2+i] = hash
}
cmd := NewBoolSliceCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) ScriptFlush() *StatusCmd {
cmd := NewStatusCmd("script", "flush")
c(cmd)
return cmd
}
func (c cmdable) ScriptKill() *StatusCmd {
cmd := NewStatusCmd("script", "kill")
c(cmd)
return cmd
}
func (c cmdable) ScriptLoad(script string) *StringCmd {
cmd := NewStringCmd("script", "load", script)
c(cmd)
return cmd
}
//------------------------------------------------------------------------------
func (c cmdable) DebugObject(key string) *StringCmd {
cmd := NewStringCmd("debug", "object", key)
c(cmd)
return cmd
}
//------------------------------------------------------------------------------
// Publish posts the message to the channel.
func (c cmdable) Publish(channel string, message interface{}) *IntCmd {
cmd := NewIntCmd("publish", channel, message)
c(cmd)
return cmd
}
func (c cmdable) PubSubChannels(pattern string) *StringSliceCmd {
args := []interface{}{"pubsub", "channels"}
if pattern != "*" {
args = append(args, pattern)
}
cmd := NewStringSliceCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) PubSubNumSub(channels ...string) *StringIntMapCmd {
args := make([]interface{}, 2+len(channels))
args[0] = "pubsub"
args[1] = "numsub"
for i, channel := range channels {
args[2+i] = channel
}
cmd := NewStringIntMapCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) PubSubNumPat() *IntCmd {
cmd := NewIntCmd("pubsub", "numpat")
c(cmd)
return cmd
}
//------------------------------------------------------------------------------
func (c cmdable) ClusterSlots() *ClusterSlotsCmd {
cmd := NewClusterSlotsCmd("cluster", "slots")
c(cmd)
return cmd
}
func (c cmdable) ClusterNodes() *StringCmd {
cmd := NewStringCmd("cluster", "nodes")
c(cmd)
return cmd
}
func (c cmdable) ClusterMeet(host, port string) *StatusCmd {
cmd := NewStatusCmd("cluster", "meet", host, port)
c(cmd)
return cmd
}
func (c cmdable) ClusterForget(nodeID string) *StatusCmd {
cmd := NewStatusCmd("cluster", "forget", nodeID)
c(cmd)
return cmd
}
func (c cmdable) ClusterReplicate(nodeID string) *StatusCmd {
cmd := NewStatusCmd("cluster", "replicate", nodeID)
c(cmd)
return cmd
}
func (c cmdable) ClusterResetSoft() *StatusCmd {
cmd := NewStatusCmd("cluster", "reset", "soft")
c(cmd)
return cmd
}
func (c cmdable) ClusterResetHard() *StatusCmd {
cmd := NewStatusCmd("cluster", "reset", "hard")
c(cmd)
return cmd
}
func (c cmdable) ClusterInfo() *StringCmd {
cmd := NewStringCmd("cluster", "info")
c(cmd)
return cmd
}
func (c cmdable) ClusterKeySlot(key string) *IntCmd {
cmd := NewIntCmd("cluster", "keyslot", key)
c(cmd)
return cmd
}
func (c cmdable) ClusterGetKeysInSlot(slot int, count int) *StringSliceCmd {
cmd := NewStringSliceCmd("cluster", "getkeysinslot", slot, count)
c(cmd)
return cmd
}
func (c cmdable) ClusterCountFailureReports(nodeID string) *IntCmd {
cmd := NewIntCmd("cluster", "count-failure-reports", nodeID)
c(cmd)
return cmd
}
func (c cmdable) ClusterCountKeysInSlot(slot int) *IntCmd {
cmd := NewIntCmd("cluster", "countkeysinslot", slot)
c(cmd)
return cmd
}
func (c cmdable) ClusterDelSlots(slots ...int) *StatusCmd {
args := make([]interface{}, 2+len(slots))
args[0] = "cluster"
args[1] = "delslots"
for i, slot := range slots {
args[2+i] = slot
}
cmd := NewStatusCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) ClusterDelSlotsRange(min, max int) *StatusCmd {
size := max - min + 1
slots := make([]int, size)
for i := 0; i < size; i++ {
slots[i] = min + i
}
return c.ClusterDelSlots(slots...)
}
func (c cmdable) ClusterSaveConfig() *StatusCmd {
cmd := NewStatusCmd("cluster", "saveconfig")
c(cmd)
return cmd
}
func (c cmdable) ClusterSlaves(nodeID string) *StringSliceCmd {
cmd := NewStringSliceCmd("cluster", "slaves", nodeID)
c(cmd)
return cmd
}
func (c cmdable) ReadOnly() *StatusCmd {
cmd := NewStatusCmd("readonly")
c(cmd)
return cmd
}
func (c cmdable) ReadWrite() *StatusCmd {
cmd := NewStatusCmd("readwrite")
c(cmd)
return cmd
}
func (c cmdable) ClusterFailover() *StatusCmd {
cmd := NewStatusCmd("cluster", "failover")
c(cmd)
return cmd
}
func (c cmdable) ClusterAddSlots(slots ...int) *StatusCmd {
args := make([]interface{}, 2+len(slots))
args[0] = "cluster"
args[1] = "addslots"
for i, num := range slots {
args[2+i] = num
}
cmd := NewStatusCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) ClusterAddSlotsRange(min, max int) *StatusCmd {
size := max - min + 1
slots := make([]int, size)
for i := 0; i < size; i++ {
slots[i] = min + i
}
return c.ClusterAddSlots(slots...)
}
//------------------------------------------------------------------------------
func (c cmdable) GeoAdd(key string, geoLocation ...*GeoLocation) *IntCmd {
args := make([]interface{}, 2+3*len(geoLocation))
args[0] = "geoadd"
args[1] = key
for i, eachLoc := range geoLocation {
args[2+3*i] = eachLoc.Longitude
args[2+3*i+1] = eachLoc.Latitude
args[2+3*i+2] = eachLoc.Name
}
cmd := NewIntCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) GeoRadius(key string, longitude, latitude float64, query *GeoRadiusQuery) *GeoLocationCmd {
cmd := NewGeoLocationCmd(query, "georadius", key, longitude, latitude)
c(cmd)
return cmd
}
func (c cmdable) GeoRadiusRO(key string, longitude, latitude float64, query *GeoRadiusQuery) *GeoLocationCmd {
cmd := NewGeoLocationCmd(query, "georadius_ro", key, longitude, latitude)
c(cmd)
return cmd
}
func (c cmdable) GeoRadiusByMember(key, member string, query *GeoRadiusQuery) *GeoLocationCmd {
cmd := NewGeoLocationCmd(query, "georadiusbymember", key, member)
c(cmd)
return cmd
}
func (c cmdable) GeoRadiusByMemberRO(key, member string, query *GeoRadiusQuery) *GeoLocationCmd {
cmd := NewGeoLocationCmd(query, "georadiusbymember_ro", key, member)
c(cmd)
return cmd
}
func (c cmdable) GeoDist(key string, member1, member2, unit string) *FloatCmd {
if unit == "" {
unit = "km"
}
cmd := NewFloatCmd("geodist", key, member1, member2, unit)
c(cmd)
return cmd
}
func (c cmdable) GeoHash(key string, members ...string) *StringSliceCmd {
args := make([]interface{}, 2+len(members))
args[0] = "geohash"
args[1] = key
for i, member := range members {
args[2+i] = member
}
cmd := NewStringSliceCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) GeoPos(key string, members ...string) *GeoPosCmd {
args := make([]interface{}, 2+len(members))
args[0] = "geopos"
args[1] = key
for i, member := range members {
args[2+i] = member
}
cmd := NewGeoPosCmd(args...)
c(cmd)
return cmd
}
//------------------------------------------------------------------------------
func (c cmdable) MemoryUsage(key string, samples ...int) *IntCmd {
args := []interface{}{"memory", "usage", key}
if len(samples) > 0 {
if len(samples) != 1 {
panic("MemoryUsage expects single sample count")
}
args = append(args, "SAMPLES", samples[0])
}
cmd := NewIntCmd(args...)
c(cmd)
return cmd
}
//------------------------------------------------------------------------------
// SlotsSetSlot 设置slot的状态,slotStatus必须为下列其一:
// 1 SlotStatusMigrating("migrating")
// 2 or SlotStatusStable ("stable")
func (c cmdable) SlotsSetSlot(slot int, slotStatus string) *StatusCmd {
args := []interface{}{"slotssetslot", slot, slotStatus}
cmd := NewStatusCmd(args...)
c(cmd)
return cmd
}
// SlotsMgrtSlot migrate slot keys
func (c cmdable) SlotsMgrtSlot(host string, port int, timeoutInMills int, slot int, keyNum int64) *IntSliceCmd {
args := []interface{}{"slotsmgrtslot", host, port, timeoutInMills, slot, keyNum}
cmd := NewIntSliceCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) SlotsHashKey(keys ...string) *IntSliceCmd {
args := make([]interface{}, 1+len(keys))
args[0] = "slotshashkey"
for i, key := range keys {
args[1+i] = key
}
cmd := NewIntSliceCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) SlotsInfo(startSlot int, count int) *IntMatrixCmd {
args := []interface{}{"slotsinfo", startSlot, count}
cmd := NewIntMatrixCmd(args...)
c(cmd)
return cmd
}
func (c cmdable) SlotsMgrtState(startSlot int, count int) *IntMatrixCmd {
args := []interface{}{"slotsmgrtstate", startSlot, count}
cmd := NewIntMatrixCmd(args...)
c(cmd)
return cmd
} | }
if a.Block >= 0 {
args = append(args, "block", int64(a.Block/time.Millisecond))
} |
lib.rs | // DO NOT EDIT !
// This file was generated automatically from 'src/mako/api/lib.rs.mako'
// DO NOT EDIT !
//! This documentation was generated from *Cloud User Accounts* crate version *1.0.5+20160316*, where *20160316* is the exact revision of the *clouduseraccounts:vm_beta* schema built by the [mako](http://www.makotemplates.org/) code generator *v1.0.5*.
//!
//! Everything else about the *Cloud User Accounts* *vm_beta* API can be found at the
//! [official documentation site](https://cloud.google.com/compute/docs/access/user-accounts/api/latest/).
//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/clouduseraccountsvm_beta).
//! # Features
//!
//! Handle the following *Resources* with ease from the central [hub](struct.CloudUserAccounts.html) ...
//!
//! * global accounts operations
//! * [*delete*](struct.GlobalAccountsOperationDeleteCall.html), [*get*](struct.GlobalAccountsOperationGetCall.html) and [*list*](struct.GlobalAccountsOperationListCall.html)
//! * [groups](struct.Group.html)
//! * [*add member*](struct.GroupAddMemberCall.html), [*delete*](struct.GroupDeleteCall.html), [*get*](struct.GroupGetCall.html), [*insert*](struct.GroupInsertCall.html), [*list*](struct.GroupListCall.html) and [*remove member*](struct.GroupRemoveMemberCall.html)
//! * linux
//! * [*get authorized keys view*](struct.LinuxGetAuthorizedKeysViewCall.html) and [*get linux account views*](struct.LinuxGetLinuxAccountViewCall.html)
//! * [users](struct.User.html)
//! * [*add public key*](struct.UserAddPublicKeyCall.html), [*delete*](struct.UserDeleteCall.html), [*get*](struct.UserGetCall.html), [*insert*](struct.UserInsertCall.html), [*list*](struct.UserListCall.html) and [*remove public key*](struct.UserRemovePublicKeyCall.html)
//!
//!
//!
//!
//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](http://byron.github.io/google-apis-rs).
//!
//! # Structure of this Library
//!
//! The API is structured into the following primary items:
//!
//! * **[Hub](struct.CloudUserAccounts.html)**
//! * a central object to maintain state and allow accessing all *Activities*
//! * creates [*Method Builders*](trait.MethodsBuilder.html) which in turn
//! allow access to individual [*Call Builders*](trait.CallBuilder.html)
//! * **[Resources](trait.Resource.html)**
//! * primary types that you can apply *Activities* to
//! * a collection of properties and *Parts*
//! * **[Parts](trait.Part.html)**
//! * a collection of properties
//! * never directly used in *Activities*
//! * **[Activities](trait.CallBuilder.html)**
//! * operations to apply to *Resources*
//!
//! All *structures* are marked with applicable traits to further categorize them and ease browsing.
//!
//! Generally speaking, you can invoke *Activities* like this:
//!
//! ```Rust,ignore
//! let r = hub.resource().activity(...).doit()
//! ```
//!
//! Or specifically ...
//!
//! ```ignore
//! let r = hub.groups().delete(...).doit()
//! let r = hub.users().add_public_key(...).doit()
//! let r = hub.users().insert(...).doit()
//! let r = hub.groups().add_member(...).doit()
//! let r = hub.users().delete(...).doit()
//! let r = hub.users().remove_public_key(...).doit()
//! let r = hub.groups().insert(...).doit()
//! let r = hub.global_accounts_operations().get(...).doit()
//! let r = hub.groups().remove_member(...).doit()
//! ```
//!
//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities`
//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be
//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired.
//! The `doit()` method performs the actual communication with the server and returns the respective result.
//!
//! # Usage
//!
//! ## Setting up your Project
//!
//! To use this library, you would put the following lines into your `Cargo.toml` file:
//!
//! ```toml
//! [dependencies]
//! google-clouduseraccountsvm_beta = "*"
//! ```
//!
//! ## A complete example
//!
//! ```test_harness,no_run
//! extern crate hyper;
//! extern crate hyper_rustls;
//! extern crate yup_oauth2 as oauth2;
//! extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta;
//! use clouduseraccountsvm_beta::PublicKey;
//! use clouduseraccountsvm_beta::{Result, Error};
//! # #[test] fn egal() {
//! use std::default::Default;
//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
//! use clouduseraccountsvm_beta::CloudUserAccounts;
//!
//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and
//! // `client_secret`, among other things.
//! let secret: ApplicationSecret = Default::default();
//! // Instantiate the authenticator. It will choose a suitable authentication flow for you,
//! // unless you replace `None` with the desired Flow.
//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
//! // retrieve them from storage.
//! let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
//! hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
//! <MemoryStorage as Default>::default(), None);
//! let mut hub = CloudUserAccounts::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
//! // As the method needs a request, you would usually fill it with the desired information
//! // into the respective structure. Some of the parts shown here might not be applicable !
//! // Values shown here are possibly random and not representative !
//! let mut req = PublicKey::default();
//!
//! // You can configure optional parameters by calling the respective setters at will, and
//! // execute the final call using `doit()`.
//! // Values shown here are possibly random and not representative !
//! let result = hub.users().add_public_key(req, "project", "user")
//! .doit();
//!
//! match result {
//! Err(e) => match e {
//! // The Error enum provides details about what exactly happened.
//! // You can also just use its `Debug`, `Display` or `Error` traits
//! Error::HttpError(_)
//! |Error::MissingAPIKey
//! |Error::MissingToken(_)
//! |Error::Cancelled
//! |Error::UploadSizeLimitExceeded(_, _)
//! |Error::Failure(_)
//! |Error::BadRequest(_)
//! |Error::FieldClash(_)
//! |Error::JsonDecodeError(_, _) => println!("{}", e),
//! },
//! Ok(res) => println!("Success: {:?}", res),
//! }
//! # }
//! ```
//! ## Handling Errors
//!
//! All errors produced by the system are provided either as [Result](enum.Result.html) enumeration as return value of
//! the doit() methods, or handed as possibly intermediate results to either the
//! [Hub Delegate](trait.Delegate.html), or the [Authenticator Delegate](https://docs.rs/yup-oauth2/*/yup_oauth2/trait.AuthenticatorDelegate.html).
//!
//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This
//! makes the system potentially resilient to all kinds of errors.
//!
//! ## Uploads and Downloads
//! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be
//! read by you to obtain the media.
//! If such a method also supports a [Response Result](trait.ResponseResult.html), it will return that by default.
//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making
//! this call: `.param("alt", "media")`.
//!
//! Methods supporting uploads can do so using up to 2 different protocols:
//! *simple* and *resumable*. The distinctiveness of each is represented by customized
//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively.
//!
//! ## Customization and Callbacks
//!
//! You may alter the way an `doit()` method is called by providing a [delegate](trait.Delegate.html) to the
//! [Method Builder](trait.CallBuilder.html) before making the final `doit()` call.
//! Respective methods will be called to provide progress information, as well as determine whether the system should
//! retry on failure.
//!
//! The [delegate trait](trait.Delegate.html) is default-implemented, allowing you to customize it with minimal effort.
//!
//! ## Optional Parts in Server-Requests
//!
//! All structures provided by this library are made to be [enocodable](trait.RequestValue.html) and
//! [decodable](trait.ResponseResult.html) via *json*. Optionals are used to indicate that partial requests are responses
//! are valid.
//! Most optionals are are considered [Parts](trait.Part.html) which are identifiable by name, which will be sent to
//! the server to indicate either the set parts of the request or the desired parts in the response.
//!
//! ## Builder Arguments
//!
//! Using [method builders](trait.CallBuilder.html), you are able to prepare an action call by repeatedly calling it's methods.
//! These will always take a single argument, for which the following statements are true.
//!
//! * [PODs][wiki-pod] are handed by copy
//! * strings are passed as `&str`
//! * [request values](trait.RequestValue.html) are moved
//!
//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times.
//!
//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure
//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern
//! [google-go-api]: https://github.com/google/google-api-go-client
//!
//!
// Unused attributes happen thanks to defined, but unused structures
// We don't warn about this, as depending on the API, some data structures or facilities are never used.
// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any
// unused imports in fully featured APIs. Same with unused_mut ... .
#![allow(unused_imports, unused_mut, dead_code)]
// DO NOT EDIT !
// This file was generated automatically from 'src/mako/api/lib.rs.mako'
// DO NOT EDIT !
#[macro_use]
extern crate serde_derive;
extern crate hyper;
extern crate serde;
extern crate serde_json;
extern crate yup_oauth2 as oauth2;
extern crate mime;
extern crate url;
mod cmn;
use std::collections::HashMap;
use std::cell::RefCell;
use std::borrow::BorrowMut;
use std::default::Default;
use std::collections::BTreeMap;
use serde_json as json;
use std::io;
use std::fs;
use std::mem;
use std::thread::sleep;
use std::time::Duration;
pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, Error, CallBuilder, Hub, ReadSeek, Part,
ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, MethodsBuilder,
Resource, ErrorResponse, remove_json_null_values};
// ##############
// UTILITIES ###
// ############
/// Identifies the an OAuth2 authorization scope.
/// A scope is needed when requesting an
/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication).
#[derive(PartialEq, Eq, Hash)]
pub enum Scope {
/// View your Google Cloud User Accounts
CloudUseraccountReadonly,
/// View your data across Google Cloud Platform services
CloudPlatformReadOnly,
/// View and manage your data across Google Cloud Platform services
CloudPlatform,
/// Manage your Google Cloud User Accounts
CloudUseraccount,
}
impl AsRef<str> for Scope {
fn as_ref(&self) -> &str {
match *self {
Scope::CloudUseraccountReadonly => "https://www.googleapis.com/auth/cloud.useraccounts.readonly",
Scope::CloudPlatformReadOnly => "https://www.googleapis.com/auth/cloud-platform.read-only",
Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform",
Scope::CloudUseraccount => "https://www.googleapis.com/auth/cloud.useraccounts",
}
}
}
impl Default for Scope {
fn default() -> Scope {
Scope::CloudUseraccountReadonly
}
}
// ########
// HUB ###
// ######
/// Central instance to access all CloudUserAccounts related resource activities
///
/// # Examples
///
/// Instantiate a new hub
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate yup_oauth2 as oauth2;
/// extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta;
/// use clouduseraccountsvm_beta::PublicKey;
/// use clouduseraccountsvm_beta::{Result, Error};
/// # #[test] fn egal() {
/// use std::default::Default;
/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// use clouduseraccountsvm_beta::CloudUserAccounts;
///
/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and
/// // `client_secret`, among other things.
/// let secret: ApplicationSecret = Default::default();
/// // Instantiate the authenticator. It will choose a suitable authentication flow for you,
/// // unless you replace `None` with the desired Flow.
/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
/// // retrieve them from storage.
/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// <MemoryStorage as Default>::default(), None);
/// let mut hub = CloudUserAccounts::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = PublicKey::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.users().add_public_key(req, "project", "user")
/// .doit();
///
/// match result {
/// Err(e) => match e {
/// // The Error enum provides details about what exactly happened.
/// // You can also just use its `Debug`, `Display` or `Error` traits
/// Error::HttpError(_)
/// |Error::MissingAPIKey
/// |Error::MissingToken(_)
/// |Error::Cancelled
/// |Error::UploadSizeLimitExceeded(_, _)
/// |Error::Failure(_)
/// |Error::BadRequest(_)
/// |Error::FieldClash(_)
/// |Error::JsonDecodeError(_, _) => println!("{}", e),
/// },
/// Ok(res) => println!("Success: {:?}", res),
/// }
/// # }
/// ```
pub struct CloudUserAccounts<C, A> {
client: RefCell<C>,
auth: RefCell<A>,
_user_agent: String,
_base_url: String,
_root_url: String,
}
impl<'a, C, A> Hub for CloudUserAccounts<C, A> {}
impl<'a, C, A> CloudUserAccounts<C, A>
where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
pub fn new(client: C, authenticator: A) -> CloudUserAccounts<C, A> {
CloudUserAccounts {
client: RefCell::new(client),
auth: RefCell::new(authenticator),
_user_agent: "google-api-rust-client/1.0.5".to_string(),
_base_url: "https://www.googleapis.com/clouduseraccounts/vm_beta/projects/".to_string(),
_root_url: "https://www.googleapis.com/".to_string(),
}
}
pub fn global_accounts_operations(&'a self) -> GlobalAccountsOperationMethods<'a, C, A> {
GlobalAccountsOperationMethods { hub: &self }
}
pub fn groups(&'a self) -> GroupMethods<'a, C, A> {
GroupMethods { hub: &self }
}
pub fn linux(&'a self) -> LinuxMethods<'a, C, A> {
LinuxMethods { hub: &self }
}
pub fn users(&'a self) -> UserMethods<'a, C, A> {
UserMethods { hub: &self }
}
/// Set the user-agent header field to use in all requests to the server.
/// It defaults to `google-api-rust-client/1.0.5`.
///
/// Returns the previously set user-agent.
pub fn user_agent(&mut self, agent_name: String) -> String {
mem::replace(&mut self._user_agent, agent_name)
}
/// Set the base url to use in all requests to the server.
/// It defaults to `https://www.googleapis.com/clouduseraccounts/vm_beta/projects/`.
///
/// Returns the previously set base url.
pub fn base_url(&mut self, new_base_url: String) -> String {
mem::replace(&mut self._base_url, new_base_url)
}
/// Set the root url to use in all requests to the server.
/// It defaults to `https://www.googleapis.com/`.
///
/// Returns the previously set root url.
pub fn root_url(&mut self, new_root_url: String) -> String {
mem::replace(&mut self._root_url, new_root_url)
}
}
// ############
// SCHEMAS ###
// ##########
/// There is no detailed description.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [list groups](struct.GroupListCall.html) (response)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct GroupList {
/// [Output Only] A token used to continue a truncated list request.
#[serde(rename="nextPageToken")]
pub next_page_token: Option<String>,
/// [Output Only] A list of Group resources.
pub items: Option<Vec<Group>>,
/// [Output Only] Type of resource. Always clouduseraccounts#groupList for lists of groups.
pub kind: Option<String>,
/// [Output Only] Unique identifier for the resource; defined by the server.
pub id: Option<String>,
/// [Output Only] Server defined URL for this resource.
#[serde(rename="selfLink")]
pub self_link: Option<String>,
}
impl ResponseResult for GroupList {}
/// There is no detailed description.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [get linux account views linux](struct.LinuxGetLinuxAccountViewCall.html) (response)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LinuxGetLinuxAccountViewsResponse {
/// [Output Only] A list of authorized user accounts and groups.
pub resource: Option<LinuxAccountViews>,
}
impl ResponseResult for LinuxGetLinuxAccountViewsResponse {}
/// There is no detailed description.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [add member groups](struct.GroupAddMemberCall.html) (request)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct GroupsAddMemberRequest {
/// Fully-qualified URLs of the User resources to add.
pub users: Option<Vec<String>>,
}
impl RequestValue for GroupsAddMemberRequest {}
/// [Output Only] Metadata about this warning in key: value format. For example:
/// "data": [ { "key": "scope", "value": "zones/us-east1-d" }
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct OperationWarningsData {
/// [Output Only] A key that provides more detail on the warning being returned. For example, for warnings where there are no results in a list request for a particular zone, this key might be scope and the key value might be the zone name. Other examples might be a key indicating a deprecated resource and a suggested replacement, or a warning about invalid network settings (for example, if an instance attempts to perform IP forwarding but is not enabled for IP forwarding).
pub key: Option<String>,
/// [Output Only] A warning data value corresponding to the key.
pub value: Option<String>,
}
impl NestedType for OperationWarningsData {}
impl Part for OperationWarningsData {}
/// A list of all Linux accounts for this project. This API is only used by Compute Engine virtual machines to get information about user accounts for a project or instance. Linux resources are read-only views into users and groups managed by the Compute Engine Accounts API.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LinuxAccountViews {
/// [Output Only] Type of the resource. Always clouduseraccounts#linuxAccountViews for Linux resources.
pub kind: Option<String>,
/// [Output Only] A list of all users within a project.
#[serde(rename="userViews")]
pub user_views: Option<Vec<LinuxUserView>>,
/// [Output Only] A list of all groups within a project.
#[serde(rename="groupViews")]
pub group_views: Option<Vec<LinuxGroupView>>,
}
impl Part for LinuxAccountViews {}
/// A detailed view of a Linux user account.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LinuxUserView {
/// [Output Only] The username of the account.
pub username: Option<String>,
/// [Output Only] The path to the login shell for this account.
pub shell: Option<String>,
/// [Output Only] The GECOS (user information) entry for this account.
pub gecos: Option<String>,
/// [Output Only] User ID.
pub uid: Option<u32>,
/// [Output Only] The path to the home directory for this account.
#[serde(rename="homeDirectory")]
pub home_directory: Option<String>,
/// [Output Only] User's default group ID.
pub gid: Option<u32>,
}
impl Part for LinuxUserView {}
/// [Output Only] If warning messages are generated during processing of the operation, this field will be populated.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct OperationWarnings {
/// [Output Only] A human-readable description of the warning code.
pub message: Option<String>,
/// [Output Only] A warning code, if applicable. For example, Compute Engine returns NO_RESULTS_ON_PAGE if there are no results in the response.
pub code: Option<String>,
/// [Output Only] Metadata about this warning in key: value format. For example:
/// "data": [ { "key": "scope", "value": "zones/us-east1-d" }
pub data: Option<Vec<OperationWarningsData>>,
}
impl NestedType for OperationWarnings {}
impl Part for OperationWarnings {}
/// Contains a list of Operation resources.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [list global accounts operations](struct.GlobalAccountsOperationListCall.html) (response)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct OperationList {
/// [Output Only] This token allows you to get the next page of results for list requests. If the number of results is larger than maxResults, use the nextPageToken as a value for the query parameter pageToken in the next list request. Subsequent list requests will have their own nextPageToken to continue paging through the results.
#[serde(rename="nextPageToken")]
pub next_page_token: Option<String>,
/// [Output Only] A list of Operation resources.
pub items: Option<Vec<Operation>>,
/// [Output Only] Type of resource. Always compute#operations for Operations resource.
pub kind: Option<String>,
/// [Output Only] The unique identifier for the resource. This identifier is defined by the server.
pub id: Option<String>,
/// [Output Only] Server-defined URL for this resource.
#[serde(rename="selfLink")]
pub self_link: Option<String>,
}
impl ResponseResult for OperationList {}
/// [Output Only] If errors are generated during processing of the operation, this field will be populated.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct OperationError {
/// [Output Only] The array of errors encountered while processing this operation.
pub errors: Option<Vec<OperationErrorErrors>>,
}
impl NestedType for OperationError {}
impl Part for OperationError {}
/// [Output Only] The array of errors encountered while processing this operation.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct OperationErrorErrors {
/// [Output Only] An optional, human-readable error message.
pub message: Option<String>,
/// [Output Only] The error type identifier for this error.
pub code: Option<String>,
/// [Output Only] Indicates the field in the request that caused the error. This property is optional.
pub location: Option<String>,
}
impl NestedType for OperationErrorErrors {}
impl Part for OperationErrorErrors {}
/// There is no detailed description.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [list users](struct.UserListCall.html) (response)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct UserList {
/// [Output Only] A token used to continue a truncated list request.
#[serde(rename="nextPageToken")]
pub next_page_token: Option<String>,
/// [Output Only] A list of User resources.
pub items: Option<Vec<User>>,
/// [Output Only] Type of resource. Always clouduseraccounts#userList for lists of users.
pub kind: Option<String>,
/// [Output Only] Unique identifier for the resource; defined by the server.
pub id: Option<String>,
/// [Output Only] Server defined URL for this resource.
#[serde(rename="selfLink")]
pub self_link: Option<String>,
}
impl ResponseResult for UserList {}
/// A detailed view of a Linux group.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LinuxGroupView {
/// [Output Only] Group name.
#[serde(rename="groupName")]
pub group_name: Option<String>,
/// [Output Only] The Group ID.
pub gid: Option<u32>,
/// [Output Only] List of user accounts that belong to the group.
pub members: Option<Vec<String>>,
}
impl Part for LinuxGroupView {}
/// A public key for authenticating to guests.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [add public key users](struct.UserAddPublicKeyCall.html) (request)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct PublicKey {
/// Optional expiration timestamp. If provided, the timestamp must be in RFC3339 text format. If not provided, the public key never expires.
#[serde(rename="expirationTimestamp")]
pub expiration_timestamp: Option<String>,
/// [Output Only] Creation timestamp in RFC3339 text format.
#[serde(rename="creationTimestamp")]
pub creation_timestamp: Option<String>,
/// An optional textual description of the resource; provided by the client when the resource is created.
pub description: Option<String>,
/// Public key text in SSH format, defined by RFC4253 section 6.6.
pub key: Option<String>,
/// [Output Only] The fingerprint of the key is defined by RFC4716 to be the MD5 digest of the public key.
pub fingerprint: Option<String>,
}
impl RequestValue for PublicKey {}
/// There is no detailed description.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [remove member groups](struct.GroupRemoveMemberCall.html) (request)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct GroupsRemoveMemberRequest {
/// Fully-qualified URLs of the User resources to remove.
pub users: Option<Vec<String>>,
}
impl RequestValue for GroupsRemoveMemberRequest {}
/// A User resource.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [add public key users](struct.UserAddPublicKeyCall.html) (none)
/// * [list users](struct.UserListCall.html) (none)
/// * [delete users](struct.UserDeleteCall.html) (none)
/// * [insert users](struct.UserInsertCall.html) (request)
/// * [get users](struct.UserGetCall.html) (response)
/// * [remove public key users](struct.UserRemovePublicKeyCall.html) (none)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct User {
/// [Output Only] Type of the resource. Always clouduseraccounts#user for users.
pub kind: Option<String>,
/// Name of the resource; provided by the client when the resource is created.
pub name: Option<String>,
/// [Output Only] Public keys that this user may use to login.
#[serde(rename="publicKeys")]
pub public_keys: Option<Vec<PublicKey>>,
/// [Output Only] A list of URLs to Group resources who contain the user. Users are only members of groups in the same project.
pub groups: Option<Vec<String>>,
/// Email address of account's owner. This account will be validated to make sure it exists. The email can belong to any domain, but it must be tied to a Google account.
pub owner: Option<String>,
/// [Output Only] Creation timestamp in RFC3339 text format.
#[serde(rename="creationTimestamp")]
pub creation_timestamp: Option<String>,
/// [Output Only] Unique identifier for the resource; defined by the server.
pub id: Option<String>,
/// [Output Only] Server defined URL for the resource.
#[serde(rename="selfLink")]
pub self_link: Option<String>,
/// An optional textual description of the resource; provided by the client when the resource is created.
pub description: Option<String>,
}
impl RequestValue for User {}
impl Resource for User {}
impl ResponseResult for User {}
/// There is no detailed description.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [get authorized keys view linux](struct.LinuxGetAuthorizedKeysViewCall.html) (response)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LinuxGetAuthorizedKeysViewResponse {
/// [Output Only] A list of authorized public keys for a user.
pub resource: Option<AuthorizedKeysView>,
}
impl ResponseResult for LinuxGetAuthorizedKeysViewResponse {}
/// A Group resource.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [delete groups](struct.GroupDeleteCall.html) (none)
/// * [remove member groups](struct.GroupRemoveMemberCall.html) (none)
/// * [get groups](struct.GroupGetCall.html) (response)
/// * [add member groups](struct.GroupAddMemberCall.html) (none)
/// * [insert groups](struct.GroupInsertCall.html) (request)
/// * [list groups](struct.GroupListCall.html) (none)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Group {
/// [Output Only] Type of the resource. Always clouduseraccounts#group for groups.
pub kind: Option<String>,
/// Name of the resource; provided by the client when the resource is created.
pub name: Option<String>,
/// [Output Only] A list of URLs to User resources who belong to the group. Users may only be members of groups in the same project.
pub members: Option<Vec<String>>,
/// [Output Only] Creation timestamp in RFC3339 text format.
#[serde(rename="creationTimestamp")]
pub creation_timestamp: Option<String>,
/// [Output Only] Unique identifier for the resource; defined by the server.
pub id: Option<String>,
/// [Output Only] Server defined URL for the resource.
#[serde(rename="selfLink")]
pub self_link: Option<String>,
/// An optional textual description of the resource; provided by the client when the resource is created.
pub description: Option<String>,
}
impl RequestValue for Group {}
impl Resource for Group {}
impl ResponseResult for Group {}
/// A list of authorized public keys for a user account.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct AuthorizedKeysView {
/// [Output Only] The list of authorized public keys in SSH format.
pub keys: Option<Vec<String>>,
/// [Output Only] Whether the user has the ability to elevate on the instance that requested the authorized keys.
pub sudoer: Option<bool>,
}
impl Part for AuthorizedKeysView {}
/// An Operation resource, used to manage asynchronous API requests.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [delete groups](struct.GroupDeleteCall.html) (response)
/// * [add public key users](struct.UserAddPublicKeyCall.html) (response)
/// * [insert users](struct.UserInsertCall.html) (response)
/// * [add member groups](struct.GroupAddMemberCall.html) (response)
/// * [delete users](struct.UserDeleteCall.html) (response)
/// * [remove public key users](struct.UserRemovePublicKeyCall.html) (response)
/// * [insert groups](struct.GroupInsertCall.html) (response)
/// * [get global accounts operations](struct.GlobalAccountsOperationGetCall.html) (response)
/// * [remove member groups](struct.GroupRemoveMemberCall.html) (response)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Operation {
/// [Output Only] The status of the operation, which can be one of the following: PENDING, RUNNING, or DONE.
pub status: Option<String>,
/// [Output Only] A textual description of the operation, which is set when the operation is created.
pub description: Option<String>,
/// [Output Only] If warning messages are generated during processing of the operation, this field will be populated.
pub warnings: Option<Vec<OperationWarnings>>,
/// [Output Only] If errors are generated during processing of the operation, this field will be populated.
pub error: Option<OperationError>,
/// [Output Only] The unique target ID, which identifies a specific incarnation of the target resource.
#[serde(rename="targetId")]
pub target_id: Option<String>,
/// [Output Only] User who requested the operation, for example: [email protected].
pub user: Option<String>,
/// [Output Only] The time that this operation was started by the server. This value is in RFC3339 text format.
#[serde(rename="startTime")]
pub start_time: Option<String>,
/// [Output Only] Reserved for future use.
#[serde(rename="clientOperationId")]
pub client_operation_id: Option<String>,
/// [Output Only] Creation timestamp in RFC3339 text format.
#[serde(rename="creationTimestamp")]
pub creation_timestamp: Option<String>,
/// [Output Only] The unique identifier for the resource. This identifier is defined by the server.
pub id: Option<String>,
/// [Output Only] Type of the resource. Always compute#operation for Operation resources.
pub kind: Option<String>,
/// [Output Only] Name of the resource.
pub name: Option<String>,
/// [Output Only] The URL of the zone where the operation resides. Only available when performing per-zone operations.
pub zone: Option<String>,
/// [Output Only] The URL of the region where the operation resides. Only available when performing regional operations.
pub region: Option<String>,
/// [Output Only] The type of operation, such as insert, update, or delete, and so on.
#[serde(rename="operationType")]
pub operation_type: Option<String>,
/// [Output Only] Server-defined URL for the resource.
#[serde(rename="selfLink")]
pub self_link: Option<String>,
/// [Output Only] The time that this operation was requested. This value is in RFC3339 text format.
#[serde(rename="insertTime")]
pub insert_time: Option<String>,
/// [Output Only] If the operation fails, this field contains the HTTP error message that was returned, such as NOT FOUND.
#[serde(rename="httpErrorMessage")]
pub http_error_message: Option<String>,
/// [Output Only] An optional progress indicator that ranges from 0 to 100. There is no requirement that this be linear or support any granularity of operations. This should not be used to guess when the operation will be complete. This number should monotonically increase as the operation progresses.
pub progress: Option<i32>,
/// [Output Only] The time that this operation was completed. This value is in RFC3339 text format.
#[serde(rename="endTime")]
pub end_time: Option<String>,
/// [Output Only] If the operation fails, this field contains the HTTP error status code that was returned. For example, a 404 means the resource was not found.
#[serde(rename="httpErrorStatusCode")]
pub http_error_status_code: Option<i32>,
/// [Output Only] An optional textual description of the current status of the operation.
#[serde(rename="statusMessage")]
pub status_message: Option<String>,
/// [Output Only] The URL of the resource that the operation modifies.
#[serde(rename="targetLink")]
pub target_link: Option<String>,
}
impl ResponseResult for Operation {}
// ###################
// MethodBuilders ###
// #################
/// A builder providing access to all methods supported on *globalAccountsOperation* resources.
/// It is not used directly, but through the `CloudUserAccounts` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate yup_oauth2 as oauth2;
/// extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta;
///
/// # #[test] fn egal() {
/// use std::default::Default;
/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// use clouduseraccountsvm_beta::CloudUserAccounts;
///
/// let secret: ApplicationSecret = Default::default();
/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// <MemoryStorage as Default>::default(), None);
/// let mut hub = CloudUserAccounts::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `delete(...)`, `get(...)` and `list(...)`
/// // to build up your call.
/// let rb = hub.global_accounts_operations();
/// # }
/// ```
pub struct GlobalAccountsOperationMethods<'a, C, A>
where C: 'a, A: 'a {
hub: &'a CloudUserAccounts<C, A>,
}
impl<'a, C, A> MethodsBuilder for GlobalAccountsOperationMethods<'a, C, A> {}
impl<'a, C, A> GlobalAccountsOperationMethods<'a, C, A> {
/// Create a builder to help you perform the following task:
///
/// Deletes the specified operation resource.
///
/// # Arguments
///
/// * `project` - Project ID for this request.
/// * `operation` - Name of the Operations resource to delete.
pub fn delete(&self, project: &str, operation: &str) -> GlobalAccountsOperationDeleteCall<'a, C, A> {
GlobalAccountsOperationDeleteCall {
hub: self.hub,
_project: project.to_string(),
_operation: operation.to_string(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Retrieves the list of operation resources contained within the specified project.
///
/// # Arguments
///
/// * `project` - Project ID for this request.
pub fn list(&self, project: &str) -> GlobalAccountsOperationListCall<'a, C, A> {
GlobalAccountsOperationListCall {
hub: self.hub,
_project: project.to_string(),
_page_token: Default::default(),
_order_by: Default::default(),
_max_results: Default::default(),
_filter: Default::default(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Retrieves the specified operation resource.
///
/// # Arguments
///
/// * `project` - Project ID for this request.
/// * `operation` - Name of the Operations resource to return.
pub fn get(&self, project: &str, operation: &str) -> GlobalAccountsOperationGetCall<'a, C, A> {
GlobalAccountsOperationGetCall {
hub: self.hub,
_project: project.to_string(),
_operation: operation.to_string(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
}
/// A builder providing access to all methods supported on *user* resources.
/// It is not used directly, but through the `CloudUserAccounts` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate yup_oauth2 as oauth2;
/// extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta;
///
/// # #[test] fn egal() {
/// use std::default::Default;
/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// use clouduseraccountsvm_beta::CloudUserAccounts;
///
/// let secret: ApplicationSecret = Default::default();
/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// <MemoryStorage as Default>::default(), None);
/// let mut hub = CloudUserAccounts::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `add_public_key(...)`, `delete(...)`, `get(...)`, `insert(...)`, `list(...)` and `remove_public_key(...)`
/// // to build up your call.
/// let rb = hub.users();
/// # }
/// ```
pub struct UserMethods<'a, C, A>
where C: 'a, A: 'a {
hub: &'a CloudUserAccounts<C, A>,
}
impl<'a, C, A> MethodsBuilder for UserMethods<'a, C, A> {}
impl<'a, C, A> UserMethods<'a, C, A> {
/// Create a builder to help you perform the following task:
///
/// Adds a public key to the specified User resource with the data included in the request.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `project` - Project ID for this request.
/// * `user` - Name of the user for this request.
pub fn add_public_key(&self, request: PublicKey, project: &str, user: &str) -> UserAddPublicKeyCall<'a, C, A> {
UserAddPublicKeyCall {
hub: self.hub,
_request: request,
_project: project.to_string(),
_user: user.to_string(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Retrieves a list of users contained within the specified project.
///
/// # Arguments
///
/// * `project` - Project ID for this request.
pub fn list(&self, project: &str) -> UserListCall<'a, C, A> {
UserListCall {
hub: self.hub,
_project: project.to_string(),
_page_token: Default::default(),
_order_by: Default::default(),
_max_results: Default::default(),
_filter: Default::default(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Creates a User resource in the specified project using the data included in the request.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `project` - Project ID for this request.
pub fn insert(&self, request: User, project: &str) -> UserInsertCall<'a, C, A> {
UserInsertCall {
hub: self.hub,
_request: request,
_project: project.to_string(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Returns the specified User resource.
///
/// # Arguments
///
/// * `project` - Project ID for this request.
/// * `user` - Name of the user resource to return.
pub fn get(&self, project: &str, user: &str) -> UserGetCall<'a, C, A> {
UserGetCall {
hub: self.hub,
_project: project.to_string(),
_user: user.to_string(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Removes the specified public key from the user.
///
/// # Arguments
///
/// * `project` - Project ID for this request.
/// * `user` - Name of the user for this request.
/// * `fingerprint` - The fingerprint of the public key to delete. Public keys are identified by their fingerprint, which is defined by RFC4716 to be the MD5 digest of the public key.
pub fn remove_public_key(&self, project: &str, user: &str, fingerprint: &str) -> UserRemovePublicKeyCall<'a, C, A> {
UserRemovePublicKeyCall {
hub: self.hub,
_project: project.to_string(),
_user: user.to_string(),
_fingerprint: fingerprint.to_string(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Deletes the specified User resource.
///
/// # Arguments
///
/// * `project` - Project ID for this request.
/// * `user` - Name of the user resource to delete.
pub fn delete(&self, project: &str, user: &str) -> UserDeleteCall<'a, C, A> {
UserDeleteCall {
hub: self.hub,
_project: project.to_string(),
_user: user.to_string(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
}
/// A builder providing access to all methods supported on *group* resources.
/// It is not used directly, but through the `CloudUserAccounts` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate yup_oauth2 as oauth2;
/// extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta;
///
/// # #[test] fn egal() {
/// use std::default::Default;
/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// use clouduseraccountsvm_beta::CloudUserAccounts;
///
/// let secret: ApplicationSecret = Default::default();
/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// <MemoryStorage as Default>::default(), None);
/// let mut hub = CloudUserAccounts::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `add_member(...)`, `delete(...)`, `get(...)`, `insert(...)`, `list(...)` and `remove_member(...)`
/// // to build up your call.
/// let rb = hub.groups();
/// # }
/// ```
pub struct GroupMethods<'a, C, A>
where C: 'a, A: 'a {
hub: &'a CloudUserAccounts<C, A>,
}
impl<'a, C, A> MethodsBuilder for GroupMethods<'a, C, A> {}
impl<'a, C, A> GroupMethods<'a, C, A> {
/// Create a builder to help you perform the following task:
///
/// Deletes the specified Group resource.
///
/// # Arguments
///
/// * `project` - Project ID for this request.
/// * `groupName` - Name of the Group resource to delete.
pub fn delete(&self, project: &str, group_name: &str) -> GroupDeleteCall<'a, C, A> {
GroupDeleteCall {
hub: self.hub,
_project: project.to_string(),
_group_name: group_name.to_string(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Returns the specified Group resource.
///
/// # Arguments
///
/// * `project` - Project ID for this request.
/// * `groupName` - Name of the Group resource to return.
pub fn get(&self, project: &str, group_name: &str) -> GroupGetCall<'a, C, A> {
GroupGetCall {
hub: self.hub,
_project: project.to_string(),
_group_name: group_name.to_string(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Adds users to the specified group.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `project` - Project ID for this request.
/// * `groupName` - Name of the group for this request.
pub fn add_member(&self, request: GroupsAddMemberRequest, project: &str, group_name: &str) -> GroupAddMemberCall<'a, C, A> {
GroupAddMemberCall {
hub: self.hub,
_request: request,
_project: project.to_string(),
_group_name: group_name.to_string(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Creates a Group resource in the specified project using the data included in the request.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `project` - Project ID for this request.
pub fn insert(&self, request: Group, project: &str) -> GroupInsertCall<'a, C, A> {
GroupInsertCall {
hub: self.hub,
_request: request,
_project: project.to_string(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Retrieves the list of groups contained within the specified project.
///
/// # Arguments
///
/// * `project` - Project ID for this request.
pub fn list(&self, project: &str) -> GroupListCall<'a, C, A> {
GroupListCall {
hub: self.hub,
_project: project.to_string(),
_page_token: Default::default(),
_order_by: Default::default(),
_max_results: Default::default(),
_filter: Default::default(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Removes users from the specified group.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `project` - Project ID for this request.
/// * `groupName` - Name of the group for this request.
pub fn remove_member(&self, request: GroupsRemoveMemberRequest, project: &str, group_name: &str) -> GroupRemoveMemberCall<'a, C, A> {
GroupRemoveMemberCall {
hub: self.hub,
_request: request,
_project: project.to_string(),
_group_name: group_name.to_string(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
}
/// A builder providing access to all methods supported on *linux* resources.
/// It is not used directly, but through the `CloudUserAccounts` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate yup_oauth2 as oauth2;
/// extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta;
///
/// # #[test] fn egal() {
/// use std::default::Default;
/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// use clouduseraccountsvm_beta::CloudUserAccounts;
///
/// let secret: ApplicationSecret = Default::default();
/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// <MemoryStorage as Default>::default(), None);
/// let mut hub = CloudUserAccounts::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `get_authorized_keys_view(...)` and `get_linux_account_views(...)`
/// // to build up your call.
/// let rb = hub.linux();
/// # }
/// ```
pub struct LinuxMethods<'a, C, A>
where C: 'a, A: 'a {
hub: &'a CloudUserAccounts<C, A>,
}
impl<'a, C, A> MethodsBuilder for LinuxMethods<'a, C, A> {}
impl<'a, C, A> LinuxMethods<'a, C, A> {
/// Create a builder to help you perform the following task:
///
/// Retrieves a list of user accounts for an instance within a specific project.
///
/// # Arguments
///
/// * `project` - Project ID for this request.
/// * `zone` - Name of the zone for this request.
/// * `instance` - The fully-qualified URL of the virtual machine requesting the views.
pub fn get_linux_account_views(&self, project: &str, zone: &str, instance: &str) -> LinuxGetLinuxAccountViewCall<'a, C, A> {
LinuxGetLinuxAccountViewCall {
hub: self.hub,
_project: project.to_string(),
_zone: zone.to_string(),
_instance: instance.to_string(),
_page_token: Default::default(),
_order_by: Default::default(),
_max_results: Default::default(),
_filter: Default::default(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Returns a list of authorized public keys for a specific user account.
///
/// # Arguments
///
/// * `project` - Project ID for this request.
/// * `zone` - Name of the zone for this request.
/// * `user` - The user account for which you want to get a list of authorized public keys.
/// * `instance` - The fully-qualified URL of the virtual machine requesting the view.
pub fn get_authorized_keys_view(&self, project: &str, zone: &str, user: &str, instance: &str) -> LinuxGetAuthorizedKeysViewCall<'a, C, A> {
LinuxGetAuthorizedKeysViewCall {
hub: self.hub,
_project: project.to_string(),
_zone: zone.to_string(),
_user: user.to_string(),
_instance: instance.to_string(),
_login: Default::default(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
}
// ###################
// CallBuilders ###
// #################
/// Deletes the specified operation resource.
///
/// A builder for the *delete* method supported by a *globalAccountsOperation* resource.
/// It is not used directly, but through a `GlobalAccountsOperationMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use clouduseraccountsvm_beta::CloudUserAccounts;
///
/// # let secret: ApplicationSecret = Default::default();
/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// # hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// # <MemoryStorage as Default>::default(), None);
/// # let mut hub = CloudUserAccounts::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.global_accounts_operations().delete("project", "operation")
/// .doit();
/// # }
/// ```
pub struct GlobalAccountsOperationDeleteCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a CloudUserAccounts<C, A>,
_project: String,
_operation: String,
_delegate: Option<&'a mut Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for GlobalAccountsOperationDeleteCall<'a, C, A> {}
impl<'a, C, A> GlobalAccountsOperationDeleteCall<'a, C, A> where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
/// Perform the operation you have build so far.
pub fn doit(mut self) -> Result<hyper::client::Response> {
use std::io::{Read, Seek};
use hyper::header::{ContentType, ContentLength, Authorization, Bearer, UserAgent, Location};
let mut dd = DefaultDelegate;
let mut dlg: &mut Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(MethodInfo { id: "clouduseraccounts.globalAccountsOperations.delete",
http_method: hyper::method::Method::Delete });
let mut params: Vec<(&str, String)> = Vec::with_capacity((3 + self._additional_params.len()));
params.push(("project", self._project.to_string()));
params.push(("operation", self._operation.to_string()));
for &field in ["project", "operation"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
let mut url = self.hub._base_url.clone() + "{project}/global/operations/{operation}";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{project}", "project"), ("{operation}", "operation")].iter() {
let mut replace_with: Option<&str> = None;
for &(name, ref value) in params.iter() {
if name == param_name {
replace_with = Some(value);
break;
}
}
url = url.replace(find_this, replace_with.expect("to find substitution value in params"));
}
{
let mut indices_for_removal: Vec<usize> = Vec::with_capacity(2);
for param_name in ["operation", "project"].iter() {
if let Some(index) = params.iter().position(|t| &t.0 == param_name) {
indices_for_removal.push(index);
}
}
for &index in indices_for_removal.iter() {
params.remove(index);
}
}
if params.len() > 0 {
url.push('?');
url.push_str(&url::form_urlencoded::serialize(params));
}
loop {
let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) {
Ok(token) => token,
Err(err) => {
match dlg.token(&*err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(Error::MissingToken(err))
}
}
}
};
let auth_header = Authorization(Bearer { token: token.access_token });
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
let mut req = client.borrow_mut().request(hyper::method::Method::Delete, &url)
.header(UserAgent(self.hub._user_agent.clone()))
.header(auth_header.clone());
dlg.pre_request();
req.send()
};
match req_result {
Err(err) => {
if let oauth2::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(Error::HttpError(err))
}
Ok(mut res) => {
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
if let oauth2::Retry::After(d) = dlg.http_failure(&res,
json::from_str(&json_err).ok(),
json::from_str(&json_err).ok()) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<ErrorResponse>(&json_err){
Err(_) => Err(Error::Failure(res)),
Ok(serr) => Err(Error::BadRequest(serr))
}
}
let result_value = res;
dlg.finished(true);
return Ok(result_value)
}
}
}
}
/// Project ID for this request.
///
/// Sets the *project* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn project(mut self, new_value: &str) -> GlobalAccountsOperationDeleteCall<'a, C, A> {
self._project = new_value.to_string();
self
}
/// Name of the Operations resource to delete.
///
/// Sets the *operation* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn operation(mut self, new_value: &str) -> GlobalAccountsOperationDeleteCall<'a, C, A> {
self._operation = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut Delegate) -> GlobalAccountsOperationDeleteCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known paramters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *alt* (query-string) - Data format for the response.
pub fn param<T>(mut self, name: T, value: T) -> GlobalAccountsOperationDeleteCall<'a, C, A>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead the default `Scope` variant
/// `Scope::CloudPlatform`.
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> GlobalAccountsOperationDeleteCall<'a, C, A>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Retrieves the list of operation resources contained within the specified project.
///
/// A builder for the *list* method supported by a *globalAccountsOperation* resource.
/// It is not used directly, but through a `GlobalAccountsOperationMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use clouduseraccountsvm_beta::CloudUserAccounts;
///
/// # let secret: ApplicationSecret = Default::default();
/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// # hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// # <MemoryStorage as Default>::default(), None);
/// # let mut hub = CloudUserAccounts::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.global_accounts_operations().list("project")
/// .page_token("justo")
/// .order_by("amet.")
/// .max_results(20)
/// .filter("labore")
/// .doit();
/// # }
/// ```
pub struct GlobalAccountsOperationListCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a CloudUserAccounts<C, A>,
_project: String,
_page_token: Option<String>,
_order_by: Option<String>,
_max_results: Option<u32>,
_filter: Option<String>,
_delegate: Option<&'a mut Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for GlobalAccountsOperationListCall<'a, C, A> {}
impl<'a, C, A> GlobalAccountsOperationListCall<'a, C, A> where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
/// Perform the operation you have build so far.
pub fn doit(mut self) -> Result<(hyper::client::Response, OperationList)> {
use std::io::{Read, Seek};
use hyper::header::{ContentType, ContentLength, Authorization, Bearer, UserAgent, Location};
let mut dd = DefaultDelegate;
let mut dlg: &mut Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(MethodInfo { id: "clouduseraccounts.globalAccountsOperations.list",
http_method: hyper::method::Method::Get });
let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len()));
params.push(("project", self._project.to_string()));
if let Some(value) = self._page_token {
params.push(("pageToken", value.to_string()));
}
if let Some(value) = self._order_by {
params.push(("orderBy", value.to_string()));
}
if let Some(value) = self._max_results {
params.push(("maxResults", value.to_string()));
}
if let Some(value) = self._filter {
params.push(("filter", value.to_string()));
}
for &field in ["alt", "project", "pageToken", "orderBy", "maxResults", "filter"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "{project}/global/operations";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::CloudUseraccountReadonly.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{project}", "project")].iter() {
let mut replace_with: Option<&str> = None;
for &(name, ref value) in params.iter() {
if name == param_name {
replace_with = Some(value);
break;
}
}
url = url.replace(find_this, replace_with.expect("to find substitution value in params"));
}
{
let mut indices_for_removal: Vec<usize> = Vec::with_capacity(1);
for param_name in ["project"].iter() {
if let Some(index) = params.iter().position(|t| &t.0 == param_name) {
indices_for_removal.push(index);
}
}
for &index in indices_for_removal.iter() {
params.remove(index);
}
}
if params.len() > 0 {
url.push('?');
url.push_str(&url::form_urlencoded::serialize(params));
}
loop {
let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) {
Ok(token) => token,
Err(err) => {
match dlg.token(&*err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(Error::MissingToken(err))
}
}
}
};
let auth_header = Authorization(Bearer { token: token.access_token });
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url)
.header(UserAgent(self.hub._user_agent.clone()))
.header(auth_header.clone());
dlg.pre_request();
req.send()
};
match req_result {
Err(err) => {
if let oauth2::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(Error::HttpError(err))
}
Ok(mut res) => {
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
if let oauth2::Retry::After(d) = dlg.http_failure(&res,
json::from_str(&json_err).ok(),
json::from_str(&json_err).ok()) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<ErrorResponse>(&json_err){
Err(_) => Err(Error::Failure(res)),
Ok(serr) => Err(Error::BadRequest(serr))
}
}
let result_value = {
let mut json_response = String::new();
res.read_to_string(&mut json_response).unwrap();
match json::from_str(&json_response) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&json_response, &err);
return Err(Error::JsonDecodeError(json_response, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
/// Project ID for this request.
///
/// Sets the *project* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn project(mut self, new_value: &str) -> GlobalAccountsOperationListCall<'a, C, A> {
self._project = new_value.to_string();
self
}
/// Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(mut self, new_value: &str) -> GlobalAccountsOperationListCall<'a, C, A> {
self._page_token = Some(new_value.to_string());
self
}
/// Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name.
///
/// You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first.
///
/// Currently, only sorting by name or creationTimestamp desc is supported.
///
/// Sets the *order by* query property to the given value.
pub fn order_by(mut self, new_value: &str) -> GlobalAccountsOperationListCall<'a, C, A> {
self._order_by = Some(new_value.to_string());
self
}
/// The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.
///
/// Sets the *max results* query property to the given value.
pub fn max_results(mut self, new_value: u32) -> GlobalAccountsOperationListCall<'a, C, A> {
self._max_results = Some(new_value);
self
}
/// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: field_name comparison_string literal_string.
///
/// The field_name is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The comparison_string must be either eq (equals) or ne (not equals). The literal_string is the string value to filter to. The literal value must be valid for the type of field you are filtering by (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field.
///
/// For example, to filter for instances that do not have a name of example-instance, you would use filter=name ne example-instance.
///
/// Compute Engine Beta API Only: If you use filtering in the Beta API, you can also filter on nested fields. For example, you could filter on instances that have set the scheduling.automaticRestart field to true. In particular, use filtering on nested fields to take advantage of instance labels to organize and filter results based on label values.
///
/// The Beta API also supports filtering on multiple expressions by providing each separate expression within parentheses. For example, (scheduling.automaticRestart eq true) (zone eq us-central1-f). Multiple expressions are treated as AND expressions, meaning that resources must match all expressions to pass the filters.
///
/// Sets the *filter* query property to the given value.
pub fn filter(mut self, new_value: &str) -> GlobalAccountsOperationListCall<'a, C, A> {
self._filter = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut Delegate) -> GlobalAccountsOperationListCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known paramters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *alt* (query-string) - Data format for the response.
pub fn param<T>(mut self, name: T, value: T) -> GlobalAccountsOperationListCall<'a, C, A>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead the default `Scope` variant
/// `Scope::CloudUseraccountReadonly`.
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> GlobalAccountsOperationListCall<'a, C, A>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Retrieves the specified operation resource.
///
/// A builder for the *get* method supported by a *globalAccountsOperation* resource.
/// It is not used directly, but through a `GlobalAccountsOperationMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use clouduseraccountsvm_beta::CloudUserAccounts;
///
/// # let secret: ApplicationSecret = Default::default();
/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// # hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// # <MemoryStorage as Default>::default(), None);
/// # let mut hub = CloudUserAccounts::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.global_accounts_operations().get("project", "operation")
/// .doit();
/// # }
/// ```
pub struct GlobalAccountsOperationGetCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a CloudUserAccounts<C, A>,
_project: String,
_operation: String,
_delegate: Option<&'a mut Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for GlobalAccountsOperationGetCall<'a, C, A> {}
impl<'a, C, A> GlobalAccountsOperationGetCall<'a, C, A> where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
/// Perform the operation you have build so far.
pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> {
use std::io::{Read, Seek};
use hyper::header::{ContentType, ContentLength, Authorization, Bearer, UserAgent, Location};
let mut dd = DefaultDelegate;
let mut dlg: &mut Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(MethodInfo { id: "clouduseraccounts.globalAccountsOperations.get",
http_method: hyper::method::Method::Get });
let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len()));
params.push(("project", self._project.to_string()));
params.push(("operation", self._operation.to_string()));
for &field in ["alt", "project", "operation"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "{project}/global/operations/{operation}";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::CloudUseraccountReadonly.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{project}", "project"), ("{operation}", "operation")].iter() {
let mut replace_with: Option<&str> = None;
for &(name, ref value) in params.iter() {
if name == param_name {
replace_with = Some(value);
break;
}
}
url = url.replace(find_this, replace_with.expect("to find substitution value in params"));
}
{
let mut indices_for_removal: Vec<usize> = Vec::with_capacity(2);
for param_name in ["operation", "project"].iter() {
if let Some(index) = params.iter().position(|t| &t.0 == param_name) {
indices_for_removal.push(index);
}
}
for &index in indices_for_removal.iter() {
params.remove(index);
}
}
if params.len() > 0 {
url.push('?');
url.push_str(&url::form_urlencoded::serialize(params));
}
loop {
let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) {
Ok(token) => token,
Err(err) => {
match dlg.token(&*err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(Error::MissingToken(err))
}
}
}
};
let auth_header = Authorization(Bearer { token: token.access_token });
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url)
.header(UserAgent(self.hub._user_agent.clone()))
.header(auth_header.clone());
dlg.pre_request();
req.send()
};
match req_result {
Err(err) => {
if let oauth2::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(Error::HttpError(err))
}
Ok(mut res) => {
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
if let oauth2::Retry::After(d) = dlg.http_failure(&res,
json::from_str(&json_err).ok(),
json::from_str(&json_err).ok()) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<ErrorResponse>(&json_err){
Err(_) => Err(Error::Failure(res)),
Ok(serr) => Err(Error::BadRequest(serr))
}
}
let result_value = {
let mut json_response = String::new();
res.read_to_string(&mut json_response).unwrap();
match json::from_str(&json_response) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&json_response, &err);
return Err(Error::JsonDecodeError(json_response, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
/// Project ID for this request.
///
/// Sets the *project* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn project(mut self, new_value: &str) -> GlobalAccountsOperationGetCall<'a, C, A> {
self._project = new_value.to_string();
self
}
/// Name of the Operations resource to return.
///
/// Sets the *operation* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn operation(mut self, new_value: &str) -> GlobalAccountsOperationGetCall<'a, C, A> {
self._operation = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut Delegate) -> GlobalAccountsOperationGetCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known paramters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *alt* (query-string) - Data format for the response.
pub fn param<T>(mut self, name: T, value: T) -> GlobalAccountsOperationGetCall<'a, C, A>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead the default `Scope` variant
/// `Scope::CloudUseraccountReadonly`.
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> GlobalAccountsOperationGetCall<'a, C, A>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Adds a public key to the specified User resource with the data included in the request.
///
/// A builder for the *addPublicKey* method supported by a *user* resource.
/// It is not used directly, but through a `UserMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta;
/// use clouduseraccountsvm_beta::PublicKey;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use clouduseraccountsvm_beta::CloudUserAccounts;
///
/// # let secret: ApplicationSecret = Default::default();
/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// # hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// # <MemoryStorage as Default>::default(), None);
/// # let mut hub = CloudUserAccounts::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = PublicKey::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.users().add_public_key(req, "project", "user")
/// .doit();
/// # }
/// ```
pub struct UserAddPublicKeyCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a CloudUserAccounts<C, A>,
_request: PublicKey,
_project: String,
_user: String,
_delegate: Option<&'a mut Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for UserAddPublicKeyCall<'a, C, A> {}
impl<'a, C, A> UserAddPublicKeyCall<'a, C, A> where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
/// Perform the operation you have build so far.
pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> {
use std::io::{Read, Seek};
use hyper::header::{ContentType, ContentLength, Authorization, Bearer, UserAgent, Location};
let mut dd = DefaultDelegate;
let mut dlg: &mut Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(MethodInfo { id: "clouduseraccounts.users.addPublicKey",
http_method: hyper::method::Method::Post });
let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len()));
params.push(("project", self._project.to_string()));
params.push(("user", self._user.to_string()));
for &field in ["alt", "project", "user"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "{project}/global/users/{user}/addPublicKey";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{project}", "project"), ("{user}", "user")].iter() {
let mut replace_with: Option<&str> = None;
for &(name, ref value) in params.iter() {
if name == param_name {
replace_with = Some(value);
break;
}
}
url = url.replace(find_this, replace_with.expect("to find substitution value in params"));
}
{
let mut indices_for_removal: Vec<usize> = Vec::with_capacity(2);
for param_name in ["user", "project"].iter() {
if let Some(index) = params.iter().position(|t| &t.0 == param_name) {
indices_for_removal.push(index);
}
}
for &index in indices_for_removal.iter() {
params.remove(index);
}
}
if params.len() > 0 {
url.push('?');
url.push_str(&url::form_urlencoded::serialize(params));
}
let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default());
let mut request_value_reader =
{
let mut value = json::value::to_value(&self._request).expect("serde to work");
remove_json_null_values(&mut value);
let mut dst = io::Cursor::new(Vec::with_capacity(128));
json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap();
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
loop {
let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) {
Ok(token) => token,
Err(err) => {
match dlg.token(&*err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(Error::MissingToken(err))
}
}
}
};
let auth_header = Authorization(Bearer { token: token.access_token });
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
let mut req = client.borrow_mut().request(hyper::method::Method::Post, &url)
.header(UserAgent(self.hub._user_agent.clone()))
.header(auth_header.clone())
.header(ContentType(json_mime_type.clone()))
.header(ContentLength(request_size as u64))
.body(&mut request_value_reader);
dlg.pre_request();
req.send()
};
match req_result {
Err(err) => {
if let oauth2::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(Error::HttpError(err))
}
Ok(mut res) => {
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
if let oauth2::Retry::After(d) = dlg.http_failure(&res,
json::from_str(&json_err).ok(),
json::from_str(&json_err).ok()) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<ErrorResponse>(&json_err){
Err(_) => Err(Error::Failure(res)),
Ok(serr) => Err(Error::BadRequest(serr))
}
}
let result_value = {
let mut json_response = String::new();
res.read_to_string(&mut json_response).unwrap();
match json::from_str(&json_response) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&json_response, &err);
return Err(Error::JsonDecodeError(json_response, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: PublicKey) -> UserAddPublicKeyCall<'a, C, A> {
self._request = new_value;
self
}
/// Project ID for this request.
///
/// Sets the *project* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn project(mut self, new_value: &str) -> UserAddPublicKeyCall<'a, C, A> {
self._project = new_value.to_string();
self
}
/// Name of the user for this request.
///
/// Sets the *user* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn user(mut self, new_value: &str) -> UserAddPublicKeyCall<'a, C, A> {
self._user = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserAddPublicKeyCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known paramters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *alt* (query-string) - Data format for the response.
pub fn param<T>(mut self, name: T, value: T) -> UserAddPublicKeyCall<'a, C, A>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead the default `Scope` variant
/// `Scope::CloudPlatform`.
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> UserAddPublicKeyCall<'a, C, A>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Retrieves a list of users contained within the specified project.
///
/// A builder for the *list* method supported by a *user* resource.
/// It is not used directly, but through a `UserMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use clouduseraccountsvm_beta::CloudUserAccounts;
///
/// # let secret: ApplicationSecret = Default::default();
/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// # hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// # <MemoryStorage as Default>::default(), None);
/// # let mut hub = CloudUserAccounts::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.users().list("project")
/// .page_token("aliquyam")
/// .order_by("ea")
/// .max_results(40)
/// .filter("justo")
/// .doit();
/// # }
/// ```
pub struct UserListCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a CloudUserAccounts<C, A>,
_project: String,
_page_token: Option<String>,
_order_by: Option<String>,
_max_results: Option<u32>,
_filter: Option<String>,
_delegate: Option<&'a mut Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for UserListCall<'a, C, A> {}
impl<'a, C, A> UserListCall<'a, C, A> where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
/// Perform the operation you have build so far.
pub fn doit(mut self) -> Result<(hyper::client::Response, UserList)> {
use std::io::{Read, Seek};
use hyper::header::{ContentType, ContentLength, Authorization, Bearer, UserAgent, Location};
let mut dd = DefaultDelegate;
let mut dlg: &mut Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(MethodInfo { id: "clouduseraccounts.users.list",
http_method: hyper::method::Method::Get });
let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len()));
params.push(("project", self._project.to_string()));
if let Some(value) = self._page_token {
params.push(("pageToken", value.to_string()));
}
if let Some(value) = self._order_by {
params.push(("orderBy", value.to_string()));
}
if let Some(value) = self._max_results {
params.push(("maxResults", value.to_string()));
}
if let Some(value) = self._filter {
params.push(("filter", value.to_string()));
}
for &field in ["alt", "project", "pageToken", "orderBy", "maxResults", "filter"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "{project}/global/users";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::CloudUseraccountReadonly.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{project}", "project")].iter() {
let mut replace_with: Option<&str> = None;
for &(name, ref value) in params.iter() {
if name == param_name {
replace_with = Some(value);
break;
}
}
url = url.replace(find_this, replace_with.expect("to find substitution value in params"));
}
{
let mut indices_for_removal: Vec<usize> = Vec::with_capacity(1);
for param_name in ["project"].iter() {
if let Some(index) = params.iter().position(|t| &t.0 == param_name) {
indices_for_removal.push(index);
}
}
for &index in indices_for_removal.iter() {
params.remove(index);
}
}
if params.len() > 0 {
url.push('?');
url.push_str(&url::form_urlencoded::serialize(params));
}
loop {
let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) {
Ok(token) => token,
Err(err) => {
match dlg.token(&*err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(Error::MissingToken(err))
}
}
}
};
let auth_header = Authorization(Bearer { token: token.access_token });
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url)
.header(UserAgent(self.hub._user_agent.clone()))
.header(auth_header.clone());
dlg.pre_request();
req.send()
};
match req_result {
Err(err) => {
if let oauth2::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(Error::HttpError(err))
}
Ok(mut res) => {
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
if let oauth2::Retry::After(d) = dlg.http_failure(&res,
json::from_str(&json_err).ok(),
json::from_str(&json_err).ok()) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<ErrorResponse>(&json_err){
Err(_) => Err(Error::Failure(res)),
Ok(serr) => Err(Error::BadRequest(serr))
}
}
let result_value = {
let mut json_response = String::new();
res.read_to_string(&mut json_response).unwrap();
match json::from_str(&json_response) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&json_response, &err);
return Err(Error::JsonDecodeError(json_response, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
/// Project ID for this request.
///
/// Sets the *project* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn project(mut self, new_value: &str) -> UserListCall<'a, C, A> {
self._project = new_value.to_string();
self
}
/// Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(mut self, new_value: &str) -> UserListCall<'a, C, A> {
self._page_token = Some(new_value.to_string());
self
}
/// Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name.
///
/// You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first.
///
/// Currently, only sorting by name or creationTimestamp desc is supported.
///
/// Sets the *order by* query property to the given value.
pub fn order_by(mut self, new_value: &str) -> UserListCall<'a, C, A> {
self._order_by = Some(new_value.to_string());
self
}
/// The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.
///
/// Sets the *max results* query property to the given value.
pub fn max_results(mut self, new_value: u32) -> UserListCall<'a, C, A> {
self._max_results = Some(new_value);
self
}
/// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: field_name comparison_string literal_string.
///
/// The field_name is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The comparison_string must be either eq (equals) or ne (not equals). The literal_string is the string value to filter to. The literal value must be valid for the type of field you are filtering by (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field.
///
/// For example, to filter for instances that do not have a name of example-instance, you would use filter=name ne example-instance.
///
/// Compute Engine Beta API Only: If you use filtering in the Beta API, you can also filter on nested fields. For example, you could filter on instances that have set the scheduling.automaticRestart field to true. In particular, use filtering on nested fields to take advantage of instance labels to organize and filter results based on label values.
///
/// The Beta API also supports filtering on multiple expressions by providing each separate expression within parentheses. For example, (scheduling.automaticRestart eq true) (zone eq us-central1-f). Multiple expressions are treated as AND expressions, meaning that resources must match all expressions to pass the filters.
///
/// Sets the *filter* query property to the given value.
pub fn filter(mut self, new_value: &str) -> UserListCall<'a, C, A> {
self._filter = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserListCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known paramters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *alt* (query-string) - Data format for the response.
pub fn param<T>(mut self, name: T, value: T) -> UserListCall<'a, C, A>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead the default `Scope` variant
/// `Scope::CloudUseraccountReadonly`.
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> UserListCall<'a, C, A>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Creates a User resource in the specified project using the data included in the request.
///
/// A builder for the *insert* method supported by a *user* resource.
/// It is not used directly, but through a `UserMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta;
/// use clouduseraccountsvm_beta::User;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use clouduseraccountsvm_beta::CloudUserAccounts;
///
/// # let secret: ApplicationSecret = Default::default();
/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// # hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// # <MemoryStorage as Default>::default(), None);
/// # let mut hub = CloudUserAccounts::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = User::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.users().insert(req, "project")
/// .doit();
/// # }
/// ```
pub struct UserInsertCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a CloudUserAccounts<C, A>,
_request: User,
_project: String,
_delegate: Option<&'a mut Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for UserInsertCall<'a, C, A> {}
impl<'a, C, A> UserInsertCall<'a, C, A> where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
/// Perform the operation you have build so far.
pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> {
use std::io::{Read, Seek};
use hyper::header::{ContentType, ContentLength, Authorization, Bearer, UserAgent, Location};
let mut dd = DefaultDelegate;
let mut dlg: &mut Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(MethodInfo { id: "clouduseraccounts.users.insert",
http_method: hyper::method::Method::Post });
let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len()));
params.push(("project", self._project.to_string()));
for &field in ["alt", "project"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "{project}/global/users";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{project}", "project")].iter() {
let mut replace_with: Option<&str> = None;
for &(name, ref value) in params.iter() {
if name == param_name {
replace_with = Some(value);
break;
}
}
url = url.replace(find_this, replace_with.expect("to find substitution value in params"));
}
{
let mut indices_for_removal: Vec<usize> = Vec::with_capacity(1);
for param_name in ["project"].iter() {
if let Some(index) = params.iter().position(|t| &t.0 == param_name) {
indices_for_removal.push(index);
}
}
for &index in indices_for_removal.iter() {
params.remove(index);
}
}
if params.len() > 0 {
url.push('?');
url.push_str(&url::form_urlencoded::serialize(params));
}
let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default());
let mut request_value_reader =
{
let mut value = json::value::to_value(&self._request).expect("serde to work");
remove_json_null_values(&mut value);
let mut dst = io::Cursor::new(Vec::with_capacity(128));
json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap();
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
loop {
let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) {
Ok(token) => token,
Err(err) => {
match dlg.token(&*err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(Error::MissingToken(err))
}
}
}
};
let auth_header = Authorization(Bearer { token: token.access_token });
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
let mut req = client.borrow_mut().request(hyper::method::Method::Post, &url)
.header(UserAgent(self.hub._user_agent.clone()))
.header(auth_header.clone())
.header(ContentType(json_mime_type.clone()))
.header(ContentLength(request_size as u64))
.body(&mut request_value_reader);
dlg.pre_request();
req.send()
};
match req_result {
Err(err) => {
if let oauth2::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(Error::HttpError(err))
}
Ok(mut res) => {
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
if let oauth2::Retry::After(d) = dlg.http_failure(&res,
json::from_str(&json_err).ok(),
json::from_str(&json_err).ok()) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<ErrorResponse>(&json_err){
Err(_) => Err(Error::Failure(res)),
Ok(serr) => Err(Error::BadRequest(serr))
}
}
let result_value = {
let mut json_response = String::new();
res.read_to_string(&mut json_response).unwrap();
match json::from_str(&json_response) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&json_response, &err);
return Err(Error::JsonDecodeError(json_response, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: User) -> UserInsertCall<'a, C, A> {
self._request = new_value;
self
}
/// Project ID for this request.
///
/// Sets the *project* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn project(mut self, new_value: &str) -> UserInsertCall<'a, C, A> {
self._project = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserInsertCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known paramters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *alt* (query-string) - Data format for the response.
pub fn param<T>(mut self, name: T, value: T) -> UserInsertCall<'a, C, A>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead the default `Scope` variant
/// `Scope::CloudPlatform`.
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> UserInsertCall<'a, C, A>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Returns the specified User resource.
///
/// A builder for the *get* method supported by a *user* resource.
/// It is not used directly, but through a `UserMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use clouduseraccountsvm_beta::CloudUserAccounts;
///
/// # let secret: ApplicationSecret = Default::default();
/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// # hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// # <MemoryStorage as Default>::default(), None);
/// # let mut hub = CloudUserAccounts::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.users().get("project", "user")
/// .doit();
/// # }
/// ```
pub struct UserGetCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a CloudUserAccounts<C, A>,
_project: String,
_user: String,
_delegate: Option<&'a mut Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for UserGetCall<'a, C, A> {}
impl<'a, C, A> UserGetCall<'a, C, A> where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
/// Perform the operation you have build so far.
pub fn doit(mut self) -> Result<(hyper::client::Response, User)> {
use std::io::{Read, Seek};
use hyper::header::{ContentType, ContentLength, Authorization, Bearer, UserAgent, Location};
let mut dd = DefaultDelegate;
let mut dlg: &mut Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(MethodInfo { id: "clouduseraccounts.users.get",
http_method: hyper::method::Method::Get });
let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len()));
params.push(("project", self._project.to_string()));
params.push(("user", self._user.to_string()));
for &field in ["alt", "project", "user"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "{project}/global/users/{user}";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::CloudUseraccountReadonly.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{project}", "project"), ("{user}", "user")].iter() {
let mut replace_with: Option<&str> = None;
for &(name, ref value) in params.iter() {
if name == param_name {
replace_with = Some(value);
break;
}
}
url = url.replace(find_this, replace_with.expect("to find substitution value in params"));
}
{
let mut indices_for_removal: Vec<usize> = Vec::with_capacity(2);
for param_name in ["user", "project"].iter() {
if let Some(index) = params.iter().position(|t| &t.0 == param_name) {
indices_for_removal.push(index);
}
}
for &index in indices_for_removal.iter() {
params.remove(index);
}
}
if params.len() > 0 {
url.push('?');
url.push_str(&url::form_urlencoded::serialize(params));
}
loop {
let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) {
Ok(token) => token,
Err(err) => {
match dlg.token(&*err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(Error::MissingToken(err))
}
}
}
};
let auth_header = Authorization(Bearer { token: token.access_token });
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url)
.header(UserAgent(self.hub._user_agent.clone()))
.header(auth_header.clone());
dlg.pre_request();
req.send()
};
match req_result {
Err(err) => {
if let oauth2::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(Error::HttpError(err))
}
Ok(mut res) => {
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
if let oauth2::Retry::After(d) = dlg.http_failure(&res,
json::from_str(&json_err).ok(),
json::from_str(&json_err).ok()) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<ErrorResponse>(&json_err){
Err(_) => Err(Error::Failure(res)),
Ok(serr) => Err(Error::BadRequest(serr))
}
}
let result_value = {
let mut json_response = String::new();
res.read_to_string(&mut json_response).unwrap();
match json::from_str(&json_response) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&json_response, &err);
return Err(Error::JsonDecodeError(json_response, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
/// Project ID for this request.
///
/// Sets the *project* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn project(mut self, new_value: &str) -> UserGetCall<'a, C, A> {
self._project = new_value.to_string();
self
}
/// Name of the user resource to return.
///
/// Sets the *user* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn user(mut self, new_value: &str) -> UserGetCall<'a, C, A> {
self._user = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserGetCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known paramters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *alt* (query-string) - Data format for the response.
pub fn param<T>(mut self, name: T, value: T) -> UserGetCall<'a, C, A>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead the default `Scope` variant
/// `Scope::CloudUseraccountReadonly`.
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> UserGetCall<'a, C, A>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Removes the specified public key from the user.
///
/// A builder for the *removePublicKey* method supported by a *user* resource.
/// It is not used directly, but through a `UserMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use clouduseraccountsvm_beta::CloudUserAccounts;
///
/// # let secret: ApplicationSecret = Default::default();
/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// # hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// # <MemoryStorage as Default>::default(), None);
/// # let mut hub = CloudUserAccounts::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.users().remove_public_key("project", "user", "fingerprint")
/// .doit();
/// # }
/// ```
pub struct UserRemovePublicKeyCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a CloudUserAccounts<C, A>,
_project: String,
_user: String,
_fingerprint: String,
_delegate: Option<&'a mut Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for UserRemovePublicKeyCall<'a, C, A> {}
impl<'a, C, A> UserRemovePublicKeyCall<'a, C, A> where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
/// Perform the operation you have build so far.
pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> {
use std::io::{Read, Seek};
use hyper::header::{ContentType, ContentLength, Authorization, Bearer, UserAgent, Location};
let mut dd = DefaultDelegate;
let mut dlg: &mut Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(MethodInfo { id: "clouduseraccounts.users.removePublicKey",
http_method: hyper::method::Method::Post });
let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len()));
params.push(("project", self._project.to_string()));
params.push(("user", self._user.to_string()));
params.push(("fingerprint", self._fingerprint.to_string()));
for &field in ["alt", "project", "user", "fingerprint"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "{project}/global/users/{user}/removePublicKey";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{project}", "project"), ("{user}", "user")].iter() {
let mut replace_with: Option<&str> = None;
for &(name, ref value) in params.iter() {
if name == param_name {
replace_with = Some(value);
break;
}
}
url = url.replace(find_this, replace_with.expect("to find substitution value in params"));
}
{
let mut indices_for_removal: Vec<usize> = Vec::with_capacity(2);
for param_name in ["user", "project"].iter() {
if let Some(index) = params.iter().position(|t| &t.0 == param_name) {
indices_for_removal.push(index);
}
}
for &index in indices_for_removal.iter() {
params.remove(index);
}
}
if params.len() > 0 {
url.push('?');
url.push_str(&url::form_urlencoded::serialize(params));
}
loop {
let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) {
Ok(token) => token,
Err(err) => {
match dlg.token(&*err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(Error::MissingToken(err))
}
}
}
};
let auth_header = Authorization(Bearer { token: token.access_token });
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
let mut req = client.borrow_mut().request(hyper::method::Method::Post, &url)
.header(UserAgent(self.hub._user_agent.clone()))
.header(auth_header.clone());
dlg.pre_request();
req.send()
};
match req_result {
Err(err) => {
if let oauth2::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(Error::HttpError(err))
}
Ok(mut res) => {
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
if let oauth2::Retry::After(d) = dlg.http_failure(&res,
json::from_str(&json_err).ok(),
json::from_str(&json_err).ok()) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<ErrorResponse>(&json_err){
Err(_) => Err(Error::Failure(res)),
Ok(serr) => Err(Error::BadRequest(serr))
}
}
let result_value = {
let mut json_response = String::new();
res.read_to_string(&mut json_response).unwrap();
match json::from_str(&json_response) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&json_response, &err);
return Err(Error::JsonDecodeError(json_response, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
/// Project ID for this request.
///
/// Sets the *project* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn project(mut self, new_value: &str) -> UserRemovePublicKeyCall<'a, C, A> {
self._project = new_value.to_string();
self
}
/// Name of the user for this request.
///
/// Sets the *user* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn user(mut self, new_value: &str) -> UserRemovePublicKeyCall<'a, C, A> {
self._user = new_value.to_string();
self
}
/// The fingerprint of the public key to delete. Public keys are identified by their fingerprint, which is defined by RFC4716 to be the MD5 digest of the public key.
///
/// Sets the *fingerprint* query property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn fingerprint(mut self, new_value: &str) -> UserRemovePublicKeyCall<'a, C, A> {
self._fingerprint = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserRemovePublicKeyCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known paramters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *alt* (query-string) - Data format for the response.
pub fn param<T>(mut self, name: T, value: T) -> UserRemovePublicKeyCall<'a, C, A>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead the default `Scope` variant
/// `Scope::CloudPlatform`.
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> UserRemovePublicKeyCall<'a, C, A>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Deletes the specified User resource.
///
/// A builder for the *delete* method supported by a *user* resource.
/// It is not used directly, but through a `UserMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use clouduseraccountsvm_beta::CloudUserAccounts;
///
/// # let secret: ApplicationSecret = Default::default();
/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// # hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// # <MemoryStorage as Default>::default(), None);
/// # let mut hub = CloudUserAccounts::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.users().delete("project", "user")
/// .doit();
/// # }
/// ```
pub struct | <'a, C, A>
where C: 'a, A: 'a {
hub: &'a CloudUserAccounts<C, A>,
_project: String,
_user: String,
_delegate: Option<&'a mut Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for UserDeleteCall<'a, C, A> {}
impl<'a, C, A> UserDeleteCall<'a, C, A> where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
/// Perform the operation you have build so far.
pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> {
use std::io::{Read, Seek};
use hyper::header::{ContentType, ContentLength, Authorization, Bearer, UserAgent, Location};
let mut dd = DefaultDelegate;
let mut dlg: &mut Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(MethodInfo { id: "clouduseraccounts.users.delete",
http_method: hyper::method::Method::Delete });
let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len()));
params.push(("project", self._project.to_string()));
params.push(("user", self._user.to_string()));
for &field in ["alt", "project", "user"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "{project}/global/users/{user}";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{project}", "project"), ("{user}", "user")].iter() {
let mut replace_with: Option<&str> = None;
for &(name, ref value) in params.iter() {
if name == param_name {
replace_with = Some(value);
break;
}
}
url = url.replace(find_this, replace_with.expect("to find substitution value in params"));
}
{
let mut indices_for_removal: Vec<usize> = Vec::with_capacity(2);
for param_name in ["user", "project"].iter() {
if let Some(index) = params.iter().position(|t| &t.0 == param_name) {
indices_for_removal.push(index);
}
}
for &index in indices_for_removal.iter() {
params.remove(index);
}
}
if params.len() > 0 {
url.push('?');
url.push_str(&url::form_urlencoded::serialize(params));
}
loop {
let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) {
Ok(token) => token,
Err(err) => {
match dlg.token(&*err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(Error::MissingToken(err))
}
}
}
};
let auth_header = Authorization(Bearer { token: token.access_token });
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
let mut req = client.borrow_mut().request(hyper::method::Method::Delete, &url)
.header(UserAgent(self.hub._user_agent.clone()))
.header(auth_header.clone());
dlg.pre_request();
req.send()
};
match req_result {
Err(err) => {
if let oauth2::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(Error::HttpError(err))
}
Ok(mut res) => {
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
if let oauth2::Retry::After(d) = dlg.http_failure(&res,
json::from_str(&json_err).ok(),
json::from_str(&json_err).ok()) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<ErrorResponse>(&json_err){
Err(_) => Err(Error::Failure(res)),
Ok(serr) => Err(Error::BadRequest(serr))
}
}
let result_value = {
let mut json_response = String::new();
res.read_to_string(&mut json_response).unwrap();
match json::from_str(&json_response) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&json_response, &err);
return Err(Error::JsonDecodeError(json_response, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
/// Project ID for this request.
///
/// Sets the *project* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn project(mut self, new_value: &str) -> UserDeleteCall<'a, C, A> {
self._project = new_value.to_string();
self
}
/// Name of the user resource to delete.
///
/// Sets the *user* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn user(mut self, new_value: &str) -> UserDeleteCall<'a, C, A> {
self._user = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut Delegate) -> UserDeleteCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known paramters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *alt* (query-string) - Data format for the response.
pub fn param<T>(mut self, name: T, value: T) -> UserDeleteCall<'a, C, A>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead the default `Scope` variant
/// `Scope::CloudPlatform`.
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> UserDeleteCall<'a, C, A>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Deletes the specified Group resource.
///
/// A builder for the *delete* method supported by a *group* resource.
/// It is not used directly, but through a `GroupMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use clouduseraccountsvm_beta::CloudUserAccounts;
///
/// # let secret: ApplicationSecret = Default::default();
/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// # hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// # <MemoryStorage as Default>::default(), None);
/// # let mut hub = CloudUserAccounts::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.groups().delete("project", "groupName")
/// .doit();
/// # }
/// ```
pub struct GroupDeleteCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a CloudUserAccounts<C, A>,
_project: String,
_group_name: String,
_delegate: Option<&'a mut Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for GroupDeleteCall<'a, C, A> {}
impl<'a, C, A> GroupDeleteCall<'a, C, A> where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
/// Perform the operation you have build so far.
pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> {
use std::io::{Read, Seek};
use hyper::header::{ContentType, ContentLength, Authorization, Bearer, UserAgent, Location};
let mut dd = DefaultDelegate;
let mut dlg: &mut Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(MethodInfo { id: "clouduseraccounts.groups.delete",
http_method: hyper::method::Method::Delete });
let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len()));
params.push(("project", self._project.to_string()));
params.push(("groupName", self._group_name.to_string()));
for &field in ["alt", "project", "groupName"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "{project}/global/groups/{groupName}";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{project}", "project"), ("{groupName}", "groupName")].iter() {
let mut replace_with: Option<&str> = None;
for &(name, ref value) in params.iter() {
if name == param_name {
replace_with = Some(value);
break;
}
}
url = url.replace(find_this, replace_with.expect("to find substitution value in params"));
}
{
let mut indices_for_removal: Vec<usize> = Vec::with_capacity(2);
for param_name in ["groupName", "project"].iter() {
if let Some(index) = params.iter().position(|t| &t.0 == param_name) {
indices_for_removal.push(index);
}
}
for &index in indices_for_removal.iter() {
params.remove(index);
}
}
if params.len() > 0 {
url.push('?');
url.push_str(&url::form_urlencoded::serialize(params));
}
loop {
let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) {
Ok(token) => token,
Err(err) => {
match dlg.token(&*err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(Error::MissingToken(err))
}
}
}
};
let auth_header = Authorization(Bearer { token: token.access_token });
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
let mut req = client.borrow_mut().request(hyper::method::Method::Delete, &url)
.header(UserAgent(self.hub._user_agent.clone()))
.header(auth_header.clone());
dlg.pre_request();
req.send()
};
match req_result {
Err(err) => {
if let oauth2::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(Error::HttpError(err))
}
Ok(mut res) => {
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
if let oauth2::Retry::After(d) = dlg.http_failure(&res,
json::from_str(&json_err).ok(),
json::from_str(&json_err).ok()) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<ErrorResponse>(&json_err){
Err(_) => Err(Error::Failure(res)),
Ok(serr) => Err(Error::BadRequest(serr))
}
}
let result_value = {
let mut json_response = String::new();
res.read_to_string(&mut json_response).unwrap();
match json::from_str(&json_response) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&json_response, &err);
return Err(Error::JsonDecodeError(json_response, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
/// Project ID for this request.
///
/// Sets the *project* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn project(mut self, new_value: &str) -> GroupDeleteCall<'a, C, A> {
self._project = new_value.to_string();
self
}
/// Name of the Group resource to delete.
///
/// Sets the *group name* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn group_name(mut self, new_value: &str) -> GroupDeleteCall<'a, C, A> {
self._group_name = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupDeleteCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known paramters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *alt* (query-string) - Data format for the response.
pub fn param<T>(mut self, name: T, value: T) -> GroupDeleteCall<'a, C, A>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead the default `Scope` variant
/// `Scope::CloudPlatform`.
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> GroupDeleteCall<'a, C, A>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Returns the specified Group resource.
///
/// A builder for the *get* method supported by a *group* resource.
/// It is not used directly, but through a `GroupMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use clouduseraccountsvm_beta::CloudUserAccounts;
///
/// # let secret: ApplicationSecret = Default::default();
/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// # hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// # <MemoryStorage as Default>::default(), None);
/// # let mut hub = CloudUserAccounts::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.groups().get("project", "groupName")
/// .doit();
/// # }
/// ```
pub struct GroupGetCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a CloudUserAccounts<C, A>,
_project: String,
_group_name: String,
_delegate: Option<&'a mut Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for GroupGetCall<'a, C, A> {}
impl<'a, C, A> GroupGetCall<'a, C, A> where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
/// Perform the operation you have build so far.
pub fn doit(mut self) -> Result<(hyper::client::Response, Group)> {
use std::io::{Read, Seek};
use hyper::header::{ContentType, ContentLength, Authorization, Bearer, UserAgent, Location};
let mut dd = DefaultDelegate;
let mut dlg: &mut Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(MethodInfo { id: "clouduseraccounts.groups.get",
http_method: hyper::method::Method::Get });
let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len()));
params.push(("project", self._project.to_string()));
params.push(("groupName", self._group_name.to_string()));
for &field in ["alt", "project", "groupName"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "{project}/global/groups/{groupName}";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::CloudUseraccountReadonly.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{project}", "project"), ("{groupName}", "groupName")].iter() {
let mut replace_with: Option<&str> = None;
for &(name, ref value) in params.iter() {
if name == param_name {
replace_with = Some(value);
break;
}
}
url = url.replace(find_this, replace_with.expect("to find substitution value in params"));
}
{
let mut indices_for_removal: Vec<usize> = Vec::with_capacity(2);
for param_name in ["groupName", "project"].iter() {
if let Some(index) = params.iter().position(|t| &t.0 == param_name) {
indices_for_removal.push(index);
}
}
for &index in indices_for_removal.iter() {
params.remove(index);
}
}
if params.len() > 0 {
url.push('?');
url.push_str(&url::form_urlencoded::serialize(params));
}
loop {
let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) {
Ok(token) => token,
Err(err) => {
match dlg.token(&*err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(Error::MissingToken(err))
}
}
}
};
let auth_header = Authorization(Bearer { token: token.access_token });
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url)
.header(UserAgent(self.hub._user_agent.clone()))
.header(auth_header.clone());
dlg.pre_request();
req.send()
};
match req_result {
Err(err) => {
if let oauth2::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(Error::HttpError(err))
}
Ok(mut res) => {
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
if let oauth2::Retry::After(d) = dlg.http_failure(&res,
json::from_str(&json_err).ok(),
json::from_str(&json_err).ok()) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<ErrorResponse>(&json_err){
Err(_) => Err(Error::Failure(res)),
Ok(serr) => Err(Error::BadRequest(serr))
}
}
let result_value = {
let mut json_response = String::new();
res.read_to_string(&mut json_response).unwrap();
match json::from_str(&json_response) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&json_response, &err);
return Err(Error::JsonDecodeError(json_response, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
/// Project ID for this request.
///
/// Sets the *project* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn project(mut self, new_value: &str) -> GroupGetCall<'a, C, A> {
self._project = new_value.to_string();
self
}
/// Name of the Group resource to return.
///
/// Sets the *group name* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn group_name(mut self, new_value: &str) -> GroupGetCall<'a, C, A> {
self._group_name = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupGetCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known paramters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *alt* (query-string) - Data format for the response.
pub fn param<T>(mut self, name: T, value: T) -> GroupGetCall<'a, C, A>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead the default `Scope` variant
/// `Scope::CloudUseraccountReadonly`.
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> GroupGetCall<'a, C, A>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Adds users to the specified group.
///
/// A builder for the *addMember* method supported by a *group* resource.
/// It is not used directly, but through a `GroupMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta;
/// use clouduseraccountsvm_beta::GroupsAddMemberRequest;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use clouduseraccountsvm_beta::CloudUserAccounts;
///
/// # let secret: ApplicationSecret = Default::default();
/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// # hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// # <MemoryStorage as Default>::default(), None);
/// # let mut hub = CloudUserAccounts::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = GroupsAddMemberRequest::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.groups().add_member(req, "project", "groupName")
/// .doit();
/// # }
/// ```
pub struct GroupAddMemberCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a CloudUserAccounts<C, A>,
_request: GroupsAddMemberRequest,
_project: String,
_group_name: String,
_delegate: Option<&'a mut Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for GroupAddMemberCall<'a, C, A> {}
impl<'a, C, A> GroupAddMemberCall<'a, C, A> where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
/// Perform the operation you have build so far.
pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> {
use std::io::{Read, Seek};
use hyper::header::{ContentType, ContentLength, Authorization, Bearer, UserAgent, Location};
let mut dd = DefaultDelegate;
let mut dlg: &mut Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(MethodInfo { id: "clouduseraccounts.groups.addMember",
http_method: hyper::method::Method::Post });
let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len()));
params.push(("project", self._project.to_string()));
params.push(("groupName", self._group_name.to_string()));
for &field in ["alt", "project", "groupName"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "{project}/global/groups/{groupName}/addMember";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{project}", "project"), ("{groupName}", "groupName")].iter() {
let mut replace_with: Option<&str> = None;
for &(name, ref value) in params.iter() {
if name == param_name {
replace_with = Some(value);
break;
}
}
url = url.replace(find_this, replace_with.expect("to find substitution value in params"));
}
{
let mut indices_for_removal: Vec<usize> = Vec::with_capacity(2);
for param_name in ["groupName", "project"].iter() {
if let Some(index) = params.iter().position(|t| &t.0 == param_name) {
indices_for_removal.push(index);
}
}
for &index in indices_for_removal.iter() {
params.remove(index);
}
}
if params.len() > 0 {
url.push('?');
url.push_str(&url::form_urlencoded::serialize(params));
}
let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default());
let mut request_value_reader =
{
let mut value = json::value::to_value(&self._request).expect("serde to work");
remove_json_null_values(&mut value);
let mut dst = io::Cursor::new(Vec::with_capacity(128));
json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap();
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
loop {
let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) {
Ok(token) => token,
Err(err) => {
match dlg.token(&*err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(Error::MissingToken(err))
}
}
}
};
let auth_header = Authorization(Bearer { token: token.access_token });
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
let mut req = client.borrow_mut().request(hyper::method::Method::Post, &url)
.header(UserAgent(self.hub._user_agent.clone()))
.header(auth_header.clone())
.header(ContentType(json_mime_type.clone()))
.header(ContentLength(request_size as u64))
.body(&mut request_value_reader);
dlg.pre_request();
req.send()
};
match req_result {
Err(err) => {
if let oauth2::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(Error::HttpError(err))
}
Ok(mut res) => {
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
if let oauth2::Retry::After(d) = dlg.http_failure(&res,
json::from_str(&json_err).ok(),
json::from_str(&json_err).ok()) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<ErrorResponse>(&json_err){
Err(_) => Err(Error::Failure(res)),
Ok(serr) => Err(Error::BadRequest(serr))
}
}
let result_value = {
let mut json_response = String::new();
res.read_to_string(&mut json_response).unwrap();
match json::from_str(&json_response) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&json_response, &err);
return Err(Error::JsonDecodeError(json_response, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: GroupsAddMemberRequest) -> GroupAddMemberCall<'a, C, A> {
self._request = new_value;
self
}
/// Project ID for this request.
///
/// Sets the *project* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn project(mut self, new_value: &str) -> GroupAddMemberCall<'a, C, A> {
self._project = new_value.to_string();
self
}
/// Name of the group for this request.
///
/// Sets the *group name* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn group_name(mut self, new_value: &str) -> GroupAddMemberCall<'a, C, A> {
self._group_name = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupAddMemberCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known paramters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *alt* (query-string) - Data format for the response.
pub fn param<T>(mut self, name: T, value: T) -> GroupAddMemberCall<'a, C, A>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead the default `Scope` variant
/// `Scope::CloudPlatform`.
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> GroupAddMemberCall<'a, C, A>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Creates a Group resource in the specified project using the data included in the request.
///
/// A builder for the *insert* method supported by a *group* resource.
/// It is not used directly, but through a `GroupMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta;
/// use clouduseraccountsvm_beta::Group;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use clouduseraccountsvm_beta::CloudUserAccounts;
///
/// # let secret: ApplicationSecret = Default::default();
/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// # hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// # <MemoryStorage as Default>::default(), None);
/// # let mut hub = CloudUserAccounts::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = Group::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.groups().insert(req, "project")
/// .doit();
/// # }
/// ```
pub struct GroupInsertCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a CloudUserAccounts<C, A>,
_request: Group,
_project: String,
_delegate: Option<&'a mut Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for GroupInsertCall<'a, C, A> {}
impl<'a, C, A> GroupInsertCall<'a, C, A> where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
/// Perform the operation you have build so far.
pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> {
use std::io::{Read, Seek};
use hyper::header::{ContentType, ContentLength, Authorization, Bearer, UserAgent, Location};
let mut dd = DefaultDelegate;
let mut dlg: &mut Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(MethodInfo { id: "clouduseraccounts.groups.insert",
http_method: hyper::method::Method::Post });
let mut params: Vec<(&str, String)> = Vec::with_capacity((4 + self._additional_params.len()));
params.push(("project", self._project.to_string()));
for &field in ["alt", "project"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "{project}/global/groups";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{project}", "project")].iter() {
let mut replace_with: Option<&str> = None;
for &(name, ref value) in params.iter() {
if name == param_name {
replace_with = Some(value);
break;
}
}
url = url.replace(find_this, replace_with.expect("to find substitution value in params"));
}
{
let mut indices_for_removal: Vec<usize> = Vec::with_capacity(1);
for param_name in ["project"].iter() {
if let Some(index) = params.iter().position(|t| &t.0 == param_name) {
indices_for_removal.push(index);
}
}
for &index in indices_for_removal.iter() {
params.remove(index);
}
}
if params.len() > 0 {
url.push('?');
url.push_str(&url::form_urlencoded::serialize(params));
}
let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default());
let mut request_value_reader =
{
let mut value = json::value::to_value(&self._request).expect("serde to work");
remove_json_null_values(&mut value);
let mut dst = io::Cursor::new(Vec::with_capacity(128));
json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap();
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
loop {
let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) {
Ok(token) => token,
Err(err) => {
match dlg.token(&*err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(Error::MissingToken(err))
}
}
}
};
let auth_header = Authorization(Bearer { token: token.access_token });
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
let mut req = client.borrow_mut().request(hyper::method::Method::Post, &url)
.header(UserAgent(self.hub._user_agent.clone()))
.header(auth_header.clone())
.header(ContentType(json_mime_type.clone()))
.header(ContentLength(request_size as u64))
.body(&mut request_value_reader);
dlg.pre_request();
req.send()
};
match req_result {
Err(err) => {
if let oauth2::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(Error::HttpError(err))
}
Ok(mut res) => {
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
if let oauth2::Retry::After(d) = dlg.http_failure(&res,
json::from_str(&json_err).ok(),
json::from_str(&json_err).ok()) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<ErrorResponse>(&json_err){
Err(_) => Err(Error::Failure(res)),
Ok(serr) => Err(Error::BadRequest(serr))
}
}
let result_value = {
let mut json_response = String::new();
res.read_to_string(&mut json_response).unwrap();
match json::from_str(&json_response) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&json_response, &err);
return Err(Error::JsonDecodeError(json_response, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: Group) -> GroupInsertCall<'a, C, A> {
self._request = new_value;
self
}
/// Project ID for this request.
///
/// Sets the *project* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn project(mut self, new_value: &str) -> GroupInsertCall<'a, C, A> {
self._project = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupInsertCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known paramters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *alt* (query-string) - Data format for the response.
pub fn param<T>(mut self, name: T, value: T) -> GroupInsertCall<'a, C, A>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead the default `Scope` variant
/// `Scope::CloudPlatform`.
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> GroupInsertCall<'a, C, A>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Retrieves the list of groups contained within the specified project.
///
/// A builder for the *list* method supported by a *group* resource.
/// It is not used directly, but through a `GroupMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use clouduseraccountsvm_beta::CloudUserAccounts;
///
/// # let secret: ApplicationSecret = Default::default();
/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// # hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// # <MemoryStorage as Default>::default(), None);
/// # let mut hub = CloudUserAccounts::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.groups().list("project")
/// .page_token("elitr")
/// .order_by("amet")
/// .max_results(41)
/// .filter("labore")
/// .doit();
/// # }
/// ```
pub struct GroupListCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a CloudUserAccounts<C, A>,
_project: String,
_page_token: Option<String>,
_order_by: Option<String>,
_max_results: Option<u32>,
_filter: Option<String>,
_delegate: Option<&'a mut Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for GroupListCall<'a, C, A> {}
impl<'a, C, A> GroupListCall<'a, C, A> where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
/// Perform the operation you have build so far.
pub fn doit(mut self) -> Result<(hyper::client::Response, GroupList)> {
use std::io::{Read, Seek};
use hyper::header::{ContentType, ContentLength, Authorization, Bearer, UserAgent, Location};
let mut dd = DefaultDelegate;
let mut dlg: &mut Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(MethodInfo { id: "clouduseraccounts.groups.list",
http_method: hyper::method::Method::Get });
let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len()));
params.push(("project", self._project.to_string()));
if let Some(value) = self._page_token {
params.push(("pageToken", value.to_string()));
}
if let Some(value) = self._order_by {
params.push(("orderBy", value.to_string()));
}
if let Some(value) = self._max_results {
params.push(("maxResults", value.to_string()));
}
if let Some(value) = self._filter {
params.push(("filter", value.to_string()));
}
for &field in ["alt", "project", "pageToken", "orderBy", "maxResults", "filter"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "{project}/global/groups";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::CloudUseraccountReadonly.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{project}", "project")].iter() {
let mut replace_with: Option<&str> = None;
for &(name, ref value) in params.iter() {
if name == param_name {
replace_with = Some(value);
break;
}
}
url = url.replace(find_this, replace_with.expect("to find substitution value in params"));
}
{
let mut indices_for_removal: Vec<usize> = Vec::with_capacity(1);
for param_name in ["project"].iter() {
if let Some(index) = params.iter().position(|t| &t.0 == param_name) {
indices_for_removal.push(index);
}
}
for &index in indices_for_removal.iter() {
params.remove(index);
}
}
if params.len() > 0 {
url.push('?');
url.push_str(&url::form_urlencoded::serialize(params));
}
loop {
let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) {
Ok(token) => token,
Err(err) => {
match dlg.token(&*err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(Error::MissingToken(err))
}
}
}
};
let auth_header = Authorization(Bearer { token: token.access_token });
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
let mut req = client.borrow_mut().request(hyper::method::Method::Get, &url)
.header(UserAgent(self.hub._user_agent.clone()))
.header(auth_header.clone());
dlg.pre_request();
req.send()
};
match req_result {
Err(err) => {
if let oauth2::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(Error::HttpError(err))
}
Ok(mut res) => {
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
if let oauth2::Retry::After(d) = dlg.http_failure(&res,
json::from_str(&json_err).ok(),
json::from_str(&json_err).ok()) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<ErrorResponse>(&json_err){
Err(_) => Err(Error::Failure(res)),
Ok(serr) => Err(Error::BadRequest(serr))
}
}
let result_value = {
let mut json_response = String::new();
res.read_to_string(&mut json_response).unwrap();
match json::from_str(&json_response) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&json_response, &err);
return Err(Error::JsonDecodeError(json_response, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
/// Project ID for this request.
///
/// Sets the *project* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn project(mut self, new_value: &str) -> GroupListCall<'a, C, A> {
self._project = new_value.to_string();
self
}
/// Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(mut self, new_value: &str) -> GroupListCall<'a, C, A> {
self._page_token = Some(new_value.to_string());
self
}
/// Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name.
///
/// You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first.
///
/// Currently, only sorting by name or creationTimestamp desc is supported.
///
/// Sets the *order by* query property to the given value.
pub fn order_by(mut self, new_value: &str) -> GroupListCall<'a, C, A> {
self._order_by = Some(new_value.to_string());
self
}
/// The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.
///
/// Sets the *max results* query property to the given value.
pub fn max_results(mut self, new_value: u32) -> GroupListCall<'a, C, A> {
self._max_results = Some(new_value);
self
}
/// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: field_name comparison_string literal_string.
///
/// The field_name is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The comparison_string must be either eq (equals) or ne (not equals). The literal_string is the string value to filter to. The literal value must be valid for the type of field you are filtering by (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field.
///
/// For example, to filter for instances that do not have a name of example-instance, you would use filter=name ne example-instance.
///
/// Compute Engine Beta API Only: If you use filtering in the Beta API, you can also filter on nested fields. For example, you could filter on instances that have set the scheduling.automaticRestart field to true. In particular, use filtering on nested fields to take advantage of instance labels to organize and filter results based on label values.
///
/// The Beta API also supports filtering on multiple expressions by providing each separate expression within parentheses. For example, (scheduling.automaticRestart eq true) (zone eq us-central1-f). Multiple expressions are treated as AND expressions, meaning that resources must match all expressions to pass the filters.
///
/// Sets the *filter* query property to the given value.
pub fn filter(mut self, new_value: &str) -> GroupListCall<'a, C, A> {
self._filter = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupListCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known paramters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *alt* (query-string) - Data format for the response.
pub fn param<T>(mut self, name: T, value: T) -> GroupListCall<'a, C, A>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead the default `Scope` variant
/// `Scope::CloudUseraccountReadonly`.
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> GroupListCall<'a, C, A>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Removes users from the specified group.
///
/// A builder for the *removeMember* method supported by a *group* resource.
/// It is not used directly, but through a `GroupMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta;
/// use clouduseraccountsvm_beta::GroupsRemoveMemberRequest;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use clouduseraccountsvm_beta::CloudUserAccounts;
///
/// # let secret: ApplicationSecret = Default::default();
/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// # hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// # <MemoryStorage as Default>::default(), None);
/// # let mut hub = CloudUserAccounts::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = GroupsRemoveMemberRequest::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.groups().remove_member(req, "project", "groupName")
/// .doit();
/// # }
/// ```
pub struct GroupRemoveMemberCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a CloudUserAccounts<C, A>,
_request: GroupsRemoveMemberRequest,
_project: String,
_group_name: String,
_delegate: Option<&'a mut Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for GroupRemoveMemberCall<'a, C, A> {}
impl<'a, C, A> GroupRemoveMemberCall<'a, C, A> where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
/// Perform the operation you have build so far.
pub fn doit(mut self) -> Result<(hyper::client::Response, Operation)> {
use std::io::{Read, Seek};
use hyper::header::{ContentType, ContentLength, Authorization, Bearer, UserAgent, Location};
let mut dd = DefaultDelegate;
let mut dlg: &mut Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(MethodInfo { id: "clouduseraccounts.groups.removeMember",
http_method: hyper::method::Method::Post });
let mut params: Vec<(&str, String)> = Vec::with_capacity((5 + self._additional_params.len()));
params.push(("project", self._project.to_string()));
params.push(("groupName", self._group_name.to_string()));
for &field in ["alt", "project", "groupName"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "{project}/global/groups/{groupName}/removeMember";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{project}", "project"), ("{groupName}", "groupName")].iter() {
let mut replace_with: Option<&str> = None;
for &(name, ref value) in params.iter() {
if name == param_name {
replace_with = Some(value);
break;
}
}
url = url.replace(find_this, replace_with.expect("to find substitution value in params"));
}
{
let mut indices_for_removal: Vec<usize> = Vec::with_capacity(2);
for param_name in ["groupName", "project"].iter() {
if let Some(index) = params.iter().position(|t| &t.0 == param_name) {
indices_for_removal.push(index);
}
}
for &index in indices_for_removal.iter() {
params.remove(index);
}
}
if params.len() > 0 {
url.push('?');
url.push_str(&url::form_urlencoded::serialize(params));
}
let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default());
let mut request_value_reader =
{
let mut value = json::value::to_value(&self._request).expect("serde to work");
remove_json_null_values(&mut value);
let mut dst = io::Cursor::new(Vec::with_capacity(128));
json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap();
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
loop {
let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) {
Ok(token) => token,
Err(err) => {
match dlg.token(&*err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(Error::MissingToken(err))
}
}
}
};
let auth_header = Authorization(Bearer { token: token.access_token });
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
let mut req = client.borrow_mut().request(hyper::method::Method::Post, &url)
.header(UserAgent(self.hub._user_agent.clone()))
.header(auth_header.clone())
.header(ContentType(json_mime_type.clone()))
.header(ContentLength(request_size as u64))
.body(&mut request_value_reader);
dlg.pre_request();
req.send()
};
match req_result {
Err(err) => {
if let oauth2::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(Error::HttpError(err))
}
Ok(mut res) => {
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
if let oauth2::Retry::After(d) = dlg.http_failure(&res,
json::from_str(&json_err).ok(),
json::from_str(&json_err).ok()) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<ErrorResponse>(&json_err){
Err(_) => Err(Error::Failure(res)),
Ok(serr) => Err(Error::BadRequest(serr))
}
}
let result_value = {
let mut json_response = String::new();
res.read_to_string(&mut json_response).unwrap();
match json::from_str(&json_response) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&json_response, &err);
return Err(Error::JsonDecodeError(json_response, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: GroupsRemoveMemberRequest) -> GroupRemoveMemberCall<'a, C, A> {
self._request = new_value;
self
}
/// Project ID for this request.
///
/// Sets the *project* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn project(mut self, new_value: &str) -> GroupRemoveMemberCall<'a, C, A> {
self._project = new_value.to_string();
self
}
/// Name of the group for this request.
///
/// Sets the *group name* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn group_name(mut self, new_value: &str) -> GroupRemoveMemberCall<'a, C, A> {
self._group_name = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut Delegate) -> GroupRemoveMemberCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known paramters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *alt* (query-string) - Data format for the response.
pub fn param<T>(mut self, name: T, value: T) -> GroupRemoveMemberCall<'a, C, A>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead the default `Scope` variant
/// `Scope::CloudPlatform`.
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> GroupRemoveMemberCall<'a, C, A>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Retrieves a list of user accounts for an instance within a specific project.
///
/// A builder for the *getLinuxAccountViews* method supported by a *linux* resource.
/// It is not used directly, but through a `LinuxMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use clouduseraccountsvm_beta::CloudUserAccounts;
///
/// # let secret: ApplicationSecret = Default::default();
/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// # hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// # <MemoryStorage as Default>::default(), None);
/// # let mut hub = CloudUserAccounts::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.linux().get_linux_account_views("project", "zone", "instance")
/// .page_token("Lorem")
/// .order_by("sea")
/// .max_results(80)
/// .filter("duo")
/// .doit();
/// # }
/// ```
pub struct LinuxGetLinuxAccountViewCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a CloudUserAccounts<C, A>,
_project: String,
_zone: String,
_instance: String,
_page_token: Option<String>,
_order_by: Option<String>,
_max_results: Option<u32>,
_filter: Option<String>,
_delegate: Option<&'a mut Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for LinuxGetLinuxAccountViewCall<'a, C, A> {}
impl<'a, C, A> LinuxGetLinuxAccountViewCall<'a, C, A> where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
/// Perform the operation you have build so far.
pub fn doit(mut self) -> Result<(hyper::client::Response, LinuxGetLinuxAccountViewsResponse)> {
use std::io::{Read, Seek};
use hyper::header::{ContentType, ContentLength, Authorization, Bearer, UserAgent, Location};
let mut dd = DefaultDelegate;
let mut dlg: &mut Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(MethodInfo { id: "clouduseraccounts.linux.getLinuxAccountViews",
http_method: hyper::method::Method::Post });
let mut params: Vec<(&str, String)> = Vec::with_capacity((9 + self._additional_params.len()));
params.push(("project", self._project.to_string()));
params.push(("zone", self._zone.to_string()));
params.push(("instance", self._instance.to_string()));
if let Some(value) = self._page_token {
params.push(("pageToken", value.to_string()));
}
if let Some(value) = self._order_by {
params.push(("orderBy", value.to_string()));
}
if let Some(value) = self._max_results {
params.push(("maxResults", value.to_string()));
}
if let Some(value) = self._filter {
params.push(("filter", value.to_string()));
}
for &field in ["alt", "project", "zone", "instance", "pageToken", "orderBy", "maxResults", "filter"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "{project}/zones/{zone}/linuxAccountViews";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone")].iter() {
let mut replace_with: Option<&str> = None;
for &(name, ref value) in params.iter() {
if name == param_name {
replace_with = Some(value);
break;
}
}
url = url.replace(find_this, replace_with.expect("to find substitution value in params"));
}
{
let mut indices_for_removal: Vec<usize> = Vec::with_capacity(2);
for param_name in ["zone", "project"].iter() {
if let Some(index) = params.iter().position(|t| &t.0 == param_name) {
indices_for_removal.push(index);
}
}
for &index in indices_for_removal.iter() {
params.remove(index);
}
}
if params.len() > 0 {
url.push('?');
url.push_str(&url::form_urlencoded::serialize(params));
}
loop {
let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) {
Ok(token) => token,
Err(err) => {
match dlg.token(&*err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(Error::MissingToken(err))
}
}
}
};
let auth_header = Authorization(Bearer { token: token.access_token });
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
let mut req = client.borrow_mut().request(hyper::method::Method::Post, &url)
.header(UserAgent(self.hub._user_agent.clone()))
.header(auth_header.clone());
dlg.pre_request();
req.send()
};
match req_result {
Err(err) => {
if let oauth2::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(Error::HttpError(err))
}
Ok(mut res) => {
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
if let oauth2::Retry::After(d) = dlg.http_failure(&res,
json::from_str(&json_err).ok(),
json::from_str(&json_err).ok()) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<ErrorResponse>(&json_err){
Err(_) => Err(Error::Failure(res)),
Ok(serr) => Err(Error::BadRequest(serr))
}
}
let result_value = {
let mut json_response = String::new();
res.read_to_string(&mut json_response).unwrap();
match json::from_str(&json_response) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&json_response, &err);
return Err(Error::JsonDecodeError(json_response, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
/// Project ID for this request.
///
/// Sets the *project* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn project(mut self, new_value: &str) -> LinuxGetLinuxAccountViewCall<'a, C, A> {
self._project = new_value.to_string();
self
}
/// Name of the zone for this request.
///
/// Sets the *zone* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn zone(mut self, new_value: &str) -> LinuxGetLinuxAccountViewCall<'a, C, A> {
self._zone = new_value.to_string();
self
}
/// The fully-qualified URL of the virtual machine requesting the views.
///
/// Sets the *instance* query property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn instance(mut self, new_value: &str) -> LinuxGetLinuxAccountViewCall<'a, C, A> {
self._instance = new_value.to_string();
self
}
/// Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(mut self, new_value: &str) -> LinuxGetLinuxAccountViewCall<'a, C, A> {
self._page_token = Some(new_value.to_string());
self
}
/// Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name.
///
/// You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first.
///
/// Currently, only sorting by name or creationTimestamp desc is supported.
///
/// Sets the *order by* query property to the given value.
pub fn order_by(mut self, new_value: &str) -> LinuxGetLinuxAccountViewCall<'a, C, A> {
self._order_by = Some(new_value.to_string());
self
}
/// The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests.
///
/// Sets the *max results* query property to the given value.
pub fn max_results(mut self, new_value: u32) -> LinuxGetLinuxAccountViewCall<'a, C, A> {
self._max_results = Some(new_value);
self
}
/// Sets a filter expression for filtering listed resources, in the form filter={expression}. Your {expression} must be in the format: field_name comparison_string literal_string.
///
/// The field_name is the name of the field you want to compare. Only atomic field types are supported (string, number, boolean). The comparison_string must be either eq (equals) or ne (not equals). The literal_string is the string value to filter to. The literal value must be valid for the type of field you are filtering by (string, number, boolean). For string fields, the literal value is interpreted as a regular expression using RE2 syntax. The literal value must match the entire field.
///
/// For example, to filter for instances that do not have a name of example-instance, you would use filter=name ne example-instance.
///
/// Compute Engine Beta API Only: If you use filtering in the Beta API, you can also filter on nested fields. For example, you could filter on instances that have set the scheduling.automaticRestart field to true. In particular, use filtering on nested fields to take advantage of instance labels to organize and filter results based on label values.
///
/// The Beta API also supports filtering on multiple expressions by providing each separate expression within parentheses. For example, (scheduling.automaticRestart eq true) (zone eq us-central1-f). Multiple expressions are treated as AND expressions, meaning that resources must match all expressions to pass the filters.
///
/// Sets the *filter* query property to the given value.
pub fn filter(mut self, new_value: &str) -> LinuxGetLinuxAccountViewCall<'a, C, A> {
self._filter = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut Delegate) -> LinuxGetLinuxAccountViewCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known paramters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *alt* (query-string) - Data format for the response.
pub fn param<T>(mut self, name: T, value: T) -> LinuxGetLinuxAccountViewCall<'a, C, A>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead the default `Scope` variant
/// `Scope::CloudPlatform`.
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> LinuxGetLinuxAccountViewCall<'a, C, A>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Returns a list of authorized public keys for a specific user account.
///
/// A builder for the *getAuthorizedKeysView* method supported by a *linux* resource.
/// It is not used directly, but through a `LinuxMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_clouduseraccountsvm_beta as clouduseraccountsvm_beta;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use clouduseraccountsvm_beta::CloudUserAccounts;
///
/// # let secret: ApplicationSecret = Default::default();
/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// # hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// # <MemoryStorage as Default>::default(), None);
/// # let mut hub = CloudUserAccounts::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.linux().get_authorized_keys_view("project", "zone", "user", "instance")
/// .login(true)
/// .doit();
/// # }
/// ```
pub struct LinuxGetAuthorizedKeysViewCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a CloudUserAccounts<C, A>,
_project: String,
_zone: String,
_user: String,
_instance: String,
_login: Option<bool>,
_delegate: Option<&'a mut Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for LinuxGetAuthorizedKeysViewCall<'a, C, A> {}
impl<'a, C, A> LinuxGetAuthorizedKeysViewCall<'a, C, A> where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
/// Perform the operation you have build so far.
pub fn doit(mut self) -> Result<(hyper::client::Response, LinuxGetAuthorizedKeysViewResponse)> {
use std::io::{Read, Seek};
use hyper::header::{ContentType, ContentLength, Authorization, Bearer, UserAgent, Location};
let mut dd = DefaultDelegate;
let mut dlg: &mut Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(MethodInfo { id: "clouduseraccounts.linux.getAuthorizedKeysView",
http_method: hyper::method::Method::Post });
let mut params: Vec<(&str, String)> = Vec::with_capacity((7 + self._additional_params.len()));
params.push(("project", self._project.to_string()));
params.push(("zone", self._zone.to_string()));
params.push(("user", self._user.to_string()));
params.push(("instance", self._instance.to_string()));
if let Some(value) = self._login {
params.push(("login", value.to_string()));
}
for &field in ["alt", "project", "zone", "user", "instance", "login"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "{project}/zones/{zone}/authorizedKeysView/{user}";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{project}", "project"), ("{zone}", "zone"), ("{user}", "user")].iter() {
let mut replace_with: Option<&str> = None;
for &(name, ref value) in params.iter() {
if name == param_name {
replace_with = Some(value);
break;
}
}
url = url.replace(find_this, replace_with.expect("to find substitution value in params"));
}
{
let mut indices_for_removal: Vec<usize> = Vec::with_capacity(3);
for param_name in ["user", "zone", "project"].iter() {
if let Some(index) = params.iter().position(|t| &t.0 == param_name) {
indices_for_removal.push(index);
}
}
for &index in indices_for_removal.iter() {
params.remove(index);
}
}
if params.len() > 0 {
url.push('?');
url.push_str(&url::form_urlencoded::serialize(params));
}
loop {
let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) {
Ok(token) => token,
Err(err) => {
match dlg.token(&*err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(Error::MissingToken(err))
}
}
}
};
let auth_header = Authorization(Bearer { token: token.access_token });
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
let mut req = client.borrow_mut().request(hyper::method::Method::Post, &url)
.header(UserAgent(self.hub._user_agent.clone()))
.header(auth_header.clone());
dlg.pre_request();
req.send()
};
match req_result {
Err(err) => {
if let oauth2::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(Error::HttpError(err))
}
Ok(mut res) => {
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
if let oauth2::Retry::After(d) = dlg.http_failure(&res,
json::from_str(&json_err).ok(),
json::from_str(&json_err).ok()) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<ErrorResponse>(&json_err){
Err(_) => Err(Error::Failure(res)),
Ok(serr) => Err(Error::BadRequest(serr))
}
}
let result_value = {
let mut json_response = String::new();
res.read_to_string(&mut json_response).unwrap();
match json::from_str(&json_response) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&json_response, &err);
return Err(Error::JsonDecodeError(json_response, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
/// Project ID for this request.
///
/// Sets the *project* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn project(mut self, new_value: &str) -> LinuxGetAuthorizedKeysViewCall<'a, C, A> {
self._project = new_value.to_string();
self
}
/// Name of the zone for this request.
///
/// Sets the *zone* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn zone(mut self, new_value: &str) -> LinuxGetAuthorizedKeysViewCall<'a, C, A> {
self._zone = new_value.to_string();
self
}
/// The user account for which you want to get a list of authorized public keys.
///
/// Sets the *user* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn user(mut self, new_value: &str) -> LinuxGetAuthorizedKeysViewCall<'a, C, A> {
self._user = new_value.to_string();
self
}
/// The fully-qualified URL of the virtual machine requesting the view.
///
/// Sets the *instance* query property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn instance(mut self, new_value: &str) -> LinuxGetAuthorizedKeysViewCall<'a, C, A> {
self._instance = new_value.to_string();
self
}
/// Whether the view was requested as part of a user-initiated login.
///
/// Sets the *login* query property to the given value.
pub fn login(mut self, new_value: bool) -> LinuxGetAuthorizedKeysViewCall<'a, C, A> {
self._login = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut Delegate) -> LinuxGetAuthorizedKeysViewCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known paramters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *userIp* (query-string) - IP address of the site where the request originates. Use this if you want to enforce per-user limits.
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *alt* (query-string) - Data format for the response.
pub fn param<T>(mut self, name: T, value: T) -> LinuxGetAuthorizedKeysViewCall<'a, C, A>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization scope for the method you are building.
///
/// Use this method to actively specify which scope should be used, instead the default `Scope` variant
/// `Scope::CloudPlatform`.
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> LinuxGetAuthorizedKeysViewCall<'a, C, A>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
| UserDeleteCall |
main.go | package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
"strings"
)
const (
EnvSlackWebhook = "SLACK_WEBHOOK"
EnvSlackIcon = "SLACK_ICON"
EnvSlackIconEmoji = "SLACK_ICON_EMOJI"
EnvSlackChannel = "SLACK_CHANNEL"
EnvSlackTitle = "SLACK_TITLE"
EnvSlackMessage = "SLACK_MESSAGE"
EnvSlackColor = "SLACK_COLOR"
EnvSlackUserName = "SLACK_USERNAME"
EnvSlackFooter = "SLACK_FOOTER"
EnvGithubActor = "GITHUB_ACTOR"
EnvSiteName = "SITE_NAME"
EnvHostName = "HOST_NAME"
EnvMinimal = "MSG_MINIMAL"
)
type Webhook struct {
Text string `json:"text,omitempty"`
UserName string `json:"username,omitempty"`
IconURL string `json:"icon_url,omitempty"`
IconEmoji string `json:"icon_emoji,omitempty"`
Channel string `json:"channel,omitempty"`
UnfurlLinks bool `json:"unfurl_links"`
Attachments []Attachment `json:"attachments,omitempty"`
}
type Attachment struct {
Fallback string `json:"fallback"`
Pretext string `json:"pretext,omitempty"`
Color string `json:"color,omitempty"`
AuthorName string `json:"author_name,omitempty"`
AuthorLink string `json:"author_link,omitempty"`
AuthorIcon string `json:"author_icon,omitempty"`
Footer string `json:"footer,omitempty"`
Fields []Field `json:"fields,omitempty"`
}
type Field struct {
Title string `json:"title,omitempty"`
Value string `json:"value,omitempty"`
Short bool `json:"short,omitempty"`
}
func main() {
endpoint := os.Getenv(EnvSlackWebhook)
if endpoint == "" {
fmt.Fprintln(os.Stderr, "URL is required")
os.Exit(1)
}
text := os.Getenv(EnvSlackMessage)
if text == "" {
fmt.Fprintln(os.Stderr, "Message is required")
os.Exit(1)
}
minimal := os.Getenv(EnvMinimal)
fields := []Field{}
if minimal == "true" {
mainFields := []Field{
{
Title: os.Getenv(EnvSlackTitle),
Value: envOr(EnvSlackMessage, "EOM"),
Short: false,
},
}
fields = append(mainFields, fields...)
} else if minimal != "" {
requiredFields := strings.Split(minimal, ",")
mainFields := []Field{
{
Title: os.Getenv(EnvSlackTitle),
Value: envOr(EnvSlackMessage, "EOM"),
Short: false,
},
}
for _,requiredField := range requiredFields {
switch strings.ToLower(requiredField) {
case "ref":
field := []Field{
{
Title: "Ref",
Value: os.Getenv("GITHUB_REF"),
Short: true,
},
}
mainFields = append(field, mainFields...)
case "event":
field := []Field{
{
Title: "Event",
Value: os.Getenv("GITHUB_EVENT_NAME"),
Short: true,
},
}
mainFields = append(field, mainFields...)
case "actions url":
field := []Field{
{
Title: "Actions URL",
Value: "https://github.com/" + os.Getenv("GITHUB_REPOSITORY") + "/commit/" + os.Getenv("GITHUB_SHA") + "/checks",
Short: false,
},
}
mainFields = append(field, mainFields...)
}
}
fields = append(mainFields, fields...)
} else {
mainFields := []Field{
{
Title: "Ref",
Value: os.Getenv("GITHUB_REF"),
Short: true,
}, {
Title: "Event",
Value: os.Getenv("GITHUB_EVENT_NAME"),
Short: true,
},
{
Title: "Actions URL",
Value: "https://github.com/" + os.Getenv("GITHUB_REPOSITORY") + "/commit/" + os.Getenv("GITHUB_SHA") + "/checks",
Short: false,
},
{
Title: os.Getenv(EnvSlackTitle),
Value: envOr(EnvSlackMessage, "EOM"),
Short: false,
},
}
fields = append(mainFields, fields...)
}
hostName := os.Getenv(EnvHostName)
if hostName != "" {
newfields := []Field{
{
Title: os.Getenv("SITE_TITLE"),
Value: os.Getenv(EnvSiteName),
Short: true,
},
{
Title: os.Getenv("HOST_TITLE"),
Value: os.Getenv(EnvHostName),
Short: true,
},
}
fields = append(newfields, fields...)
}
msg := Webhook{
UserName: os.Getenv(EnvSlackUserName),
IconURL: os.Getenv(EnvSlackIcon),
IconEmoji: os.Getenv(EnvSlackIconEmoji),
Channel: os.Getenv(EnvSlackChannel),
Attachments: []Attachment{
{
Fallback: envOr(EnvSlackMessage, "GITHUB_ACTION="+os.Getenv("GITHUB_ACTION")+" \n GITHUB_ACTOR="+os.Getenv("GITHUB_ACTOR")+" \n GITHUB_EVENT_NAME="+os.Getenv("GITHUB_EVENT_NAME")+" \n GITHUB_REF="+os.Getenv("GITHUB_REF")+" \n GITHUB_REPOSITORY="+os.Getenv("GITHUB_REPOSITORY")+" \n GITHUB_WORKFLOW="+os.Getenv("GITHUB_WORKFLOW")),
Color: envOr(EnvSlackColor, "good"),
AuthorName: envOr(EnvGithubActor, ""),
AuthorLink: "http://github.com/" + os.Getenv(EnvGithubActor),
AuthorIcon: "http://github.com/" + os.Getenv(EnvGithubActor) + ".png?size=32",
Footer: envOr(EnvSlackFooter, "<https://github.com/rtCamp/github-actions-library|Powered By rtCamp's GitHub Actions Library>"),
Fields: fields,
},
},
}
if err := send(endpoint, msg); err != nil {
fmt.Fprintf(os.Stderr, "Error sending message: %s\n", err)
os.Exit(2)
}
}
func envOr(name, def string) string {
if d, ok := os.LookupEnv(name); ok {
return d
}
return def
}
func send(endpoint string, msg Webhook) error | {
enc, err := json.Marshal(msg)
if err != nil {
return err
}
b := bytes.NewBuffer(enc)
res, err := http.Post(endpoint, "application/json", b)
if err != nil {
return err
}
if res.StatusCode >= 299 {
return fmt.Errorf("Error on message: %s\n", res.Status)
}
fmt.Println(res.Status)
return nil
} |
|
biosphere.py | from .migrations import migrate_exchanges, migrate_datasets
def drop_unspecified_subcategories(db):
"""Drop subcategories if they are in the following:
* ``unspecified``
* ``(unspecified)``
* ``''`` (empty string)
* ``None``
"""
UNSPECIFIED = {"unspecified", "(unspecified)", "", None}
for ds in db:
if ds.get("categories"):
while ds["categories"] and ds["categories"][-1] in UNSPECIFIED:
ds["categories"] = ds["categories"][:-1]
for exc in ds.get("exchanges", []):
if exc.get("categories"):
while exc["categories"] and exc["categories"][-1] in UNSPECIFIED:
exc["categories"] = exc["categories"][:-1]
return db
| Assumes that each dataset and each exchange have a ``name``. Will change names even if exchange is already linked."""
db = migrate_exchanges(db, migration="biosphere-2-3-names")
if not lcia:
db = migrate_datasets(db, migration="biosphere-2-3-names")
return db
def normalize_biosphere_categories(db, lcia=False):
"""Normalize biosphere categories to ecoinvent 3.1 standard"""
db = migrate_exchanges(db, migration="biosphere-2-3-categories")
if not lcia:
db = migrate_datasets(db, migration="biosphere-2-3-categories")
return db
def strip_biosphere_exc_locations(db):
"""Biosphere flows don't have locations - if any are included they can confuse linking"""
for ds in db:
for exc in ds.get("exchanges", []):
if exc.get("type") == "biosphere" and "location" in exc:
del exc["location"]
return db
def ensure_categories_are_tuples(db):
for ds in db:
if ds.get("categories") and type(ds["categories"]) != tuple:
ds["categories"] = tuple(ds["categories"])
return db |
def normalize_biosphere_names(db, lcia=False):
"""Normalize biosphere flow names to ecoinvent 3.1 standard.
|
testing.rs | use crate::contract::{execute, instantiate, query};
use crate::mock_querier::mock_dependencies;
use anchor_token::staking::ExecuteMsg::UpdateConfig;
use anchor_token::staking::{
ConfigResponse, Cw20HookMsg, ExecuteMsg, InstantiateMsg, QueryMsg, StakerInfoResponse,
StateResponse,
};
use cosmwasm_std::testing::{mock_env, mock_info};
use cosmwasm_std::{
attr, from_binary, to_binary, CosmosMsg, Decimal, StdError, SubMsg, Uint128, WasmMsg,
};
use cw20::{Cw20ExecuteMsg, Cw20ReceiveMsg};
#[test]
fn proper_initialization() {
let mut deps = mock_dependencies(&[]);
let msg = InstantiateMsg {
anchor_token: "reward0000".to_string(),
staking_token: "staking0000".to_string(),
distribution_schedule: vec![(100, 200, Uint128::from(1000000u128))],
};
let info = mock_info("addr0000", &[]);
// we can just call .unwrap() to assert this was a success
let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap();
// it worked, let's query the state
let res = query(deps.as_ref(), mock_env(), QueryMsg::Config {}).unwrap();
let config: ConfigResponse = from_binary(&res).unwrap();
assert_eq!(
config,
ConfigResponse {
anchor_token: "reward0000".to_string(),
staking_token: "staking0000".to_string(),
distribution_schedule: vec![(100, 200, Uint128::from(1000000u128))],
}
);
let res = query(
deps.as_ref(),
mock_env(),
QueryMsg::State { block_time: None },
)
.unwrap();
let state: StateResponse = from_binary(&res).unwrap();
assert_eq!(
state,
StateResponse {
last_distributed: mock_env().block.time.seconds(),
total_bond_amount: Uint128::zero(),
global_reward_index: Decimal::zero(),
}
);
}
#[test]
fn test_bond_tokens() {
let mut deps = mock_dependencies(&[]);
let msg = InstantiateMsg {
anchor_token: "reward0000".to_string(),
staking_token: "staking0000".to_string(),
distribution_schedule: vec![
(
mock_env().block.time.seconds(),
mock_env().block.time.seconds() + 100,
Uint128::from(1000000u128),
),
(
mock_env().block.time.seconds() + 100,
mock_env().block.time.seconds() + 200,
Uint128::from(10000000u128),
),
],
};
let info = mock_info("addr0000", &[]);
let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap();
let msg = ExecuteMsg::Receive(Cw20ReceiveMsg {
sender: "addr0000".to_string(),
amount: Uint128::from(100u128),
msg: to_binary(&Cw20HookMsg::Bond {}).unwrap(),
});
let info = mock_info("staking0000", &[]);
let mut env = mock_env();
let _res = execute(deps.as_mut(), env.clone(), info.clone(), msg).unwrap();
assert_eq!(
from_binary::<StakerInfoResponse>(
&query(
deps.as_ref(),
mock_env(),
QueryMsg::StakerInfo {
staker: "addr0000".to_string(),
block_time: None,
},
)
.unwrap(),
)
.unwrap(),
StakerInfoResponse {
staker: "addr0000".to_string(),
reward_index: Decimal::zero(),
pending_reward: Uint128::zero(),
bond_amount: Uint128::from(100u128),
}
);
assert_eq!(
from_binary::<StateResponse>(
&query(
deps.as_ref(),
mock_env(),
QueryMsg::State { block_time: None }
)
.unwrap()
)
.unwrap(),
StateResponse {
total_bond_amount: Uint128::from(100u128),
global_reward_index: Decimal::zero(),
last_distributed: mock_env().block.time.seconds(),
}
);
// bond 100 more tokens
let msg = ExecuteMsg::Receive(Cw20ReceiveMsg {
sender: "addr0000".to_string(),
amount: Uint128::from(100u128),
msg: to_binary(&Cw20HookMsg::Bond {}).unwrap(),
});
env.block.time = env.block.time.plus_seconds(10);
let _res = execute(deps.as_mut(), env, info, msg).unwrap();
assert_eq!(
from_binary::<StakerInfoResponse>(
&query(
deps.as_ref(),
mock_env(),
QueryMsg::StakerInfo {
staker: "addr0000".to_string(),
block_time: None,
},
)
.unwrap(),
)
.unwrap(),
StakerInfoResponse {
staker: "addr0000".to_string(),
reward_index: Decimal::from_ratio(1000u128, 1u128),
pending_reward: Uint128::from(100000u128),
bond_amount: Uint128::from(200u128),
}
);
assert_eq!(
from_binary::<StateResponse>(
&query(
deps.as_ref(),
mock_env(),
QueryMsg::State { block_time: None }
)
.unwrap()
)
.unwrap(),
StateResponse {
total_bond_amount: Uint128::from(200u128),
global_reward_index: Decimal::from_ratio(1000u128, 1u128),
last_distributed: mock_env().block.time.seconds() + 10,
}
);
// failed with unautorized
let msg = ExecuteMsg::Receive(Cw20ReceiveMsg {
sender: "addr0000".to_string(),
amount: Uint128::from(100u128),
msg: to_binary(&Cw20HookMsg::Bond {}).unwrap(),
});
let info = mock_info("staking0001", &[]);
let res = execute(deps.as_mut(), mock_env(), info, msg);
match res {
Err(StdError::GenericErr { msg, .. }) => assert_eq!(msg, "unauthorized"),
_ => panic!("Must return unauthorized error"),
}
}
#[test]
fn test_unbond() {
let mut deps = mock_dependencies(&[]);
let msg = InstantiateMsg {
anchor_token: "reward0000".to_string(),
staking_token: "staking0000".to_string(),
distribution_schedule: vec![
(12345, 12345 + 100, Uint128::from(1000000u128)),
(12345 + 100, 12345 + 200, Uint128::from(10000000u128)),
],
};
let info = mock_info("addr0000", &[]);
let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap();
// bond 100 tokens
let msg = ExecuteMsg::Receive(Cw20ReceiveMsg {
sender: "addr0000".to_string(),
amount: Uint128::from(100u128),
msg: to_binary(&Cw20HookMsg::Bond {}).unwrap(),
});
let info = mock_info("staking0000", &[]);
let _res = execute(deps.as_mut(), mock_env(), info, msg).unwrap();
// unbond 150 tokens; failed
let msg = ExecuteMsg::Unbond {
amount: Uint128::from(150u128),
};
let info = mock_info("addr0000", &[]);
let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap_err();
match res {
StdError::GenericErr { msg, .. } => {
assert_eq!(msg, "Cannot unbond more than bond amount");
}
_ => panic!("Must return generic error"),
};
// normal unbond
let msg = ExecuteMsg::Unbond {
amount: Uint128::from(100u128),
};
let info = mock_info("addr0000", &[]);
let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap();
assert_eq!(
res.messages,
vec![SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute {
contract_addr: "staking0000".to_string(),
msg: to_binary(&Cw20ExecuteMsg::Transfer {
recipient: "addr0000".to_string(),
amount: Uint128::from(100u128),
})
.unwrap(),
funds: vec![],
}))]
);
}
#[test]
fn test_compute_reward() {
let mut deps = mock_dependencies(&[]);
let msg = InstantiateMsg {
anchor_token: "reward0000".to_string(),
staking_token: "staking0000".to_string(),
distribution_schedule: vec![
(
mock_env().block.time.seconds(),
mock_env().block.time.seconds() + 100,
Uint128::from(1000000u128),
),
(
mock_env().block.time.seconds() + 100,
mock_env().block.time.seconds() + 200,
Uint128::from(10000000u128),
),
],
};
let info = mock_info("addr0000", &[]);
let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap();
// bond 100 tokens
let msg = ExecuteMsg::Receive(Cw20ReceiveMsg {
sender: "addr0000".to_string(),
amount: Uint128::from(100u128),
msg: to_binary(&Cw20HookMsg::Bond {}).unwrap(),
});
let info = mock_info("staking0000", &[]);
let mut env = mock_env();
let _res = execute(deps.as_mut(), env.clone(), info.clone(), msg).unwrap();
// 100 seconds passed
// 1,000,000 rewards distributed
env.block.time = env.block.time.plus_seconds(100);
// bond 100 more tokens
let msg = ExecuteMsg::Receive(Cw20ReceiveMsg {
sender: "addr0000".to_string(),
amount: Uint128::from(100u128),
msg: to_binary(&Cw20HookMsg::Bond {}).unwrap(),
});
let _res = execute(deps.as_mut(), env.clone(), info, msg).unwrap();
assert_eq!(
from_binary::<StakerInfoResponse>(
&query(
deps.as_ref(),
mock_env(),
QueryMsg::StakerInfo {
staker: "addr0000".to_string(),
block_time: None,
},
)
.unwrap()
)
.unwrap(),
StakerInfoResponse {
staker: "addr0000".to_string(),
reward_index: Decimal::from_ratio(10000u128, 1u128),
pending_reward: Uint128::from(1000000u128),
bond_amount: Uint128::from(200u128),
}
);
// 100 seconds passed
// 1,000,000 rewards distributed
env.block.time = env.block.time.plus_seconds(10);
let info = mock_info("addr0000", &[]);
// unbond
let msg = ExecuteMsg::Unbond {
amount: Uint128::from(100u128),
};
let _res = execute(deps.as_mut(), env, info, msg).unwrap();
assert_eq!(
from_binary::<StakerInfoResponse>(
&query(
deps.as_ref(),
mock_env(),
QueryMsg::StakerInfo {
staker: "addr0000".to_string(),
block_time: None,
},
)
.unwrap()
)
.unwrap(),
StakerInfoResponse {
staker: "addr0000".to_string(),
reward_index: Decimal::from_ratio(15000u64, 1u64),
pending_reward: Uint128::from(2000000u128),
bond_amount: Uint128::from(100u128),
}
);
// query future block
assert_eq!(
from_binary::<StakerInfoResponse>(
&query(
deps.as_ref(),
mock_env(),
QueryMsg::StakerInfo {
staker: "addr0000".to_string(),
block_time: Some(mock_env().block.time.plus_seconds(120).seconds()),
},
)
.unwrap()
)
.unwrap(),
StakerInfoResponse {
staker: "addr0000".to_string(),
reward_index: Decimal::from_ratio(25000u64, 1u64),
pending_reward: Uint128::from(3000000u128),
bond_amount: Uint128::from(100u128),
}
);
}
#[test]
fn test_withdraw() {
let mut deps = mock_dependencies(&[]);
let msg = InstantiateMsg {
anchor_token: "reward0000".to_string(),
staking_token: "staking0000".to_string(),
distribution_schedule: vec![
(
mock_env().block.time.seconds(),
mock_env().block.time.seconds() + 100,
Uint128::from(1000000u128),
),
(
mock_env().block.time.seconds() + 100,
mock_env().block.time.seconds() + 200,
Uint128::from(10000000u128),
),
],
};
let info = mock_info("addr0000", &[]);
let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap();
// bond 100 tokens
let msg = ExecuteMsg::Receive(Cw20ReceiveMsg {
sender: "addr0000".to_string(),
amount: Uint128::from(100u128),
msg: to_binary(&Cw20HookMsg::Bond {}).unwrap(),
});
let info = mock_info("staking0000", &[]);
let mut env = mock_env();
let _res = execute(deps.as_mut(), env.clone(), info, msg).unwrap();
// 100 seconds passed
// 1,000,000 rewards distributed
env.block.time = env.block.time.plus_seconds(100);
let info = mock_info("addr0000", &[]);
let msg = ExecuteMsg::Withdraw {};
let res = execute(deps.as_mut(), env, info, msg).unwrap();
assert_eq!(
res.messages,
vec![SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute {
contract_addr: "reward0000".to_string(),
msg: to_binary(&Cw20ExecuteMsg::Transfer {
recipient: "addr0000".to_string(),
amount: Uint128::from(1000000u128),
})
.unwrap(),
funds: vec![],
}))]
);
}
#[test]
fn | () {
let mut deps = mock_dependencies(&[]);
let msg = InstantiateMsg {
anchor_token: "reward0000".to_string(),
staking_token: "staking0000".to_string(),
distribution_schedule: vec![
(
mock_env().block.time.seconds(),
mock_env().block.time.seconds() + 100,
Uint128::from(1000000u128),
),
(
mock_env().block.time.seconds() + 100,
mock_env().block.time.seconds() + 200,
Uint128::from(10000000u128),
),
],
};
let info = mock_info("addr0000", &[]);
let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap();
// bond 100 tokens
let msg = ExecuteMsg::Receive(Cw20ReceiveMsg {
sender: "addr0000".to_string(),
amount: Uint128::from(100u128),
msg: to_binary(&Cw20HookMsg::Bond {}).unwrap(),
});
let info = mock_info("staking0000", &[]);
let mut env = mock_env();
let _res = execute(deps.as_mut(), env.clone(), info, msg).unwrap();
// 100 seconds is passed
// 1,000,000 rewards distributed
env.block.time = env.block.time.plus_seconds(100);
let info = mock_info("addr0000", &[]);
let msg = ExecuteMsg::Withdraw {};
let res = execute(deps.as_mut(), env.clone(), info, msg).unwrap();
assert_eq!(
res.messages,
vec![SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute {
contract_addr: "reward0000".to_string(),
msg: to_binary(&Cw20ExecuteMsg::Transfer {
recipient: "addr0000".to_string(),
amount: Uint128::from(1000000u128),
})
.unwrap(),
funds: vec![],
}))]
);
// execute migration after 50 seconds
env.block.time = env.block.time.plus_seconds(50);
deps.querier.with_anc_minter("gov0000".to_string());
let msg = ExecuteMsg::MigrateStaking {
new_staking_contract: "newstaking0000".to_string(),
};
// unauthorized attempt
let info = mock_info("notgov0000", &[]);
let res = execute(deps.as_mut(), env.clone(), info, msg.clone());
match res {
Err(StdError::GenericErr { msg, .. }) => assert_eq!(msg, "unauthorized"),
_ => panic!("Must return unauthorized error"),
}
// successful attempt
let info = mock_info("gov0000", &[]);
let res = execute(deps.as_mut(), env, info, msg).unwrap();
assert_eq!(
res.attributes,
vec![
attr("action", "migrate_staking"),
attr("distributed_amount", "6000000"), // 1000000 + (10000000 / 2)
attr("remaining_amount", "5000000") // 11,000,000 - 6000000
]
);
assert_eq!(
res.messages,
vec![SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute {
contract_addr: "reward0000".to_string(),
msg: to_binary(&Cw20ExecuteMsg::Transfer {
recipient: "newstaking0000".to_string(),
amount: Uint128::from(5000000u128),
})
.unwrap(),
funds: vec![],
}))]
);
// query config
let res = query(deps.as_ref(), mock_env(), QueryMsg::Config {}).unwrap();
let config: ConfigResponse = from_binary(&res).unwrap();
assert_eq!(
config,
ConfigResponse {
anchor_token: "reward0000".to_string(),
staking_token: "staking0000".to_string(),
distribution_schedule: vec![
(
mock_env().block.time.seconds(),
mock_env().block.time.seconds() + 100,
Uint128::from(1000000u128)
),
(
mock_env().block.time.seconds() + 100,
mock_env().block.time.seconds() + 150,
Uint128::from(5000000u128)
), // slot was modified
]
}
);
}
#[test]
fn test_update_config() {
let mut deps = mock_dependencies(&[]);
let msg = InstantiateMsg {
anchor_token: "reward0000".to_string(),
staking_token: "staking0000".to_string(),
distribution_schedule: vec![
(
mock_env().block.time.seconds(),
mock_env().block.time.seconds() + 100,
Uint128::from(1000000u128),
),
(
mock_env().block.time.seconds() + 100,
mock_env().block.time.seconds() + 200,
Uint128::from(10000000u128),
),
(
mock_env().block.time.seconds() + 200,
mock_env().block.time.seconds() + 300,
Uint128::from(10000000u128),
),
(
mock_env().block.time.seconds() + 300,
mock_env().block.time.seconds() + 400,
Uint128::from(10000000u128),
),
(
mock_env().block.time.seconds() + 400,
mock_env().block.time.seconds() + 500,
Uint128::from(10000000u128),
),
],
};
let info = mock_info("addr0000", &[]);
let _res = instantiate(deps.as_mut(), mock_env(), info, msg).unwrap();
let update_config = UpdateConfig {
distribution_schedule: vec![(
mock_env().block.time.seconds() + 300,
mock_env().block.time.seconds() + 400,
Uint128::from(10000000u128),
)],
};
deps.querier.with_anc_minter("gov0000".to_string());
let info = mock_info("notgov", &[]);
let res = execute(deps.as_mut(), mock_env(), info, update_config);
match res {
Err(StdError::GenericErr { msg, .. }) => assert_eq!(msg, "unauthorized"),
_ => panic!("Must return unauthorized error"),
}
// do some bond and update rewards
// bond 100 tokens
let msg = ExecuteMsg::Receive(Cw20ReceiveMsg {
sender: "addr0000".to_string(),
amount: Uint128::from(100u128),
msg: to_binary(&Cw20HookMsg::Bond {}).unwrap(),
});
let info = mock_info("staking0000", &[]);
let mut env = mock_env();
let _res = execute(deps.as_mut(), env.clone(), info, msg).unwrap();
// 100 seconds is passed
// 1,000,000 rewards distributed
env.block.time = env.block.time.plus_seconds(100);
let info = mock_info("addr0000", &[]);
let msg = ExecuteMsg::Withdraw {};
let res = execute(deps.as_mut(), env.clone(), info, msg).unwrap();
assert_eq!(
res.messages,
vec![SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute {
contract_addr: "reward0000".to_string(),
msg: to_binary(&Cw20ExecuteMsg::Transfer {
recipient: "addr0000".to_string(),
amount: Uint128::from(1000000u128),
})
.unwrap(),
funds: vec![],
}))]
);
let update_config = UpdateConfig {
distribution_schedule: vec![
(
mock_env().block.time.seconds(),
mock_env().block.time.seconds() + 100,
Uint128::from(5000000u128),
),
(
mock_env().block.time.seconds() + 100,
mock_env().block.time.seconds() + 200,
Uint128::from(10000000u128),
),
(
mock_env().block.time.seconds() + 200,
mock_env().block.time.seconds() + 300,
Uint128::from(10000000u128),
),
(
mock_env().block.time.seconds() + 300,
mock_env().block.time.seconds() + 400,
Uint128::from(10000000u128),
),
(
mock_env().block.time.seconds() + 400,
mock_env().block.time.seconds() + 500,
Uint128::from(10000000u128),
),
],
};
deps.querier.with_anc_minter("gov0000".to_string());
let info = mock_info("gov0000", &[]);
let res = execute(deps.as_mut(), mock_env(), info, update_config);
match res {
Err(StdError::GenericErr { msg, .. }) => {
assert_eq!(msg, "new schedule removes already started distribution")
}
_ => panic!("Must return unauthorized error"),
}
// do some bond and update rewards
// bond 100 tokens
let msg = ExecuteMsg::Receive(Cw20ReceiveMsg {
sender: "addr0000".to_string(),
amount: Uint128::from(100u128),
msg: to_binary(&Cw20HookMsg::Bond {}).unwrap(),
});
let info = mock_info("staking0000", &[]);
let _res = execute(deps.as_mut(), env.clone(), info, msg).unwrap();
// 100 seconds is passed
// 1,000,000 rewards distributed
env.block.time = env.block.time.plus_seconds(100);
let info = mock_info("addr0000", &[]);
let msg = ExecuteMsg::Withdraw {};
let _res = execute(deps.as_mut(), env, info, msg).unwrap();
//cannot update previous scehdule
let update_config = UpdateConfig {
distribution_schedule: vec![
(
mock_env().block.time.seconds(),
mock_env().block.time.seconds() + 100,
Uint128::from(5000000u128),
),
(
mock_env().block.time.seconds() + 100,
mock_env().block.time.seconds() + 200,
Uint128::from(10000000u128),
),
(
mock_env().block.time.seconds() + 200,
mock_env().block.time.seconds() + 300,
Uint128::from(10000000u128),
),
(
mock_env().block.time.seconds() + 300,
mock_env().block.time.seconds() + 400,
Uint128::from(10000000u128),
),
(
mock_env().block.time.seconds() + 400,
mock_env().block.time.seconds() + 500,
Uint128::from(10000000u128),
),
],
};
deps.querier.with_anc_minter("gov0000".to_string());
let info = mock_info("gov0000", &[]);
let res = execute(deps.as_mut(), mock_env(), info, update_config);
match res {
Err(StdError::GenericErr { msg, .. }) => {
assert_eq!(msg, "new schedule removes already started distribution")
}
_ => panic!("Must return unauthorized error"),
}
//successful one
let update_config = UpdateConfig {
distribution_schedule: vec![
(
mock_env().block.time.seconds(),
mock_env().block.time.seconds() + 100,
Uint128::from(1000000u128),
),
(
mock_env().block.time.seconds() + 100,
mock_env().block.time.seconds() + 200,
Uint128::from(10000000u128),
),
(
mock_env().block.time.seconds() + 200,
mock_env().block.time.seconds() + 300,
Uint128::from(10000000u128),
),
(
mock_env().block.time.seconds() + 300,
mock_env().block.time.seconds() + 400,
Uint128::from(20000000u128),
),
(
mock_env().block.time.seconds() + 400,
mock_env().block.time.seconds() + 500,
Uint128::from(10000000u128),
),
],
};
deps.querier.with_anc_minter("gov0000".to_string());
let info = mock_info("gov0000", &[]);
let res = execute(deps.as_mut(), mock_env(), info, update_config).unwrap();
assert_eq!(res.attributes, vec![("action", "update_config")]);
// query config
let res = query(deps.as_ref(), mock_env(), QueryMsg::Config {}).unwrap();
let config: ConfigResponse = from_binary(&res).unwrap();
assert_eq!(
config.distribution_schedule,
vec![
(
mock_env().block.time.seconds(),
mock_env().block.time.seconds() + 100,
Uint128::from(1000000u128),
),
(
mock_env().block.time.seconds() + 100,
mock_env().block.time.seconds() + 200,
Uint128::from(10000000u128),
),
(
mock_env().block.time.seconds() + 200,
mock_env().block.time.seconds() + 300,
Uint128::from(10000000u128),
),
(
mock_env().block.time.seconds() + 300,
mock_env().block.time.seconds() + 400,
Uint128::from(20000000u128),
),
(
mock_env().block.time.seconds() + 400,
mock_env().block.time.seconds() + 500,
Uint128::from(10000000u128),
),
]
);
//successful one
let update_config = UpdateConfig {
distribution_schedule: vec![
(
mock_env().block.time.seconds(),
mock_env().block.time.seconds() + 100,
Uint128::from(1000000u128),
),
(
mock_env().block.time.seconds() + 100,
mock_env().block.time.seconds() + 200,
Uint128::from(10000000u128),
),
(
mock_env().block.time.seconds() + 200,
mock_env().block.time.seconds() + 300,
Uint128::from(10000000u128),
),
(
mock_env().block.time.seconds() + 300,
mock_env().block.time.seconds() + 400,
Uint128::from(20000000u128),
),
(
mock_env().block.time.seconds() + 400,
mock_env().block.time.seconds() + 500,
Uint128::from(50000000u128),
),
],
};
deps.querier.with_anc_minter("gov0000".to_string());
let info = mock_info("gov0000", &[]);
let res = execute(deps.as_mut(), mock_env(), info, update_config).unwrap();
assert_eq!(res.attributes, vec![("action", "update_config")]);
// query config
let res = query(deps.as_ref(), mock_env(), QueryMsg::Config {}).unwrap();
let config: ConfigResponse = from_binary(&res).unwrap();
assert_eq!(
config.distribution_schedule,
vec![
(
mock_env().block.time.seconds(),
mock_env().block.time.seconds() + 100,
Uint128::from(1000000u128),
),
(
mock_env().block.time.seconds() + 100,
mock_env().block.time.seconds() + 200,
Uint128::from(10000000u128),
),
(
mock_env().block.time.seconds() + 200,
mock_env().block.time.seconds() + 300,
Uint128::from(10000000u128),
),
(
mock_env().block.time.seconds() + 300,
mock_env().block.time.seconds() + 400,
Uint128::from(20000000u128),
),
(
mock_env().block.time.seconds() + 400,
mock_env().block.time.seconds() + 500,
Uint128::from(50000000u128),
),
]
);
let update_config = UpdateConfig {
distribution_schedule: vec![
(
mock_env().block.time.seconds(),
mock_env().block.time.seconds() + 100,
Uint128::from(1000000u128),
),
(
mock_env().block.time.seconds() + 100,
mock_env().block.time.seconds() + 200,
Uint128::from(10000000u128),
),
(
mock_env().block.time.seconds() + 200,
mock_env().block.time.seconds() + 300,
Uint128::from(10000000u128),
),
(
mock_env().block.time.seconds() + 300,
mock_env().block.time.seconds() + 400,
Uint128::from(90000000u128),
),
(
mock_env().block.time.seconds() + 400,
mock_env().block.time.seconds() + 500,
Uint128::from(80000000u128),
),
],
};
deps.querier.with_anc_minter("gov0000".to_string());
let info = mock_info("gov0000", &[]);
let res = execute(deps.as_mut(), mock_env(), info, update_config).unwrap();
assert_eq!(res.attributes, vec![("action", "update_config")]);
// query config
let res = query(deps.as_ref(), mock_env(), QueryMsg::Config {}).unwrap();
let config: ConfigResponse = from_binary(&res).unwrap();
assert_eq!(
config.distribution_schedule,
vec![
(
mock_env().block.time.seconds(),
mock_env().block.time.seconds() + 100,
Uint128::from(1000000u128),
),
(
mock_env().block.time.seconds() + 100,
mock_env().block.time.seconds() + 200,
Uint128::from(10000000u128),
),
(
mock_env().block.time.seconds() + 200,
mock_env().block.time.seconds() + 300,
Uint128::from(10000000u128),
),
(
mock_env().block.time.seconds() + 300,
mock_env().block.time.seconds() + 400,
Uint128::from(90000000u128),
),
(
mock_env().block.time.seconds() + 400,
mock_env().block.time.seconds() + 500,
Uint128::from(80000000u128),
),
]
);
let update_config = UpdateConfig {
distribution_schedule: vec![
(
mock_env().block.time.seconds(),
mock_env().block.time.seconds() + 100,
Uint128::from(1000000u128),
),
(
mock_env().block.time.seconds() + 100,
mock_env().block.time.seconds() + 200,
Uint128::from(10000000u128),
),
(
mock_env().block.time.seconds() + 200,
mock_env().block.time.seconds() + 300,
Uint128::from(10000000u128),
),
(
mock_env().block.time.seconds() + 300,
mock_env().block.time.seconds() + 400,
Uint128::from(90000000u128),
),
(
mock_env().block.time.seconds() + 400,
mock_env().block.time.seconds() + 500,
Uint128::from(80000000u128),
),
(
mock_env().block.time.seconds() + 500,
mock_env().block.time.seconds() + 600,
Uint128::from(60000000u128),
),
],
};
deps.querier.with_anc_minter("gov0000".to_string());
let info = mock_info("gov0000", &[]);
let res = execute(deps.as_mut(), mock_env(), info, update_config).unwrap();
assert_eq!(res.attributes, vec![("action", "update_config")]);
// query config
let res = query(deps.as_ref(), mock_env(), QueryMsg::Config {}).unwrap();
let config: ConfigResponse = from_binary(&res).unwrap();
assert_eq!(
config.distribution_schedule,
vec![
(
mock_env().block.time.seconds(),
mock_env().block.time.seconds() + 100,
Uint128::from(1000000u128),
),
(
mock_env().block.time.seconds() + 100,
mock_env().block.time.seconds() + 200,
Uint128::from(10000000u128),
),
(
mock_env().block.time.seconds() + 200,
mock_env().block.time.seconds() + 300,
Uint128::from(10000000u128),
),
(
mock_env().block.time.seconds() + 300,
mock_env().block.time.seconds() + 400,
Uint128::from(90000000u128),
),
(
mock_env().block.time.seconds() + 400,
mock_env().block.time.seconds() + 500,
Uint128::from(80000000u128),
),
(
mock_env().block.time.seconds() + 500,
mock_env().block.time.seconds() + 600,
Uint128::from(60000000u128),
)
]
);
}
| test_migrate_staking |
lazycache_test.go | /*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package lazycache
import (
"fmt"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/hyperledger/fabric-sdk-go/pkg/util/concurrent/lazyref"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/hyperledger/fabric-sdk-go/pkg/util/test"
)
func ExampleCache_MustGet() {
cache := New("Example_Cache", func(key Key) (interface{}, error) {
return fmt.Sprintf("Value_for_key_%s", key), nil
})
defer cache.Close()
key := NewStringKey("Key1")
fmt.Println(cache.MustGet(key))
// Output: Value_for_key_Key1
}
func ExampleCache_Get() {
cache := New("Example_Cache", func(key Key) (interface{}, error) {
if key.String() == "error" {
return nil, fmt.Errorf("some error")
}
return fmt.Sprintf("Value_for_key_%s", key), nil
})
defer cache.Close()
value, err := cache.Get(NewStringKey("Key1"))
if err != nil {
fmt.Printf("Error returned: %s\n", err)
}
fmt.Println(value)
value, err = cache.Get(NewStringKey("error"))
if err != nil {
fmt.Printf("Error returned: %s\n", err)
}
fmt.Println(value)
}
func ExampleCache_Get_expiring() {
cache := New("Example_Expiring_Cache",
func(key Key) (interface{}, error) {
if key.String() == "error" {
return nil, fmt.Errorf("some error")
}
return fmt.Sprintf("Value_for_key_%s", key), nil
},
lazyref.WithAbsoluteExpiration(time.Second),
lazyref.WithFinalizer(func(expiredValue interface{}) {
fmt.Printf("Expired value: %s\n", expiredValue)
}),
)
defer cache.Close()
value, err := cache.Get(NewStringKey("Key1"))
if err != nil {
fmt.Printf("Error returned: %s\n", err)
} else {
fmt.Print(value)
}
_, err = cache.Get(NewStringKey("error"))
if err != nil {
fmt.Printf("Error returned: %s\n", err)
}
}
func ExampleCache_Get_expiringWithData() {
cache := NewWithData("Example_Expiring_Cache",
func(key Key, data interface{}) (interface{}, error) {
return fmt.Sprintf("Value_for_%s_%d", key, data.(int)), nil
},
lazyref.WithAbsoluteExpiration(20*time.Millisecond),
)
defer cache.Close()
for i := 0; i < 5; i++ {
value, err := cache.Get(NewStringKey("Key"), i)
if err != nil {
fmt.Printf("Error returned: %s", err)
} else {
fmt.Print(value)
}
time.Sleep(15 * time.Millisecond)
}
}
func TestGet(t *testing.T) {
var numTimesInitialized int32
expectedTimesInitialized := 2
cache := New("Example_Cache", func(key Key) (interface{}, error) {
if key.String() == "error" {
return nil, fmt.Errorf("some error")
}
atomic.AddInt32(&numTimesInitialized, 1)
return fmt.Sprintf("Value_for_key_%s", key), nil
})
concurrency := 100
var wg sync.WaitGroup
wg.Add(concurrency)
for i := 0; i < concurrency; i++ {
go func() {
defer wg.Done()
value, err := cache.Get(NewStringKey("Key1"))
if err != nil {
test.Failf(t, "Error returned: %s", err)
}
expectedValue := "Value_for_key_Key1"
if value != expectedValue {
test.Failf(t, "Expecting value [%s] but got [%s]", expectedValue, value)
}
value, err = cache.Get(NewStringKey("Key2"))
if err != nil {
test.Failf(t, "Error returned: %s", err)
}
expectedValue = "Value_for_key_Key2"
if value != expectedValue {
test.Failf(t, "Expecting value [%s] but got [%s]", expectedValue, value)
}
_, err = cache.Get(NewStringKey("error"))
if err == nil {
test.Failf(t, "Expecting error but got none")
}
}()
}
wg.Wait()
if num := atomic.LoadInt32(&numTimesInitialized); num != int32(expectedTimesInitialized) {
t.Fatalf("Expecting initializer to be called %d time(s) but it was called %d time(s)", expectedTimesInitialized, num)
}
cache.Close()
}
func TestDelete(t *testing.T) {
cache := New("Example_Cache", func(key Key) (interface{}, error) {
if key.String() == "error" {
return nil, fmt.Errorf("some error")
}
return fmt.Sprintf("Value_for_key_%s", key), nil
})
defer cache.Close()
_, err := cache.Get(NewStringKey("Key1"))
if err != nil {
test.Failf(t, "Error returned: %s", err)
}
_, ok := cache.m.Load("Key1")
if !ok {
test.Failf(t, "value not exist in map")
}
cache.Delete(NewStringKey("Key1"))
_, ok = cache.m.Load("Key1")
if ok {
test.Failf(t, "value exist in map after delete")
}
}
func TestMustGetPanic(t *testing.T) {
cache := New("Example_Cache", func(key Key) (interface{}, error) {
if key.String() == "error" {
return nil, fmt.Errorf("some error")
}
return fmt.Sprintf("Value_for_key_%s", key), nil
})
value := cache.MustGet(NewStringKey("Key1"))
expectedValue := "Value_for_key_Key1"
if value != expectedValue {
t.Fatalf("Expecting value [%s] but got [%s]", expectedValue, value)
}
defer func() {
if r := recover(); r == nil {
t.Fatalf("Expecting panic but got none")
}
}()
cache.MustGet(NewStringKey("error"))
t.Fatal("Expecting panic but got none")
cache.Close()
}
type closableValue struct {
str string
closeCalled int32
}
func (v *closableValue) Close() {
atomic.StoreInt32(&v.closeCalled, 1)
}
func (v *closableValue) CloseCalled() bool {
return atomic.LoadInt32(&v.closeCalled) == 1
}
func TestClose(t *testing.T) {
cache := New("Example_Cache", func(key Key) (interface{}, error) {
return &closableValue{
str: fmt.Sprintf("Value_for_key_%s", key),
}, nil
})
cval, err := cache.Get(NewStringKey("Key1"))
if err != nil {
t.Fatalf("Error returned: %s", err)
}
expectedValue := "Value_for_key_Key1"
cvalue := cval.(*closableValue)
if cvalue.str != expectedValue {
t.Fatalf("Expecting value [%s] but got [%s]", expectedValue, cvalue.str)
}
if cvalue.CloseCalled() {
t.Fatal("Not expecting close to be called but is was")
}
// Get again - should succeed
cval, err = cache.Get(NewStringKey("Key1"))
if err != nil {
t.Fatalf("Error returned: %s", err)
}
cvalue = cval.(*closableValue)
if cvalue.str != expectedValue {
t.Fatalf("Expecting value [%s] but got [%s]", expectedValue, cvalue.str)
}
if cvalue.CloseCalled() {
t.Fatal("Not expecting close to be called but is was")
}
// Close the cache
cache.Close()
assert.True(t, cache.IsClosed())
// Close again should be fine
cache.Close()
if !cvalue.CloseCalled() {
t.Fatal("Expecting close to be called but is wasn't")
}
_, err = cache.Get(NewStringKey("Key1"))
if err == nil {
t.Fatal("Expecting error since cache is closed")
}
}
// TestGetExpiring tests that the cache value expires and that the
// finalizer is called when it expires and also after the cache is closed.
func TestGetExpiring(t *testing.T) {
var numTimesInitialized int32
var numTimesFinalized int32
cache := New("Example_Expiring_Cache",
func(key Key) (interface{}, error) {
if key.String() == "error" {
return nil, fmt.Errorf("some error")
}
atomic.AddInt32(&numTimesInitialized, 1)
return fmt.Sprintf("Value_for_key_%s", key), nil
},
lazyref.WithAbsoluteExpiration(25*time.Millisecond),
lazyref.WithFinalizer(func(expiredValue interface{}) {
atomic.AddInt32(&numTimesFinalized, 1)
}),
)
for i := 0; i < 10; i++ {
time.Sleep(10 * time.Millisecond)
value, err := cache.Get(NewStringKey("Key1"))
require.NoErrorf(t, err, "error returned for Key1")
expectedValue := "Value_for_key_Key1"
assert.Equal(t, expectedValue, value)
value, err = cache.Get(NewStringKey("Key2"))
require.NoErrorf(t, err, "error returned for Key2")
expectedValue = "Value_for_key_Key2"
assert.Equal(t, expectedValue, value)
_, err = cache.Get(NewStringKey("error"))
require.Errorf(t, err, "expecting error 'error' key")
}
initializedTimes := atomic.LoadInt32(&numTimesInitialized)
assert.Truef(t, initializedTimes > 2, "Expecting initializer to be called more than %d times but it was called %d time(s)", 2, initializedTimes)
finalizedTimes := atomic.LoadInt32(&numTimesFinalized)
assert.Truef(t, finalizedTimes > 2, "Expecting finalizer to be called more than %d times but it was called %d time(s)", 2, finalizedTimes)
// Closing the cache should also close all of the lazy refs and call our finalizer
cache.Close()
finalizedTimesAfterClose := atomic.LoadInt32(&numTimesFinalized)
assert.Truef(t, finalizedTimesAfterClose == initializedTimes, "Expecting finalizer to be called %d times but it was called %d time(s)", initializedTimes, finalizedTimesAfterClose)
}
// TestGetExpiringWithData tests that the data passed to Get() is
// used in the initializer each time the value expires.
func TestGetExpiringWithData(t *testing.T) |
// TestGetExpiringError tests that the lazy reference value is NOT cached if
// an error is returned from the initializer.
func TestGetExpiringError(t *testing.T) {
var numTimesInitialized int32
var numTimesFinalized int32
cache := New("Example_Expiring_Cache",
func(key Key) (interface{}, error) {
atomic.AddInt32(&numTimesInitialized, 1)
return nil, fmt.Errorf("some error")
},
lazyref.WithFinalizer(func(expiredValue interface{}) {
atomic.AddInt32(&numTimesFinalized, 1)
}),
)
iterations := 10
for i := 0; i < iterations; i++ {
time.Sleep(10 * time.Millisecond)
_, err := cache.Get(NewStringKey("error"))
require.Errorf(t, err, "expecting error 'error' key")
}
initializedTimes := atomic.LoadInt32(&numTimesInitialized)
assert.Equalf(t, int32(iterations), initializedTimes, "Expecting initializer to be called every time since no value should have been cached when returning an error")
finalizedTimes := atomic.LoadInt32(&numTimesFinalized)
assert.Equalf(t, int32(0), finalizedTimes, "Expecting finalizer not to be called due to error but it was called %d time(s)", finalizedTimes)
cache.Close()
finalizedTimesAfterClose := atomic.LoadInt32(&numTimesFinalized)
assert.Equalf(t, int32(0), finalizedTimesAfterClose, "Expecting finalizer not to be called due to error but it was called %d time(s)", finalizedTimesAfterClose)
}
| {
var numTimesInitialized int32
var numTimesFinalized int32
cache := NewWithData("Example_Expiring_Cache",
func(key Key, data interface{}) (interface{}, error) {
atomic.AddInt32(&numTimesInitialized, 1)
return fmt.Sprintf("Value_for_key_%s_[%d]", key, data.(int)), nil
},
lazyref.WithAbsoluteExpiration(25*time.Millisecond),
lazyref.WithFinalizer(func(expiredValue interface{}) {
atomic.AddInt32(&numTimesFinalized, 1)
}),
)
defer cache.Close()
numTimesIndexChanged := 0
prevIndex := 0
for i := 0; i < 10; i++ {
time.Sleep(10 * time.Millisecond)
value, err := cache.Get(NewStringKey("Key"), i)
require.NoError(t, err)
strValue := value.(string)
i := strings.Index(strValue, "[")
assert.Truef(t, i > 0, "expecting to find [ in value")
j := strings.Index(strValue, "]")
assert.Truef(t, j > 0, "expecting to find ] in value")
index, err := strconv.Atoi(strValue[i+1 : j])
require.NoError(t, err)
assert.Truef(t, index <= i, "expecting index to be less than or equal to i")
if index != prevIndex {
numTimesIndexChanged++
prevIndex = index
}
}
assert.Truef(t, numTimesIndexChanged > 2, "expecting that the index would change at least 2 times but it changed %d tim(s)", numTimesIndexChanged)
} |
IpcApp.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
* @module NativeApp
*/
import { AsyncMethodsOf, PromiseReturnType } from "@bentley/bentleyjs-core";
import {
BackendError, IModelError, IModelStatus, IpcAppChannel, IpcAppFunctions, IpcAppNotifications, IpcInvokeReturn, IpcListener, IpcSocketFrontend,
iTwinChannel, RemoveFunction,
} from "@bentley/imodeljs-common";
import { IModelApp, IModelAppOptions } from "./IModelApp";
/**
* Options for [[IpcApp.startup]]
* @public
*/
export interface IpcAppOptions {
iModelApp?: IModelAppOptions;
}
/**
* The frontend of apps with a dedicated backend that can use [Ipc]($docs/learning/IpcInterface.md).
* @public
*/
export class | {
private static _ipc: IpcSocketFrontend | undefined;
/** Get the implementation of the [[IpcSocketFrontend]] interface. */
private static get ipc(): IpcSocketFrontend { return this._ipc!; }
/** Determine whether Ipc is available for this frontend. This will only be true if [[startup]] has been called on this class. */
public static get isValid(): boolean { return undefined !== this._ipc; }
/**
* Establish a message handler function for the supplied channel over Ipc. The handler will be called when messages are sent for
* the channel via [[BackendIpc.send]].
* @param channel the name of the channel
* @param handler the message handler
* @returns A function to remove the handler
* @note Ipc is only supported if [[isValid]] is true.
*/
public static addListener(channel: string, handler: IpcListener): RemoveFunction {
return this.ipc.addListener(iTwinChannel(channel), handler);
}
/**
* Remove a previously registered listener
* @param channel The name of the channel for the listener previously registered with [[addListener]]
* @param listener The function passed to [[addListener]]
*/
public static removeListener(channel: string, listener: IpcListener) {
this.ipc.removeListener(iTwinChannel(channel), listener);
}
/**
* Send a message to the backend via `channel` and expect a result asynchronously. The handler must be established on the backend via [[BackendIpc.handle]]
* @param channel The name of the channel for the method.
* @see Electron [ipcRenderer.invoke](https://www.electronjs.org/docs/api/ipc-renderer) documentation for details.
* Note that this interface may be implemented via Electron for desktop apps, or via
* [WebSockets](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API) for mobile or web-based
* Ipc connections. In either case, the Electron documentation provides the specifications for how it works.
* @note `args` are serialized with the [Structured Clone Algorithm](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm), so only
* primitive types and `ArrayBuffers` are allowed.
*/
public static async invoke(channel: string, ...args: any[]): Promise<any> {
return this.ipc.invoke(iTwinChannel(channel), ...args);
}
/**
* Send a message over the socket.
* @param channel The name of the channel for the message.
* @param data The optional data of the message.
* @note `data` is serialized with the [Structured Clone Algorithm](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm), so only
* primitive types and `ArrayBuffers` are allowed.
*/
public static send(channel: string, ...data: any[]) {
return this.ipc.send(iTwinChannel(channel), ...data);
}
/**
* Call a method on the backend through an Ipc channel.
* @param channelName the channel registered by the backend handler.
* @param methodName the name of a method implemented by the backend handler.
* @param args arguments to `methodName`
* @return a Promise with the return value from `methodName`
* @note If the backend implementation throws an exception, this method will throw a [[BackendError]] exception
* with the `errorNumber` and `message` from the backend.
* @note Ipc is only supported if [[isValid]] is true.
* @internal
*/
public static async callIpcChannel(channelName: string, methodName: string, ...args: any[]): Promise<any> {
const retVal = (await this.invoke(channelName, methodName, ...args)) as IpcInvokeReturn;
if (undefined !== retVal.error) {
const err = new BackendError(retVal.error.errorNumber, retVal.error.name, retVal.error.message);
err.stack = retVal.error.stack;
throw err;
}
return retVal.result;
}
public static async callIpcHost<T extends AsyncMethodsOf<IpcAppFunctions>>(methodName: T, ...args: Parameters<IpcAppFunctions[T]>) {
return this.callIpcChannel(IpcAppChannel.Functions, methodName, ...args) as PromiseReturnType<IpcAppFunctions[T]>;
}
/** start an IpcApp.
* @note this should not be called directly. It is called by NativeApp.startup */
public static async startup(ipc: IpcSocketFrontend, opts?: IpcAppOptions) {
this._ipc = ipc;
IpcAppNotifyHandler.register(); // receives notifications from backend
await IModelApp.startup(opts?.iModelApp);
}
/** @internal */
public static async shutdown() {
this._ipc = undefined;
await IModelApp.shutdown();
}
}
/**
* Base class for all implementations of an Ipc notification response interface. This class is implemented on your frontend to supply
* methods to receive notifications from your backend.
*
* Create a subclass to implement your Ipc response interface. Your class should be declared like this:
* ```ts
* class MyNotificationHandler extends NotificationHandler implements MyNotifications
* ```
* to ensure all method names and signatures are correct. Your methods cannot have a return value.
*
* Then, call `MyNotificationHandler.register` at startup to connect your class to your channel.
* @public
*/
export abstract class NotificationHandler {
/** All subclasses must implement this method to specify their response channel name. */
public abstract get channelName(): string;
public registerImpl(): RemoveFunction {
return IpcApp.addListener(this.channelName, (_evt: Event, funcName: string, ...args: any[]) => {
const func = (this as any)[funcName];
if (typeof func !== "function")
throw new IModelError(IModelStatus.FunctionNotFound, `Method "${this.constructor.name}.${funcName}" not found on NotificationHandler registered for channel: ${this.channelName}`);
func.call(this, ...args);
});
}
/**
* Register this class as the handler for notifications on its channel. This static method creates a new instance
* that becomes the notification handler and is `this` when its methods are called.
* @returns A function that can be called to remove the handler.
* @note this method should only be called once per channel. If it is called multiple times, multiple handlers are established.
*/
public static register(): RemoveFunction {
return (new (this as any)() as NotificationHandler).registerImpl(); // create an instance of subclass. "as any" is necessary because base class is abstract
}
}
/** IpcApp notifications from backend */
class IpcAppNotifyHandler extends NotificationHandler implements IpcAppNotifications {
public get channelName() { return IpcAppChannel.AppNotify; }
public notifyApp() { }
}
| IpcApp |
has_comments.rs | use ditto_cst::*;
pub trait HasComments {
fn has_comments(&self) -> bool;
fn has_leading_comments(&self) -> bool;
}
impl<T: HasComments> HasComments for Box<T> {
fn has_comments(&self) -> bool {
self.as_ref().has_comments()
}
fn has_leading_comments(&self) -> bool {
self.as_ref().has_leading_comments()
}
}
impl HasComments for Expression {
fn has_comments(&self) -> bool {
match self {
Self::True(keyword) => keyword.0.has_comments(),
Self::False(keyword) => keyword.0.has_comments(),
Self::Unit(keyword) => keyword.0.has_comments(),
Self::String(token) => token.has_comments(),
Self::Int(token) => token.has_comments(),
Self::Float(token) => token.has_comments(),
Self::Constructor(constructor) => constructor.has_comments(),
Self::Variable(variable) => variable.has_comments(),
Self::Parens(parens) => parens.has_comments(),
Self::Array(brackets) => brackets.has_comments(),
Self::If {
if_keyword,
condition,
then_keyword,
true_clause,
else_keyword,
false_clause,
} => {
if_keyword.0.has_comments()
|| condition.has_comments()
|| then_keyword.0.has_comments()
|| true_clause.has_comments()
|| else_keyword.0.has_comments()
|| false_clause.has_comments()
}
Self::Function {
parameters, | return_type_annotation,
right_arrow,
body,
} => {
parameters.has_comments()
|| return_type_annotation.has_comments()
|| right_arrow.0.has_comments()
|| body.has_comments()
}
Self::Call {
function,
arguments,
} => function.has_comments() || arguments.has_comments(),
Self::Match {
match_keyword,
expression,
with_keyword,
head_arm,
tail_arms,
} => {
match_keyword.0.has_comments()
|| expression.has_comments()
|| with_keyword.0.has_comments()
|| head_arm.has_comments()
|| tail_arms.iter().any(|arm| arm.has_comments())
}
Self::Effect {
do_keyword,
open_brace,
effect,
close_brace,
} => {
do_keyword.0.has_comments()
|| open_brace.0.has_comments()
|| effect.has_comments()
|| close_brace.0.has_comments()
}
Self::BinOp { lhs, operator, rhs } => {
lhs.has_comments() || operator.has_comments() || rhs.has_comments()
}
Self::RecordAccess { target, dot, label } => {
target.has_comments() || dot.has_comments() || label.has_comments()
}
Self::Record(braces) => {
braces.open_brace.0.has_comments()
|| braces.value.has_comments()
|| braces.close_brace.0.has_comments()
}
}
}
fn has_leading_comments(&self) -> bool {
match self {
Self::True(keyword) => keyword.0.has_leading_comments(),
Self::False(keyword) => keyword.0.has_leading_comments(),
Self::Unit(keyword) => keyword.0.has_leading_comments(),
Self::String(token) => token.has_leading_comments(),
Self::Int(token) => token.has_leading_comments(),
Self::Float(token) => token.has_leading_comments(),
Self::Constructor(constructor) => constructor.has_leading_comments(),
Self::Variable(variable) => variable.has_leading_comments(),
Self::Parens(parens) => parens.open_paren.0.has_leading_comments(),
Self::Array(brackets) => brackets.open_bracket.0.has_leading_comments(),
Self::If { if_keyword, .. } => if_keyword.0.has_leading_comments(),
Self::Function { box parameters, .. } => parameters.open_paren.0.has_leading_comments(),
Self::Call { function, .. } => function.has_leading_comments(),
Self::Match { match_keyword, .. } => match_keyword.0.has_leading_comments(),
Self::Effect { do_keyword, .. } => do_keyword.0.has_leading_comments(),
Self::BinOp { lhs, .. } => lhs.has_leading_comments(),
Self::RecordAccess { target, .. } => target.has_leading_comments(),
Self::Record(braces) => braces.open_brace.0.has_leading_comments(),
}
}
}
impl HasComments for FunctionParameter {
fn has_comments(&self) -> bool {
match self {
Self::Name(name) => name.has_comments(),
Self::Unused(unused_name) => unused_name.has_comments(),
}
}
fn has_leading_comments(&self) -> bool {
match self {
Self::Name(name) => name.has_leading_comments(),
Self::Unused(unused_name) => unused_name.has_leading_comments(),
}
}
}
impl HasComments for RecordField {
fn has_comments(&self) -> bool {
self.label.has_comments() || self.equals.0.has_comments() || self.value.has_comments()
}
fn has_leading_comments(&self) -> bool {
self.label.has_leading_comments()
}
}
impl HasComments for RecordTypeField {
fn has_comments(&self) -> bool {
self.label.has_comments() || self.colon.0.has_comments() || self.value.has_comments()
}
fn has_leading_comments(&self) -> bool {
self.label.has_leading_comments()
}
}
impl HasComments for Effect {
fn has_comments(&self) -> bool {
match self {
Self::Return {
return_keyword,
expression,
} => return_keyword.0.has_comments() || expression.has_comments(),
Self::Bind {
name,
left_arrow,
expression,
semicolon,
rest,
} => {
name.has_comments()
|| left_arrow.0.has_comments()
|| expression.has_comments()
|| semicolon.0.has_comments()
|| rest.has_comments()
}
Self::Expression {
expression,
rest: None,
} => expression.has_comments(),
Self::Expression {
expression,
rest: Some((semicolon, rest)),
} => expression.has_comments() || semicolon.0.has_comments() || rest.has_comments(),
}
}
fn has_leading_comments(&self) -> bool {
match self {
Self::Return { return_keyword, .. } => return_keyword.0.has_leading_comments(),
Self::Bind { name, .. } => name.has_leading_comments(),
Self::Expression { expression, .. } => expression.has_leading_comments(),
}
}
}
impl HasComments for MatchArm {
fn has_comments(&self) -> bool {
let Self {
pipe,
pattern,
right_arrow,
expression,
} = self;
pipe.0.has_comments()
|| pattern.has_comments()
|| right_arrow.0.has_comments()
|| expression.has_comments()
}
fn has_leading_comments(&self) -> bool {
self.pipe.0.has_leading_comments()
}
}
impl HasComments for Pattern {
fn has_comments(&self) -> bool {
match self {
Self::NullaryConstructor { constructor } => constructor.has_comments(),
Self::Constructor {
constructor,
arguments,
} => constructor.has_comments() || arguments.has_comments(),
Self::Variable { name } => name.has_comments(),
Self::Unused { unused_name } => unused_name.has_comments(),
}
}
fn has_leading_comments(&self) -> bool {
match self {
Self::NullaryConstructor { constructor } => constructor.has_leading_comments(),
Self::Constructor { constructor, .. } => constructor.has_leading_comments(),
Self::Variable { name } => name.has_leading_comments(),
Self::Unused { unused_name } => unused_name.has_leading_comments(),
}
}
}
impl HasComments for BinOp {
fn has_comments(&self) -> bool {
match self {
Self::RightPizza(token) => token.0.has_comments(),
}
}
fn has_leading_comments(&self) -> bool {
match self {
Self::RightPizza(token) => token.0.has_leading_comments(),
}
}
}
impl HasComments for Type {
fn has_comments(&self) -> bool {
match self {
Self::Parens(parens) => parens.has_comments(),
Self::Variable(variable) => variable.has_comments(),
Self::Constructor(constructor) => constructor.has_comments(),
Self::Function {
parameters,
right_arrow,
return_type,
} => {
parameters.has_comments()
|| right_arrow.0.has_comments()
|| return_type.has_comments()
}
Self::Call {
function,
arguments,
} => function.has_comments() || arguments.has_comments(),
Self::RecordClosed(braces) => {
braces.open_brace.0.has_comments()
|| braces.value.has_comments()
|| braces.close_brace.0.has_comments()
}
Self::RecordOpen(braces) => {
braces.open_brace.0.has_comments()
|| braces.value.0.has_comments() // type variable
|| braces.value.1 .0.has_comments() // pipe
|| braces.value.2.has_comments() // fields
|| braces.close_brace.0.has_comments()
}
}
}
fn has_leading_comments(&self) -> bool {
match self {
Self::Parens(parens) => parens.open_paren.0.has_leading_comments(),
Self::Variable(variable) => variable.has_leading_comments(),
Self::Constructor(constructor) => constructor.has_leading_comments(),
Self::Function { parameters, .. } => parameters.open_paren.0.has_leading_comments(),
Self::Call { function, .. } => function.has_leading_comments(),
Self::RecordClosed(braces) => braces.open_brace.0.has_leading_comments(),
Self::RecordOpen(braces) => braces.open_brace.0.has_leading_comments(),
}
}
}
impl HasComments for TypeCallFunction {
fn has_comments(&self) -> bool {
match self {
Self::Constructor(constructor) => constructor.has_comments(),
Self::Variable(variable) => variable.has_comments(),
}
}
fn has_leading_comments(&self) -> bool {
match self {
Self::Constructor(constructor) => constructor.has_leading_comments(),
Self::Variable(variable) => variable.has_leading_comments(),
}
}
}
impl HasComments for TypeAnnotation {
fn has_comments(&self) -> bool {
self.0 .0.has_comments() || self.1.has_comments()
}
fn has_leading_comments(&self) -> bool {
self.0 .0.has_leading_comments()
}
}
impl<T: HasComments> HasComments for Parens<T> {
fn has_comments(&self) -> bool {
self.open_paren.0.has_comments()
|| self.value.has_comments()
|| self.close_paren.0.has_comments()
}
fn has_leading_comments(&self) -> bool {
self.open_paren.0.has_leading_comments()
}
}
impl<T: HasComments> HasComments for Brackets<T> {
fn has_comments(&self) -> bool {
self.open_bracket.0.has_comments()
|| self.value.has_comments()
|| self.close_bracket.0.has_comments()
}
fn has_leading_comments(&self) -> bool {
self.open_bracket.0.has_leading_comments()
}
}
impl<T: HasComments> HasComments for CommaSep1<T> {
fn has_comments(&self) -> bool {
self.head.has_comments()
|| self.tail.has_comments()
|| self
.trailing_comma
.as_ref()
.map_or(false, |trailing_comma| trailing_comma.has_comments())
}
fn has_leading_comments(&self) -> bool {
self.head.has_leading_comments()
}
}
impl<T: HasComments> HasComments for Vec<T> {
fn has_comments(&self) -> bool {
self.iter().any(|x| x.has_comments())
}
fn has_leading_comments(&self) -> bool {
if let Some(first) = self.first() {
first.has_leading_comments()
} else {
false
}
}
}
impl<Value: HasComments> HasComments for Qualified<Value> {
fn has_comments(&self) -> bool {
self.module_name
.as_ref()
.map_or(false, |module_name| module_name.has_comments())
|| self.value.has_comments()
}
fn has_leading_comments(&self) -> bool {
if let Some(module_name) = self.module_name.as_ref() {
module_name.has_leading_comments()
} else {
self.value.has_leading_comments()
}
}
}
impl<T: HasComments> HasComments for Option<T> {
fn has_comments(&self) -> bool {
self.as_ref().map_or(false, |x| x.has_comments())
}
fn has_leading_comments(&self) -> bool {
self.as_ref().map_or(false, |x| x.has_leading_comments())
}
}
impl<Fst: HasComments, Snd: HasComments> HasComments for (Fst, Snd) {
fn has_comments(&self) -> bool {
self.0.has_comments() || self.1.has_comments()
}
fn has_leading_comments(&self) -> bool {
self.0.has_leading_comments()
}
}
impl HasComments for Import {
fn has_comments(&self) -> bool {
match self {
Self::Value(name) => name.has_comments(),
Self::Type(proper_name, everything) => {
proper_name.has_comments() || everything.has_comments()
}
}
}
fn has_leading_comments(&self) -> bool {
match self {
Self::Value(name) => name.has_leading_comments(),
Self::Type(proper_name, _everything) => proper_name.has_leading_comments(),
}
}
}
impl HasComments for Export {
fn has_comments(&self) -> bool {
match self {
Self::Value(name) => name.has_comments(),
Self::Type(proper_name, everything) => {
proper_name.has_comments() || everything.has_comments()
}
}
}
fn has_leading_comments(&self) -> bool {
match self {
Self::Value(name) => name.has_leading_comments(),
Self::Type(proper_name, _everything) => proper_name.has_leading_comments(),
}
}
}
impl HasComments for Dot {
fn has_comments(&self) -> bool {
self.0.has_comments()
}
fn has_leading_comments(&self) -> bool {
self.0.has_leading_comments()
}
}
impl HasComments for DoubleDot {
fn has_comments(&self) -> bool {
self.0.has_comments()
}
fn has_leading_comments(&self) -> bool {
self.0.has_leading_comments()
}
}
impl HasComments for Comma {
fn has_comments(&self) -> bool {
self.0.has_comments()
}
fn has_leading_comments(&self) -> bool {
self.0.has_leading_comments()
}
}
impl HasComments for Name {
fn has_comments(&self) -> bool {
self.0.has_comments()
}
fn has_leading_comments(&self) -> bool {
self.0.has_leading_comments()
}
}
impl HasComments for UnusedName {
fn has_comments(&self) -> bool {
self.0.has_comments()
}
fn has_leading_comments(&self) -> bool {
self.0.has_leading_comments()
}
}
impl HasComments for ProperName {
fn has_comments(&self) -> bool {
self.0.has_comments()
}
fn has_leading_comments(&self) -> bool {
self.0.has_leading_comments()
}
} | |
app.py | import dash
from dash import html
from dash import dcc
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output
from server import app
from views.db_connect import db_conn_page
from views.data_general_situation import data_general_situation_page
from views.data_overall import data_overall_page
from views.data_oper2 import data_oper2_page
from views.data_temp import data_temp_page
from views.data_adt import data_adt_page
from views.data_bar import data_bar_page
from views.data_drug import data_drug_page
from views.data_anti import data_anti_page
from views.data_rout import data_rout_page
from views.data_exam import data_exam_page
app.layout = html.Div(
[
# 存储当前连接用户信息
dcc.Store(id='db_con_url', storage_type='session'),
# 存储当前统计时段信息
dcc.Store(id='count_time', storage_type='session'),
# 概览页面数据存储
dcc.Store(id='general_situation_first_level_first_fig_data', storage_type='session'),
dcc.Store(id='general_situation_first_level_second_fig_data', storage_type='session'),
dcc.Store(id='general_situation_first_level_third_fig_data', storage_type='session'),
dcc.Store(id='general_situation_secod_level_fig_data', storage_type='session'),
dcc.Store(id='general_situation_third_level_first_fig_data', storage_type='session'),
dcc.Store(id='general_situation_third_level_second_fig_data', storage_type='session'),
dcc.Store(id='general_situation_third_level_second_fig_data1', storage_type='session'),
# 抗菌药物、菌检出、药敏页面数据存储
dcc.Store(id='anti_bar_drug_first_level_first_fig_data', storage_type='session'),
dcc.Store(id='anti_bar_drug_first_level_second_fig_data', storage_type='session'),
dcc.Store(id='anti_second_level_first_fig_data', storage_type='session'),
dcc.Store(id='anti_second_level_second_fig_data', storage_type='session'),
dcc.Store(id='anti_second_level_third_fig_data', storage_type='session'),
dcc.Store(id='bar_third_level_first_fig_data', storage_type='session'),
dcc.Store(id='bar_third_level_second_fig_data', storage_type='session'),
dcc.Store(id='drug_fourth_level_first_fig_data', storage_type='session'),
dcc.Store(id='drug_fourth_level_second_fig_data', storage_type='session'),
# 手术数据存储
dcc.Store(id='oper2_first_level_first_fig_data', storage_type='session'),
dcc.Store(id='oper2_first_level_second_fig_data', storage_type='session'),
dcc.Store(id='oper2_second_level_first_fig_data', storage_type='session'),
dcc.Store(id='oper2_second_level_second_fig_data', storage_type='session'),
dcc.Store(id='oper2_second_level_third_fig_data', storage_type='session'),
# 常规检验数据存储
dcc.Store(id='rout_exam_temp_first_level_first_fig_data', storage_type='session'),
dcc.Store(id='rout_exam_temp_first_level_second_fig_data', storage_type='session'),
dcc.Store(id='temp_second_level_first_fig_data', storage_type='session'),
dcc.Store(id='rout_third_level_first_fig_data', storage_type='session'),
dcc.Store(id='rout_third_level_second_fig_data', storage_type='session'),
dcc.Store(id='exam_fourth_level_first_fig_data', storage_type='session'),
dcc.Store(id='exam_fourth_level_second_fig_data', storage_type='session'),
# 监听url变化
dcc.Location(id='url'),
html.Div(
[
# 最上方系统log栏
dbc.NavbarSimple(
brand="数据质量明细",
brand_href="/dash/",
brand_style={"font-family": "Roboto",
"font-size": "x-large",
"font-weight": "600",
"letter-spacing": "2.5px",
"color": "#606060",
},
color="#F9F9F9",
dark=True,
fluid=True,
style={"box-shadow": "0 2px 5px 0 rgb(0 0 0 / 26%)", "margin-bottom": "5px"},
),
dbc.Row(
[
# 左侧菜单栏
dbc.Col(
dbc.Row(
[
dbc.ListGroup(
[
dbc.ListGroupItem("数据库连接",id='db_connect', href="/dash/db_connect",color="primary"),
dbc.ListGroupItem("数据明细概况", id='data_general_situation', href="/dash/data_general_situation"),
dbc.ListGroupItem("抗菌药物/菌检出/药敏", id='data_anti', href="/dash/data_anti"),
dbc.ListGroupItem("手术",id='data_oper2', href="/dash/data_oper2" ),
dbc.ListGroupItem("生化/体温/检查",id='data_rout', href="/dash/data_rout" ),
# dbc.ListGroupItem("患者人数",id='data_overall', href="/dash/data_overall" ),
# dbc.ListGroupItem("体温",id='data_temp', href="/dash/data_temp" ),
# dbc.ListGroupItem("入出转",id='data_adt', href="/dash/data_adt" ),
# dbc.ListGroupItem("菌检出",id='data_bar', href="/dash/data_bar" ),
# dbc.ListGroupItem("药敏",id='data_drug', href="/dash/data_drug" ),
# dbc.ListGroupItem("生化",id='data_rout', href="/dash/data_rout" ),
# dbc.ListGroupItem("检查",id='data_exam', href="/dash/data_exam" ),
], flush=True,
style={
'padding': '1.5rem 1rem',
'text-align': 'center',
'letter-spacing': '0.05rem',
'font-weight': '800',
'width': '100%',
'height': '10%',
}
),
dbc.ListGroup(
[
dbc.ListGroupItem(
[
dbc.Label(html.B("统计时段:", style={'font-size': 'large'}),
id="count-time",
style={'display': 'flex', 'margin-left': '-15px'}),
dbc.Row(
[
dbc.Col(dbc.Label('开始时间:', style={'font-size': 'smaller'}),width=4,style={'margin-left':'0px','margin-right':'0px','padding-left':'0px','padding-right':'0px',}),
dbc.Col(dcc.Input(type='date', id='btime',style={'text-align':'center'}),width=8,style={'margin-left':'0px','margin-right':'0px','padding-left':'0px','padding-right':'0px',}),
], justify='center',
style={'display': 'flex', 'align-items': 'center',
'margin-top': '20px'}
),
dbc.Row(
[
dbc.Col(dbc.Label('结束时间:', style={'font-size': 'smaller'}),width=4,style={'margin-left':'0px','margin-right':'0px','padding-left':'0px','padding-right':'0px',}),
dbc.Col(dcc.Input(type='date', id='etime',style={'text-align':'center'}),width=8,style={'margin-left':'0px','margin-right':'0px','padding-left':'0px','padding-right':'0px',}),
], justify='center',
style={'display': 'flex', 'align-items': 'center', 'margin-top': '5px'}
),
], style={'background-color': 'aliceblue'}
),
dbc.ListGroupItem(dbc.Button('提交', id='data-chioce-sub'),
style={'background-color': 'aliceblue'})
], flush=True,
style={
'padding': '1.5rem 1rem',
'text-align': 'center',
'letter-spacing': '0.05rem',
'font-weight': '800',
'width': '100%',
'height': '40%',
}
),
], style={"height": '100%',
'background-color': 'aliceblue',
"box-shadow": "0 2px 5px 0 rgb(0 0 0 / 26%)",
"margin": "0px 2px 0px -2px",
"display": 'flex'
}
), className='col-sm-2 col-md-2 sidebar',
style={"height": '860px', }),
# style={"height": '500px', }),
# 右侧展示栏
dbc.Col(
[
dbc.Row(html.Br()),
# dbc.Row(html.Br()),
dbc.Row(id = 'data-show',style={"justify":"center"})
], className='col-sm-10 col-sm-offset-3 col-md-10 col-md-offset-2 main',
style={"box-shadow": "0 2px 5px 0 rgb(0 0 0 / 26%)", }
),
], className="container-fluid", )
]
)
]
)
# 路由总控
@app.callback(
[Output('data-show', 'children'),
Output('db_connect', 'color'),
Output('data_general_situation', 'color'),
Output('data_anti', 'color'),
Output('data_oper2', 'color'),
Output('data_rout', 'color'),],
Input('url', 'pathname')
)
def render_page_content(pathname):
color_dic={ 'rount_page':'',
'db_connect':'',
'data_general_situation':'',
'data_anti':'',
'data_oper2':'',
'data_rout':'',
}
if pathname is None:
pathname = "/dash | endswith("/dash/") or pathname.endswith("/db_connect"):
color_dic['rount_page'] = db_conn_page
color_dic['db_connect'] = 'primary'
return list(color_dic.values())
elif pathname.endswith("/data_general_situation") :
color_dic['rount_page'] = data_general_situation_page
color_dic['data_general_situation'] = 'primary'
return list(color_dic.values())
elif pathname.endswith("/data_anti") :
color_dic['rount_page'] = data_anti_page
color_dic['data_anti'] = 'primary'
return list(color_dic.values())
elif pathname.endswith("/data_oper2") :
color_dic['rount_page'] = data_oper2_page
color_dic['data_oper2'] = 'primary'
return list(color_dic.values())
elif pathname.endswith("/data_rout") :
color_dic['rount_page'] = data_rout_page
color_dic['data_rout'] = 'primary'
return list(color_dic.values())
else:
return html.H1('您访问的页面不存在!')
if __name__ == '__main__':
# app.run_server(host='10.0.68.111',debug=False,port=8081, workers = 10)
app.run_server(debug=False,port=8081)
# app.run_server(host='10.0.68.111',debug=True,port=8081) | /"
if pathname. |
employees.ts | import Employees from '../models/employees';
import followers from '../models/followers';
import projects from '../models/projects';
import user_accept from '../models/user_accept';
var async = require("async");
var moment=require("moment");
const mongoose = require('mongoose');
var Followers = mongoose.model('followers');
var empmodel = mongoose.model('employees');
var projectsmodel = mongoose.model('projects');
var activities = mongoose.model('activities');
//var User_accept = mongoose.model('user_accept');
export default class | {
followers = followers;
projects = projects;
model = Employees;
User_accept = user_accept;
/*
@author : Vaibhav Mali
@date : 12 Dec 2017
@API : save_update_Employees
@desc : Save and update employees.
*/
save_update_Employees = (req, res) => {
var followers = Followers;
var employees = req.body.reqData;
const current_date = new Date();
//console.log(current_date);
//current_date.setDate(Number(current_date.getDate()) + 60);
// console.log(current_date);
var model = this.model;
var count = 0;
var dt = {
success: ""
};
var successData = {
successData : []
}
var failedData = {
failedData : []
}
var length = employees.length ? employees.length : 0;
async.forEach(employees, function (employee, callback) {
if(employee && employee._id != "" && employee._id != null && employee._id != undefined){
//If employee is already exist
var _idstatus = mongoose.Types.ObjectId.isValid(employee._id);
if (_idstatus == false) {
count = length;
var err = employee._id + ' Employee Id is invalid';
employee.error = err;
failedData.failedData.push(employee);
callback();
}
var employee_id = mongoose.Types.ObjectId(employee._id);
empmodel.find({ "_id": employee_id }, function (err, data) {
if(data && data.length > 0){
// followers.findOneAndUpdate({ "email": employee.email}, { "$set": { "modify_date": current_date }}).exec(function (err, data6) {
//if(data6 && data6.length > 0){
empmodel.findOneAndUpdate({ "_id": employee_id}, { "$set": { "name": employee.name ? employee.name : data[0]._doc.name , "email": employee.email ? employee.email : data[0]._doc.email, "address": employee.address ? employee.address : data[0]._doc.address,"type": employee.type ? employee.type : data[0]._doc.type, "modify_date": current_date} }).exec(function (err, data3) {
if (err) {
count = length;
employee.error = err;
failedData.failedData.push(employee);
callback();
}
else {
dt.success = "true";
successData.successData.push(employee);
callback();
}
});
// }
// else{
// }
// })
}
else{
count = length;
employee.error = "Employee Id is invalid.";
failedData.failedData.push(employee);
callback();
}
})
}
else{
//If employee is new
count = length;
employee.error = "Employee Id is invalid.";
failedData.failedData.push(employee);
callback();
}
count = count + 1;
}, function (err, cb) {
var result = {};
result['success'] = successData;
result['failed'] = failedData;
if(count >= length){
res.send(result);
}
return;
});
};
/*
@author : Vaibhav Mali
@date : 12 Dec 2017
@API : getEmployeeDetails
@desc : Get employee details by Id.
*/
getEmployeeDetails = (req, res) => {
var User_accept = this.User_accept;
var model = this.model;
var empid = req.params.id;
var projects = projectsmodel;
if(req && req.user){
var _idstatus = mongoose.Types.ObjectId.isValid(empid);
if (_idstatus == false) {
var resData = {};
var err = empid + 'Employee Id is invalid';
resData['error'] = err;
res.send(resData);
}
else{
var employee_id = mongoose.Types.ObjectId(empid);
model.find({ "_id": employee_id }, function (err, data) {
if(err){
var resData = {};
resData['error'] = err;
res.send(resData);
}
else if (data && data.length > 0) {
Followers.find({ "email": data[0]._doc.email }, function (err, data1) {
var resData = {};
var dt = {};
dt['name'] = data[0]._doc.name;
dt['act_status'] = data[0]._doc.act_status;
dt['email'] = data[0]._doc.email;
dt['address'] = data[0]._doc.address;
dt['type'] = data[0]._doc.type;
var projectcount = 0;
var projectslength = data1.length ? data1.length : 0;
var tempprojects = {projects: []};
var tempprojects1 = {projects: []};
async.forEach(data1, function (follower, callback) {
var tempactivities = {activities: []};
var project = {}
if(follower._doc.project_id != null && follower._doc.project_id != "" && follower._doc.project_id != undefined){
var project_id = mongoose.Types.ObjectId(follower._doc.project_id);
projects.find({ "_id": project_id }, function (err, data2) {
if(data2 && data2.length > 0){
project["_id"] = data2[0]._doc._id;
project["project_name"] = data2[0]._doc.project_name;
project["desc"] = data2[0]._doc.desc;
project["role"] = follower._doc.role;
project["accept"] = 1;
activities.find({ "pid": project_id }, function (err, data3) {
if(data3 && data3.length > 0){
var count = 0;
async.forEach(data3, function (activity, callback) {
var tempdata = {};
tempdata["_id"] = activity._doc._id;
tempdata["activity_name"] = activity._doc.activity_name;
tempactivities.activities.push(tempdata)
count = count + 1;
callback();
}, function (err, cb) {
if(count >= data3.length){
project["activities"] = tempactivities.activities;
if(follower._doc.ismanager == 1){
tempprojects1.projects.push(project);
}else{
tempprojects.projects.push(project);
}
projectcount = projectcount + 1;
callback();
}
});
}
else{
projectcount = projectcount + 1;
if(follower._doc.ismanager == 1){
tempprojects1.projects.push(project);
}else{
tempprojects.projects.push(project);
}
callback(); callback();
}
})
}
else{
projectcount = projectcount + 1;
callback();
}
})
}
else{
projectcount = projectcount + 1;
callback();
}
}, function (err, cb) {
var result = {};
if(projectcount >= projectslength){
projectcount = 0;
var tempactivities = {activities: []};
var project = {}
User_accept.find({ "to_email": req.user.emails[0].value,"accept":0}, function (err, data9) {
if(data9 && data9.length > 0) {
async.forEach(data9, function (requestuser, callback) {
var project_id = mongoose.Types.ObjectId(requestuser._doc.project_id);
projects.find({ "_id": project_id }, function (err, data2) {
if(data2 && data2.length > 0){
project["_id"] = data2[0]._doc._id;
project["project_name"] = data2[0]._doc.project_name;
project["desc"] = data2[0]._doc.desc;
project["accept"] = 0;
activities.find({ "pid": project_id }, function (err, data3) {
if(data3 && data3.length > 0){
var count = 0;
async.forEach(data3, function (activity, callback) {
var tempdata = {};
tempdata["_id"] = activity._doc._id;
tempdata["activity_name"] = activity._doc.activity_name;
tempactivities.activities.push(tempdata)
count = count + 1;
callback();
}, function (err, cb) {
if(count >= data3.length){
project["activities"] = tempactivities.activities;
tempprojects.projects.push(project);
projectcount = projectcount + 1;
callback();
}
});
}
else{
projectcount = projectcount + 1;
tempprojects.projects.push(project);
callback();
}
})
}
else{
projectcount = projectcount + 1;
callback();
}
})
}, function (err, cb) {
if(projectcount >= data9.length){
dt["MyProjects"] = tempprojects1.projects;
dt["AssignedProjects"] = tempprojects.projects;
var resData = {};
resData['details'] = dt;
res.send(resData);
}
});
}
else{
dt["MyProjects"] = tempprojects1.projects;
dt["AssignedProjects"] = tempprojects.projects;
var resData = {};
resData['details'] = dt;
res.send(resData);
}
})
}
return;
});
})
}
else{
var resData = {};
resData['details'] = null;
res.send(resData);
}
});
}
}
else{
var resData = {};
resData["res_status"] = 404;
resData["error"] = "Please login and continue";
res.send(resData);
}
};
toTimestamp(strDate){
var datum = Date.parse(strDate);
return datum/1000;
}
/*
@author : Vaibhav Mali
@date : 04 Jan 2018
@API : getemployeeDetailswithProjectPagination
@desc : Get employee and projects details with project pagination.
*/
getemployeeDetailswithProjectPagination = (req, res) => {
var User_accept = this.User_accept;
var me = this;
var model = this.model;
var projects = projectsmodel;
var empemail = req.body.reqData.email;
var limit = req.body.reqData.limit;
var pagenumber = req.body.reqData.page;
var dt = {};
if(req && req.user){
model.find({ "email": empemail }, function (err, data) {
if(err){
var resData = {};
resData['error'] = err;
res.send(resData);
}
else if (data && data.length > 0) {
//My Projects
Followers.paginate({"email": data[0]._doc.email,"ismanager" : 1}, {sort:{"modify_date":-1}, page: pagenumber, limit: limit }, function(err, data1) {
// Followers.find({ "email": data[0]._doc.email }, function (err, data1) {
/* data1.docs.sort(function(a,b){
var c:any = new Date(a.modify_date);
var d:any = new Date(b.modify_date);
return d-c;
});*/
dt['name'] = data[0]._doc.name;
dt['act_status'] = data[0]._doc.act_status;
dt['email'] = data[0]._doc.email;
dt['address'] = data[0]._doc.address;
dt['type'] = data[0]._doc.type;
var projectcount = 0;
var projectslength = data1.docs.length ? data1.docs.length : 0;
var tempprojects = {projects: []};
var tempprojects1 = {projects: []};
async.eachSeries(data1.docs, function (follower, callback) {
var tempactivities = {activities: []};
var project = {}
if(follower._doc.project_id != null && follower._doc.project_id != "" && follower._doc.project_id != undefined){
var project_id = mongoose.Types.ObjectId(follower._doc.project_id);
projects.find({ "_id": project_id }, function (err, data2) {
if(data2 && data2.length > 0){
project["_id"] = data2[0]._doc._id;
project["project_name"] = data2[0]._doc.project_name;
project["desc"] = data2[0]._doc.desc;
project["role"] = follower._doc.role;
project["modify_date"] = follower._doc.modify_date;
project["accept"] = 1;
activities.find({ "pid": project_id }, function (err, data3) {
if(data3 && data3.length > 0){
var count = 0;
async.forEach(data3, function (activity, callback) {
var tempdata = {};
tempdata["_id"] = activity._doc._id;
tempdata["activity_name"] = activity._doc.activity_name;
tempactivities.activities.push(tempdata)
count = count + 1;
callback();
}, function (err, cb) {
if(count >= data3.length){
project["activities"] = tempactivities.activities;
tempprojects.projects.push(project);
projectcount = projectcount + 1;
callback();
}
});
}
else{
projectcount = projectcount + 1;
tempprojects.projects.push(project);
callback();
}
})
}
else{
projectcount = projectcount + 1;
callback();
}
})
}
else{
projectcount = projectcount + 1;
callback();
}
}, function (err, cb) {
var result = {};
if(projectcount >= projectslength){
var projectcount1 = 0;
var tempactivities = {activities: []};
var project = {}
dt["MyProjects"] = tempprojects.projects;
dt["MyProjectsPages"] = data1.pages;
dt["MyProjectsTotal"] = data1.total;
//Assigned Projects which accepted.
Followers.paginate({"email": data[0]._doc.email,"ismanager" : 0}, { sort:{"modify_date":-1},page: pagenumber, limit: limit }, function(err, data1) {
// Followers.find({ "email": data[0]._doc.email }, function (err, data1) {
/* data1.docs.sort(function(a,b){
var c:any = new Date(a.modify_date);
var d:any = new Date(b.modify_date);
return d-c;
});*/
var resData = {};
dt['name'] = data[0]._doc.name;
dt['act_status'] = data[0]._doc.act_status;
dt['email'] = data[0]._doc.email;
dt['address'] = data[0]._doc.address;
dt['type'] = data[0]._doc.type;
var projectcount = 0;
var projectslength = data1.docs.length ? data1.docs.length : 0;
var tempprojects = {projects: []};
var tempprojects1 = {projects: []};
async.eachSeries(data1.docs, function (follower, callback) {
var tempactivities = {activities: []};
var project = {}
if(follower._doc.project_id != null && follower._doc.project_id != "" && follower._doc.project_id != undefined){
var project_id = mongoose.Types.ObjectId(follower._doc.project_id);
// projects.paginate({}, { page: pagenumber, limit: limit }, function(err, result) {
projects.find({ "_id": project_id }, function (err, data2) {
if(data2 && data2.length > 0){
project["_id"] = data2[0]._doc._id;
project["project_name"] = data2[0]._doc.project_name;
project["desc"] = data2[0]._doc.desc;
project["role"] = follower._doc.role;
project["accept"] = 1;
project["modify_date"] = follower._doc.modify_date;
activities.find({ "pid": project_id }, function (err, data3) {
if(data3 && data3.length > 0){
var count = 0;
async.forEach(data3, function (activity, callback) {
var tempdata = {};
tempdata["_id"] = activity._doc._id;
tempdata["activity_name"] = activity._doc.activity_name;
tempactivities.activities.push(tempdata)
count = count + 1;
callback();
}, function (err, cb) {
if(count >= data3.length){
project["activities"] = tempactivities.activities;
tempprojects1.projects.push(project);
projectcount = projectcount + 1;
callback();
}
});
}
else{
projectcount = projectcount + 1;
tempprojects1.projects.push(project);
callback();
}
})
}
else{
projectcount = projectcount + 1;
callback();
}
})
}
else{
projectcount = projectcount + 1;
callback();
}
}, function (err, cb) {
var result = {};
if(projectcount >= projectslength){
var projectcount1 = 0;
var tempactivities = {activities: []};
var project = {}
dt["AcceptedProjects"] = tempprojects1.projects;
dt["AcceptedProjectsPages"] = data1.pages;
dt["AcceptedProjectsTotal"] = data1.total;
var tempprojects = {projects: []};
//Assigned Projects which request.
User_accept.paginate({"to_email": data[0]._doc.email,"accept" : 0}, { sort:{"modify_date":-1},page: pagenumber, limit: limit }, function(err, data9) {
// User_accept.find({ "to_email": req.user.emails[0].value,"accept":0}, function (err, data9) {
/*data9.docs.sort(function(a,b){
var c:any = new Date(a.modify_date);
var d:any = new Date(b.modify_date);
return d-c;
});*/
async.eachSeries(data9.docs, function (requestuser, callback) {
var tempactivities = {activities: []};
var project = {}
var project_id = mongoose.Types.ObjectId(requestuser._doc.project_id);
projects.find({ "_id": project_id }, function (err, data2) {
if(data2 && data2.length > 0){
project["_id"] = data2[0]._doc._id;
project["project_name"] = data2[0]._doc.project_name;
project["desc"] = data2[0]._doc.desc;
project["role"] = requestuser._doc.role;
project["modify_date"] = requestuser._doc.modify_date;
project["accept"] = 0;
activities.find({ "pid": project_id }, function (err, data3) {
if(data3 && data3.length > 0){
var count = 0;
async.forEach(data3, function (activity, callback) {
var tempdata = {};
tempdata["_id"] = activity._doc._id;
tempdata["activity_name"] = activity._doc.activity_name;
tempactivities.activities.push(tempdata)
count = count + 1;
callback();
}, function (err, cb) {
if(count >= data3.length){
project["activities"] = tempactivities.activities;
tempprojects.projects.push(project);
projectcount1 = projectcount1 + 1;
callback();
}
});
}
else{
projectcount1 = projectcount1 + 1;
tempprojects.projects.push(project);
callback();
}
})
}
else{
projectcount1 = projectcount1 + 1;
callback();
}
})
}, function (err, cb) {
if(projectcount1 >= data9.docs.length){
dt["RequestedProjects"] = tempprojects.projects;
dt["RequestedProjectsPages"] = data9.pages;
dt["RequestedProjectsTotal"] = data9.total;
var resData = {};
resData['details'] = dt;
res.send(resData);
return;
}
});
})
}
});
})
}
});
})
}
else{
var resData = {};
resData['details'] = null;
res.send(resData);
}
});
}
else{
var resData = {};
resData["res_status"] = 404;
resData["error"] = "Please login and continue";
res.send(resData);
}
};
SortObjectArraydesc(det,key) {
var temp;
var i = 0, j = 0;
for (i = 0; i < det.length - 1; i++) {
for (j = i + 1; j < det.length; j++) {
if (det[i].key < det[j].key) {
temp = det[i];
det[i] = det[j];
det[j] = temp;
}
}
}
return det;
}
/*
@author : Vaibhav Mali
@date : 12 Dec 2017
@API : getEmployeeDetailsByEmail
@desc : Get employee details by Email.
*/
getEmployeeDetailsByEmail = (req, res) => {
var User_accept = this.User_accept;
var model = this.model;
var empid = req.params.id;
var projects = projectsmodel;
var empemail = req.body.reqData.email;
var dt = {};
if(req && req.user){
model.find({ "email": empemail }, function (err, data) {
if(err){
var resData = {};
resData['error'] = err;
res.send(resData);
}
else if (data && data.length > 0) {
Followers.find({ "email": data[0]._doc.email }, function (err, data1) {
var resData = {};
dt['name'] = data[0]._doc.name;
dt['act_status'] = data[0]._doc.act_status;
dt['email'] = data[0]._doc.email;
dt['address'] = data[0]._doc.address;
dt['type'] = data[0]._doc.type;
var projectcount = 0;
var projectslength = data1.length ? data1.length : 0;
var tempprojects = {projects: []};
var tempprojects1 = {projects: []};
async.forEach(data1, function (follower, callback) {
var tempactivities = {activities: []};
var project = {}
if(follower._doc.project_id != null && follower._doc.project_id != "" && follower._doc.project_id != undefined){
var project_id = mongoose.Types.ObjectId(follower._doc.project_id);
projects.find({ "_id": project_id }, function (err, data2) {
if(data2 && data2.length > 0){
project["_id"] = data2[0]._doc._id;
project["project_name"] = data2[0]._doc.project_name;
project["desc"] = data2[0]._doc.desc;
project["role"] = follower._doc.role;
project["accept"] = 1;
activities.find({ "pid": project_id }, function (err, data3) {
if(data3 && data3.length > 0){
var count = 0;
async.forEach(data3, function (activity, callback) {
var tempdata = {};
tempdata["_id"] = activity._doc._id;
tempdata["activity_name"] = activity._doc.activity_name;
tempactivities.activities.push(tempdata)
count = count + 1;
callback();
}, function (err, cb) {
if(count >= data3.length){
project["activities"] = tempactivities.activities;
if(follower._doc.ismanager == 1){
tempprojects1.projects.push(project);
}else{
tempprojects.projects.push(project);
}
projectcount = projectcount + 1;
callback();
}
});
}
else{
projectcount = projectcount + 1;
if(follower._doc.ismanager == 1){
tempprojects1.projects.push(project);
}else{
tempprojects.projects.push(project);
}
callback();
}
})
}
else{
projectcount = projectcount + 1;
callback();
}
})
}
else{
projectcount = projectcount + 1;
callback();
}
}, function (err, cb) {
var result = {};
if(projectcount >= projectslength){
var projectcount1 = 0;
var tempactivities = {activities: []};
var project = {}
// User_accept.find({ "to_email": req.user.emails[0].value,"accept":0}, function (err, data9) {
/* if(data9 && data9.length > 0) {
async.forEach(data9, function (requestuser, callback) {
var project_id = mongoose.Types.ObjectId(requestuser._doc.project_id);
projects.find({ "_id": project_id }, function (err, data2) {
if(data2 && data2.length > 0){
project["_id"] = data2[0]._doc._id;
project["project_name"] = data2[0]._doc.project_name;
project["desc"] = data2[0]._doc.desc;
project["accept"] = 0;
activities.find({ "pid": project_id }, function (err, data3) {
if(data3 && data3.length > 0){
var count = 0;
async.forEach(data3, function (activity, callback) {
var tempdata = {};
tempdata["_id"] = activity._doc._id;
tempdata["activity_name"] = activity._doc.activity_name;
tempactivities.activities.push(tempdata)
count = count + 1;
callback();
}, function (err, cb) {
if(count >= data3.length){
project["activities"] = tempactivities.activities;
tempprojects.projects.push(project);
projectcount1 = projectcount1 + 1;
callback();
// return;
}
});
}
else{
projectcount1 = projectcount1 + 1;
tempprojects.projects.push(project);
callback();
}
})
}
else{
projectcount1 = projectcount1 + 1;
callback();
}
})
}, function (err, cb) {
if(projectcount1 >= data9.length){
dt["MyProjects"] = tempprojects1.projects;
dt["AssignedProjects"] = tempprojects.projects;
var resData = {};
resData['details'] = dt;
res.send(resData);
return;
}
});
}
else{*/
dt["MyProjects"] = tempprojects1.projects;
dt["AssignedProjects"] = tempprojects.projects;
var resData = {};
resData['details'] = dt;
res.send(resData);
return;
// }
// })
}
// return;
});
})
}
else{
var resData = {};
resData['details'] = null;
res.send(resData);
}
});
}
else{
var resData = {};
resData["res_status"] = 404;
resData["error"] = "Please login and continue";
res.send(resData);
}
};
/*
@author : Vaibhav Mali
@date : 19 Dec 2017
@API : getRequestDetails
@desc : Get requested projects details.
*/
getRequestDetails = (req, res) => {
var User_accept = this.User_accept;
var model = this.model;
var projects = projectsmodel;
var tempprojects = {projects: []};
var dt = {};
//var empemail = req.body.reqData.email;
var projectcount1 = 0;
if(req && req.user){
User_accept.find({ "to_email": req.user.emails[0].value,"accept":0}, function (err, data9) {
async.forEach(data9, function (requestuser, callback) {
var tempactivities = {activities: []};
var project = {}
var project_id = mongoose.Types.ObjectId(requestuser._doc.project_id);
projects.find({ "_id": project_id }, function (err, data2) {
if(data2 && data2.length > 0){
project["_id"] = data2[0]._doc._id;
project["project_name"] = data2[0]._doc.project_name;
project["desc"] = data2[0]._doc.desc;
project["accept"] = 0;
activities.find({ "pid": project_id }, function (err, data3) {
if(data3 && data3.length > 0){
var count = 0;
async.forEach(data3, function (activity, callback) {
var tempdata = {};
tempdata["_id"] = activity._doc._id;
tempdata["activity_name"] = activity._doc.activity_name;
tempactivities.activities.push(tempdata)
count = count + 1;
callback();
}, function (err, cb) {
if(count >= data3.length){
project["activities"] = tempactivities.activities;
tempprojects.projects.push(project);
projectcount1 = projectcount1 + 1;
callback();
// return;
}
});
}
else{
projectcount1 = projectcount1 + 1;
tempprojects.projects.push(project);
callback();
}
})
}
else{
projectcount1 = projectcount1 + 1;
callback();
}
})
}, function (err, cb) {
if(projectcount1 >= data9.length){
dt["RequestedProjects"] = tempprojects.projects;
var resData = {};
resData['details'] = dt;
res.send(resData);
return;
}
});
})
}
else{
var resData = {};
resData["res_status"] = 404;
resData["error"] = "Please login and continue";
res.send(resData);
}
}
/*
@author : Vaibhav Mali
@date : 01 Jan 2018
@API : logout
@desc : To logout user.
*/
logout = (req, res) => {
var resData;
var _id = req.params.id;
var _idstatus = mongoose.Types.ObjectId.isValid(_id);
if (_idstatus == false) {
var err = _id + ' Employee Id is invalid';
res.send(err)
//cb(err)
}
var employee_id = mongoose.Types.ObjectId(_id);
empmodel.find({ "_id": employee_id }, function (err, data) {
if(data && data.length > 0){
empmodel.findOneAndUpdate({ "_id": employee_id}, { "$set": { "act_status": 0 } }).exec(function (err, data3) {
if (err) {
res.send(err)
//cb(err)
}
else {
var dt = {success:""};
dt.success = "true";
res.send(dt)
// cb(null,dt)
}
});
}
})
}
/*
@author : Vaibhav Mali
@date : 12 Dec 2017
@API : getAllEmployeeDetails
@desc : Get all employee details.
*/
getAllEmployeeDetails = (req, res) => {
var model = this.model;
var employees = {};
var employeetemp = {employees:[]};
var count = 0;
if(req && req.user){
model.find({email:{"$ne":req.user.emails[0].value}}, function (err, data) {
if(data && data.length){
async.forEach(data, function (employee, callback) {
employeetemp.employees.push(employee._doc);
count = count + 1;
callback();
}, function (err, cb) {
if(count >= data.length){
employees['employees'] = employeetemp.employees;
res.send(employees);
}
return;
});
}
else{
employees['employees'] = employeetemp.employees;
res.send(employees);
}
});
}
else{
employees['error'] = "Please login and continue";
res.send(employees);
}
};
/*
@author : Vaibhav Mali
@date : 05 Jan 2018
@API : getAllEmployeeDetailswithPagination
@desc : Get all employee details with pagination.
*/
getAllEmployeeDetailswithPagination = (req, res) => {
var model = this.model;
var employees = {};
var employeetemp = {employees:[]};
var limit = req.body.reqData.limit;
var pagenumber = req.body.reqData.page;
var count = 0;
if(req && req.user){
model.paginate({email:{"$ne":req.user.emails[0].value}}, { page: pagenumber, limit: limit }, function(err, data) {
// model.find({email:{"$ne":req.user.emails[0].value}}, function (err, data) {
if(data && data.docs.length){
async.forEach(data.docs, function (employee, callback) {
employeetemp.employees.push(employee._doc);
count = count + 1;
callback();
}, function (err, cb) {
if(count >= data.docs.length){
employees['employees'] = employeetemp.employees;
employees['Pages'] = data.pages;
employees['Total'] = data.total;
res.send(employees);
}
return;
});
}
else{
employees['employees'] = employeetemp.employees;
employees['Pages'] = data.pages;
employees['Total'] = data.total;
res.send(employees);
}
});
}
else{
employees['error'] = "Please login and continue";
res.send(employees);
}
};
/*
@author : Vaibhav Mali
@date : 12 Dec 2017
@API : getCurrentLoginDetails
@desc : Get details of current logged in employee.
*/
getCurrentLoginDetails = (req, res) => {
var model = this.model;
var resData = {}
if(req && req.user){
model.find({ "email": req.user.emails[0].value }, function (err, data) {
resData["_id"] = data[0]._doc._id;
resData["name"] = data[0]._doc.name;
resData["login_status"] = 1;
resData["email"] = req.user.emails[0].value;
resData["type"]=data[0]._doc.type;
res.send(resData);
})
}
else{
resData["login_status"] = 0;
resData["error"] = "Please login and continue";
res.send(resData);
}
}
success = (req, res) => {
console.log("Success");
}
failure = (req, res) => {
console.log("failure");
}
} | EmployeesCtrl |
__main__.py | from scraper import scrape
def | ():
scrape()
if __name__ == '__main__':
main()
| main |
core.py | # AUTOGENERATED! DO NOT EDIT! File to edit: 00_core.ipynb (unless otherwise specified).
__all__ = ['repeat_one']
# Cell
import ipywidgets as widgets
from fastai2.vision.all import*
from .dashboard_two import ds_choice
# Cell
def | (source, n=128):
"""Single image helper for displaying batch"""
return [get_image_files(ds_choice.source)[9]]*n | repeat_one |
PointWall.py | """
This file provides the template for designing the agent and environment. The below hyperparameters must be assigned to a value for the algorithm to work properly.
"""
import numpy as np
# from environment import Environment
from environment_adapter import EnvironmentAdapter
from agent import Agent
from collections import OrderedDict
def design_agent_and_env(FLAGS):
"""
1. DESIGN AGENT
The key hyperparameters for agent construction are
a. Number of levels in agent hierarchy
b. Max sequence length in which each policy will specialize
c. Max number of atomic actions allowed in an episode
d. Environment timesteps per atomic action
See Section 3 of this file for other agent hyperparameters that can be configured.
"""
FLAGS.layers = 3 # Enter number of levels in agent hierarchy
FLAGS.time_scale = 10 # Enter max sequence length in which each policy will specialize
# Enter max number of atomic actions. This will typically be FLAGS.time_scale**(FLAGS.layers). However, in the UR5 Reacher task, we use a shorter episode length.
"""
2. DESIGN ENVIRONMENT
a. Designer must provide the original UMDP (S,A,T,G,R).
- The S,A,T components can be fulfilled by providing the Mujoco model.
- The user must separately specifiy the initial state space.
- G can be provided by specifying the end goal space.
- R, which by default uses a shortest path {-1,0} reward function, can be implemented by specifying two components: (i) a function that maps the state space to the end goal space and (ii) the end goal achievement thresholds for each dimensions of the end goal.
b. In order to convert the original UMDP into a hierarchy of k UMDPs, the designer must also provide
- The subgoal action space, A_i, for all higher-level UMDPs i > 0
- R_i for levels 0 <= i < k-1 (i.e., all levels that try to achieve goals in the subgoal space). As in the original UMDP, R_i can be implemented by providing two components:(i) a function that maps the state space to the subgoal space and (ii) the subgoal achievement thresholds.
c. Designer should also provide subgoal and end goal visualization functions in order to show video of training. These can be updated in "display_subgoal" and "display_end_goal" methods in the "environment.py" file.
"""
# Provide file name of Mujoco model(i.e., "pendulum.xml"). Make sure file is stored in "mujoco_files" folder
model_name = "ant_reacher.xml"
# FROM HIRO code:
# ( 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14)
# CONTEXT_RANGE_MIN = (-10, -10, -0.5, -1, -1, -1, -1, -0.5, -0.3, -0.5, -0.3, -0.5, -0.3, -0.5, -0.3)
# CONTEXT_RANGE_MAX = ( 10, 10, 0.5, 1, 1, 1, 1, 0.5, 0.3, 0.5, 0.3, 0.5, 0.3, 0.5, 0.3)
normalization_dict = None if not FLAGS.normalization else {
'lows': OrderedDict((
(0, -14.), # xpos
(1, -14.), # ypos
)),
'highs': OrderedDict((
(0, 14.), # xpos
(1, 14.), # ypos
)),
'end_goal_dims': [0,1],
'subgoal_dims': [0,1],
}
project_state_to_end_goal = lambda sim, state: state[..., :2]
project_state_to_subgoal = lambda sim, state: state[..., :2]
env = EnvironmentAdapter("maze", "Point", "WallDict", project_state_to_end_goal, project_state_to_subgoal, FLAGS.show, normalization_dict, featurize_image=FLAGS.featurize_image, seed=FLAGS.seed)
# To properly visualize goals, update "display_end_goal" and "display_subgoals" methods in "environment.py"
"""
3. SET MISCELLANEOUS HYPERPARAMETERS
Below are some other agent hyperparameters that can affect results, including
a. Subgoal testing percentage
b. Subgoal penalty
c. Exploration noise
d. Replay buffer size
"""
agent_params = {}
# Define percentage of actions that a subgoal level (i.e. level i > 0) will test subgoal actions
agent_params["subgoal_test_perc"] = 0.3
# Define subgoal penalty for missing subgoal. Please note that by default the Q value target for missed subgoals does not include Q-value of next state (i.e, discount rate = 0). As a result, the Q-value target for missed subgoal just equals penalty. For instance in this 3-level UR5 implementation, if a level proposes a subgoal and misses it, the Q target value for this action would be -10. To incorporate the next state in the penalty, go to the "penalize_subgoal" method in the "layer.py" file.
agent_params["subgoal_penalty"] = -FLAGS.time_scale
# Define exploration noise that is added to both subgoal actions and atomic actions. Noise added is Gaussian N(0, noise_percentage * action_dim_range)
agent_params["atomic_noise"] = [0.1 for i in range(2)]
agent_params["subgoal_noise"] = [0.01 for i in range(len(env.subgoal_thresholds))]
agent_params["oracle_noise"] = [0.01 for i in range(len(env.subgoal_thresholds))]
agent_params["vpn_noise"] = [0.05 for i in range(len(env.subgoal_thresholds))]
# Define number of episodes of transitions to be stored by each level of the hierarchy
agent_params["episodes_to_store"] = 500
# Provide training schedule for agent. Training by default will alternate between exploration and testing. Hyperparameter below indicates number of exploration episodes. Testing occurs for 100 episodes. To change number of testing episodes, go to "ran_HAC.py".
agent_params["num_exploration_episodes"] = 100
# For other relavent agent hyperparameters, please refer to the "agent.py" and "layer.py" files
agent_params["num_batches"] = 250
# Ensure environment customization have been properly entered
# check_validity(model_name, goal_space_train, goal_space_test, end_goal_thresholds, initial_state_space, subgoal_bounds, subgoal_thresholds, max_actions, timesteps_per_action)
# Instantiate and return agent and environment
# env = Environment(model_name, goal_space_train, goal_space_test, project_state_to_end_goal, end_goal_thresholds, initial_state_space, subgoal_bounds, project_state_to_subgoal, subgoal_thresholds, max_actions, timesteps_per_action, FLAGS.show)
agent = Agent(FLAGS,env,agent_params) |
return agent, env |
|
aws-cloudformation-resourcedefaultversion.go | // Code generated by "go generate". Please don't change this file directly.
package cloudformation
import (
"bytes"
"encoding/json"
"fmt"
"github.com/awslabs/goformation/v6/cloudformation/policies"
)
// ResourceDefaultVersion AWS CloudFormation Resource (AWS::CloudFormation::ResourceDefaultVersion)
// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudformation-resourcedefaultversion.html
type ResourceDefaultVersion struct {
// TypeName AWS CloudFormation Property
// Required: false
// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudformation-resourcedefaultversion.html#cfn-cloudformation-resourcedefaultversion-typename
TypeName *string `json:"TypeName,omitempty"`
// TypeVersionArn AWS CloudFormation Property
// Required: false
// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudformation-resourcedefaultversion.html#cfn-cloudformation-resourcedefaultversion-typeversionarn
TypeVersionArn *string `json:"TypeVersionArn,omitempty"`
// VersionId AWS CloudFormation Property
// Required: false
// See: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudformation-resourcedefaultversion.html#cfn-cloudformation-resourcedefaultversion-versionid
VersionId *string `json:"VersionId,omitempty"`
// AWSCloudFormationDeletionPolicy represents a CloudFormation DeletionPolicy
AWSCloudFormationDeletionPolicy policies.DeletionPolicy `json:"-"`
// AWSCloudFormationUpdateReplacePolicy represents a CloudFormation UpdateReplacePolicy
AWSCloudFormationUpdateReplacePolicy policies.UpdateReplacePolicy `json:"-"`
// AWSCloudFormationDependsOn stores the logical ID of the resources to be created before this resource
AWSCloudFormationDependsOn []string `json:"-"`
// AWSCloudFormationMetadata stores structured data associated with this resource
AWSCloudFormationMetadata map[string]interface{} `json:"-"`
// AWSCloudFormationCondition stores the logical ID of the condition that must be satisfied for this resource to be created
AWSCloudFormationCondition string `json:"-"`
}
// AWSCloudFormationType returns the AWS CloudFormation resource type
func (r *ResourceDefaultVersion) AWSCloudFormationType() string {
return "AWS::CloudFormation::ResourceDefaultVersion"
}
// MarshalJSON is a custom JSON marshalling hook that embeds this object into
// an AWS CloudFormation JSON resource's 'Properties' field and adds a 'Type'.
func (r ResourceDefaultVersion) MarshalJSON() ([]byte, error) {
type Properties ResourceDefaultVersion
return json.Marshal(&struct {
Type string
Properties Properties
DependsOn []string `json:"DependsOn,omitempty"`
Metadata map[string]interface{} `json:"Metadata,omitempty"`
DeletionPolicy policies.DeletionPolicy `json:"DeletionPolicy,omitempty"`
UpdateReplacePolicy policies.UpdateReplacePolicy `json:"UpdateReplacePolicy,omitempty"`
Condition string `json:"Condition,omitempty"`
}{
Type: r.AWSCloudFormationType(),
Properties: (Properties)(r),
DependsOn: r.AWSCloudFormationDependsOn,
Metadata: r.AWSCloudFormationMetadata,
DeletionPolicy: r.AWSCloudFormationDeletionPolicy,
UpdateReplacePolicy: r.AWSCloudFormationUpdateReplacePolicy,
Condition: r.AWSCloudFormationCondition,
})
}
// UnmarshalJSON is a custom JSON unmarshalling hook that strips the outer
// AWS CloudFormation resource object, and just keeps the 'Properties' field.
func (r *ResourceDefaultVersion) UnmarshalJSON(b []byte) error {
type Properties ResourceDefaultVersion
res := &struct {
Type string
Properties *Properties
DependsOn interface{}
Metadata map[string]interface{}
DeletionPolicy string
UpdateReplacePolicy string
Condition string
}{}
dec := json.NewDecoder(bytes.NewReader(b))
dec.DisallowUnknownFields() // Force error if unknown field is found
if err := dec.Decode(&res); err != nil {
fmt.Printf("ERROR: %s\n", err)
return err
}
// If the resource has no Properties set, it could be nil
if res.Properties != nil {
*r = ResourceDefaultVersion(*res.Properties)
}
if res.DependsOn != nil {
switch obj := res.DependsOn.(type) {
case string:
r.AWSCloudFormationDependsOn = []string{obj}
case []interface{}:
s := make([]string, 0, len(obj))
for _, v := range obj {
if value, ok := v.(string); ok {
s = append(s, value)
}
}
r.AWSCloudFormationDependsOn = s
}
}
if res.Metadata != nil {
r.AWSCloudFormationMetadata = res.Metadata
}
if res.DeletionPolicy != "" {
r.AWSCloudFormationDeletionPolicy = policies.DeletionPolicy(res.DeletionPolicy)
}
if res.UpdateReplacePolicy != "" |
if res.Condition != "" {
r.AWSCloudFormationCondition = res.Condition
}
return nil
}
| {
r.AWSCloudFormationUpdateReplacePolicy = policies.UpdateReplacePolicy(res.UpdateReplacePolicy)
} |
query_macro.rs | use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;
use syn::{Expr, Ident, LitStr, Result, Token, Type};
use heck::SnakeCase;
use proc_macro2::TokenStream;
use toql_query_parser::PestQueryParser;
use pest::Parser;
use toql_query_parser::Rule;
#[derive(Debug)]
enum TokenType {
Field,
Wildcard,
Predicate,
Selection,
Query,
Unknown,
}
#[derive(Debug)]
pub struct QueryMacro {
pub struct_type: Type,
pub query: LitStr,
pub arguments: Punctuated<Expr, Token![,]>,
}
impl Parse for QueryMacro {
fn parse(input: ParseStream) -> Result<Self> {
Ok(QueryMacro {
struct_type: { (input.parse()?, input.parse::<Token![,]>()?).0 },
query: input.parse()?,
arguments: {
let lookahead = input.lookahead1();
if lookahead.peek(Token![,]) {
// arguments ?
input.parse::<Token![,]>()?; // skip ,
input.parse_terminated(Expr::parse)?
} else {
Punctuated::new()
}
},
})
}
}
#[derive(Debug, PartialEq)]
enum Concatenation {
And,
Or,
}
#[derive(Debug)]
struct FieldInfo {
pub sort: TokenStream,
pub hidden: TokenStream,
pub field: TokenStream,
pub args: Vec<TokenStream>,
pub single_array_argument: bool,
pub name: String,
pub filter_name: Option<String>,
pub token_type: TokenType,
pub concat: Concatenation,
}
impl FieldInfo {
pub fn new() -> Self {
FieldInfo {
sort: quote!(),
hidden: quote!(),
field: quote!(),
single_array_argument: false,
args: Vec::new(),
name: String::new(),
filter_name: None,
token_type: TokenType::Unknown,
concat: Concatenation::And,
}
}
fn concatenated_token(&self, struct_type: &Type) -> TokenStream {
let token = match self.token_type {
TokenType::Field => {
// Separate with underscore, convert to snake_case for rust
let fnname = self
.name
.split('_')
.map(|n| syn::parse_str::<Ident>(&format!("r#{}", n.to_snake_case())).unwrap());
// let reserved = Ident::new("r#", Span::call_site());
let sort = &self.sort;
let hidden = &self.hidden;
let filter = self.filter();
Some(
quote!(<#struct_type as toql::query_fields::QueryFields>::fields(). #(#fnname()).* #sort #hidden #filter),
)
}
TokenType::Wildcard => Some(if self.name.is_empty() {
quote!(toql::query_path::QueryPath::wildcard(<#struct_type as toql::query_fields::QueryFields>::fields()))
} else {
let fnname = self
.name
.split('_')
.map(|n| syn::parse_str::<Ident>(&format!("r#{}", n.to_snake_case())).unwrap());
quote!(toql::query_path::QueryPath::wildcard(<#struct_type as toql::query_fields::QueryFields>::fields(). #(#fnname()).*))
}),
TokenType::Query => {
let query = &self.args.get(0);
Some(quote!(toql::query::Query::<#struct_type>::from(#query)))
}
TokenType::Predicate => {
let args = &self.args;
//let fnname = self.name.split("_").map(|n| Ident::new(&n.to_snake_case(), Span::call_site()));
let fnname = self
.name
.split('_')
.map(|n| syn::parse_str::<Ident>(&format!("r#{}", n.to_snake_case())).unwrap());
let are = if self.single_array_argument {
quote!(.are( #(#args),* ))
} else {
if self.args.is_empty() {
quote!()
} else {
quote!(.are( &[#(#args),*] ))
}
};
Some(
quote!(<#struct_type as toql::query_fields::QueryFields>::fields(). #(#fnname()).* #are ),
)
}
TokenType::Selection => {
if self.name.is_empty() {
Some(
quote!(toql::query_path::QueryPath::selection(<#struct_type as toql::query_fields::QueryFields>::fields(),"std")),
)
} else {
let (name, path) = if let Some(pos) = self.name.rfind('_') {
(&self.name[pos + 1..], Some(&self.name[..pos]))
} else {
(self.name.as_str(), None)
};
match path {
Some(p) => {
let fnname = p.split('_').map(|n| {
syn::parse_str::<Ident>(&format!("r#{}", n.to_snake_case()))
.unwrap()
});
Some(
quote!(toql::query_path::QueryPath::selection(<#struct_type as toql::query_fields::QueryFields>::fields(). #(#fnname()).*, #name)),
)
}
None => Some(
quote!(toql::query_path::QueryPath::selection(<#struct_type as toql::query_fields::QueryFields>::fields(), #name)),
),
}
}
}
TokenType::Unknown => None,
};
match token {
Some(token) => {
if self.concat == Concatenation::And {
quote!(.and(#token))
} else {
quote!(.or(#token))
}
}
None => quote!(),
}
}
fn filter(&self) -> TokenStream |
}
pub fn parse(
toql_string: &LitStr,
struct_type: Type,
query_args: &mut syn::punctuated::Iter<'_, syn::Expr>,
) -> std::result::Result<TokenStream, TokenStream> {
use crate::syn::spanned::Spanned;
let mut output_stream: TokenStream = quote!(toql::query::Query::<#struct_type>::new());
// eprintln!("About to parse {}", toql_string);
match PestQueryParser::parse(Rule::query, &toql_string.value()) {
Ok(pairs) => {
output_stream.extend(evaluate_pair(
&mut pairs.flatten(),
&struct_type,
query_args,
)?);
if let Some(arg) = query_args.next() {
return Err(
quote_spanned!(arg.span() => compile_error!("Missing placeholder for argument")),
);
}
}
Err(e) => {
let msg = e.to_string();
return Err(quote_spanned!(toql_string.span() => compile_error!(#msg)));
}
};
Ok(output_stream)
}
fn evaluate_pair(
pairs: &mut pest::iterators::FlatPairs<toql_query_parser::Rule>,
struct_type: &Type,
query_args: &mut syn::punctuated::Iter<'_, syn::Expr>,
) -> std::result::Result<TokenStream, TokenStream> {
//fn evaluate_pair(pairs: &pest::iterators::Pair<'_, toql_parser::Rule>) ->TokenStream2 {
let mut field_info = FieldInfo::new();
let mut output_stream = quote!();
while let Some(pair) = pairs.next() {
let span = pair.clone().as_span();
match pair.as_rule() {
Rule::lpar => {
let content = evaluate_pair(pairs, struct_type, query_args)?;
output_stream.extend(if field_info.concat == Concatenation::And {
quote!( .and_parentized(toql::query::Query::<#struct_type>::new() #content))
} else {
quote!( .or_parentized(toql::query::Query::<#struct_type>::new() #content))
});
}
Rule::rpar => {
break;
}
Rule::sort => {
let p = span.as_str()[1..].parse::<u8>().unwrap_or(1);
if let Some('+') = span.as_str().chars().next() {
field_info.sort = quote!(.asc(#p));
} else {
field_info.sort = quote!(.desc(#p));
}
}
Rule::hidden => {
field_info.hidden = quote!(.hide());
}
Rule::wildcard => {
field_info.name = span
.as_str()
.trim_end_matches('*')
.trim_end_matches('_')
.to_string(); // Somehow name rules fdont work
field_info.token_type = TokenType::Wildcard;
}
Rule::filter0_name => {
field_info.filter_name = Some(span.as_str().to_string());
}
Rule::filter1_name => {
field_info.filter_name = Some(span.as_str().to_string());
}
Rule::filter2_name => {
field_info.filter_name = Some(span.as_str().to_string());
}
Rule::filterx_name => {
field_info.filter_name = Some(span.as_str().to_string());
}
Rule::filterc_name => {
field_info.filter_name = Some(span.as_str().to_string());
}
Rule::num_u64 => {
let v = span.as_str().parse::<u64>().unwrap_or(0); // should not be invalid, todo check range
field_info.args.push(quote!(#v));
}
Rule::num_i64 => {
let v = span.as_str().parse::<i64>().unwrap_or(0); // should not be invalid, todo check range
field_info.args.push(quote!(#v));
}
Rule::num_f64 => {
let v = span.as_str().parse::<f64>().unwrap_or(0.0); // should not be invalid, todo check range
field_info.args.push(quote!(#v));
}
Rule::string => {
let v = span
.as_str()
.trim_start_matches('\'')
.trim_end_matches('\'')
.replace("''", "'");
field_info.args.push(quote!(#v));
}
Rule::num_placeholder => {
field_info.single_array_argument = true; // first argument contains whole array
let v = query_args.next();
match v {
Some(v) => field_info.args.push(quote!(#v)),
None => {
return Err(quote!(compile_error!("Missing argument for placeholder");));
}
}
}
Rule::selection_clause => {
field_info.token_type = TokenType::Selection;
}
Rule::selection_name => {
field_info.name = span.as_str().trim_start_matches('#').to_string();
}
Rule::predicate_clause => {
field_info.token_type = TokenType::Predicate;
}
Rule::field_path => {
field_info.name = span.as_str().to_string();
}
Rule::field_clause => {
field_info.token_type = TokenType::Field;
}
Rule::predicate_name => {
field_info.name = span.as_str().trim_start_matches('@').to_string();
}
Rule::query_placeholder => {
field_info.token_type = TokenType::Query;
let v = query_args.next();
match v {
Some(v) => field_info.args.push(quote!(#v)),
None => return Err(quote!(compile_error!("Missing argument for placeholder"))),
};
}
Rule::separator => {
output_stream.extend(field_info.concatenated_token(struct_type));
field_info = FieldInfo::new();
let concat = span.as_str().chars().next().unwrap_or(',');
field_info.concat = if concat == ',' {
Concatenation::And
} else {
Concatenation::Or
};
}
_ => {}
}
}
output_stream.extend(field_info.concatenated_token(struct_type));
Ok(output_stream)
}
| {
let args = &self.args;
match &self.filter_name {
Some(f) => {
let f = f.to_uppercase();
match f.as_str() {
"EQ" => quote!(.eq(#(#args),*)),
"EQN" => quote!(.eqn()),
"NE" => quote!(.ne(#(#args),*)),
"NEN" => quote!(.nen()),
"GT" => quote!(.gt(#(#args),*)),
"GE" => quote!(.ge(#(#args),*)),
"LT" => quote!(.lt(#(#args),*)),
"LE" => quote!(.le(#(#args),*)),
"LK" => quote!(.lk(#(#args),*)),
"IN" => {
if self.single_array_argument {
quote!(.ins( #(#args),* ))
} else {
quote!(.ins( &[#(#args),*] ))
}
}
"OUT" => {
if self.single_array_argument {
quote!(.out( #(#args),* ))
} else {
quote!(.out( &[#(#args),*] ))
}
}
"BW" => quote!(.bw(#(#args),*)),
_ => {
if f.starts_with("FN ") {
let name = f.trim_start_matches("FN ");
let args = &self.args;
if self.single_array_argument {
quote!(.fnc(#name, #(#args),* ))
} else {
quote!(.fnc(#name, &[#(#args),*] ))
}
} else {
let error = format!("Invalid filter `{}`.", f);
quote!(compile_error!(#error))
}
}
}
}
None => quote!(),
}
} |
tor_daemon.go | package metrics
import (
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/yawning/bulb"
"sigs.k8s.io/controller-runtime/pkg/metrics"
"strconv"
"strings"
)
var (
circuitsCountGauge = prometheus.NewGauge(
prometheus.GaugeOpts{
Name: "circuits",
Help: "Count of currently open circuits",
},
)
streamsCountGauge = prometheus.NewGauge(
prometheus.GaugeOpts{
Name: "streams",
Help: "Count of currently open streams",
},
)
orconnsCountGauge = prometheus.NewGauge(
prometheus.GaugeOpts{
Name: "orconns",
Help: "Count of currently open ORConns",
},
)
trafficReadCounter = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "traffic_read",
Help: "Total traffic read",
},
)
trafficWrittenCounter = prometheus.NewCounter(
prometheus.CounterOpts{
Name: "traffic_written",
Help: "Total traffic written",
},
)
)
type TorDaemonMetricsExporter struct {
Bulb *bulb.Conn
}
func (e *TorDaemonMetricsExporter) Connect(socket, port string) error {
var err error
if socket != "" {
e.Bulb, err = bulb.Dial("unix", socket)
} else if port != "" {
e.Bulb, err = bulb.Dial("tcp4", port)
} else {
return errors.New("no endpoint specified")
}
if err != nil {
return errors.Wrap(err, "failed to connect to Tor")
}
//c.Debug(true)
if err = e.Bulb.Authenticate(""); err != nil {
return errors.Wrap(err, "Could not authenticate")
}
return nil
}
func (e* TorDaemonMetricsExporter) Reconnect(socket, port string) error {
if err := e.Close(); err != nil { | return err
}
return e.Connect(socket, port)
}
func (e *TorDaemonMetricsExporter) Close() error {
defer e.Bulb.Close()
return nil
}
func (e *TorDaemonMetricsExporter) getInfoFloat(val string) (float64, error) {
resp, err := e.Bulb.Request("GETINFO " + val)
if err != nil {
return -1, err
}
if len(resp.Data) != 1 {
return -1, errors.Errorf("GETINFO %s returned unknown response", val)
}
vals := strings.SplitN(resp.Data[0], "=", 2)
if len(vals) != 2 {
return -1, errors.Errorf("GETINFO %s returned invalid response", val)
}
return strconv.ParseFloat(vals[1], 64)
}
// Do a GETINFO %val, return the number of lines that match %match
func (e *TorDaemonMetricsExporter) linesWithMatch(val, match string) (int, error) {
resp, err := e.Bulb.Request("GETINFO " + val)
if err != nil {
return -1, errors.Wrap(err, "GETINFO circuit-status failed")
}
if len(resp.Data) < 2 {
return 0, nil
}
ct := 0
for _, line := range strings.Split(resp.Data[1], "\n") {
if strings.Contains(line, match) {
ct++
}
}
return ct, nil
}
func (e *TorDaemonMetricsExporter) scrapeTraffic() error {
if trafficRead, err := e.getInfoFloat("traffic/read"); err != nil {
return errors.Wrap(err, "could not scrape read_bytes")
} else {
trafficReadCounter.Add(trafficRead)
}
if trafficWritten, err := e.getInfoFloat("traffic/written"); err != nil {
return errors.Wrap(err, "could not scrape written_bytes")
} else {
trafficWrittenCounter.Add(trafficWritten)
}
return nil
}
func (e *TorDaemonMetricsExporter) scrapeStatus() error {
if circuitsCount, err := e.linesWithMatch("circuit-status", " BUILT "); err != nil {
return errors.Wrapf(err, "could not scrape circuit-status")
} else {
circuitsCountGauge.Set(float64(circuitsCount))
}
if streamsCount, err := e.linesWithMatch("stream-status", "SUCCEEDED"); err != nil {
return errors.Wrapf(err, "could not scrape stream-status")
} else {
streamsCountGauge.Set(float64(streamsCount))
}
if orconnsCount, err := e.linesWithMatch("orconn-status", " CONNECTED"); err != nil {
return errors.Wrapf(err, "could not scrape orconn-status")
} else {
orconnsCountGauge.Set(float64(orconnsCount))
}
return nil
}
func (e *TorDaemonMetricsExporter) Start(socket, port string) error {
if err := e.Connect(socket, port); err != nil {
return err
}
metrics.Registry.MustRegister(trafficWrittenCounter, trafficReadCounter, orconnsCountGauge, streamsCountGauge, circuitsCountGauge)
return nil
} | |
user.ts | import { Credential } from "./credential"; |
export class User {
id: number;
name: string;
email?: string;
credential?: Credential;
} | |
conftest.py | """Common test functions."""
from pathlib import Path
import re
from unittest.mock import AsyncMock, MagicMock, PropertyMock, patch
from uuid import uuid4
from aiohttp import web
from aiohttp.test_utils import TestClient
from awesomeversion import AwesomeVersion
import pytest
from supervisor.api import RestAPI
from supervisor.bootstrap import initialize_coresys
from supervisor.const import REQUEST_FROM
from supervisor.coresys import CoreSys
from supervisor.dbus.network import NetworkManager
from supervisor.docker import DockerAPI
from supervisor.store.addon import AddonStore
from supervisor.store.repository import Repository
from supervisor.utils.gdbus import DBus
from tests.common import exists_fixture, load_fixture, load_json_fixture
# pylint: disable=redefined-outer-name, protected-access
async def mock_async_return_true() -> bool:
"""Mock methods to return True."""
return True
@pytest.fixture
def docker() -> DockerAPI:
"""Mock DockerAPI."""
images = [MagicMock(tags=["homeassistant/amd64-hassio-supervisor:latest"])]
with patch("docker.DockerClient", return_value=MagicMock()), patch(
"supervisor.docker.DockerAPI.images", return_value=MagicMock()
), patch("supervisor.docker.DockerAPI.containers", return_value=MagicMock()), patch(
"supervisor.docker.DockerAPI.api", return_value=MagicMock()
), patch(
"supervisor.docker.DockerAPI.images.list", return_value=images
), patch(
"supervisor.docker.DockerAPI.info",
return_value=MagicMock(),
), patch(
"supervisor.docker.DockerConfig",
return_value=MagicMock(),
):
docker_obj = DockerAPI()
docker_obj.info.logging = "journald"
docker_obj.info.storage = "overlay2"
docker_obj.info.version = "1.0.0"
docker_obj.config.registries = {}
yield docker_obj
@pytest.fixture
def dbus() -> DBus:
"""Mock DBUS."""
dbus_commands = []
async def mock_get_properties(dbus_obj, interface):
latest = dbus_obj.object_path.split("/")[-1]
fixture = interface.replace(".", "_")
if latest.isnumeric():
fixture = f"{fixture}_{latest}"
return load_json_fixture(f"{fixture}.json")
async def mock_wait_signal(_, __):
pass
async def mock_send(_, command, silent=False):
if silent:
return ""
fixture = command[6].replace("/", "_")[1:]
if command[1] == "introspect":
filetype = "xml"
if not exists_fixture(f"{fixture}.{filetype}"):
fixture = re.sub(r"_[0-9]+$", "", fixture)
# special case
if exists_fixture(f"{fixture}_*.{filetype}"):
fixture = f"{fixture}_*"
else:
fixture = f"{fixture}-{command[10].split('.')[-1]}"
filetype = "fixture"
dbus_commands.append(fixture)
return load_fixture(f"{fixture}.{filetype}")
with patch("supervisor.utils.gdbus.DBus._send", new=mock_send), patch(
"supervisor.utils.gdbus.DBus.wait_signal", new=mock_wait_signal
), patch(
"supervisor.dbus.interface.DBusInterface.is_connected",
return_value=True,
), patch(
"supervisor.utils.gdbus.DBus.get_properties", new=mock_get_properties
):
yield dbus_commands
@pytest.fixture
async def network_manager(dbus) -> NetworkManager:
"""Mock NetworkManager."""
nm_obj = NetworkManager()
nm_obj.dbus = dbus
# Init
await nm_obj.connect()
await nm_obj.update()
yield nm_obj
@pytest.fixture
async def coresys(loop, docker, network_manager, aiohttp_client) -> CoreSys:
"""Create a CoreSys Mock."""
with patch("supervisor.bootstrap.initialize_system_data"), patch(
"supervisor.bootstrap.setup_diagnostics"
), patch(
"supervisor.bootstrap.fetch_timezone",
return_value="Europe/Zurich",
), patch(
"aiohttp.ClientSession",
return_value=TestClient.session,
): | # Mock save json
coresys_obj._ingress.save_data = MagicMock()
coresys_obj._auth.save_data = MagicMock()
coresys_obj._updater.save_data = MagicMock()
coresys_obj._config.save_data = MagicMock()
coresys_obj._jobs.save_data = MagicMock()
coresys_obj._resolution.save_data = MagicMock()
# Mock test client
coresys_obj.arch._default_arch = "amd64"
coresys_obj._machine = "qemux86-64"
coresys_obj._machine_id = uuid4()
# Mock host communication
coresys_obj._dbus._network = network_manager
# Mock docker
coresys_obj._docker = docker
# Set internet state
coresys_obj.supervisor._connectivity = True
coresys_obj.host.network._connectivity = True
# WebSocket
coresys_obj.homeassistant.api.check_api_state = mock_async_return_true
coresys_obj.homeassistant._websocket._client = AsyncMock(
ha_version=AwesomeVersion("2021.2.4")
)
yield coresys_obj
@pytest.fixture
def sys_machine():
"""Mock sys_machine."""
with patch("supervisor.coresys.CoreSys.machine", new_callable=PropertyMock) as mock:
yield mock
@pytest.fixture
def sys_supervisor():
"""Mock sys_supervisor."""
with patch(
"supervisor.coresys.CoreSys.supervisor", new_callable=PropertyMock
) as mock:
mock.return_value = MagicMock()
yield MagicMock
@pytest.fixture
async def api_client(aiohttp_client, coresys: CoreSys):
"""Fixture for RestAPI client."""
@web.middleware
async def _security_middleware(request: web.Request, handler: web.RequestHandler):
"""Make request are from Core."""
request[REQUEST_FROM] = coresys.homeassistant
return await handler(request)
api = RestAPI(coresys)
api.webapp = web.Application(middlewares=[_security_middleware])
api.start = AsyncMock()
await api.load()
yield await aiohttp_client(api.webapp)
@pytest.fixture
def store_manager(coresys: CoreSys):
"""Fixture for the store manager."""
sm_obj = coresys.store
with patch("supervisor.store.data.StoreData.update", return_value=MagicMock()):
yield sm_obj
@pytest.fixture
def run_dir(tmp_path):
"""Fixture to inject hassio env."""
with patch("supervisor.core.RUN_SUPERVISOR_STATE") as mock_run:
tmp_state = Path(tmp_path, "supervisor")
mock_run.write_text = tmp_state.write_text
yield tmp_state
@pytest.fixture
def store_addon(coresys: CoreSys, tmp_path):
"""Store add-on fixture."""
addon_obj = AddonStore(coresys, "test_store_addon")
coresys.addons.store[addon_obj.slug] = addon_obj
coresys.store.data.addons[addon_obj.slug] = load_json_fixture("add-on.json")
yield addon_obj
@pytest.fixture
def repository(coresys: CoreSys):
"""Repository fixture."""
repository_obj = Repository(
coresys, "https://github.com/awesome-developer/awesome-repo"
)
coresys.store.repositories[repository_obj.slug] = repository_obj
yield repository_obj | coresys_obj = await initialize_coresys()
|
util.rs | use std::path::{Path, PathBuf};
use nu_engine::env::current_dir_str;
use nu_path::canonicalize_with;
use nu_protocol::engine::{EngineState, Stack};
use nu_protocol::ShellError;
use dialoguer::Input;
use std::error::Error;
#[derive(Default)]
pub struct FileStructure {
pub resources: Vec<Resource>,
}
#[allow(dead_code)]
impl FileStructure {
pub fn new() -> FileStructure {
FileStructure { resources: vec![] }
}
pub fn contains_more_than_one_file(&self) -> bool {
self.resources.len() > 1
}
pub fn contains_files(&self) -> bool {
!self.resources.is_empty()
}
pub fn paths_applying_with<F>(
&mut self,
to: F,
) -> Result<Vec<(PathBuf, PathBuf)>, Box<dyn std::error::Error>>
where
F: Fn((PathBuf, usize)) -> Result<(PathBuf, PathBuf), Box<dyn std::error::Error>>,
{
self.resources
.iter()
.map(|f| (PathBuf::from(&f.location), f.at))
.map(to)
.collect()
}
pub fn walk_decorate(
&mut self,
start_path: &Path,
engine_state: &EngineState,
stack: &Stack,
) -> Result<(), ShellError> {
self.resources = Vec::<Resource>::new();
self.build(start_path, 0, engine_state, stack)?;
self.resources.sort();
Ok(())
}
fn build(
&mut self,
src: &Path,
lvl: usize,
engine_state: &EngineState,
stack: &Stack,
) -> Result<(), ShellError> {
let source = canonicalize_with(src, current_dir_str(engine_state, stack)?)?;
if source.is_dir() {
for entry in std::fs::read_dir(src)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
self.build(&path, lvl + 1, engine_state, stack)?;
}
self.resources.push(Resource {
location: path.to_path_buf(),
at: lvl,
});
}
} else {
self.resources.push(Resource {
location: source,
at: lvl,
});
}
Ok(())
}
}
#[derive(Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct | {
pub at: usize,
pub location: PathBuf,
}
impl Resource {}
#[allow(dead_code)]
pub fn get_interactive_confirmation(prompt: String) -> Result<bool, Box<dyn Error>> {
let input = Input::new()
.with_prompt(prompt)
.validate_with(|c_input: &String| -> Result<(), String> {
if c_input.len() == 1
&& (c_input == "y" || c_input == "Y" || c_input == "n" || c_input == "N")
{
Ok(())
} else if c_input.len() > 1 {
Err("Enter only one letter (Y/N)".to_string())
} else {
Err("Input not valid".to_string())
}
})
.default("Y/N".into())
.interact_text()?;
if input == "y" || input == "Y" {
Ok(true)
} else {
Ok(false)
}
}
| Resource |
app.module.ts | import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import {AppRoutingModule, routingComponents} from './app-routing.module';
import {ReactiveFormsModule} from '@angular/forms';
@NgModule({
imports: [ BrowserModule, AppRoutingModule, ReactiveFormsModule],
declarations: [ AppComponent, routingComponents ],
bootstrap: [ AppComponent ]
})
export class | { }
| AppModule |
aggregation.rs | // Copyright 2017 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
use std::rc::Rc;
use tipb::schema::ColumnInfo;
use tipb::executor::Aggregation;
use tipb::expression::{Expr, ExprType};
use util::collections::{HashMap, HashMapEntry as Entry};
use coprocessor::codec::table::RowColsDict;
use coprocessor::codec::datum::{self, approximate_size, Datum, DatumEncoder};
use coprocessor::endpoint::SINGLE_GROUP;
use coprocessor::select::aggregate::{self, AggrFunc};
use coprocessor::select::xeval::EvalContext;
use coprocessor::dag::expr::Expression;
use coprocessor::metrics::*;
use coprocessor::Result;
use super::{inflate_with_col_for_dag, Executor, ExprColumnRefVisitor, Row};
struct AggrFuncExpr {
args: Vec<Expression>,
tp: ExprType,
}
impl AggrFuncExpr {
fn batch_build(ctx: &EvalContext, expr: Vec<Expr>) -> Result<Vec<AggrFuncExpr>> {
expr.into_iter()
.map(|v| AggrFuncExpr::build(ctx, v))
.collect()
}
fn build(ctx: &EvalContext, mut expr: Expr) -> Result<AggrFuncExpr> {
let args = box_try!(Expression::batch_build(
ctx,
expr.take_children().into_vec()
));
let tp = expr.get_tp();
Ok(AggrFuncExpr { args: args, tp: tp })
}
fn eval_args(&self, ctx: &EvalContext, row: &[Datum]) -> Result<Vec<Datum>> {
let res: Vec<Datum> = box_try!(self.args.iter().map(|v| v.eval(ctx, row)).collect());
Ok(res)
}
}
impl AggrFunc {
fn | (
&mut self,
ctx: &EvalContext,
expr: &AggrFuncExpr,
row: &[Datum],
) -> Result<()> {
let vals = expr.eval_args(ctx, row)?;
self.update(ctx, vals)?;
Ok(())
}
}
pub struct AggregationExecutor<'a> {
group_by: Vec<Expression>,
aggr_func: Vec<AggrFuncExpr>,
group_keys: Vec<Rc<Vec<u8>>>,
group_key_aggrs: HashMap<Rc<Vec<u8>>, Vec<Box<AggrFunc>>>,
cursor: usize,
executed: bool,
ctx: Rc<EvalContext>,
cols: Rc<Vec<ColumnInfo>>,
related_cols_offset: Vec<usize>, // offset of related columns
src: Box<Executor + 'a>,
}
impl<'a> AggregationExecutor<'a> {
pub fn new(
mut meta: Aggregation,
ctx: Rc<EvalContext>,
columns: Rc<Vec<ColumnInfo>>,
src: Box<Executor + 'a>,
) -> Result<AggregationExecutor<'a>> {
// collect all cols used in aggregation
let mut visitor = ExprColumnRefVisitor::new(columns.len());
let group_by = meta.take_group_by().into_vec();
visitor.batch_visit(&group_by)?;
let aggr_func = meta.take_agg_func().into_vec();
visitor.batch_visit(&aggr_func)?;
COPR_EXECUTOR_COUNT
.with_label_values(&["aggregation"])
.inc();
Ok(AggregationExecutor {
group_by: box_try!(Expression::batch_build(ctx.as_ref(), group_by)),
aggr_func: AggrFuncExpr::batch_build(ctx.as_ref(), aggr_func)?,
group_keys: vec![],
group_key_aggrs: map![],
cursor: 0,
executed: false,
ctx: ctx,
cols: columns,
related_cols_offset: visitor.column_offsets(),
src: src,
})
}
fn get_group_key(&self, row: &[Datum]) -> Result<Vec<u8>> {
if self.group_by.is_empty() {
let single_group = Datum::Bytes(SINGLE_GROUP.to_vec());
return Ok(box_try!(datum::encode_value(&[single_group])));
}
let mut vals = Vec::with_capacity(self.group_by.len());
for expr in &self.group_by {
let v = box_try!(expr.eval(&self.ctx, row));
vals.push(v);
}
let res = box_try!(datum::encode_value(&vals));
Ok(res)
}
fn aggregate(&mut self) -> Result<()> {
while let Some(row) = self.src.next()? {
let cols = inflate_with_col_for_dag(
&self.ctx,
&row.data,
self.cols.clone(),
&self.related_cols_offset,
row.handle,
)?;
let group_key = Rc::new(self.get_group_key(&cols)?);
match self.group_key_aggrs.entry(group_key.clone()) {
Entry::Vacant(e) => {
let mut aggrs = Vec::with_capacity(self.aggr_func.len());
for expr in &self.aggr_func {
let mut aggr = aggregate::build_aggr_func(expr.tp)?;
aggr.update_with_expr(&self.ctx, expr, &cols)?;
aggrs.push(aggr);
}
self.group_keys.push(group_key);
e.insert(aggrs);
}
Entry::Occupied(e) => {
let aggrs = e.into_mut();
for (expr, aggr) in self.aggr_func.iter().zip(aggrs) {
aggr.update_with_expr(&self.ctx, expr, &cols)?;
}
}
}
}
Ok(())
}
}
impl<'a> Executor for AggregationExecutor<'a> {
fn next(&mut self) -> Result<Option<Row>> {
if !self.executed {
self.aggregate()?;
self.executed = true;
}
if self.cursor >= self.group_keys.len() {
return Ok(None);
}
// calc all aggr func
let mut aggr_cols = Vec::with_capacity(2 * self.aggr_func.len());
let group_key = &self.group_keys[self.cursor];
let mut aggrs = self.group_key_aggrs.remove(group_key).unwrap();
for aggr in &mut aggrs {
aggr.calc(&mut aggr_cols)?;
}
// construct row data
let value_size = group_key.len() + approximate_size(&aggr_cols, false);
let mut value = Vec::with_capacity(value_size);
box_try!(value.encode(aggr_cols.as_slice(), false));
if !self.group_by.is_empty() {
value.extend_from_slice(group_key);
}
self.cursor += 1;
Ok(Some(Row {
handle: 0,
data: RowColsDict::new(map![], value),
}))
}
}
#[cfg(test)]
mod test {
use std::i64;
use kvproto::kvrpcpb::IsolationLevel;
use protobuf::RepeatedField;
use tipb::executor::TableScan;
use tipb::expression::{Expr, ExprType};
use coprocessor::codec::datum::{Datum, DatumDecoder};
use coprocessor::codec::mysql::decimal::Decimal;
use coprocessor::codec::mysql::types;
use storage::{SnapshotStore, Statistics};
use util::codec::number::NumberEncoder;
use super::*;
use super::super::table_scan::TableScanExecutor;
use super::super::scanner::test::{get_range, new_col_info, TestStore};
use super::super::topn::test::gen_table_data;
#[inline]
fn build_expr(tp: ExprType, id: Option<i64>, child: Option<Expr>) -> Expr {
let mut expr = Expr::new();
expr.set_tp(tp);
if tp == ExprType::ColumnRef {
expr.mut_val().encode_i64(id.unwrap()).unwrap();
} else {
expr.mut_children().push(child.unwrap());
}
expr
}
fn build_group_by(col_ids: &[i64]) -> Vec<Expr> {
let mut group_by = Vec::with_capacity(col_ids.len());
for id in col_ids {
group_by.push(build_expr(ExprType::ColumnRef, Some(*id), None));
}
group_by
}
fn build_aggr_func(aggrs: &[(ExprType, i64)]) -> Vec<Expr> {
let mut aggr_func = Vec::with_capacity(aggrs.len());
for aggr in aggrs {
let &(tp, id) = aggr;
let col_ref = build_expr(ExprType::ColumnRef, Some(id), None);
aggr_func.push(build_expr(tp, None, Some(col_ref)));
}
aggr_func
}
#[test]
fn test_aggregation() {
// prepare data and store
let tid = 1;
let cis = vec![
new_col_info(1, types::LONG_LONG),
new_col_info(2, types::VARCHAR),
new_col_info(3, types::NEW_DECIMAL),
];
let raw_data = vec![
vec![
Datum::I64(1),
Datum::Bytes(b"a".to_vec()),
Datum::Dec(7.into()),
],
vec![
Datum::I64(2),
Datum::Bytes(b"a".to_vec()),
Datum::Dec(7.into()),
],
vec![
Datum::I64(3),
Datum::Bytes(b"b".to_vec()),
Datum::Dec(8.into()),
],
vec![
Datum::I64(4),
Datum::Bytes(b"a".to_vec()),
Datum::Dec(7.into()),
],
vec![
Datum::I64(5),
Datum::Bytes(b"f".to_vec()),
Datum::Dec(5.into()),
],
vec![
Datum::I64(6),
Datum::Bytes(b"b".to_vec()),
Datum::Dec(8.into()),
],
vec![
Datum::I64(7),
Datum::Bytes(b"f".to_vec()),
Datum::Dec(6.into()),
],
];
let table_data = gen_table_data(tid, &cis, &raw_data);
let mut test_store = TestStore::new(&table_data);
// init table scan meta
let mut table_scan = TableScan::new();
table_scan.set_table_id(tid);
table_scan.set_columns(RepeatedField::from_vec(cis.clone()));
// init TableScan Exectutor
let key_ranges = vec![get_range(tid, i64::MIN, i64::MAX)];
let (snapshot, start_ts) = test_store.get_snapshot();
let store = SnapshotStore::new(snapshot, start_ts, IsolationLevel::SI, true);
let mut statistics = Statistics::default();
let ts_ect = TableScanExecutor::new(&table_scan, key_ranges, store, &mut statistics);
// init aggregation meta
let mut aggregation = Aggregation::default();
let group_by_cols = vec![1, 2];
let group_by = build_group_by(&group_by_cols);
aggregation.set_group_by(RepeatedField::from_vec(group_by));
let aggr_funcs = vec![(ExprType::Avg, 0), (ExprType::Count, 2)];
let aggr_funcs = build_aggr_func(&aggr_funcs);
aggregation.set_agg_func(RepeatedField::from_vec(aggr_funcs));
// init Aggregation Executor
let mut aggr_ect = AggregationExecutor::new(
aggregation,
Rc::new(EvalContext::default()),
Rc::new(cis),
Box::new(ts_ect),
).unwrap();
let expect_row_cnt = 4;
let mut row_data = Vec::with_capacity(expect_row_cnt);
while let Some(row) = aggr_ect.next().unwrap() {
row_data.push(row.data);
}
assert_eq!(row_data.len(), expect_row_cnt);
let expect_row_data = vec![
(
3 as u64,
Decimal::from(7),
3 as u64,
b"a".as_ref(),
Decimal::from(7),
),
(
2 as u64,
Decimal::from(9),
2 as u64,
b"b".as_ref(),
Decimal::from(8),
),
(
1 as u64,
Decimal::from(5),
1 as u64,
b"f".as_ref(),
Decimal::from(5),
),
(
1 as u64,
Decimal::from(7),
1 as u64,
b"f".as_ref(),
Decimal::from(6),
),
];
let expect_col_cnt = 5;
for (row, expect_cols) in row_data.into_iter().zip(expect_row_data) {
let ds = row.value.as_slice().decode().unwrap();
assert_eq!(ds.len(), expect_col_cnt);
assert_eq!(ds[0], Datum::from(expect_cols.0));
assert_eq!(ds[1], Datum::from(expect_cols.1));
assert_eq!(ds[2], Datum::from(expect_cols.2));
assert_eq!(ds[3], Datum::from(expect_cols.3));
assert_eq!(ds[4], Datum::from(expect_cols.4));
}
}
}
| update_with_expr |
FormikFormField.tsx | import * as React from 'react';
import { isString, isUndefined } from 'lodash';
import { Field, FastField, FieldProps, getIn, connect, FormikContext } from 'formik';
import {
ICommonFormFieldProps,
IFieldLayoutPropsWithoutInput,
IFieldValidationStatus,
IFormFieldApi,
IValidationProps,
} from './interface';
import { WatchValue } from '../WatchValue';
import { StandardFieldLayout } from './layouts/index';
import { composeValidators, Validator, Validation } from './Validation';
import { renderContent } from './fields/renderContent';
export interface IFormikFieldProps<T> {
/**
* The name/path to the field in the Formik form.
* Accepts lodash paths; see: https://lodash.com/docs/#get
*/
name: string;
/**
* Toggles between `Field` (false) and `FastField` (true)
* Defaults to `FastField` (true)
*
* Use `fastField={false}` if the field depends on other fields.
* See: https://jaredpalmer.com/formik/docs/api/fastfield#when-to-use-fastfield
*/
fastField?: boolean;
/** Inline validation function or functions */
validate?: Validator | Validator[];
/** A callback that is invoked whenever the field value changes */
onChange?: (value: T, prevValue: T) => void;
}
export interface IFormikFormFieldImplState {
internalValidators: Validator[];
}
export type IFormikFormFieldProps<T> = IFormikFieldProps<T> & ICommonFormFieldProps & IFieldLayoutPropsWithoutInput;
type IFormikFormFieldImplProps<T> = IFormikFormFieldProps<T> & { formik: FormikContext<T> };
const ifString = (val: any): string => (isString(val) ? val : undefined);
export class | <T = any>
extends React.Component<IFormikFormFieldImplProps<T>, IFormikFormFieldImplState>
implements IFormFieldApi {
public static defaultProps: Partial<IFormikFormFieldProps<any>> = {
layout: StandardFieldLayout,
fastField: true,
};
public state: IFormikFormFieldImplState = {
internalValidators: [],
};
private addValidator = (internalValidator: Validator) => {
this.setState(prevState => ({
internalValidators: prevState.internalValidators.concat(internalValidator),
}));
};
private removeValidator = (internalValidator: Validator) => {
this.setState(prevState => ({
internalValidators: prevState.internalValidators.filter(x => x !== internalValidator),
}));
};
public name = () => this.props.name;
public label = () => ifString(this.props.label);
public value = () => getIn(this.props.formik.values, this.props.name);
public touched = () => {
const { formik, name, touched } = this.props;
return !isUndefined(touched) ? touched : getIn(formik.touched, name);
};
public validationMessage = () => {
const { name, formik, validationMessage } = this.props;
return ifString(validationMessage) || getIn(formik.errors, name);
};
public validationStatus = () => {
return (this.props.validationStatus || (this.validationMessage() ? 'error' : null)) as IFieldValidationStatus;
};
public render() {
const { internalValidators } = this.state;
const { name, validate, onChange } = this.props; // IFormikFieldProps
const { input, layout } = this.props; // ICommonFieldProps
const { label, help, required, actions } = this.props; // IFieldLayoutPropsWithoutInput
const fieldLayoutPropsWithoutInput: IFieldLayoutPropsWithoutInput = { label, help, required, actions };
const renderField = (props: FieldProps<any>) => {
const { field } = props;
const validationProps: IValidationProps = {
touched: this.touched(),
validationMessage: this.validationMessage(),
validationStatus: this.validationStatus(),
addValidator: this.addValidator,
removeValidator: this.removeValidator,
};
const inputElement = renderContent(input, { ...field, validation: validationProps });
return (
<WatchValue onChange={onChange} value={field.value}>
{renderContent(layout, { ...fieldLayoutPropsWithoutInput, ...validationProps, input: inputElement })}
</WatchValue>
);
};
const validator = createFieldValidator(label, required, [].concat(validate).concat(internalValidators));
if (this.props.fastField) {
return <FastField name={name} validate={validator} render={renderField} />;
}
return <Field name={name} validate={validator} render={renderField} />;
}
}
/** Returns a Validator composed of all the `validate` functions (and `isRequired` if `required` is truthy) */
export function createFieldValidator<T>(
label: IFormikFormFieldProps<T>['label'],
required: boolean,
validate: Validator[],
): Validator {
const validator = composeValidators([!!required && Validation.isRequired()].concat(validate));
if (!validator) {
return null;
}
const labelString = isString(label) ? label : undefined;
return (value: any) => validator(value, labelString);
}
export const FormikFormField = connect(FormikFormFieldImpl);
| FormikFormFieldImpl |
miniflow.py | """
# !/usr/bin/env python
# -*- coding: utf-8 -*-
@Time : 2022/3/26 16:58
@File : miniflow.py
"""
"""
Implement the backward method of the Sigmoid node.
"""
import numpy as np
class Node(object):
"""
Base class for nodes in the network.
Arguments:
`inbound_nodes`: A list of nodes with edges into this node.
"""
def __init__(self, inbound_nodes=[]):
"""
Node's constructor (runs when the object is instantiated). Sets
properties that all nodes need.
"""
# A list of nodes with edges into this node.
self.inbound_nodes = inbound_nodes
# The eventual value of this node. Set by running
# the forward() method.
self.value = None
# A list of nodes that this node outputs to.
self.outbound_nodes = []
# New property! Keys are the inputs to this node and
# their values are the partials of this node with
# respect to that input.
self.gradients = {}
# Sets this node as an outbound node for all of
# this node's inputs.
for node in inbound_nodes:
node.outbound_nodes.append(self)
def forward(self):
"""
Every node that uses this class as a base class will
need to define its own `forward` method.
"""
raise NotImplementedError
def backward(self):
"""
Every node that uses this class as a base class will
need to define its own `backward` method.
"""
raise NotImplementedError
class Input(Node):
"""
A generic input into the network.
"""
def __init__(self):
# The base class constructor has to run to set all
# the properties here.
#
# The most important property on an Input is value.
# self.value is set during `topological_sort` later.
Node.__init__(self)
def forward(self):
# Do nothing because nothing is calculated.
pass
def backward(self):
# An Input node has no inputs so the gradient (derivative)
# is zero.
# The key, `self`, is reference to this object.
self.gradients = {self: 0}
# Weights and bias may be inputs, so you need to sum
# the gradient from output gradients.
for n in self.outbound_nodes:
grad_cost = n.gradients[self]
self.gradients[self] += grad_cost * 1
class Linear(Node):
"""
Represents a node that performs a linear transform.
"""
def __init__(self, X, W, b):
# The base class (Node) constructor. Weights and bias
# are treated like inbound nodes.
Node.__init__(self, [X, W, b])
def forward(self):
"""
Performs the math behind a linear transform.
"""
X = self.inbound_nodes[0].value
W = self.inbound_nodes[1].value
b = self.inbound_nodes[2].value
self.value = np.dot(X, W) + b
def backward(self):
"""
Calculates the gradient based on the output values.
"""
# Initialize a partial for each of the inbound_nodes.
self.gradients = {n: np.zeros_like(n.value) for n in self.inbound_nodes}
# Cycle through the outputs. The gradient will change depending
# on each output, so the gradients are summed over all outputs.
for n in self.outbound_nodes:
# Get the partial of the cost with respect to this node.
grad_cost = n.gradients[self]
# Set the partial of the loss with respect to this node's inputs.
self.gradients[self.inbound_nodes[0]] += np.dot(grad_cost, self.inbound_nodes[1].value.T)
# Set the partial of the loss with respect to this node's weights.
self.gradients[self.inbound_nodes[1]] += np.dot(self.inbound_nodes[0].value.T, grad_cost)
# Set the partial of the loss with respect to this node's bias.
self.gradients[self.inbound_nodes[2]] += np.sum(grad_cost, axis=0, keepdims=False)
class Sigmoid(Node):
"""
Represents a node that performs the sigmoid activation function.
"""
def __init__(self, node):
# The base class constructor.
|
def _sigmoid(self, x):
"""
This method is separate from `forward` because it
will be used with `backward` as well.
`x`: A numpy array-like object.
"""
return 1. / (1. + np.exp(-x))
def forward(self):
"""
Perform the sigmoid function and set the value.
"""
input_value = self.inbound_nodes[0].value
self.value = self._sigmoid(input_value)
def backward(self):
"""
Calculates the gradient using the derivative of
the sigmoid function.
"""
# Initialize the gradients to 0.
self.gradients = {n: np.zeros_like(n.value) for n in self.inbound_nodes}
# Cycle through the outputs. The gradient will change depending
# on each output, so the gradients are summed over all outputs.
for n in self.outbound_nodes:
# Get the partial of the cost with respect to this node.
grad_cost = n.gradients[self]
"""
TODO: Your code goes here!
Set the gradients property to the gradients with respect to each input.
NOTE: See the Linear node and MSE node for examples.
"""
sigmoid = self.value
self.gradients[self.inbound_nodes[0]] += sigmoid * (1 - sigmoid) * grad_cost
class MSE(Node):
def __init__(self, y, a):
"""
The mean squared error cost function.
Should be used as the last node for a network.
"""
# Call the base class' constructor.
Node.__init__(self, [y, a])
def forward(self):
"""
Calculates the mean squared error.
"""
# NOTE: We reshape these to avoid possible matrix/vector broadcast
# errors.
#
# For example, if we subtract an array of shape (3,) from an array of shape
# (3,1) we get an array of shape(3,3) as the result when we want
# an array of shape (3,1) instead.
#
# Making both arrays (3,1) ensures the result is (3,1) and does
# an elementwise subtraction as expected.
y = self.inbound_nodes[0].value.reshape(-1, 1)
a = self.inbound_nodes[1].value.reshape(-1, 1)
self.m = self.inbound_nodes[0].value.shape[0]
# Save the computed output for backward.
self.diff = y - a
self.value = np.mean(self.diff**2)
def backward(self):
"""
Calculates the gradient of the cost.
This is the final node of the network so outbound nodes
are not a concern.
"""
self.gradients[self.inbound_nodes[0]] = (2 / self.m) * self.diff
self.gradients[self.inbound_nodes[1]] = (-2 / self.m) * self.diff
def topological_sort(feed_dict):
"""
Sort the nodes in topological order using Kahn's Algorithm.
`feed_dict`: A dictionary where the key is a `Input` Node and the value is the respective value feed to that Node.
Returns a list of sorted nodes.
"""
input_nodes = [n for n in feed_dict.keys()]
G = {}
nodes = [n for n in input_nodes]
while len(nodes) > 0:
n = nodes.pop(0)
if n not in G:
G[n] = {'in': set(), 'out': set()}
for m in n.outbound_nodes:
if m not in G:
G[m] = {'in': set(), 'out': set()}
G[n]['out'].add(m)
G[m]['in'].add(n)
nodes.append(m)
L = []
S = set(input_nodes)
while len(S) > 0:
n = S.pop()
if isinstance(n, Input):
n.value = feed_dict[n]
L.append(n)
for m in n.outbound_nodes:
G[n]['out'].remove(m)
G[m]['in'].remove(n)
# if no other incoming edges add to S
if len(G[m]['in']) == 0:
S.add(m)
return L
def forward_and_backward(graph):
"""
Performs a forward pass and a backward pass through a list of sorted Nodes.
Arguments:
`graph`: The result of calling `topological_sort`.
"""
# Forward pass
for n in graph:
n.forward()
# Backward pass
# see: https://docs.python.org/2.3/whatsnew/section-slices.html
for n in graph[::-1]:
n.backward()
| Node.__init__(self, [node]) |
blank.go | /* This code originated as a project for the COMP 520 class at McGill
* University in Winter 2015. Any subsequent COMP 520 student who is
* viewing this code must follow the course rules and report any viewing
* and/or use of the code. */ |
func main() {
a, _ := 0, 1
_, b := 4, 5
println(a, b)
} |
package main |
SocialMedia.tsx | import React from 'react';
import styled from 'styled-components';
import styledContainerQuery from 'styled-container-query'
import { color, Device } from '../styles/theme';
import { WrapperSection, TitleSection } from '../styles/GlobalStyle.css';
import Facebbok from '../assets/social-media/facebook.png';
import Instagram from '../assets/social-media/instagram.png';
import Twitter from '../assets/social-media/twitter.png';
import { urls } from '../domain/website';
const Items = styled.div`
align-items: center;
justify-content: center;
display: flex;
flex-direction: row;
width: 80%; |
@media ${Device.mobile} {
width: 100%;
}
`;
const Item = styled.a`
flex: 1;
text-align: center;
`;
const Title = styled(TitleSection)`
width: 20%;
float: left;
text-align: center;
margin: 0;
@media ${Device.mobile} {
width: 100%;
margin-bottom: 20px;
}
`;
const Wrapper = styled(WrapperSection)``;
const Container = styledContainerQuery.div`
min-height: 5em;
height: 100%;
grid-area: social-media;
display: flex;
align-items: center;
justify-content: center;
@media ${Device.mobile} {
padding: 30px 0;
display: initial;
}
&:container(max-width: 450px){
padding: 30px 0;
display: initial;
${Items}{
width: 100%;
}
${Title}{
width: 100%;
margin-bottom: 20px;
}
}
`;
const SocialMedia = () => {
return (
<Container color={color.background.white}>
<Title>Śledź nas na:</Title>
<Items>
<Item href={urls.external.polaSocialMedia.facebook.href} target="blank">
<img src={Facebbok} />
</Item>
<Item href={urls.external.polaSocialMedia.instagram.href} target="blank">
<img src={Instagram} />
</Item>
<Item href={urls.external.polaSocialMedia.twitter.href} target="blank">
<img src={Twitter} />
</Item>
<Item>
</Item>
</Items>
</Container>
);
};
export default SocialMedia; | float: left; |
SortedList.py | class SortedList:
""" |
_list = list()
def __init__(self, arg: list or tuple) -> None:
try:
if type(arg) == list:
self._list = arg
elif type(arg) == tuple:
self._list = self.tuple_to_list(arg)
except:
raise TypeError("It is not a list or tuple.")
self.sort()
@staticmethod
def tuple_to_list(argtuple: tuple) -> list:
return [i for i in argtuple]
def __str__(self) -> str:
return str(self._list)
def sort(self) -> None:
if not (self.__class__.__name__) == "SortedList":
raise NotImplementedError("Please implement this method.")
else:
pass
if __name__ == "__main__":
obj = SortedList((2, 3, 4))
print(obj) | This is a list object which is sorted. Actually
this is not sorted now. Because this is a parent
class.
""" |
rule.rs | use crate::entity::Entity;
use super::Property;
use crate::state::storage::dense_storage::DenseStorage;
use crate::style::{Relation, Selector, Specificity};
#[derive(Clone, Debug)] | }
impl StyleRule {
pub fn new() -> Self {
StyleRule {
selectors: Vec::new(),
properties: Vec::new(),
}
}
pub fn selector(mut self, selector: Selector) -> Self {
self.selectors.push(selector);
self
}
pub fn parent_selector(mut self, mut selector: Selector) -> Self {
selector.relation = Relation::Parent;
self.selectors.push(selector);
self
}
pub fn property(mut self, property: Property) -> Self {
self.properties.push(property);
self
}
pub fn specificity(&self) -> Specificity {
let mut specificity = Specificity([0, 0, 0]);
for selector in self.selectors.iter() {
specificity += selector.specificity();
}
return specificity;
}
} | pub struct StyleRule {
pub selectors: Vec<Selector>,
pub properties: Vec<Property>, |
borrows.rs | use std::fmt::Debug;
use std::fmt::Display;
use std::ops::Deref;
use std::ops::DerefMut;
use std::slice::Iter;
use std::slice::IterMut;
use std::sync::atomic::{AtomicIsize, Ordering};
/// Tracks the borrowing of a piece of memory.
pub enum Borrow<'a> {
Read { state: &'a AtomicIsize },
Write { state: &'a AtomicIsize },
}
impl<'a> Borrow<'a> {
/// Attempts to aquire a readonly borrow.
pub fn aquire_read(state: &'a AtomicIsize) -> Result<Borrow<'a>, &'static str> {
loop {
let read = state.load(Ordering::SeqCst);
if read < 0 {
return Err("resource already borrowed as mutable");
}
if state.compare_and_swap(read, read + 1, Ordering::SeqCst) == read {
break;
}
}
Ok(Borrow::Read { state })
}
/// Attempts to aquire a mutable borrow.
pub fn aquire_write(state: &'a AtomicIsize) -> Result<Borrow<'a>, &'static str> {
let borrowed = state.compare_and_swap(0, -1, Ordering::SeqCst);
match borrowed {
0 => Ok(Borrow::Write { state }),
x if x < 0 => Err("resource already borrowed as mutable"),
_ => Err("resource already borrowed as immutable"),
}
}
}
impl<'a> Drop for Borrow<'a> {
fn drop(&mut self) {
match *self {
Borrow::Read { state } => {
state.fetch_sub(1, Ordering::SeqCst);
}
Borrow::Write { state } => {
state.store(0, Ordering::SeqCst);
}
};
}
}
/// Represents a piece of runtime borrow checked data.
pub struct Borrowed<'a, T: 'a> {
value: &'a T,
#[allow(dead_code)]
// held for drop impl
state: Borrow<'a>,
}
impl<'a, T: 'a> Borrowed<'a, T> {
/// Constructs a new `Borrowed<'a, T>`.
pub fn new(value: &'a T, borrow: Borrow<'a>) -> Borrowed<'a, T> {
Borrowed {
value,
state: borrow,
}
}
}
impl<'a, 'b, T: 'a + Debug> Debug for Borrowed<'a, T> {
fn fmt(&self, formatter: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
self.value.fmt(formatter)
}
}
impl<'a, 'b, T: 'a + Display> Display for Borrowed<'a, T> {
fn fmt(&self, formatter: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
self.value.fmt(formatter)
}
}
impl<'a, 'b, T: 'a + PartialEq<T>> PartialEq<Borrowed<'b, T>> for Borrowed<'a, T> {
fn eq(&self, other: &Borrowed<'b, T>) -> bool {
self.value.eq(other.value)
}
}
impl<'a, 'b, T: 'a + PartialEq<T>> PartialEq<T> for Borrowed<'a, T> {
fn eq(&self, other: &T) -> bool {
self.value.eq(other)
}
}
impl<'a, 'b, T: 'a + Eq> Eq for Borrowed<'a, T> {}
impl<'a, T: 'a> Deref for Borrowed<'a, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.value
}
}
impl<'a, T: 'a> AsRef<T> for Borrowed<'a, T> {
fn as_ref(&self) -> &T {
self.value
}
}
impl<'a, T: 'a> std::borrow::Borrow<T> for Borrowed<'a, T> {
fn borrow(&self) -> &T {
self.value
}
}
/// Represents a piece of mutable runtime borrow checked data.
pub struct BorrowedMut<'a, T: 'a> {
value: &'a mut T,
#[allow(dead_code)]
// held for drop impl
state: Borrow<'a>,
}
impl<'a, T: 'a> BorrowedMut<'a, T> {
/// Constructs a new `Borrowedmut<'a, T>`.
pub fn new(value: &'a mut T, borrow: Borrow<'a>) -> BorrowedMut<'a, T> {
BorrowedMut {
value,
state: borrow,
}
}
}
impl<'a, T: 'a> Deref for BorrowedMut<'a, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.value
}
}
impl<'a, T: 'a> DerefMut for BorrowedMut<'a, T> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.value
}
}
impl<'a, T: 'a> AsRef<T> for BorrowedMut<'a, T> {
fn as_ref(&self) -> &T {
self.value
}
}
impl<'a, T: 'a> std::borrow::Borrow<T> for BorrowedMut<'a, T> {
fn borrow(&self) -> &T {
self.value
}
}
impl<'a, 'b, T: 'a + Debug> Debug for BorrowedMut<'a, T> {
fn fmt(&self, formatter: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
self.value.fmt(formatter)
}
}
impl<'a, 'b, T: 'a + Display> Display for BorrowedMut<'a, T> {
fn fmt(&self, formatter: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
self.value.fmt(formatter)
}
}
/// Represents a runtime borrow checked slice.
pub struct BorrowedSlice<'a, T: 'a> {
slice: &'a [T],
state: Borrow<'a>,
}
impl<'a, T: 'a> BorrowedSlice<'a, T> {
/// Constructs a new `BorrowedSlice<'a, T>`.
pub fn new(slice: &'a [T], borrow: Borrow<'a>) -> BorrowedSlice<'a, T> {
BorrowedSlice {
slice,
state: borrow,
}
}
/// Borrows a single element from the slice.
pub fn single(self, i: usize) -> Option<Borrowed<'a, T>> {
let slice = self.slice;
let state = self.state;
slice.get(i).map(|x| Borrowed::new(x, state))
}
}
impl<'a, T: 'a> Deref for BorrowedSlice<'a, T> {
type Target = [T];
fn | (&self) -> &Self::Target {
self.slice
}
}
impl<'a, T: 'a> IntoIterator for BorrowedSlice<'a, T> {
type Item = &'a T;
type IntoIter = BorrowedIter<'a, Iter<'a, T>>;
fn into_iter(self) -> Self::IntoIter {
BorrowedIter {
inner: self.slice.into_iter(),
state: self.state,
}
}
}
/// Represents a runtime borrow checked mut slice.
pub struct BorrowedMutSlice<'a, T: 'a> {
slice: &'a mut [T],
state: Borrow<'a>,
}
impl<'a, T: 'a> BorrowedMutSlice<'a, T> {
/// Constructs a new `BorrowedMutSlice<'a, T>`.
pub fn new(slice: &'a mut [T], borrow: Borrow<'a>) -> BorrowedMutSlice<'a, T> {
BorrowedMutSlice {
slice,
state: borrow,
}
}
/// Borrows a single element from the slice.
pub fn single(self, i: usize) -> Option<BorrowedMut<'a, T>> {
let slice = self.slice;
let state = self.state;
slice.get_mut(i).map(|x| BorrowedMut::new(x, state))
}
}
impl<'a, T: 'a> Deref for BorrowedMutSlice<'a, T> {
type Target = [T];
fn deref(&self) -> &Self::Target {
self.slice
}
}
impl<'a, T: 'a> DerefMut for BorrowedMutSlice<'a, T> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.slice
}
}
impl<'a, T: 'a> IntoIterator for BorrowedMutSlice<'a, T> {
type Item = &'a mut T;
type IntoIter = BorrowedIter<'a, IterMut<'a, T>>;
fn into_iter(self) -> Self::IntoIter {
BorrowedIter {
inner: self.slice.into_iter(),
state: self.state,
}
}
}
/// Represents a runtime borrow checked iterator.
pub struct BorrowedIter<'a, I: 'a + Iterator> {
inner: I,
#[allow(dead_code)]
// held for drop impl
state: Borrow<'a>,
}
impl<'a, I: 'a + Iterator> Iterator for BorrowedIter<'a, I> {
type Item = I::Item;
fn next(&mut self) -> Option<Self::Item> {
self.inner.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
}
impl<'a, I: 'a + ExactSizeIterator> ExactSizeIterator for BorrowedIter<'a, I> {}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicIsize, Ordering};
#[test]
fn borrow_read() {
let state = AtomicIsize::new(0);
let x = 5u8;
let _borrow = Borrowed::new(&x, Borrow::aquire_read(&state).unwrap());
assert_eq!(1, state.load(Ordering::SeqCst));
}
#[test]
fn drop_read() {
let state = AtomicIsize::new(0);
let x = 5u8;
{
let _borrow = Borrowed::new(&x, Borrow::aquire_read(&state).unwrap());
assert_eq!(1, state.load(Ordering::SeqCst));
}
assert_eq!(0, state.load(Ordering::SeqCst));
}
#[test]
fn borrow_write() {
let state = AtomicIsize::new(0);
let x = 5u8;
let _borrow = Borrowed::new(&x, Borrow::aquire_write(&state).unwrap());
assert_eq!(-1, state.load(Ordering::SeqCst));
}
#[test]
fn drop_write() {
let state = AtomicIsize::new(0);
let x = 5u8;
{
let _borrow = Borrowed::new(&x, Borrow::aquire_write(&state).unwrap());
assert_eq!(-1, state.load(Ordering::SeqCst));
}
assert_eq!(0, state.load(Ordering::SeqCst));
}
#[test]
fn read_while_reading() {
let state = AtomicIsize::new(0);
let _read = Borrow::aquire_read(&state).unwrap();
let _read2 = Borrow::aquire_read(&state).unwrap();
}
#[test]
#[should_panic(expected = "resource already borrowed as immutable")]
fn write_while_reading() {
let state = AtomicIsize::new(0);
let _read = Borrow::aquire_read(&state).unwrap();
let _write = Borrow::aquire_write(&state).unwrap();
}
#[test]
#[should_panic(expected = "resource already borrowed as mutable")]
fn read_while_writing() {
let state = AtomicIsize::new(0);
let _write = Borrow::aquire_write(&state).unwrap();
let _read = Borrow::aquire_read(&state).unwrap();
}
#[test]
#[should_panic(expected = "resource already borrowed as mutable")]
fn write_while_writing() {
let state = AtomicIsize::new(0);
let _write = Borrow::aquire_write(&state).unwrap();
let _write2 = Borrow::aquire_write(&state).unwrap();
}
}
| deref |
format4.rs | use core::convert::TryFrom;
use crate::parser::{Array, LazyArray16, Stream};
use crate::GlyphId;
/// A [format 4](https://docs.microsoft.com/en-us/typography/opentype/spec/cmap#format-4-segment-mapping-to-delta-values)
/// subtable.
#[derive(Clone, Copy)]
pub struct Subtable4<'a> {
start_codes: LazyArray16<'a, u16>,
end_codes: LazyArray16<'a, u16>,
id_deltas: LazyArray16<'a, i16>,
id_range_offsets: LazyArray16<'a, u16>,
id_range_offset_pos: usize,
// The whole subtable data.
data: &'a [u8],
}
impl<'a> Subtable4<'a> {
/// Parses a subtable from raw data.
pub fn parse(data: &'a [u8]) -> Option<Self> {
let mut s = Stream::new(data);
s.advance(6); // format + length + language
let seg_count_x2 = s.read::<u16>()?;
if seg_count_x2 < 2 {
return None;
}
let seg_count = seg_count_x2 / 2;
s.advance(6); // searchRange + entrySelector + rangeShift
let end_codes = s.read_array16::<u16>(seg_count)?;
s.skip::<u16>(); // reservedPad
let start_codes = s.read_array16::<u16>(seg_count)?;
let id_deltas = s.read_array16::<i16>(seg_count)?;
let id_range_offset_pos = s.offset();
let id_range_offsets = s.read_array16::<u16>(seg_count)?;
Some(Self {
start_codes,
end_codes,
id_deltas,
id_range_offsets,
id_range_offset_pos,
data,
})
}
/// Returns a glyph index for a code point.
///
/// Returns `None` when `code_point` is larger than `u16`.
pub fn glyph_index(&self, code_point: u32) -> Option<GlyphId> {
// This subtable supports code points only in a u16 range.
let code_point = u16::try_from(code_point).ok()?;
// A custom binary search.
let mut start = 0;
let mut end = self.start_codes.len();
while end > start {
let index = (start + end) / 2;
let end_value = self.end_codes.get(index)?;
if end_value >= code_point {
let start_value = self.start_codes.get(index)?;
if start_value > code_point {
end = index;
} else {
let id_range_offset = self.id_range_offsets.get(index)?;
let id_delta = self.id_deltas.get(index)?;
if id_range_offset == 0 {
return Some(GlyphId(code_point.wrapping_add(id_delta as u16)));
}
let delta = (u32::from(code_point) - u32::from(start_value)) * 2;
let delta = u16::try_from(delta).ok()?;
let id_range_offset_pos = (self.id_range_offset_pos + usize::from(index) * 2) as u16;
let pos = id_range_offset_pos.wrapping_add(delta);
let pos = pos.wrapping_add(id_range_offset);
let glyph_array_value: u16 = Stream::read_at(self.data, usize::from(pos))?;
// 0 indicates missing glyph.
if glyph_array_value == 0 |
let glyph_id = (glyph_array_value as i16).wrapping_add(id_delta);
return u16::try_from(glyph_id).ok().map(GlyphId);
}
} else {
start = index + 1;
}
}
None
}
/// Calls `f` for each codepoint defined in this table.
pub fn codepoints(&self, mut f: impl FnMut(u32)) {
for (start, end) in self.start_codes.into_iter().zip(self.end_codes) {
for code_point in start..=end {
f(u32::from(code_point));
}
}
}
}
impl core::fmt::Debug for Subtable4<'_> {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
write!(f, "Subtable4 {{ ... }}")
}
}
| {
return None;
} |
bitrpc.py | from jsonrpc import ServiceProxy
import sys
import string
import getpass
# ===== BEGIN USER SETTINGS =====
# if you do not set these you will be prompted for a password for every command
rpcuser = ""
rpcpass = ""
# ====== END USER SETTINGS ======
if rpcpass == "":
access = ServiceProxy("http://127.0.0.1:6666")
else:
access = ServiceProxy("http://"+rpcuser+":"+rpcpass+"@127.0.0.1:6666")
cmd = sys.argv[1].lower()
if cmd == "backupwallet":
try:
path = raw_input("Enter destination path/filename: ")
print access.backupwallet(path)
except:
print "\n---An error occurred---\n"
elif cmd == "encryptwallet":
try:
pwd = getpass.getpass(prompt="Enter passphrase: ")
pwd2 = getpass.getpass(prompt="Repeat passphrase: ")
if pwd == pwd2:
access.encryptwallet(pwd)
print "\n---Wallet encrypted. Server stopping, restart to run with encrypted wallet---\n"
else:
print "\n---Passphrases do not match---\n"
except:
print "\n---An error occurred---\n"
elif cmd == "getaccount":
try:
addr = raw_input("Enter a Bitcoin address: ")
print access.getaccount(addr)
except:
print "\n---An error occurred---\n"
elif cmd == "getaccountaddress":
try:
acct = raw_input("Enter an account name: ")
print access.getaccountaddress(acct)
except:
print "\n---An error occurred---\n"
elif cmd == "getaddressesbyaccount":
try:
acct = raw_input("Enter an account name: ")
print access.getaddressesbyaccount(acct)
except:
print "\n---An error occurred---\n"
elif cmd == "getbalance":
try:
acct = raw_input("Enter an account (optional): ")
mc = raw_input("Minimum confirmations (optional): ")
try:
print access.getbalance(acct, mc)
except:
print access.getbalance()
except:
print "\n---An error occurred---\n"
elif cmd == "getblockbycount":
try:
height = raw_input("Height: ")
print access.getblockbycount(height)
except:
print "\n---An error occurred---\n"
elif cmd == "getblockcount":
try:
print access.getblockcount()
except:
print "\n---An error occurred---\n"
elif cmd == "getblocknumber":
try:
print access.getblocknumber()
except:
print "\n---An error occurred---\n"
elif cmd == "getconnectioncount":
try:
print access.getconnectioncount()
except:
print "\n---An error occurred---\n"
elif cmd == "getdifficulty":
try:
print access.getdifficulty()
except:
print "\n---An error occurred---\n"
elif cmd == "getgenerate":
try:
print access.getgenerate()
except:
print "\n---An error occurred---\n"
elif cmd == "gethashespersec":
try:
print access.gethashespersec()
except:
print "\n---An error occurred---\n"
elif cmd == "getinfo":
try:
print access.getinfo()
except:
print "\n---An error occurred---\n"
elif cmd == "getnewaddress":
try:
acct = raw_input("Enter an account name: ")
try:
print access.getnewaddress(acct)
except:
print access.getnewaddress()
except:
print "\n---An error occurred---\n"
elif cmd == "getreceivedbyaccount":
try:
acct = raw_input("Enter an account (optional): ")
mc = raw_input("Minimum confirmations (optional): ")
try:
print access.getreceivedbyaccount(acct, mc)
except:
print access.getreceivedbyaccount()
except:
print "\n---An error occurred---\n"
elif cmd == "getreceivedbyaddress":
try:
addr = raw_input("Enter a Bitcoin address (optional): ")
mc = raw_input("Minimum confirmations (optional): ")
try:
print access.getreceivedbyaddress(addr, mc)
except:
print access.getreceivedbyaddress()
except:
print "\n---An error occurred---\n"
elif cmd == "gettransaction":
try:
txid = raw_input("Enter a transaction ID: ")
print access.gettransaction(txid)
except:
print "\n---An error occurred---\n"
elif cmd == "getwork":
try:
data = raw_input("Data (optional): ")
try:
print access.gettransaction(data)
except:
print access.gettransaction()
except:
print "\n---An error occurred---\n"
elif cmd == "help":
try:
cmd = raw_input("Command (optional): ")
try:
print access.help(cmd)
except:
print access.help()
except:
print "\n---An error occurred---\n"
elif cmd == "listaccounts":
try:
mc = raw_input("Minimum confirmations (optional): ")
try:
print access.listaccounts(mc)
except:
print access.listaccounts()
except:
print "\n---An error occurred---\n"
elif cmd == "listreceivedbyaccount":
try:
mc = raw_input("Minimum confirmations (optional): ")
incemp = raw_input("Include empty? (true/false, optional): ")
try:
print access.listreceivedbyaccount(mc, incemp)
except:
print access.listreceivedbyaccount()
except:
print "\n---An error occurred---\n"
elif cmd == "listreceivedbyaddress":
try:
mc = raw_input("Minimum confirmations (optional): ")
incemp = raw_input("Include empty? (true/false, optional): ")
try:
print access.listreceivedbyaddress(mc, incemp)
except:
print access.listreceivedbyaddress()
except:
print "\n---An error occurred---\n"
elif cmd == "listtransactions":
try:
acct = raw_input("Account (optional): ")
count = raw_input("Number of transactions (optional): ")
frm = raw_input("Skip (optional):")
try:
print access.listtransactions(acct, count, frm)
except:
print access.listtransactions()
except:
print "\n---An error occurred---\n"
elif cmd == "move":
try:
frm = raw_input("From: ")
to = raw_input("To: ")
amt = raw_input("Amount:")
mc = raw_input("Minimum confirmations (optional): ")
comment = raw_input("Comment (optional): ")
try:
print access.move(frm, to, amt, mc, comment)
except:
print access.move(frm, to, amt)
except:
print "\n---An error occurred---\n"
elif cmd == "sendfrom":
try:
frm = raw_input("From: ")
to = raw_input("To: ")
amt = raw_input("Amount:")
mc = raw_input("Minimum confirmations (optional): ")
comment = raw_input("Comment (optional): ")
commentto = raw_input("Comment-to (optional): ")
try:
print access.sendfrom(frm, to, amt, mc, comment, commentto)
except:
print access.sendfrom(frm, to, amt)
except:
print "\n---An error occurred---\n"
elif cmd == "sendmany":
try:
frm = raw_input("From: ")
to = raw_input("To (in format address1:amount1,address2:amount2,...): ")
mc = raw_input("Minimum confirmations (optional): ")
comment = raw_input("Comment (optional): ")
try:
print access.sendmany(frm,to,mc,comment)
except:
print access.sendmany(frm,to)
except:
print "\n---An error occurred---\n"
elif cmd == "sendtoaddress":
try:
to = raw_input("To (in format address1:amount1,address2:amount2,...): ")
amt = raw_input("Amount:")
comment = raw_input("Comment (optional): ")
commentto = raw_input("Comment-to (optional): ")
try:
print access.sendtoaddress(to,amt,comment,commentto)
except:
print access.sendtoaddress(to,amt)
except:
print "\n---An error occurred---\n"
elif cmd == "setaccount":
try:
addr = raw_input("Address: ")
acct = raw_input("Account:")
print access.setaccount(addr,acct)
except:
print "\n---An error occurred---\n"
elif cmd == "setgenerate":
try:
gen= raw_input("Generate? (true/false): ")
cpus = raw_input("Max processors/cores (-1 for unlimited, optional):")
try:
print access.setgenerate(gen, cpus)
except:
print access.setgenerate(gen)
except:
print "\n---An error occurred---\n"
elif cmd == "settxfee":
try:
amt = raw_input("Amount:")
print access.settxfee(amt)
except:
print "\n---An error occurred---\n"
elif cmd == "stop":
try:
print access.stop()
except:
print "\n---An error occurred---\n"
elif cmd == "validateaddress":
|
elif cmd == "walletpassphrase":
try:
pwd = getpass.getpass(prompt="Enter wallet passphrase: ")
access.walletpassphrase(pwd, 60)
print "\n---Wallet unlocked---\n"
except:
print "\n---An error occurred---\n"
elif cmd == "walletpassphrasechange":
try:
pwd = getpass.getpass(prompt="Enter old wallet passphrase: ")
pwd2 = getpass.getpass(prompt="Enter new wallet passphrase: ")
access.walletpassphrasechange(pwd, pwd2)
print
print "\n---Passphrase changed---\n"
except:
print
print "\n---An error occurred---\n"
print
else:
print "Command not found or not supported"
| try:
addr = raw_input("Address: ")
print access.validateaddress(addr)
except:
print "\n---An error occurred---\n" |
tests_complexity.py | import numpy as np
import pandas as pd
import neurokit2 as nk
import nolds
from pyentrp import entropy as pyentrp
"""
For the testing of complexity, we test our implementations against existing and established ones.
However, some of these other implementations are not really packaged in a way
SO THAT we can easily import them. Thus, we directly copied their content in this file
(below the tests).
"""
# =============================================================================
# Some sanity checks
# =============================================================================
def test_complexity_sanity():
signal = np.cos(np.linspace(start=0, stop=30, num=1000))
# Entropy
assert np.allclose(nk.entropy_fuzzy(signal), nk.entropy_sample(signal, fuzzy=True), atol=0.000001)
# Fractal
assert np.allclose(nk.fractal_dfa(signal, windows=np.array([4, 8, 12, 20])), 2.1009048365682133, atol=0.000001)
assert np.allclose(nk.fractal_dfa(signal), 1.957966586191164, atol=0.000001)
assert np.allclose(nk.fractal_dfa(signal, multifractal=True), 1.957966586191164, atol=0.000001)
assert np.allclose(nk.fractal_correlation(signal), 0.7884473170763334, atol=0.000001)
assert np.allclose(nk.fractal_correlation(signal, r="nolds"), nolds.corr_dim(signal, 2), atol=0.0001)
# =============================================================================
# Comparison against R
# =============================================================================
"""
R code:
library(TSEntropies)
library(pracma)
signal <- read.csv("https://raw.githubusercontent.com/neuropsychology/NeuroKit/master/data/bio_eventrelated_100hz.csv")$RSP
r <- 0.2 * sd(signal)
# ApEn --------------------------------------------------------------------
TSEntropies::ApEn(signal, dim=2, lag=1, r=r)
0.04383386
TSEntropies::ApEn(signal, dim=3, lag=2, r=1)
0.0004269369
pracma::approx_entropy(signal[1:200], edim=2, r=r, elag=1)
0.03632554
# SampEn ------------------------------------------------------------------
TSEntropies::SampEn(signal[1:300], dim=2, lag=1, r=r)
0.04777648
TSEntropies::FastSampEn(signal[1:300], dim=2, lag=1, r=r)
0.003490405
pracma::sample_entropy(signal[1:300], edim=2, tau=1, r=r)
0.03784376
pracma::sample_entropy(signal[1:300], edim=3, tau=2, r=r)
0.09185509
"""
def test_complexity_vs_R():
signal = pd.read_csv("https://raw.githubusercontent.com/neuropsychology/NeuroKit/master/data/bio_eventrelated_100hz.csv")["RSP"].values
r = 0.2 * np.std(signal, ddof=1)
# ApEn
apen = nk.entropy_approximate(signal, dimension=2, r=r)
assert np.allclose(apen, 0.04383386, atol=0.0001)
apen = nk.entropy_approximate(signal, dimension=3, delay=2, r=1)
assert np.allclose(apen, 0.0004269369, atol=0.0001)
apen = nk.entropy_approximate(signal[0:200], dimension=2, delay=1, r=r)
assert np.allclose(apen, 0.03632554, atol=0.0001)
# SampEn
sampen = nk.entropy_sample(signal[0:300], dimension=2, r=r)
assert np.allclose(sampen, nk.entropy_sample(signal[0:300], dimension=2, r=r, distance="infinity"), atol=0.001)
assert np.allclose(sampen, 0.03784376, atol=0.001)
sampen = nk.entropy_sample(signal[0:300], dimension=3, delay=2, r=r)
assert np.allclose(sampen, 0.09185509, atol=0.01)
# =============================================================================
# Comparison against Python implementations
# =============================================================================
def test_complexity_vs_Python():
signal = np.cos(np.linspace(start=0, stop=30, num=100))
# Shannon
shannon = nk.entropy_shannon(signal)
# assert scipy.stats.entropy(shannon, pd.Series(signal).value_counts())
assert np.allclose(shannon - pyentrp.shannon_entropy(signal), 0)
# Approximate
assert np.allclose(nk.entropy_approximate(signal), 0.17364897858477146)
assert np.allclose(nk.entropy_approximate(signal, dimension=2, r=0.2*np.std(signal, ddof=1)) - entropy_app_entropy(signal, 2), 0)
assert nk.entropy_approximate(signal, dimension=2, r=0.2*np.std(signal, ddof=1)) != pyeeg_ap_entropy(signal, 2, 0.2*np.std(signal, ddof=1))
# Sample
assert np.allclose(nk.entropy_sample(signal, dimension=2, r=0.2*np.std(signal, ddof=1)) - entropy_sample_entropy(signal, 2), 0)
assert np.allclose(nk.entropy_sample(signal, dimension=2, r=0.2) - nolds.sampen(signal, 2, 0.2), 0)
assert np.allclose(nk.entropy_sample(signal, dimension=2, r=0.2) - entro_py_sampen(signal, 2, 0.2, scale=False), 0)
assert np.allclose(nk.entropy_sample(signal, dimension=2, r=0.2) - pyeeg_samp_entropy(signal, 2, 0.2), 0)
# import sampen
# sampen.sampen2(signal[0:300], mm=2, r=r)
assert nk.entropy_sample(signal, dimension=2, r=0.2) != pyentrp.sample_entropy(signal, 2, 0.2)[1]
assert nk.entropy_sample(signal, dimension=2, r=0.2*np.sqrt(np.var(signal))) != MultiscaleEntropy_sample_entropy(signal, 2, 0.2)[0.2][2]
# MSE
# assert nk.entropy_multiscale(signal, 2, 0.2*np.sqrt(np.var(signal))) != np.trapz(MultiscaleEntropy_mse(signal, [i+1 for i in range(10)], 2, 0.2, return_type="list"))
# assert nk.entropy_multiscale(signal, 2, 0.2*np.std(signal, ddof=1)) != np.trapz(pyentrp.multiscale_entropy(signal, 2, 0.2, 10))
# Fuzzy
assert np.allclose(nk.entropy_fuzzy(signal, dimension=2, r=0.2, delay=1) - entro_py_fuzzyen(signal, 2, 0.2, 1, scale=False), 0)
# DFA
assert nk.fractal_dfa(signal, windows=np.array([4, 8, 12, 20])) != nolds.dfa(signal, nvals=[4, 8, 12, 20], fit_exp="poly")
# =============================================================================
# Wikipedia
# =============================================================================
def wikipedia_sampen(signal, m=2, r=1):
|
# =============================================================================
# Pyeeg
# =============================================================================
def pyeeg_embed_seq(time_series, tau, embedding_dimension):
if not type(time_series) == np.ndarray:
typed_time_series = np.asarray(time_series)
else:
typed_time_series = time_series
shape = (
typed_time_series.size - tau * (embedding_dimension - 1),
embedding_dimension
)
strides = (typed_time_series.itemsize, tau * typed_time_series.itemsize)
return np.lib.stride_tricks.as_strided(
typed_time_series,
shape=shape,
strides=strides
)
def pyeeg_bin_power(X, Band, Fs):
C = np.fft.fft(X)
C = abs(C)
Power = np.zeros(len(Band) - 1)
for Freq_Index in range(0, len(Band) - 1):
Freq = float(Band[Freq_Index])
Next_Freq = float(Band[Freq_Index + 1])
Power[Freq_Index] = sum(
C[int(np.floor(Freq / Fs * len(X))):
int(np.floor(Next_Freq / Fs * len(X)))]
)
Power_Ratio = Power / sum(Power)
return Power, Power_Ratio
def pyeeg_ap_entropy(X, M, R):
N = len(X)
Em = pyeeg_embed_seq(X, 1, M)
A = np.tile(Em, (len(Em), 1, 1))
B = np.transpose(A, [1, 0, 2])
D = np.abs(A - B) # D[i,j,k] = |Em[i][k] - Em[j][k]|
InRange = np.max(D, axis=2) <= R
# Probability that random M-sequences are in range
Cm = InRange.mean(axis=0)
# M+1-sequences in range if M-sequences are in range & last values are close
Dp = np.abs(
np.tile(X[M:], (N - M, 1)) - np.tile(X[M:], (N - M, 1)).T
)
Cmp = np.logical_and(Dp <= R, InRange[:-1, :-1]).mean(axis=0)
Phi_m, Phi_mp = np.sum(np.log(Cm)), np.sum(np.log(Cmp))
Ap_En = (Phi_m - Phi_mp) / (N - M)
return Ap_En
def pyeeg_samp_entropy(X, M, R):
N = len(X)
Em = pyeeg_embed_seq(X, 1, M)[:-1]
A = np.tile(Em, (len(Em), 1, 1))
B = np.transpose(A, [1, 0, 2])
D = np.abs(A - B) # D[i,j,k] = |Em[i][k] - Em[j][k]|
InRange = np.max(D, axis=2) <= R
np.fill_diagonal(InRange, 0) # Don't count self-matches
Cm = InRange.sum(axis=0) # Probability that random M-sequences are in range
Dp = np.abs(
np.tile(X[M:], (N - M, 1)) - np.tile(X[M:], (N - M, 1)).T
)
Cmp = np.logical_and(Dp <= R, InRange).sum(axis=0)
# Avoid taking log(0)
Samp_En = np.log(np.sum(Cm + 1e-100) / np.sum(Cmp + 1e-100))
return Samp_En
# =============================================================================
# Entropy
# =============================================================================
from sklearn.neighbors import KDTree
def entropy_embed(x, order=3, delay=1):
N = len(x)
if order * delay > N:
raise ValueError("Error: order * delay should be lower than x.size")
if delay < 1:
raise ValueError("Delay has to be at least 1.")
if order < 2:
raise ValueError("Order has to be at least 2.")
Y = np.zeros((order, N - (order - 1) * delay))
for i in range(order):
Y[i] = x[i * delay:i * delay + Y.shape[1]]
return Y.T
def entropy_app_samp_entropy(x, order, metric='chebyshev', approximate=True):
_all_metrics = KDTree.valid_metrics
if metric not in _all_metrics:
raise ValueError('The given metric (%s) is not valid. The valid '
'metric names are: %s' % (metric, _all_metrics))
phi = np.zeros(2)
r = 0.2 * np.std(x, axis=-1, ddof=1)
# compute phi(order, r)
_emb_data1 = entropy_embed(x, order, 1)
if approximate:
emb_data1 = _emb_data1
else:
emb_data1 = _emb_data1[:-1]
count1 = KDTree(emb_data1, metric=metric).query_radius(emb_data1, r,
count_only=True
).astype(np.float64)
# compute phi(order + 1, r)
emb_data2 = entropy_embed(x, order + 1, 1)
count2 = KDTree(emb_data2, metric=metric).query_radius(emb_data2, r,
count_only=True
).astype(np.float64)
if approximate:
phi[0] = np.mean(np.log(count1 / emb_data1.shape[0]))
phi[1] = np.mean(np.log(count2 / emb_data2.shape[0]))
else:
phi[0] = np.mean((count1 - 1) / (emb_data1.shape[0] - 1))
phi[1] = np.mean((count2 - 1) / (emb_data2.shape[0] - 1))
return phi
def entropy_app_entropy(x, order=2, metric='chebyshev'):
phi = entropy_app_samp_entropy(x, order=order, metric=metric, approximate=True)
return np.subtract(phi[0], phi[1])
def entropy_sample_entropy(x, order=2, metric='chebyshev'):
x = np.asarray(x, dtype=np.float64)
phi = entropy_app_samp_entropy(x, order=order, metric=metric,
approximate=False)
return -np.log(np.divide(phi[1], phi[0]))
# =============================================================================
# entro-py
# =============================================================================
def entro_py_sampen(x, dim, r, scale=True):
return entro_py_entropy(x, dim, r, scale=scale)
def entro_py_cross_sampen(x1, x2, dim, r, scale=True):
return entro_py_entropy([x1, x2], dim, r, scale)
def entro_py_fuzzyen(x, dim, r, n, scale=True):
return entro_py_entropy(x, dim, r, n=n, scale=scale, remove_baseline=True)
def entro_py_cross_fuzzyen(x1, x2, dim, r, n, scale=True):
return entro_py_entropy([x1, x2], dim, r, n, scale=scale, remove_baseline=True)
def entro_py_pattern_mat(x, m):
x = np.asarray(x).ravel()
if m == 1:
return x
else:
N = len(x)
patterns = np.zeros((m, N-m+1))
for i in range(m):
patterns[i, :] = x[i:N-m+i+1]
return patterns
def entro_py_entropy(x, dim, r, n=1, scale=True, remove_baseline=False):
fuzzy = True if remove_baseline else False
cross = True if type(x) == list else False
N = len(x[0]) if cross else len(x)
if scale:
if cross:
x = [entro_py_scale(np.copy(x[0])), entro_py_scale(np.copy(x[1]))]
else:
x = entro_py_scale(np.copy(x))
phi = [0, 0] # phi(m), phi(m+1)
for j in [0, 1]:
m = dim + j
npat = N-dim # https://github.com/ixjlyons/entro-py/pull/2/files
if cross:
# patterns = [entro_py_pattern_mat(x[0], m), entro_py_pattern_mat(x[1], m)]
patterns = [entro_py_pattern_mat(x[0], m)[:, :npat], entro_py_pattern_mat(x[1], m)[:, :npat]] # https://github.com/ixjlyons/entro-py/pull/2/files
else:
# patterns = entro_py_pattern_mat(x, m)
patterns = entro_py_pattern_mat(x, m)[:, :npat]
if remove_baseline:
if cross:
patterns[0] = entro_py_remove_baseline(patterns[0], axis=0)
patterns[1] = entro_py_remove_baseline(patterns[1], axis=0)
else:
patterns = entro_py_remove_baseline(patterns, axis=0)
# count = np.zeros(N-m) # https://github.com/ixjlyons/entro-py/pull/2/files
# for i in range(N-m): # https://github.com/ixjlyons/entro-py/pull/2/files
count = np.zeros(npat)
for i in range(npat):
if cross:
if m == 1:
sub = patterns[1][i]
else:
sub = patterns[1][:, [i]]
dist = np.max(np.abs(patterns[0] - sub), axis=0)
else:
if m == 1:
sub = patterns[i]
else:
sub = patterns[:, [i]]
dist = np.max(np.abs(patterns - sub), axis=0)
if fuzzy:
sim = np.exp(-np.power(dist, n) / r)
else:
sim = dist < r
count[i] = np.sum(sim) - 1
# phi[j] = np.mean(count) / (N-m-1)
phi[j] = np.mean(count) / (N-dim-1) # https://github.com/ixjlyons/entro-py/pull/2/files
return np.log(phi[0] / phi[1])
def entro_py_scale(x, axis=None):
x = entro_py_remove_baseline(x, axis=axis)
x /= np.std(x, ddof=1, axis=axis, keepdims=True)
return x
def entro_py_remove_baseline(x, axis=None):
x -= np.mean(x, axis=axis, keepdims=True)
return x
# =============================================================================
# MultiscaleEntropy https://github.com/reatank/MultiscaleEntropy/blob/master/MultiscaleEntropy/mse.py
# =============================================================================
import math
from collections.abc import Iterable
def MultiscaleEntropy_init_return_type(return_type):
if return_type == 'dict':
return {}
else:
return []
def MultiscaleEntropy_check_type(x, num_type, name):
if isinstance(x, num_type):
tmp = [x]
elif not isinstance(x, Iterable):
raise ValueError(name + ' should be a ' + num_type.__name__ + ' or an iterator of ' + num_type.__name__)
else:
tmp = []
for i in x:
tmp.append(i)
if not isinstance(i, num_type):
raise ValueError(name + ' should be a ' + num_type.__name__ + ' or an iterator of ' + num_type.__name__)
return tmp
# sum of seperate intervals of x
def MultiscaleEntropy_coarse_grain(x, scale_factor):
x = np.array(x)
x_len = len(x)
if x_len % scale_factor:
padded_len = (1+int(x_len/scale_factor))*scale_factor
else:
padded_len = x_len
tmp_x = np.zeros(padded_len)
tmp_x[:x_len] = x
tmp_x = np.reshape(tmp_x, (int(padded_len/scale_factor), scale_factor))
ans = np.reshape(np.sum(tmp_x, axis=1), (-1))/scale_factor
return ans
def MultiscaleEntropy_sample_entropy(x, m=[2], r=[0.15], sd=None, return_type='dict', safe_mode=False):
'''[Sample Entropy, the threshold will be r*sd]
Arguments:
x {[input signal]} -- [an iterator of numbers]
Keyword Arguments:
m {list} -- [m in sample entropy] (default: {[2]})
r {list} -- [r in sample entropy] (default: {[0.15]})
sd {number} -- [standard derivation of x, if None, will be calculated] (default: {None})
return_type {str} -- [can be dict or list] (default: {'dict'})
safe_mode {bool} -- [if set True, type checking will be skipped] (default: {False})
Raises:
ValueError -- [some values too big]
Returns:
[dict or list as return_type indicates] -- [if dict, nest as [scale_factor][m][r] for each value of m, r; if list, nest as [i][j] for lengths of m, r]
'''
# type checking
if not safe_mode:
m = MultiscaleEntropy_check_type(m, int, 'm')
r = MultiscaleEntropy_check_type(r, float, 'r')
if not (sd == None) and not (isinstance(sd, float) or isinstance(sd, int)):
raise ValueError('sd should be a number')
try:
x = np.array(x)
except:
raise ValueError('x should be a sequence of numbers')
# value checking
if len(x) < max(m):
raise ValueError('the max m is bigger than x\'s length')
# initialization
if sd == None:
sd = np.sqrt(np.var(x))
ans = MultiscaleEntropy_init_return_type(return_type)
# calculation
for i, rr in enumerate(r):
threshold = rr * sd
if return_type == 'dict':
ans[rr] = MultiscaleEntropy_init_return_type(return_type)
else:
ans.append(MultiscaleEntropy_init_return_type(return_type))
count = {}
tmp_m = []
for mm in m:
tmp_m.append(mm)
tmp_m.append(mm+1)
tmp_m = list(set(tmp_m))
for mm in tmp_m:
count[mm] = 0
for j in range(1, len(x)-min(m)+1):
cont = 0
for inc in range(0, len(x)-j):
if abs(x[inc]-x[j+inc]) < threshold:
cont += 1
elif cont > 0:
for mm in tmp_m:
tmp = cont - mm + 1
count[mm] += tmp if tmp > 0 else 0
cont = 0
if cont > 0:
for mm in tmp_m:
tmp = cont - mm + 1
count[mm] += tmp if tmp > 0 else 0
for mm in m:
if count[mm+1] == 0 or count[mm] == 0:
t = len(x)-mm+1
tmp = -math.log(1/(t*(t-1)))
else:
tmp = -math.log(count[mm+1]/count[mm])
if return_type == 'dict':
ans[rr][mm] = tmp
else:
ans[i].append(tmp)
return ans
def MultiscaleEntropy_mse(x, scale_factor=[i for i in range(1,21)], m=[2], r=[0.15], return_type='dict', safe_mode=False):
'''[Multiscale Entropy]
Arguments:
x {[input signal]} -- [an iterator of numbers]
Keyword Arguments:
scale_factor {list} -- [scale factors of coarse graining] (default: {[i for i in range(1,21)]})
m {list} -- [m in sample entropy] (default: {[2]})
r {list} -- [r in sample entropy] (default: {[0.15]})
return_type {str} -- [can be dict or list] (default: {'dict'})
safe_mode {bool} -- [if set True, type checking will be skipped] (default: {False})
Raises:
ValueError -- [some values too big]
Returns:
[dict or list as return_type indicates] -- [if dict, nest as [scale_factor][m][r] for each value of scale_factor, m, r; if list nest as [i][j][k] for lengths of scale_factor, m, r]
'''
# type checking
if not safe_mode:
m = MultiscaleEntropy_check_type(m, int, 'm')
r = MultiscaleEntropy_check_type(r, float, 'r')
scale_factor = MultiscaleEntropy_check_type(scale_factor, int, 'scale_factor')
try:
x = np.array(x)
except:
print('x should be a sequence of numbers')
# value checking
if max(scale_factor) > len(x):
raise ValueError('the max scale_factor is bigger than x\'s length')
# calculation
sd = np.sqrt(np.var(x))
ms_en = MultiscaleEntropy_init_return_type(return_type)
for s_f in scale_factor:
y = MultiscaleEntropy_coarse_grain(x, s_f)
if return_type == 'dict':
ms_en[s_f] = MultiscaleEntropy_sample_entropy(y, m, r, sd, 'dict', True)
else:
ms_en.append(MultiscaleEntropy_sample_entropy(y, m, r, sd, 'list', True))
if return_type == "list":
ms_en = [i[0] for i in ms_en]
ms_en = [i[0] for i in ms_en]
return ms_en
| N = len(signal)
B = 0.0
A = 0.0
# Split time series and save all templates of length m
xmi = np.array([signal[i : i + m] for i in range(N - m)])
xmj = np.array([signal[i : i + m] for i in range(N - m + 1)])
# Save all matches minus the self-match, compute B
B = np.sum([np.sum(np.abs(xmii - xmj).max(axis=1) <= r) - 1 for xmii in xmi])
# Similar for computing A
m += 1
xm = np.array([signal[i : i + m] for i in range(N - m + 1)])
A = np.sum([np.sum(np.abs(xmi - xm).max(axis=1) <= r) - 1 for xmi in xm])
# Return SampEn
return -np.log(A / B) |
ctx.go | /*
* Copyright 2021 CloudWeGo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ | import (
"context"
"github.com/cloudwego/kitex/internal"
)
type ctxRPCInfoKeyType struct{}
var ctxRPCInfoKey ctxRPCInfoKeyType
// NewCtxWithRPCInfo creates a new context with the RPCInfo given.
func NewCtxWithRPCInfo(ctx context.Context, ri RPCInfo) context.Context {
if ri != nil {
return context.WithValue(ctx, ctxRPCInfoKey, ri)
}
return ctx
}
// GetRPCInfo gets RPCInfo from ctx.
// Returns nil if not found.
func GetRPCInfo(ctx context.Context) RPCInfo {
if ri, ok := ctx.Value(ctxRPCInfoKey).(RPCInfo); ok {
return ri
}
return nil
}
// PutRPCInfo recycles the RPCInfo. This function is for internal use only.
func PutRPCInfo(ri RPCInfo) {
if v, ok := ri.(internal.Reusable); ok {
v.Recycle()
}
} |
package rpcinfo
|
plot.py | # plot.py
# --------------- #
# Import Packages #
# --------------- #
import os
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Set seaborn as default plot config
sns.set()
sns.set_style("whitegrid")
from itertools import cycle
# ---------------------------------- #
# Define Subdirectories & Info Files #
# ---------------------------------- #
data_dir = '../01_Data/'
info_dir = '../02_Info/'
plot_dir = '../04_Charts/'
# Create plot dir if necessary
if not os.path.exists(plot_dir): os.makedirs(plot_dir)
# Read in channel list & create list of sensor groups
full_channel_list = pd.read_csv(f'{info_dir}channel_list.csv', index_col='Channel_Name')
# ------------------- #
# Set Plot Parameters #
# ------------------- #
label_size = 18
tick_size = 16
line_width = 2
event_font = 12
font_rotation = 60
legend_font = 12
fig_width = 10
fig_height = 8
# ---------------------- #
# User-Defined Functions #
# ---------------------- #
def timestamp_to_seconds(timestamp):
timestamp = timestamp[11:]
hh, mm, ss = timestamp.split(':')
return(3600 * int(hh) + 60 * int(mm) + int(ss))
def convert_timestamps(timestamps, start_time):
raw_seconds = map(timestamp_to_seconds, timestamps)
return([s - start_time for s in list(raw_seconds)])
def | ():
# Define figure for the plot
fig, ax1 = plt.subplots(figsize=(fig_width, fig_height))
# Set line colors & markers; reset axis lims
current_palette_8 = sns.color_palette('deep', 8)
sns.set_palette(current_palette_8)
plot_markers = cycle(['s', 'o', '^', 'd', 'h', 'p','v', '8', 'D', '*', '<', '>', 'H'])
x_max, y_min, y_max = 0, 0, 0
return(fig, ax1, plot_markers, x_max, y_min, y_max)
def format_and_save_plot(y_lims, x_lims, secondary_axis_label, file_loc):
# Set tick parameters
ax1.tick_params(labelsize=tick_size, length=0, width=0)
# Scale axes limits & labels
ax1.grid(True)
ax1.set_ylim(bottom=y_lims[0], top=y_lims[1])
ax1.set_xlim(x_lims[0] - x_lims[1] / 500, x_lims[1])
ax1.set_xlabel('Time (s)', fontsize=label_size)
# Secondary y-axis parameters
if secondary_axis_label != 'None':
ax2 = ax1.twinx()
ax2.tick_params(labelsize=tick_size, length=0, width=0)
ax2.set_ylabel(secondary_axis_label, fontsize=label_size)
if secondary_axis_label == 'Temperature ($^\circ$F)':
ax2.set_ylim([y_lims[0] * 1.8 + 32., y_lims[1] * 1.8 + 32.])
else:
ax2.set_ylim([secondary_axis_scale * y_lims[0], secondary_axis_scale * y_lims[1]])
ax2.yaxis.grid(visible=None)
# Add vertical lines and labels for timing information (if available)
ax3 = ax1.twiny()
ax3.set_xlim(x_lims[0] - x_lims[1] / 500, x_lims[1])
ax3.set_xticks([_x for _x in Events.index.values if _x >= x_lims[0] and _x <= x_lims[1]])
ax3.tick_params(axis='x', width=1, labelrotation=font_rotation, labelsize=event_font)
ax3.set_xticklabels([Events['Event'][_x] for _x in Events.index.values if _x >= x_lims[0] and _x <= x_lims[1]], fontsize=event_font, ha='left')
ax3.xaxis.grid(visible=None)
# Add legend, clean up whitespace padding, save chart as pdf, & close fig
handles1, labels1 = ax1.get_legend_handles_labels()
ax1.legend(handles1, labels1, loc='best', fontsize=legend_font, handlelength=3, frameon=True, framealpha=0.75)
fig.tight_layout()
plt.savefig(file_loc)
plt.close()
# ----------------- #
# Main Body of Code #
# ----------------- #
# Loop through test data files & create plots
for f in os.listdir(data_dir):
# Skip if f is not a exp data file
if any([not f.endswith('.csv'), f.startswith('.'), f.endswith('_Events.csv')]):
continue
# Get test name from file & load data & event files for given experiment
test_name = f[:-4]
data_df = pd.read_csv(f'{data_dir}{f}', index_col='Time')
Events = pd.read_csv(f'{data_dir}{test_name}_Events.csv')
print (f'--- Loaded data for {test_name} ---')
# Create index column of time relative to ignition in events file
Events = pd.read_csv(f'{data_dir}{f[:-4]}_Events.csv')
Events.rename(columns={'Time':'Timestamp'}, inplace=True)
start_timestamp = Events.loc[0, 'Timestamp'][11:]
hh,mm,ss = start_timestamp.split(':')
start_time = 3600 * int(hh) + 60 * int(mm) + int(ss)
Events['Time'] = convert_timestamps(Events['Timestamp'], start_time)
Events = Events.set_index('Time')
# Define channel list as full list & drop unused channels for given experiment
channel_list = full_channel_list[[i in data_df.columns for i in full_channel_list.index]]
# Loop through channel groups to plot data from all channels in each group
for group in channel_list.groupby('Group').groups:
# Create figure for plot
print (f" Plotting {group.replace('_',' ')}")
fig, ax1, plot_markers, x_max, y_min, y_max = create_1plot_fig()
# Loop through each channel in given group
for channel in channel_list.groupby('Group').get_group(group).index.values:
# Set secondary axis default to None, get data type from channel list
secondary_axis_label = 'None'
data_type = channel_list.loc[channel, 'Type']
# Set plot parameters based on data type
if data_type == 'Temperature':
# Set y-axis labels & y_min
ax1.set_ylabel('Temperature ($^\circ$C)', fontsize=label_size)
secondary_axis_label = 'Temperature ($^\circ$F)'
y_min = 0
elif data_type == 'Velocity':
# Apply moving average & set y-axis labels, secondary scale
data_df[channel] = data_df[channel].rolling(window=10, center=True).mean()
ax1.set_ylabel('Velocity (m/s)', fontsize=label_size)
secondary_axis_label = 'Velocity (mph)'
secondary_axis_scale = 2.23694
elif data_type == 'Pressure':
# Apply moving average & set y-axis labels, secondary scale
data_df[channel] = data_df[channel].rolling(window=10, center=True).mean()
ax1.set_ylabel('Pressure (Pa)', fontsize=label_size)
elif data_type == 'Oxygen':
# Set y-axis label
ax1.set_ylabel('O$_2$ Concentration (%)', fontsize=label_size)
elif data_type.endswith('Heat Flux'):
# Apply moving average & set y-axis label
data_df[channel] = data_df[channel].rolling(window=10, center=True).mean()
ax1.set_ylabel('Heat Flux (kW/m$^2$)', fontsize=label_size)
elif data_type == 'Heat Release Rate':
# Set y-axis label
ax1.set_ylabel('Heat Release Rate (kW)', fontsize=label_size)
# Determine x max bound for current data & update max of chart if necessary
x_end = data_df[channel].index[-1]
if x_end > x_max:
x_max = x_end
# Plot channel data
ax1.plot(data_df.index, data_df[channel], lw=line_width,
marker=next(plot_markers), markevery=30, mew=3, mec='none', ms=7,
label=channel_list.loc[channel, 'Label'])
# Check if y min/max need to be updated
if data_df[channel].min() - abs(data_df[channel].min() * .1) < y_min:
y_min = data_df[channel].min() - abs(data_df[channel].min() * .1)
if data_df[channel].max() * 1.1 > y_max:
y_max = data_df[channel].max() * 1.1
# Add vertical lines for event labels; label to y axis
[ax1.axvline(_x, color='0.25', lw=1.5) for _x in Events.index.values if _x >= 0 and _x <= x_max]
# Define/create save directory, call function to format & save plot
save_dir = f'{plot_dir}{test_name}/'
if not os.path.exists(save_dir): os.makedirs(save_dir)
format_and_save_plot([y_min, y_max], [0, x_max], secondary_axis_label, f'{save_dir}{group}.pdf')
print() | create_1plot_fig |
setup.py | # -*- coding: utf-8 -*-
import setuptools
import khorosjx.utils.version
with open("README.md", "r") as fh:
long_description = fh.read()
version = khorosjx.utils.version.__version__
setuptools.setup(
name="khorosjx",
version=version,
author="Jeff Shurtliff",
author_email="[email protected]",
description="Useful tools and utilities to assist in managing a Khoros JX (formerly Jive-x) or Jive-n community.",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/jeffshurtliff/khorosjx",
packages=setuptools.find_packages(),
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Intended Audience :: Information Technology",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Operating System :: OS Independent", | "Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Topic :: Communications",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content :: Content Management System",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content :: Message Boards",
"Topic :: Internet :: WWW/HTTP :: Site Management"
],
python_requires='>=3.6',
install_requires=[
"PyYAML>=5.4.1",
"urllib3>=1.26.6",
"requests>=2.26.0",
"pandas>=1.3.3",
"python-dateutil>=2.8.2",
],
) | |
injectStylesIntoStyleTag.js | "use strict";
var stylesInDom = [];
function | (identifier) {
var result = -1;
for (var i = 0; i < stylesInDom.length; i++) {
if (stylesInDom[i].identifier === identifier) {
result = i;
break;
}
}
return result;
}
function modulesToDom(list, options) {
var idCountMap = {};
var identifiers = [];
for (var i = 0; i < list.length; i++) {
var item = list[i];
var id = options.base ? item[0] + options.base : item[0];
var count = idCountMap[id] || 0;
var identifier = "".concat(id, " ").concat(count);
idCountMap[id] = count + 1;
var index = getIndexByIdentifier(identifier);
var obj = {
css: item[1],
media: item[2],
sourceMap: item[3]
};
if (index !== -1) {
stylesInDom[index].references++;
stylesInDom[index].updater(obj);
} else {
stylesInDom.push({
identifier: identifier,
updater: addStyle(obj, options),
references: 1
});
}
identifiers.push(identifier);
}
return identifiers;
}
function addStyle(obj, options) {
var api = options.domAPI(options);
api.update(obj);
return function updateStyle(newObj) {
if (newObj) {
if (newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap) {
return;
}
api.update(obj = newObj);
} else {
api.remove();
}
};
}
module.exports = function (list, options) {
options = options || {};
list = list || [];
var lastIdentifiers = modulesToDom(list, options);
return function update(newList) {
newList = newList || [];
for (var i = 0; i < lastIdentifiers.length; i++) {
var identifier = lastIdentifiers[i];
var index = getIndexByIdentifier(identifier);
stylesInDom[index].references--;
}
var newLastIdentifiers = modulesToDom(newList, options);
for (var _i = 0; _i < lastIdentifiers.length; _i++) {
var _identifier = lastIdentifiers[_i];
var _index = getIndexByIdentifier(_identifier);
if (stylesInDom[_index].references === 0) {
stylesInDom[_index].updater();
stylesInDom.splice(_index, 1);
}
}
lastIdentifiers = newLastIdentifiers;
};
}; | getIndexByIdentifier |
south_africa.py | # -*- coding: utf-8 -*-
# python-holidays
# ---------------
# A fast, efficient Python library for generating country, province and state
# specific sets of holidays on the fly. It aims to make determining whether a
# specific date is a holiday as fast and flexible as possible.
#
# Authors: dr-prodigy <[email protected]> (c) 2017-2022
# ryanss <[email protected]> (c) 2014-2017
# Website: https://github.com/dr-prodigy/python-holidays
# License: MIT (see LICENSE file)
from datetime import date, datetime
from dateutil.easter import easter
from dateutil.relativedelta import relativedelta as rd
from holidays.constants import FRI, SUN
from holidays.constants import (
JAN,
MAR,
APR,
MAY,
JUN,
JUL,
AUG,
SEP,
OCT,
NOV,
DEC,
)
from holidays.holiday_base import HolidayBase
class SouthAfrica(HolidayBase):
|
class ZA(SouthAfrica):
pass
class ZAF(SouthAfrica):
pass
| country = "ZA"
def __init__(self, **kwargs):
# http://www.gov.za/about-sa/public-holidays
# https://en.wikipedia.org/wiki/Public_holidays_in_South_Africa
HolidayBase.__init__(self, **kwargs)
def _populate(self, year):
# Observed since 1910, with a few name changes
if year > 1909:
self[date(year, 1, 1)] = "New Year's Day"
e = easter(year)
good_friday = e - rd(days=2)
easter_monday = e + rd(days=1)
self[good_friday] = "Good Friday"
if year > 1979:
self[easter_monday] = "Family Day"
else:
self[easter_monday] = "Easter Monday"
if 1909 < year < 1952:
dec_16_name = "Dingaan's Day"
elif 1951 < year < 1980:
dec_16_name = "Day of the Covenant"
elif 1979 < year < 1995:
dec_16_name = "Day of the Vow"
else:
dec_16_name = "Day of Reconciliation"
self[date(year, DEC, 16)] = dec_16_name
self[date(year, DEC, 25)] = "Christmas Day"
if year > 1979:
dec_26_name = "Day of Goodwill"
else:
dec_26_name = "Boxing Day"
self[date(year, 12, 26)] = dec_26_name
# Observed since 1995/1/1
if year > 1994:
self[date(year, MAR, 21)] = "Human Rights Day"
self[date(year, APR, 27)] = "Freedom Day"
self[date(year, MAY, 1)] = "Workers' Day"
self[date(year, JUN, 16)] = "Youth Day"
self[date(year, AUG, 9)] = "National Women's Day"
self[date(year, SEP, 24)] = "Heritage Day"
# Once-off public holidays
national_election = "National and provincial government elections"
y2k = "Y2K changeover"
local_election = "Local government elections"
presidential = "By presidential decree"
municipal_election = "Municipal elections"
if year == 1999:
self[date(1999, JUN, 2)] = national_election
self[date(1999, DEC, 31)] = y2k
if year == 2000:
self[date(2000, JAN, 2)] = y2k
if year == 2004:
self[date(2004, APR, 14)] = national_election
if year == 2006:
self[date(2006, MAR, 1)] = local_election
if year == 2008:
self[date(2008, MAY, 2)] = presidential
if year == 2009:
self[date(2009, APR, 22)] = national_election
if year == 2011:
self[date(2011, MAY, 18)] = local_election
self[date(2011, DEC, 27)] = presidential
if year == 2014:
self[date(2014, MAY, 7)] = national_election
if year == 2016:
self[date(2016, AUG, 3)] = local_election
if year == 2019:
self[date(2019, MAY, 8)] = national_election
if year == 2021:
self[date(2021, NOV, 1)] = municipal_election
# As of 1995/1/1, whenever a public holiday falls on a Sunday,
# it rolls over to the following Monday
for k, v in list(self.items()):
if (
self.observed
and year > 1994
and k.weekday() == SUN
and k.year == year
):
add_days = 1
while self.get(k + rd(days=add_days)) is not None:
add_days += 1
self[k + rd(days=add_days)] = v + " (Observed)"
# Historic public holidays no longer observed
if 1951 < year < 1974:
self[date(year, APR, 6)] = "Van Riebeeck's Day"
elif 1979 < year < 1995:
self[date(year, APR, 6)] = "Founder's Day"
if 1986 < year < 1990:
historic_workers_day = datetime(year, MAY, 1)
# observed on first Friday in May
while historic_workers_day.weekday() != FRI:
historic_workers_day += rd(days=1)
self[historic_workers_day] = "Workers' Day"
if 1909 < year < 1994:
ascension_day = e + rd(days=40)
self[ascension_day] = "Ascension Day"
if 1909 < year < 1952:
self[date(year, MAY, 24)] = "Empire Day"
if 1909 < year < 1961:
self[date(year, MAY, 31)] = "Union Day"
elif 1960 < year < 1994:
self[date(year, MAY, 31)] = "Republic Day"
if 1951 < year < 1961:
queens_birthday = datetime(year, JUN, 7)
# observed on second Monday in June
while queens_birthday.weekday() != 0:
queens_birthday += rd(days=1)
self[queens_birthday] = "Queen's Birthday"
if 1960 < year < 1974:
self[date(year, JUL, 10)] = "Family Day"
if 1909 < year < 1952:
kings_birthday = datetime(year, AUG, 1)
# observed on first Monday in August
while kings_birthday.weekday() != 0:
kings_birthday += rd(days=1)
self[kings_birthday] = "King's Birthday"
if 1951 < year < 1980:
settlers_day = datetime(year, SEP, 1)
while settlers_day.weekday() != 0:
settlers_day += rd(days=1)
self[settlers_day] = "Settlers' Day"
if 1951 < year < 1994:
self[date(year, OCT, 10)] = "Kruger Day" |
interop.py | from enum import Enum
from typing import Dict, List
from boa3.model.builtin.interop.blockchain import *
from boa3.model.builtin.interop.contract import *
from boa3.model.builtin.interop.contract.contractmanifest import *
from boa3.model.builtin.interop.crypto import *
from boa3.model.builtin.interop.iterator import *
from boa3.model.builtin.interop.json import *
from boa3.model.builtin.interop.nativecontract import *
from boa3.model.builtin.interop.oracle import *
from boa3.model.builtin.interop.policy import *
from boa3.model.builtin.interop.role import *
from boa3.model.builtin.interop.runtime import *
from boa3.model.builtin.interop.stdlib import *
from boa3.model.builtin.interop.storage import *
from boa3.model.identifiedsymbol import IdentifiedSymbol
from boa3.model.imports.package import Package
class InteropPackage(str, Enum):
Blockchain = 'blockchain'
Contract = 'contract'
Crypto = 'crypto'
Iterator = 'iterator'
Json = 'json'
Oracle = 'oracle'
Policy = 'policy'
Role = 'role'
Runtime = 'runtime'
Stdlib = 'stdlib'
Storage = 'storage'
class Interop:
@classmethod
def interop_symbols(cls, package: str = None) -> List[IdentifiedSymbol]:
if package in InteropPackage.__members__.values():
return cls._interop_symbols[package]
lst: List[IdentifiedSymbol] = []
for symbols in cls._interop_symbols.values():
lst.extend(symbols)
return lst
# region Interops
# Interop Types
BlockType = BlockType.build()
CallFlagsType = CallFlagsType()
ContractManifestType = ContractManifestType.build()
ContractType = ContractType.build()
FindOptionsType = FindOptionsType()
Iterator = IteratorType.build()
NamedCurveType = NamedCurveType()
NotificationType = NotificationType.build()
OracleResponseCode = OracleResponseCodeType.build()
OracleType = OracleType.build()
RoleType = RoleType.build()
StorageContextType = StorageContextType.build()
StorageMapType = StorageMapType.build()
TransactionType = TransactionType.build()
TriggerType = TriggerType()
# Blockchain Interops
CurrentHash = CurrentHashProperty()
CurrentHeight = CurrentHeightProperty()
CurrentIndex = CurrentIndexProperty()
GetContract = GetContractMethod(ContractType)
GetBlock = GetBlockMethod(BlockType)
GetTransaction = GetTransactionMethod(TransactionType)
GetTransactionFromBlock = GetTransactionFromBlockMethod(TransactionType)
GetTransactionHeight = GetTransactionHeightMethod()
# Contract Interops
CallContract = CallMethod()
CreateContract = CreateMethod(ContractType)
CreateMultisigAccount = CreateMultisigAccountMethod()
CreateStandardAccount = CreateStandardAccountMethod()
DestroyContract = DestroyMethod()
GetCallFlags = GetCallFlagsMethod(CallFlagsType)
GetMinimumDeploymentFee = GetMinimumDeploymentFeeMethod()
UpdateContract = UpdateMethod()
# Native Contracts
GasScriptHash = GasProperty()
NeoScriptHash = NeoProperty()
ContractManagementScriptHash = ContractManagement
CryptoLibScriptHash = CryptoLibContract
LedgerScriptHash = LedgerContract
OracleScriptHash = OracleContract
StdLibScriptHash = StdLibContract
# Crypto Interops
CheckMultisig = CheckMultisigMethod()
CheckSig = CheckSigMethod()
Hash160 = Hash160Method()
Hash256 = Hash256Method()
Ripemd160 = Ripemd160Method()
Sha256 = Sha256Method()
VerifyWithECDsa = VerifyWithECDsaMethod()
# Iterator Interops
IteratorCreate = IteratorMethod(Iterator)
# Json Interops
JsonDeserialize = JsonDeserializeMethod()
JsonSerialize = JsonSerializeMethod()
# Policy Interops
GetExecFeeFactor = GetExecFeeFactorMethod()
GetFeePerByte = GetFeePerByteMethod()
GetStoragePrice = GetStoragePriceMethod()
IsBlocked = IsBlockedMethod()
# Role Interops
GetDesignatedByRole = GetDesignatedByRoleMethod()
# Runtime Interops
BlockTime = BlockTimeProperty()
BurnGas = BurnGasMethod()
CallingScriptHash = CallingScriptHashProperty()
CheckWitness = CheckWitnessMethod()
EntryScriptHash = EntryScriptHashProperty()
ExecutingScriptHash = ExecutingScriptHashProperty()
GasLeft = GasLeftProperty()
GetNetwork = GetNetworkMethod()
GetNotifications = GetNotificationsMethod(NotificationType)
GetRandom = GetRandomMethod()
GetTrigger = GetTriggerMethod(TriggerType)
InvocationCounter = InvocationCounterProperty()
Log = LogMethod()
Notify = NotifyMethod()
Platform = PlatformProperty()
ScriptContainer = ScriptContainerProperty()
# Stdlib Interops
Atoi = AtoiMethod()
Base58CheckDecode = Base58CheckDecodeMethod()
Base58CheckEncode = Base58CheckEncodeMethod()
Base58Encode = Base58EncodeMethod()
Base58Decode = Base58DecodeMethod()
Base64Encode = Base64EncodeMethod()
Base64Decode = Base64DecodeMethod()
Deserialize = DeserializeMethod()
Itoa = ItoaMethod()
MemoryCompare = MemoryCompareMethod()
MemorySearch = MemorySearchMethod()
Serialize = SerializeMethod()
# Storage Interops
StorageDelete = StorageDeleteMethod()
StorageFind = StorageFindMethod(FindOptionsType)
StorageGetContext = StorageGetContextMethod(StorageContextType)
StorageGetReadOnlyContext = StorageGetReadOnlyContextMethod(StorageContextType)
StorageGet = StorageGetMethod()
StoragePut = StoragePutMethod()
# endregion
# region Packages
BlockModule = Package(identifier=BlockType.identifier.lower(),
types=[BlockType]
)
TransactionModule = Package(identifier=TransactionType.identifier.lower(),
types=[TransactionType]
)
BlockchainPackage = Package(identifier=InteropPackage.Blockchain,
types=[BlockType,
TransactionType
],
methods=[CurrentHash,
CurrentHeight,
CurrentIndex,
GetBlock,
GetContract,
GetTransaction,
GetTransactionFromBlock,
GetTransactionHeight
],
packages=[BlockModule,
TransactionModule
]
)
CallFlagsTypeModule = Package(identifier=f'{CallFlagsType.identifier.lower()}type',
types=[CallFlagsType]
)
ContractModule = Package(identifier=ContractType.identifier.lower(),
types=[ContractType]
)
ContractManifestModule = Package(identifier=ContractManifestType.identifier.lower(),
types=[ContractAbiType.build(),
ContractEventDescriptorType.build(),
ContractGroupType.build(),
ContractManifestType,
ContractMethodDescriptorType.build(),
ContractParameterDefinitionType.build(),
ContractParameterType.build(),
ContractPermissionDescriptorType.build(),
ContractPermissionType.build()
]
)
ContractPackage = Package(identifier=InteropPackage.Contract,
types=[CallFlagsType,
ContractManifestType,
ContractType
],
properties=[GasScriptHash,
NeoScriptHash
],
methods=[CallContract,
CreateContract,
CreateMultisigAccount,
CreateStandardAccount,
DestroyContract,
GetCallFlags,
GetMinimumDeploymentFee,
UpdateContract
],
packages=[CallFlagsTypeModule,
ContractManifestModule,
ContractModule
]
)
CryptoPackage = Package(identifier=InteropPackage.Crypto,
types=[NamedCurveType],
methods=[CheckMultisig,
CheckSig,
Hash160,
Hash256,
Ripemd160,
Sha256,
VerifyWithECDsa,
]
)
IteratorPackage = Package(identifier=InteropPackage.Iterator,
types=[Iterator],
)
JsonPackage = Package(identifier=InteropPackage.Json,
methods=[JsonDeserialize,
JsonSerialize
]
)
NotificationModule = Package(identifier=NotificationType.identifier.lower(),
types=[NotificationType]
)
OracleResponseCodeModule = Package(identifier=OracleResponseCode.identifier.lower(),
types=[OracleResponseCode]
)
OracleModule = Package(identifier=OracleType.identifier.lower(),
types=[OracleType]
)
OraclePackage = Package(identifier=InteropPackage.Oracle,
types=[OracleResponseCode,
OracleType
],
packages=[OracleModule,
OracleResponseCodeModule
]
)
TriggerTypeModule = Package(identifier=TriggerType.identifier.lower(),
types=[TriggerType]
)
PolicyPackage = Package(identifier=InteropPackage.Policy,
methods=[GetExecFeeFactor,
GetFeePerByte,
GetStoragePrice,
IsBlocked
]
)
RolePackage = Package(identifier=InteropPackage.Role,
types=[RoleType],
methods=[GetDesignatedByRole]
)
RuntimePackage = Package(identifier=InteropPackage.Runtime,
types=[NotificationType,
TriggerType
],
properties=[BlockTime,
CallingScriptHash,
ExecutingScriptHash,
GasLeft,
Platform,
InvocationCounter,
EntryScriptHash,
ScriptContainer
],
methods=[BurnGas,
CheckWitness,
GetNetwork,
GetNotifications,
GetRandom,
GetTrigger,
Log,
Notify
],
packages=[NotificationModule,
TriggerTypeModule
]
)
FindOptionsModule = Package(identifier=FindOptionsType.identifier.lower(),
types=[FindOptionsType]
)
StdlibPackage = Package(identifier=InteropPackage.Stdlib,
methods=[Atoi,
Base58CheckDecode,
Base58CheckEncode,
Base58Encode,
Base58Decode,
Base64Encode,
Base64Decode,
Deserialize,
Itoa,
MemoryCompare,
MemorySearch,
Serialize
]
)
StorageContextModule = Package(identifier=StorageContextType.identifier.lower(),
types=[StorageContextType]
)
StorageMapModule = Package(identifier=StorageMapType.identifier.lower(),
types=[StorageMapType]
)
StoragePackage = Package(identifier=InteropPackage.Storage,
types=[FindOptionsType,
StorageContextType,
StorageMapType
],
methods=[StorageDelete,
StorageFind,
StorageGet,
StorageGetContext,
StorageGetReadOnlyContext,
StoragePut
],
packages=[FindOptionsModule,
StorageContextModule,
StorageMapModule
]
)
# endregion
package_symbols: List[IdentifiedSymbol] = [
OracleType, | JsonPackage,
OraclePackage,
PolicyPackage,
RolePackage,
RuntimePackage,
StdlibPackage,
StoragePackage
]
_interop_symbols: Dict[InteropPackage, List[IdentifiedSymbol]] = {
package.identifier: list(package.symbols.values()) for package in package_symbols if
isinstance(package, Package)
} | BlockchainPackage,
ContractPackage,
CryptoPackage,
IteratorPackage, |
PageTwo.tsx | import { createElement } from 'react'; | import { Page } from './Pages';
import { FC } from 'react';
import { SFSelect } from 'react-stateful-form';
import NextButton from './NextButton';
import PreviousButton from './PreviousButton';
import Logger from './Logger';
const PageTwo: FC = () => {
return (
<Page>
<label>
Reason for complaint:
<SFSelect
name="two/reason"
defaultEntry={'Please select a reason'}
values={['Bug', 'Typo', 'Feature Request', 'Other']}
/>
</label>
<div>
<PreviousButton />
<NextButton />
</div>
<Logger />
</Page>
);
};
export default PageTwo; | |
reddit.js | // Generated by IcedCoffeeScript 1.7.1-e
(function() {
var BaseScraper, GlobalHunter, Lock, PREFIX, RedditScraper, SUBREDDIT, constants, iced, make_esc, proof_text_check_to_med_id, sncmp, v_codes, __iced_k, __iced_k_noop, _global_hunter, _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function | () { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
iced = require('iced-runtime');
__iced_k = __iced_k_noop = function() {};
_ref = require('./base'), sncmp = _ref.sncmp, BaseScraper = _ref.BaseScraper;
constants = require('../constants').constants;
v_codes = constants.v_codes;
Lock = require('iced-lock').Lock;
make_esc = require('iced-error').make_esc;
proof_text_check_to_med_id = require('../base').proof_text_check_to_med_id;
PREFIX = "https://www.reddit.com";
SUBREDDIT = PREFIX + "/r/keybaseproofs";
GlobalHunter = (function() {
function GlobalHunter() {
this._startup_window = 20 * 60;
this._delay = 5000;
this._running = false;
this._lock = new Lock;
this._cache = {};
this._last_rc = null;
this._most_recent = null;
}
GlobalHunter.prototype.index = function(lst) {
var author, data, el, id, m, _i, _len, _results;
_results = [];
for (_i = 0, _len = lst.length; _i < _len; _i++) {
el = lst[_i];
data = el.data;
author = data.author.toLowerCase();
if (((m = data.title.match(/\(([a-zA-Z0-9_-]{43})\)/)) == null) || ((id = m[1]) == null)) {
_results.push(this._scraper.log("| [Reddit] Unindexable: " + data.title));
} else if (this._cache[id] == null) {
this._scraper.log("| [Reddit] Indexing " + author + "/" + id + ": " + data.name + " @ " + data.created_utc + " (" + PREFIX + data.permalink + ")");
_results.push(this._cache[id] = el);
} else {
_results.push(void 0);
}
}
return _results;
};
GlobalHunter.prototype.go_back = function(stop, cb) {
var after, args, body, err, esc, first, go, posts, ___iced_passed_deferral, __iced_deferrals, __iced_k;
__iced_k = __iced_k_noop;
___iced_passed_deferral = iced.findDeferral(arguments);
this._scraper.log("+ [Reddit] rescraping to " + stop);
after = null;
go = true;
first = null;
esc = make_esc(cb, "go_back");
(function(_this) {
return (function(__iced_k) {
var _results, _while;
_results = [];
_while = function(__iced_k) {
var _break, _continue, _next;
_break = function() {
return __iced_k(_results);
};
_continue = function() {
return iced.trampoline(function() {
return _while(__iced_k);
});
};
_next = function(__iced_next_arg) {
_results.push(__iced_next_arg);
return _continue();
};
if (!go) {
return _break();
} else {
args = {
url: SUBREDDIT + "/.json",
json: true,
qs: {
count: 25,
cachebust: Math.random()
}
};
if (after != null) {
args.qs.after = after;
}
_this._scraper.log("+ [Reddit] Start at after=" + after);
(function(__iced_k) {
__iced_deferrals = new iced.Deferrals(__iced_k, {
parent: ___iced_passed_deferral,
filename: "/Users/max/src/keybase/proofs/src/scrapers/reddit.iced",
funcname: "GlobalHunter.go_back"
});
_this._scraper._get_url_body(args, __iced_deferrals.defer({
assign_fn: (function(__slot_1) {
return function() {
err = arguments[0];
__slot_1._last_rc = arguments[1];
return body = arguments[2];
};
})(_this),
lineno: 54
}));
__iced_deferrals._fulfill();
})(function() {
after = body.data.after;
posts = body.data.children;
_this._scraper.log("- [Reddit] Got back " + posts.length + " posts");
if (posts.length) {
_this.index(posts);
if (first == null) {
first = posts[0];
}
}
return _next((after == null) || !posts.length || posts.slice(-1)[0].data.created_utc < stop ? go = false : void 0);
});
}
};
_while(__iced_k);
});
})(this)((function(_this) {
return function() {
if (first != null) {
_this._most_recent = first.data.created_utc;
}
_this._scraper.log("- [Reddit] rescraped; most_recent is now " + _this._most_recent);
return cb(null);
};
})(this));
};
GlobalHunter.prototype.scrape = function(cb) {
var err, stop, ___iced_passed_deferral, __iced_deferrals, __iced_k;
__iced_k = __iced_k_noop;
___iced_passed_deferral = iced.findDeferral(arguments);
stop = this._most_recent != null ? this._most_recent : Math.ceil(Date.now() / 1000) - this._startup_window;
(function(_this) {
return (function(__iced_k) {
__iced_deferrals = new iced.Deferrals(__iced_k, {
parent: ___iced_passed_deferral,
filename: "/Users/max/src/keybase/proofs/src/scrapers/reddit.iced",
funcname: "GlobalHunter.scrape"
});
_this.go_back(stop, __iced_deferrals.defer({
assign_fn: (function() {
return function() {
return err = arguments[0];
};
})(),
lineno: 71
}));
__iced_deferrals._fulfill();
});
})(this)((function(_this) {
return function() {
return cb(err);
};
})(this));
};
GlobalHunter.prototype.start_scraper_loop = function(_arg, cb) {
var err, scraper, ___iced_passed_deferral, __iced_deferrals, __iced_k;
__iced_k = __iced_k_noop;
___iced_passed_deferral = iced.findDeferral(arguments);
scraper = _arg.scraper;
this._scraper = scraper;
(function(_this) {
return (function(__iced_k) {
__iced_deferrals = new iced.Deferrals(__iced_k, {
parent: ___iced_passed_deferral,
filename: "/Users/max/src/keybase/proofs/src/scrapers/reddit.iced",
funcname: "GlobalHunter.start_scraper_loop"
});
_this.scrape(__iced_deferrals.defer({
assign_fn: (function() {
return function() {
return err = arguments[0];
};
})(),
lineno: 78
}));
__iced_deferrals._fulfill();
});
})(this)((function(_this) {
return function() {
var _results, _while;
_this._running = true;
cb(err);
_results = [];
_while = function(__iced_k) {
var _break, _continue, _next;
_break = function() {
return __iced_k(_results);
};
_continue = function() {
return iced.trampoline(function() {
return _while(__iced_k);
});
};
_next = function(__iced_next_arg) {
_results.push(__iced_next_arg);
return _continue();
};
if (!true) {
return _break();
} else {
(function(__iced_k) {
__iced_deferrals = new iced.Deferrals(__iced_k, {
parent: ___iced_passed_deferral,
filename: "/Users/max/src/keybase/proofs/src/scrapers/reddit.iced",
funcname: "GlobalHunter.start_scraper_loop"
});
setTimeout(__iced_deferrals.defer({
lineno: 82
}), _this._delay);
__iced_deferrals._fulfill();
})(function() {
(function(__iced_k) {
__iced_deferrals = new iced.Deferrals(__iced_k, {
parent: ___iced_passed_deferral,
filename: "/Users/max/src/keybase/proofs/src/scrapers/reddit.iced",
funcname: "GlobalHunter.start_scraper_loop"
});
_this.scrape(__iced_deferrals.defer({
lineno: 83
}));
__iced_deferrals._fulfill();
})(_next);
});
}
};
_while(__iced_k);
};
})(this));
};
GlobalHunter.prototype.find = function(_arg, cb) {
var err, med_id, out, rc, scraper, ___iced_passed_deferral, __iced_deferrals, __iced_k;
__iced_k = __iced_k_noop;
___iced_passed_deferral = iced.findDeferral(arguments);
scraper = _arg.scraper, med_id = _arg.med_id;
err = out = null;
(function(_this) {
return (function(__iced_k) {
__iced_deferrals = new iced.Deferrals(__iced_k, {
parent: ___iced_passed_deferral,
filename: "/Users/max/src/keybase/proofs/src/scrapers/reddit.iced",
funcname: "GlobalHunter.find"
});
_this._lock.acquire(__iced_deferrals.defer({
lineno: 89
}));
__iced_deferrals._fulfill();
});
})(this)((function(_this) {
return function() {
(function(__iced_k) {
if (!_this._running) {
(function(__iced_k) {
__iced_deferrals = new iced.Deferrals(__iced_k, {
parent: ___iced_passed_deferral,
filename: "/Users/max/src/keybase/proofs/src/scrapers/reddit.iced",
funcname: "GlobalHunter.find"
});
_this.start_scraper_loop({
scraper: scraper
}, __iced_deferrals.defer({
assign_fn: (function() {
return function() {
return err = arguments[0];
};
})(),
lineno: 91
}));
__iced_deferrals._fulfill();
})(__iced_k);
} else {
return __iced_k();
}
})(function() {
_this._lock.release();
rc = err != null ? _this._last_rc : (out = _this._cache[med_id]) != null ? v_codes.OK : v_codes.NOT_FOUND;
return cb(err, rc, out);
});
};
})(this));
};
return GlobalHunter;
})();
_global_hunter = new GlobalHunter();
exports.RedditScraper = RedditScraper = (function(_super) {
__extends(RedditScraper, _super);
function RedditScraper(opts) {
RedditScraper.__super__.constructor.call(this, opts);
}
RedditScraper.prototype._check_args = function(args) {
if (!(args.username != null)) {
return new Error("Bad args to Reddit proof: no username given");
} else if (!(args.name != null) || (args.name !== 'reddit')) {
return new Error("Bad args to Reddit proof: type is " + args.name);
} else {
return null;
}
};
RedditScraper.prototype.hunt2 = function(_arg, cb) {
var err, json, med_id, name, out, proof_text_check, rc, username, ___iced_passed_deferral, __iced_deferrals, __iced_k;
__iced_k = __iced_k_noop;
___iced_passed_deferral = iced.findDeferral(arguments);
username = _arg.username, proof_text_check = _arg.proof_text_check, name = _arg.name;
rc = v_codes.OK;
out = {};
(function(_this) {
return (function(__iced_k) {
if ((err = _this._check_args({
username: username,
name: name
})) != null) {
return __iced_k(rc = v_codes.BAD_ARGS);
} else {
med_id = proof_text_check_to_med_id(proof_text_check);
(function(__iced_k) {
__iced_deferrals = new iced.Deferrals(__iced_k, {
parent: ___iced_passed_deferral,
filename: "/Users/max/src/keybase/proofs/src/scrapers/reddit.iced",
funcname: "RedditScraper.hunt2"
});
_global_hunter.find({
scraper: _this,
med_id: med_id
}, __iced_deferrals.defer({
assign_fn: (function() {
return function() {
err = arguments[0];
rc = arguments[1];
return json = arguments[2];
};
})(),
lineno: 128
}));
__iced_deferrals._fulfill();
})(function() {
return __iced_k(rc !== v_codes.OK ? void 0 : !sncmp(json.data.author, username) ? rc = v_codes.BAD_USERNAME : out = {
api_url: PREFIX + json.data.permalink + ".json",
human_url: PREFIX + json.data.permalink,
remote_id: json.data.name
});
});
}
});
})(this)((function(_this) {
return function() {
out.rc = rc;
return cb(err, out);
};
})(this));
};
RedditScraper.prototype._check_api_url = function(_arg) {
var api_url, rxx, username;
api_url = _arg.api_url, username = _arg.username;
rxx = new RegExp("^" + SUBREDDIT, "i");
return (api_url != null) && api_url.match(rxx);
};
RedditScraper.prototype.unpack_data = function(json) {
var parent, _ref1, _ref2, _ref3, _ref4, _ref5;
if ((((_ref1 = json[0]) != null ? _ref1.kind : void 0) === 'Listing') && (((_ref2 = (parent = (_ref3 = json[0]) != null ? (_ref4 = _ref3.data) != null ? (_ref5 = _ref4.children) != null ? _ref5[0] : void 0 : void 0 : void 0)) != null ? _ref2.kind : void 0) === 't3')) {
return parent.data;
} else {
return null;
}
};
RedditScraper.prototype.check_data = function(_arg) {
var body, json, line, lstrip, med_id, proof_text_check, username;
json = _arg.json, username = _arg.username, proof_text_check = _arg.proof_text_check;
med_id = proof_text_check_to_med_id(proof_text_check);
if (!((json.subreddit != null) && (json.author != null) && (json.selftext != null) && json.title)) {
return v_codes.CONTENT_MISSING;
} else if (json.subreddit.toLowerCase() !== 'keybaseproofs') {
return v_codes.SERVICE_ERROR;
} else if (!sncmp(json.author, username)) {
return v_codes.BAD_USERNAME;
} else if (json.title.indexOf(med_id) < 0) {
return v_codes.TITLE_NOT_FOUND;
} else {
lstrip = function(line) {
var m;
if ((m = line.match(/^\s+(.*?)$/)) != null) {
return m[1];
} else {
return line;
}
};
body = ((function() {
var _i, _len, _ref1, _results;
_ref1 = json.selftext.split("\n");
_results = [];
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
line = _ref1[_i];
_results.push(lstrip(line));
}
return _results;
})()).join("\n");
if (body.indexOf(proof_text_check) < 0) {
return v_codes.TEXT_NOT_FOUND;
} else {
return v_codes.OK;
}
}
};
RedditScraper.prototype.check_status = function(_arg, cb) {
var api_url, dat, err, json, proof_text_check, rc, remote_id, username, ___iced_passed_deferral, __iced_deferrals, __iced_k;
__iced_k = __iced_k_noop;
___iced_passed_deferral = iced.findDeferral(arguments);
username = _arg.username, api_url = _arg.api_url, proof_text_check = _arg.proof_text_check, remote_id = _arg.remote_id;
(function(_this) {
return (function(__iced_k) {
__iced_deferrals = new iced.Deferrals(__iced_k, {
parent: ___iced_passed_deferral,
filename: "/Users/max/src/keybase/proofs/src/scrapers/reddit.iced",
funcname: "RedditScraper.check_status"
});
_this._get_url_body({
url: api_url,
json: true
}, __iced_deferrals.defer({
assign_fn: (function() {
return function() {
err = arguments[0];
rc = arguments[1];
return json = arguments[2];
};
})(),
lineno: 181
}));
__iced_deferrals._fulfill();
});
})(this)((function(_this) {
return function() {
rc = rc !== v_codes.OK ? rc : !(dat = _this.unpack_data(json)) ? v_codes.CONTENT_FAILURE : _this.check_data({
json: dat,
username: username,
proof_text_check: proof_text_check
});
return cb(err, rc);
};
})(this));
};
return RedditScraper;
})(BaseScraper);
}).call(this);
| ctor |
08_asynchronous_generators.ts | namespace asynchronous_generators_demo_1 {
let counter = 0;
function doSomethingAsync() {
return new Promise<number>((r) => { | r(counter);
}, 1000);
});
}
async function* g1() {
yield await doSomethingAsync();
yield await doSomethingAsync();
yield await doSomethingAsync();
}
let i: AsyncIterableIterator<number> = g1();
i.next().then((n) => console.log(n)); // 1
i.next().then((n) => console.log(n)); // 2
i.next().then((n) => console.log(n)); // 3
} | setTimeout(() => {
counter += 1; |
form.tsx | import {createStyles, makeStyles} from '@material-ui/core/styles';
import clsx from 'clsx';
import {FormApi, SubmissionErrors, ValidationErrors} from 'final-form';
import React, {FC, ReactNode, useEffect} from 'react';
import {Form as FinalForm} from 'react-final-form';
import {CommonComponentProps} from '../common-component';
export type FormSubmit = (values: Record<string, any>, form: FormApi) => SubmissionErrors | Promise<SubmissionErrors | undefined> | undefined | void;
export type FormValidate = (values: Record<string, any>) => ValidationErrors | Promise<ValidationErrors> | undefined;
export type FormRender = (props: {form: FormApi, submitting: boolean, dirty: boolean, values: Record<string, any>}) => ReactNode;
export interface FormProps extends CommonComponentProps {
submit: FormSubmit;
validate?: FormValidate;
render: FormRender;
autoClean?: boolean;
initialValues?: Record<string, any>;
}
const useStyles = makeStyles(() => createStyles({
root: {
width: '100%'
}
}));
export const Form: FC<FormProps> = props => {
const {className, submit, validate, render, autoClean = true, initialValues} = props;
const classes = useStyles();
return (
<FinalForm onSubmit={submit} initialValues={initialValues} validate={validate} subscription={{
values: true,
submitting: true,
pristine: true,
dirty: true,
submitSucceeded: autoClean
}} render={({handleSubmit, form, submitting, dirty, submitSucceeded, values}) => (
<form className={clsx(classes.root, className)} onSubmit={handleSubmit} noValidate>
{
useEffect(() => {
if (autoClean && submitSucceeded) {
// @ts-ignore | // ref: https://github.com/final-form/final-form/issues/352
form.restart();
}
}, [submitSucceeded])
}
{render({form, submitting, dirty, values})}
</form>
)}/>
);
};
export const validators = {
required: (value: any) => value ? undefined : 'Required',
number: (value: any) => !isNaN(value) ? undefined : 'Must be a number'
}; | |
face_pb2_grpc.py | # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from . import face_pb2 as face__pb2
class FaceServiceStub(object):
"""faceRecognition.FaceService 人脸服务
"""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.Compare = channel.unary_unary(
'/faceRecognition.FaceService/Compare',
request_serializer=face__pb2.CompareRequest.SerializeToString,
response_deserializer=face__pb2.CompareResponse.FromString,
)
self.Search = channel.unary_unary(
'/faceRecognition.FaceService/Search',
request_serializer=face__pb2.SearchRequest.SerializeToString,
response_deserializer=face__pb2.SearchResponse.FromString,
)
class FaceServiceServicer(object):
"""faceRecognition.FaceService 人脸服务
"""
def Compare(self, request, context):
"""Compare 实现两张人脸图片对比识别,返回两张人脸图片对比的可信度
开发管理平台功能参考: http://10.10.10.2/face/compare
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def Search(self, request, context):
"""Search 从FaceSet中搜索近似人脸数据
若存在匹配数据时返回一个FaceDetail及可信度
开发管理平台功能参考: http:/ | servicer.Compare,
request_deserializer=face__pb2.CompareRequest.FromString,
response_serializer=face__pb2.CompareResponse.SerializeToString,
),
'Search': grpc.unary_unary_rpc_method_handler(
servicer.Search,
request_deserializer=face__pb2.SearchRequest.FromString,
response_serializer=face__pb2.SearchResponse.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'faceRecognition.FaceService', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
# This class is part of an EXPERIMENTAL API.
class FaceService(object):
"""faceRecognition.FaceService 人脸服务
"""
@staticmethod
def Compare(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/faceRecognition.FaceService/Compare',
face__pb2.CompareRequest.SerializeToString,
face__pb2.CompareResponse.FromString,
options, channel_credentials,
call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def Search(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/faceRecognition.FaceService/Search',
face__pb2.SearchRequest.SerializeToString,
face__pb2.SearchResponse.FromString,
options, channel_credentials,
call_credentials, compression, wait_for_ready, timeout, metadata)
| /10.10.10.2/face/compare
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_FaceServiceServicer_to_server(servicer, server):
rpc_method_handlers = {
'Compare': grpc.unary_unary_rpc_method_handler(
|
run_squad_debug.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Run BERT on SQuAD 1.1 and SQuAD 2.0."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import json
import math
import os
import random
import modeling
import optimization
import tokenization
import six
import tensorflow as tf
flags = tf.flags
FLAGS = flags.FLAGS
## Required parameters
flags.DEFINE_string(
"bert_config_file", "./pretrained_model/cased_L-12_H-768_A-12/bert_config.json",
"The config json file corresponding to the pre-trained BERT model. "
"This specifies the model architecture.")
flags.DEFINE_string("vocab_file", "./pretrained_model/cased_L-12_H-768_A-12/vocab.txt",
"The vocabulary file that the BERT model was trained on.")
flags.DEFINE_string(
"output_dir", "/squad/squad_base/",
"The output directory where the model checkpoints will be written.")
## Other parameters
flags.DEFINE_string("train_file", "./squad/train-v1.1.json",
"SQuAD json for training. E.g., train-v1.1.json")
flags.DEFINE_string(
"predict_file", "./squad/dev-v1.1.json",
"SQuAD json for predictions. E.g., dev-v1.1.json or test-v1.1.json")
flags.DEFINE_string(
"init_checkpoint", "./tfrecord/pretraining_output/model.ckpt-20",
"Initial checkpoint (usually from a pre-trained BERT model).")
flags.DEFINE_bool(
"do_lower_case", True,
"Whether to lower case the input text. Should be True for uncased "
"models and False for cased models.")
flags.DEFINE_integer(
"max_seq_length", 384,
"The maximum total input sequence length after WordPiece tokenization. "
"Sequences longer than this will be truncated, and sequences shorter "
"than this will be padded.")
flags.DEFINE_integer(
"doc_stride", 128,
"When splitting up a long document into chunks, how much stride to "
"take between chunks.")
flags.DEFINE_integer(
"max_query_length", 64,
"The maximum number of tokens for the question. Questions longer than "
"this will be truncated to this length.")
flags.DEFINE_bool("do_train", True, "Whether to run training.")
flags.DEFINE_bool("do_predict", True, "Whether to run eval on the dev set.")
flags.DEFINE_integer("train_batch_size", 12, "Total batch size for training.")
flags.DEFINE_integer("predict_batch_size", 8,
"Total batch size for predictions.")
flags.DEFINE_float("learning_rate", 3e-5, "The initial learning rate for Adam.")
flags.DEFINE_float("num_train_epochs", 2.0,
"Total number of training epochs to perform.")
flags.DEFINE_float(
"warmup_proportion", 0.1,
"Proportion of training to perform linear learning rate warmup for. "
"E.g., 0.1 = 10% of training.")
flags.DEFINE_integer("save_checkpoints_steps", 1000,
"How often to save the model checkpoint.")
flags.DEFINE_integer("iterations_per_loop", 1000,
"How many steps to make in each estimator call.")
flags.DEFINE_integer(
"n_best_size", 20,
"The total number of n-best predictions to generate in the "
"nbest_predictions.json output file.")
flags.DEFINE_integer(
"max_answer_length", 30,
"The maximum length of an answer that can be generated. This is needed "
"because the start and end predictions are not conditioned on one another.")
flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.")
tf.flags.DEFINE_string(
"tpu_name", None,
"The Cloud TPU to use for training. This should be either the name "
"used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 "
"url.")
tf.flags.DEFINE_string(
"tpu_zone", None,
"[Optional] GCE zone where the Cloud TPU is located in. If not "
"specified, we will attempt to automatically detect the GCE project from "
"metadata.")
tf.flags.DEFINE_string(
"gcp_project", None,
"[Optional] Project name for the Cloud TPU-enabled project. If not "
"specified, we will attempt to automatically detect the GCE project from "
"metadata.")
tf.flags.DEFINE_string("master", None, "[Optional] TensorFlow master URL.")
flags.DEFINE_integer(
"num_tpu_cores", 8,
"Only used if `use_tpu` is True. Total number of TPU cores to use.")
flags.DEFINE_bool(
"verbose_logging", False,
"If true, all of the warnings related to data processing will be printed. "
"A number of warnings are expected for a normal SQuAD evaluation.")
flags.DEFINE_bool(
"version_2_with_negative", False,
"If true, the SQuAD examples contain some that do not have an answer.")
flags.DEFINE_float(
"null_score_diff_threshold", 0.0,
"If null_score - best_non_null is greater than the threshold predict null.")
class SquadExample(object):
"""A single training/test example for simple sequence classification.
For examples without an answer, the start and end position are -1.
"""
def __init__(self,
qas_id,
question_text,
doc_tokens,
orig_answer_text=None,
start_position=None,
end_position=None,
is_impossible=False):
self.qas_id = qas_id
self.question_text = question_text
self.doc_tokens = doc_tokens
self.orig_answer_text = orig_answer_text
self.start_position = start_position
self.end_position = end_position
self.is_impossible = is_impossible
def __str__(self):
return self.__repr__()
def __repr__(self):
s = ""
s += "qas_id: %s" % (tokenization.printable_text(self.qas_id))
s += ", question_text: %s" % (
tokenization.printable_text(self.question_text))
s += ", doc_tokens: [%s]" % (" ".join(self.doc_tokens))
if self.start_position:
s += ", start_position: %d" % (self.start_position)
if self.start_position:
s += ", end_position: %d" % (self.end_position)
if self.start_position:
s += ", is_impossible: %r" % (self.is_impossible)
return s
class InputFeatures(object):
"""A single set of features of data."""
def __init__(self,
unique_id,
example_index,
doc_span_index,
tokens,
token_to_orig_map,
token_is_max_context,
input_ids,
input_mask,
segment_ids,
start_position=None,
end_position=None,
is_impossible=None):
self.unique_id = unique_id
self.example_index = example_index
self.doc_span_index = doc_span_index
self.tokens = tokens
self.token_to_orig_map = token_to_orig_map
self.token_is_max_context = token_is_max_context
self.input_ids = input_ids
self.input_mask = input_mask
self.segment_ids = segment_ids
self.start_position = start_position
self.end_position = end_position
self.is_impossible = is_impossible
def read_squad_examples(input_file, is_training):
"""Read a SQuAD json file into a list of SquadExample."""
with tf.gfile.Open(input_file, "r") as reader:
input_data = json.load(reader)["data"]
def is_whitespace(c):
if c == " " or c == "\t" or c == "\r" or c == "\n" or ord(c) == 0x202F:
return True
return False
examples = []
break_count = 0 # 수정
for entry in input_data:
for paragraph in entry["paragraphs"]:
paragraph_text = paragraph["context"]
doc_tokens = []
char_to_word_offset = []
prev_is_whitespace = True
for c in paragraph_text:
if is_whitespace(c):
prev_is_whitespace = True
else:
if prev_is_whitespace:
doc_tokens.append(c)
else:
doc_tokens[-1] += c
prev_is_whitespace = False
char_to_word_offset.append(len(doc_tokens) - 1)
for qa in paragraph["qas"]:
break_count += 1
qas_id = qa["id"]
question_text = qa["question"]
start_position = None
end_position = None
orig_answer_text = None
is_impossible = False
if is_training:
if FLAGS.version_2_with_negative:
is_impossible = qa["is_impossible"]
if (len(qa["answers"]) != 1) and (not is_impossible):
raise ValueError(
"For training, each question should have exactly 1 answer.")
if not is_impossible:
answer = qa["answers"][0]
orig_answer_text = answer["text"]
answer_offset = answer["answer_start"]
answer_length = len(orig_answer_text)
start_position = char_to_word_offset[answer_offset]
end_position = char_to_word_offset[answer_offset + answer_length -
1]
# Only add answers where the text can be exactly recovered from the
# document. If this CAN'T happen it's likely due to weird Unicode
# stuff so we will just skip the example.
#
# Note that this means for training mode, every example is NOT
# guaranteed to be preserved.
actual_text = " ".join(
doc_tokens[start_position:(end_position + 1)])
cleaned_answer_text = " ".join(
tokenization.whitespace_tokenize(orig_answer_text))
if actual_text.find(cleaned_answer_text) == -1:
tf.logging.warning("Could not find answer: '%s' vs. '%s'",
actual_text, cleaned_answer_text)
continue
else:
start_position = -1
end_position = -1
orig_answer_text = ""
example = SquadExample(
qas_id=qas_id,
question_text=question_text,
doc_tokens=doc_tokens,
orig_answer_text=orig_answer_text,
start_position=start_position,
end_position=end_position,
is_impossible=is_impossible)
examples.append(example)
if break_count == 8:
break
if break_count == 8:
break
if break_count == 8:
break
return examples
def convert_examples_to_features(examples, tokenizer, max_seq_length,
doc_stride, max_query_length, is_training,
output_fn):
"""Loads a data file into a list of `InputBatch`s."""
unique_id = 1000000000
for (example_index, example) in enumerate(examples):
query_tokens = tokenizer.tokenize(example.question_text)
if len(query_tokens) > max_query_length:
query_tokens = query_tokens[0:max_query_length]
tok_to_orig_index = []
orig_to_tok_index = []
all_doc_tokens = []
for (i, token) in enumerate(example.doc_tokens):
orig_to_tok_index.append(len(all_doc_tokens))
sub_tokens = tokenizer.tokenize(token)
for sub_token in sub_tokens:
tok_to_orig_index.append(i)
all_doc_tokens.append(sub_token)
tok_start_position = None
tok_end_position = None
if is_training and example.is_impossible:
tok_start_position = -1
tok_end_position = -1
if is_training and not example.is_impossible:
tok_start_position = orig_to_tok_index[example.start_position]
if example.end_position < len(example.doc_tokens) - 1:
tok_end_position = orig_to_tok_index[example.end_position + 1] - 1
else:
tok_end_position = len(all_doc_tokens) - 1
(tok_start_position, tok_end_position) = _improve_answer_span(
all_doc_tokens, tok_start_position, tok_end_position, tokenizer,
example.orig_answer_text)
# The -3 accounts for [CLS], [SEP] and [SEP]
max_tokens_for_doc = max_seq_length - len(query_tokens) - 3
# We can have documents that are longer than the maximum sequence length.
# To deal with this we do a sliding window approach, where we take chunks
# of the up to our max length with a stride of `doc_stride`.
_DocSpan = collections.namedtuple( # pylint: disable=invalid-name
"DocSpan", ["start", "length"])
doc_spans = []
start_offset = 0
while start_offset < len(all_doc_tokens):
length = len(all_doc_tokens) - start_offset
if length > max_tokens_for_doc:
length = max_tokens_for_doc
doc_spans.append(_DocSpan(start=start_offset, length=length))
if start_offset + length == len(all_doc_tokens):
break
start_offset += min(length, doc_stride)
for (doc_span_index, doc_span) in enumerate(doc_spans):
tokens = []
token_to_orig_map = {}
token_is_max_context = {}
segment_ids = []
tokens.append("[CLS]")
segment_ids.append(0)
for token in query_tokens:
tokens.append(token)
segment_ids.append(0)
tokens.append("[SEP]")
segment_ids.append(0)
for i in range(doc_span.length):
split_token_index = doc_span.start + i
token_to_orig_map[len(tokens)] = tok_to_orig_index[split_token_index]
is_max_context = _check_is_max_context(doc_spans, doc_span_index,
split_token_index)
token_is_max_context[len(tokens)] = is_max_context
tokens.append(all_doc_tokens[split_token_index])
segment_ids.append(1)
tokens.append("[SEP]")
segment_ids.append(1)
input_ids = tokenizer.convert_tokens_to_ids(tokens)
# The mask has 1 for real tokens and 0 for padding tokens. Only real
# tokens are attended to.
input_mask = [1] * len(input_ids)
# Zero-pad up to the sequence length.
while len(input_ids) < max_seq_length:
input_ids.append(0)
input_mask.append(0)
segment_ids.append(0)
assert len(input_ids) == max_seq_length
assert len(input_mask) == max_seq_length
assert len(segment_ids) == max_seq_length
start_position = None
end_position = None
if is_training and not example.is_impossible:
# For training, if our document chunk does not contain an annotation
# we throw it out, since there is nothing to predict.
doc_start = doc_span.start
doc_end = doc_span.start + doc_span.length - 1
out_of_span = False
if not (tok_start_position >= doc_start and
tok_end_position <= doc_end):
out_of_span = True
if out_of_span:
start_position = 0
end_position = 0
else:
doc_offset = len(query_tokens) + 2
start_position = tok_start_position - doc_start + doc_offset
end_position = tok_end_position - doc_start + doc_offset
if is_training and example.is_impossible:
start_position = 0
end_position = 0
if example_index < 20:
tf.logging.info("*** Example ***")
tf.logging.info("unique_id: %s" % (unique_id))
tf.logging.info("example_index: %s" % (example_index))
tf.logging.info("doc_span_index: %s" % (doc_span_index))
tf.logging.info("tokens: %s" % " ".join(
[tokenization.printable_text(x) for x in tokens]))
tf.logging.info("token_to_orig_map: %s" % " ".join(
["%d:%d" % (x, y) for (x, y) in six.iteritems(token_to_orig_map)]))
tf.logging.info("token_is_max_context: %s" % " ".join([
"%d:%s" % (x, y) for (x, y) in six.iteritems(token_is_max_context)
]))
tf.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
tf.logging.info(
"input_mask: %s" % " ".join([str(x) for x in input_mask]))
tf.logging.info(
"segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
if is_training and example.is_impossible:
tf.logging.info("impossible example")
if is_training and not example.is_impossible:
answer_text = " ".join(tokens[start_position:(end_position + 1)])
tf.logging.info("start_position: %d" % (start_position))
tf.logging.info("end_position: %d" % (end_position))
tf.logging.info(
"answer: %s" % (tokenization.printable_text(answer_text)))
feature = InputFeatures(
unique_id=unique_id,
example_index=example_index,
doc_span_index=doc_span_index,
tokens=tokens,
token_to_orig_map=token_to_orig_map,
token_is_max_context=token_is_max_context,
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
start_position=start_position,
end_position=end_position,
is_impossible=example.is_impossible)
# Run callback
output_fn(feature)
unique_id += 1
def _improve_answer_span(doc_tokens, input_start, input_end, tokenizer,
orig_answer_text):
"""Returns tokenized answer spans that better match the annotated answer."""
# The SQuAD annotations are character based. We first project them to
# whitespace-tokenized words. But then after WordPiece tokenization, we can
# often find a "better match". For example:
#
# Question: What year was John Smith born?
# Context: The leader was John Smith (1895-1943).
# Answer: 1895
#
# The original whitespace-tokenized answer will be "(1895-1943).". However
# after tokenization, our tokens will be "( 1895 - 1943 ) .". So we can match
# the exact answer, 1895.
#
# However, this is not always possible. Consider the following:
#
# Question: What country is the top exporter of electornics?
# Context: The Japanese electronics industry is the lagest in the world.
# Answer: Japan
#
# In this case, the annotator chose "Japan" as a character sub-span of
# the word "Japanese". Since our WordPiece tokenizer does not split
# "Japanese", we just use "Japanese" as the annotation. This is fairly rare
# in SQuAD, but does happen.
tok_answer_text = " ".join(tokenizer.tokenize(orig_answer_text))
for new_start in range(input_start, input_end + 1):
for new_end in range(input_end, new_start - 1, -1):
text_span = " ".join(doc_tokens[new_start:(new_end + 1)])
if text_span == tok_answer_text:
return (new_start, new_end)
return (input_start, input_end)
def _check_is_max_context(doc_spans, cur_span_index, position):
"""Check if this is the 'max context' doc span for the token."""
# Because of the sliding window approach taken to scoring documents, a single
# token can appear in multiple documents. E.g.
# Doc: the man went to the store and bought a gallon of milk
# Span A: the man went to the
# Span B: to the store and bought
# Span C: and bought a gallon of
# ...
#
# Now the word 'bought' will have two scores from spans B and C. We only
# want to consider the score with "maximum context", which we define as
# the *minimum* of its left and right context (the *sum* of left and
# right context will always be the same, of course).
#
# In the example the maximum context for 'bought' would be span C since
# it has 1 left context and 3 right context, while span B has 4 left context
# and 0 right context.
best_score = None
best_span_index = None
for (span_index, doc_span) in enumerate(doc_spans):
end = doc_span.start + doc_span.length - 1
if position < doc_span.start:
continue
if position > end:
continue
num_left_context = position - doc_span.start
num_right_context = end - position
score = min(num_left_context, num_right_context) + 0.01 * doc_span.length
if best_score is None or score > best_score:
best_score = score
best_span_index = span_index
return cur_span_index == best_span_index
def create_model(bert_config, is_training, input_ids, input_mask, segment_ids,
use_one_hot_embeddings):
"""Creates a classification model."""
model = modeling.BertModel(
config=bert_config,
is_training=is_training,
input_ids=input_ids,
input_mask=input_mask,
token_type_ids=segment_ids,
use_one_hot_embeddings=use_one_hot_embeddings)
final_hidden = model.get_sequence_output()
final_hidden_shape = modeling.get_shape_list(final_hidden, expected_rank=3)
batch_size = final_hidden_shape[0]
seq_length = final_hidden_shape[1]
hidden_size = final_hidden_shape[2]
output_weights = tf.get_variable(
"cls/squad/output_weights", [2, hidden_size],
initializer=tf.truncated_normal_initializer(stddev=0.02))
output_bias = tf.get_variable(
"cls/squad/output_bias", [2], initializer=tf.zeros_initializer())
final_hidden_matrix = tf.reshape(final_hidden,
[batch_size * seq_length, hidden_size])
logits = tf.matmul(final_hidden_matrix, output_weights, transpose_b=True)
logits = tf.nn.bias_add(logits, output_bias)
logits = tf.reshape(logits, [batch_size, seq_length, 2])
logits = tf.transpose(logits, [2, 0, 1])
unstacked_logits = tf.unstack(logits, axis=0)
(start_logits, end_logits) = (unstacked_logits[0], unstacked_logits[1])
return (start_logits, end_logits)
def model_fn_builder(bert_config, init_checkpoint, learning_rate,
num_train_steps, num_warmup_steps, use_tpu,
use_one_hot_embeddings):
"""Returns `model_fn` closure for TPUEstimator."""
def model_fn(features, labels, mode, params): # pylint: disable=unused-argument
"""The `model_fn` for TPUEstimator."""
tf.logging.info("*** Features ***")
for name in sorted(features.keys()):
tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape))
unique_ids = features["unique_ids"]
input_ids = features["input_ids"]
input_mask = features["input_mask"]
segment_ids = features["segment_ids"]
is_training = (mode == tf.estimator.ModeKeys.TRAIN)
(start_logits, end_logits) = create_model(
bert_config=bert_config,
is_training=is_training,
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids,
use_one_hot_embeddings=use_one_hot_embeddings)
tvars = tf.trainable_variables()
initialized_variable_names = {}
scaffold_fn = None
if init_checkpoint:
(assignment_map, initialized_variable_names
) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)
if use_tpu:
def tpu_scaffold():
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
return tf.train.Scaffold()
scaffold_fn = tpu_scaffold
else:
tf.train.init_from_checkpoint(init_checkpoint, assignment_map)
tf.logging.info("**** Trainable Variables ****")
for var in tvars:
init_string = ""
if var.name in initialized_variable_names:
init_string = ", *INIT_FROM_CKPT*"
tf.logging.info(" name = %s, shape = %s%s", var.name, var.shape,
init_string)
output_spec = None
if mode == tf.estimator.ModeKeys.TRAIN:
seq_length = modeling.get_shape_list(input_ids)[1]
def compute_loss(logits, positions):
one_hot_positions = tf.one_hot(
positions, depth=seq_length, dtype=tf.float32)
log_probs = tf.nn.log_softmax(logits, axis=-1)
loss = -tf.reduce_mean(
tf.reduce_sum(one_hot_positions * log_probs, axis=-1))
return loss
start_positions = features["start_positions"]
end_positions = features["end_positions"]
start_loss = compute_loss(start_logits, start_positions)
end_loss = compute_loss(end_logits, end_positions)
total_loss = (start_loss + end_loss) / 2.0
train_op = optimization.create_optimizer(
total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu)
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
loss=total_loss,
train_op=train_op,
scaffold_fn=scaffold_fn)
elif mode == tf.estimator.ModeKeys.PREDICT:
predictions = {
"unique_ids": unique_ids,
"start_logits": start_logits,
"end_logits": end_logits,
}
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode, predictions=predictions, scaffold_fn=scaffold_fn)
else:
raise ValueError(
"Only TRAIN and PREDICT modes are supported: %s" % (mode))
return output_spec
return model_fn
def input_fn_builder(input_file, seq_length, is_training, drop_remainder):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
name_to_features = {
"unique_ids": tf.FixedLenFeature([], tf.int64),
"input_ids": tf.FixedLenFeature([seq_length], tf.int64),
"input_mask": tf.FixedLenFeature([seq_length], tf.int64),
"segment_ids": tf.FixedLenFeature([seq_length], tf.int64),
}
if is_training:
name_to_features["start_positions"] = tf.FixedLenFeature([], tf.int64)
name_to_features["end_positions"] = tf.FixedLenFeature([], tf.int64)
def _decode_record(record, name_to_features):
"""Decodes a record to a TensorFlow example."""
example = tf.parse_single_example(record, name_to_features)
# tf.Example only supports tf.int64, but the TPU only supports tf.int32.
# So cast all int64 to int32.
for name in list(example.keys()):
t = example[name]
if t.dtype == tf.int64:
t = tf.to_int32(t)
example[name] = t
return example
def input_fn(params):
"""The actual input function."""
batch_size = params["batch_size"]
# For training, we want a lot of parallel reading and shuffling.
# For eval, we want no shuffling and parallel reading doesn't matter.
d = tf.data.TFRecordDataset(input_file)
if is_training:
d = d.repeat()
d = d.shuffle(buffer_size=100)
d = d.apply(
tf.contrib.data.map_and_batch(
lambda record: _decode_record(record, name_to_features),
batch_size=batch_size,
drop_remainder=drop_remainder))
return d
return input_fn
RawResult = collections.namedtuple("RawResult",
["unique_id", "start_logits", "end_logits"])
def write_predictions(all_examples, all_features, all_results, n_best_size,
max_answer_length, do_lower_case, output_prediction_file,
output_nbest_file, output_null_log_odds_file):
"""Write final predictions to the json file and log-odds of null if needed."""
tf.logging.info("Writing predictions to: %s" % (output_prediction_file))
tf.logging.info("Writing nbest to: %s" % (output_nbest_file))
example_index_to_features = collections.defaultdict(list)
for feature in all_features:
example_index_to_features[feature.example_index].append(feature)
unique_id_to_result = {}
for result in all_results:
unique_id_to_result[result.unique_id] = result
_PrelimPrediction = collections.namedtuple( # pylint: disable=invalid-name
"PrelimPrediction",
["feature_index", "start_index", "end_index", "start_logit", "end_logit"])
all_predictions = collections.OrderedDict()
all_nbest_json = collections.OrderedDict()
scores_diff_json = collections.OrderedDict()
for (example_index, example) in enumerate(all_examples):
features = example_index_to_features[example_index]
prelim_predictions = []
# keep track of the minimum score of null start+end of position 0
score_null = 1000000 # large and positive
min_null_feature_index = 0 # the paragraph slice with min mull score
null_start_logit = 0 # the start logit at the slice with min null score
null_end_logit = 0 # the end logit at the slice with min null score
for (feature_index, feature) in enumerate(features):
result = unique_id_to_result[feature.unique_id]
start_indexes = _get_best_indexes(result.start_logits, n_best_size)
end_indexes = _get_best_indexes(result.end_logits, n_best_size)
# if we could have irrelevant answers, get the min score of irrelevant
if FLAGS.version_2_with_negative:
feature_null_score = result.start_logits[0] + result.end_logits[0]
if feature_null_score < score_null:
score_null = feature_null_score
min_null_feature_index = feature_index
null_start_logit = result.start_logits[0]
null_end_logit = result.end_logits[0]
for start_index in start_indexes:
for end_index in end_indexes:
# We could hypothetically create invalid predictions, e.g., predict
# that the start of the span is in the question. We throw out all
# invalid predictions.
if start_index >= len(feature.tokens):
continue
if end_index >= len(feature.tokens):
continue
if start_index not in feature.token_to_orig_map:
continue
if end_index not in feature.token_to_orig_map:
continue
if not feature.token_is_max_context.get(start_index, False):
continue
if end_index < start_index:
continue
length = end_index - start_index + 1
if length > max_answer_length:
continue
prelim_predictions.append(
_PrelimPrediction(
feature_index=feature_index,
start_index=start_index,
end_index=end_index,
start_logit=result.start_logits[start_index],
end_logit=result.end_logits[end_index]))
if FLAGS.version_2_with_negative:
prelim_predictions.append(
_PrelimPrediction(
feature_index=min_null_feature_index,
start_index=0,
end_index=0,
start_logit=null_start_logit,
end_logit=null_end_logit))
prelim_predictions = sorted(
prelim_predictions,
key=lambda x: (x.start_logit + x.end_logit),
reverse=True)
_NbestPrediction = collections.namedtuple( # pylint: disable=invalid-name
"NbestPrediction", ["text", "start_logit", "end_logit"])
seen_predictions = {}
nbest = []
for pred in prelim_predictions:
if len(nbest) >= n_best_size:
break
feature = features[pred.feature_index]
if pred.start_index > 0: # this is a non-null prediction
tok_tokens = feature.tokens[pred.start_index:(pred.end_index + 1)]
orig_doc_start = feature.token_to_orig_map[pred.start_index]
orig_doc_end = feature.token_to_orig_map[pred.end_index]
orig_tokens = example.doc_tokens[orig_doc_start:(orig_doc_end + 1)]
tok_text = " ".join(tok_tokens)
# De-tokenize WordPieces that have been split off.
tok_text = tok_text.replace(" ##", "")
tok_text = tok_text.replace("##", "")
# Clean whitespace
tok_text = tok_text.strip()
tok_text = " ".join(tok_text.split())
orig_text = " ".join(orig_tokens)
final_text = get_final_text(tok_text, orig_text, do_lower_case)
if final_text in seen_predictions:
continue
seen_predictions[final_text] = True
else:
final_text = ""
seen_predictions[final_text] = True
nbest.append(
_NbestPrediction(
text=final_text,
start_logit=pred.start_logit,
end_logit=pred.end_logit))
# if we didn't inlude the empty option in the n-best, inlcude it
if FLAGS.version_2_with_negative:
if "" not in seen_predictions:
nbest.append(
_NbestPrediction(
text="", start_logit=null_start_logit,
end_logit=null_end_logit))
# In very rare edge cases we could have no valid predictions. So we
# just create a nonce prediction in this case to avoid failure.
if not nbest:
nbest.append(
_NbestPrediction(text="empty", start_logit=0.0, end_logit=0.0))
assert len(nbest) >= 1
total_scores = []
best_non_null_entry = None
for entry in nbest:
total_scores.append(entry.start_logit + entry.end_logit)
if not best_non_null_entry:
if entry.text:
best_non_null_entry = entry
probs = _compute_softmax(total_scores)
nbest_json = []
for (i, entry) in enumerate(nbest):
output = collections.OrderedDict()
output["text"] = entry.text
output["probability"] = probs[i]
output["start_logit"] = entry.start_logit
output["end_logit"] = entry.end_logit
nbest_json.append(output)
assert len(nbest_json) >= 1
if not FLAGS.version_2_with_negative:
all_predictions[example.qas_id] = nbest_json[0]["text"]
else:
# predict "" iff the null score - the score of best non-null > threshold
score_diff = score_null - best_non_null_entry.start_logit - (
best_non_null_entry.end_logit)
scores_diff_json[example.qas_id] = score_diff
if score_diff > FLAGS.null_score_diff_threshold:
all_predictions[example.qas_id] = ""
else:
all_predictions[example.qas_id] = best_non_null_entry.text
all_nbest_json[example.qas_id] = nbest_json
with tf.gfile.GFile(output_prediction_file, "w") as writer:
writer.write(json.dumps(all_predictions, indent=4) + "\n")
with tf.gfile.GFile(output_nbest_file, "w") as writer:
writer.write(json.dumps(all_nbest_json, indent=4) + "\n")
if FLAGS.version_2_with_negative:
with tf.gfile.GFile(output_null_log_odds_file, "w") as writer:
writer.write(json.dumps(scores_diff_json, indent=4) + "\n")
def get_final_text(pred_text, orig_text, do_lower_case):
"""Project the tokenized prediction back to the original text."""
# When we created the data, we kept track of the alignment between original
# (whitespace tokenized) tokens and our WordPiece tokenized tokens. So
# now `orig_text` contains the span of our original text corresponding to the
# span that we predicted.
#
# However, `orig_text` may contain extra characters that we don't want in
# our prediction.
#
# For example, let's say:
# pred_text = steve smith
# orig_text = Steve Smith's
#
# We don't want to return `orig_text` because it contains the extra "'s".
#
# We don't want to return `pred_text` because it's already been normalized
# (the SQuAD eval script also does punctuation stripping/lower casing but
# our tokenizer does additional normalization like stripping accent
# characters).
#
# What we really want to return is "Steve Smith".
#
# Therefore, we have to apply a semi-complicated alignment heruistic between
# `pred_text` and `orig_text` to get a character-to-charcter alignment. This
# can fail in certain cases in which case we just return `orig_text`.
def _strip_spaces(text):
ns_chars = []
ns_to_s_map = collections.OrderedDict()
for (i, c) in enumerate(text):
if c == " ":
continue
ns_to_s_map[len(ns_chars)] = i
ns_chars.append(c)
ns_text = "".join(ns_chars)
return (ns_text, ns_to_s_map)
# We first tokenize `orig_text`, strip whitespace from the result
# and `pred_text`, and check if they are the same length. If they are
# NOT the same length, the heuristic has failed. If they are the same
# length, we assume the characters are one-to-one aligned.
tokenizer = tokenization.BasicTokenizer(do_lower_case=do_lower_case)
tok_text = " ".join(tokenizer.tokenize(orig_text))
start_position = tok_text.find(pred_text)
if start_position == -1:
if FLAGS.verbose_logging:
tf.logging.info(
"Unable to find text: '%s' in '%s'" % (pred_text, orig_text))
return orig_text
end_position = start_position + len(pred_text) - 1
(orig_ns_text, orig_ns_to_s_map) = _strip_spaces(orig_text)
(tok_ns_text, tok_ns_to_s_map) = _strip_spaces(tok_text)
if len(orig_ns_text) != len(tok_ns_text):
if FLAGS.verbose_logging:
tf.logging.info("Length not equal after stripping spaces: '%s' vs '%s'",
orig_ns_text, tok_ns_text)
return orig_text
# We then project the characters in `pred_text` back to `orig_text` using
# the character-to-character alignment.
tok_s_to_ns_map = {}
for (i, tok_index) in six.iteritems(tok_ns_to_s_map):
tok_s_to_ns_map[tok_index] = i
orig_start_position = None
if start_position in tok_s_to_ns_map:
ns_start_position = tok_s_to_ns_map[start_position]
if ns_start_position in orig_ns_to_s_map:
orig_start_position = orig_ns_to_s_map[ns_start_position]
if orig_start_position is None:
if FLAGS.verbose_logging:
tf.logging.info("Couldn't map start position")
return orig_text
orig_end_position = None
if end_position in tok_s_to_ns_map:
ns_end_position = tok_s_to_ns_map[end_position]
if ns_end_position in orig_ns_to_s_map:
orig_end_position = orig_ns_to_s_map[ns_end_position]
if orig_end_position is None:
if FLAGS.verbose_logging:
tf.logging.info("Couldn't map end position")
return orig_text
output_text = orig_text[orig_start_position:(orig_end_position + 1)]
return output_text
def _get_best_indexes(logits, n_best_size):
"""Get the n-best logits from a list."""
index_and_score = sorted(enumerate(logits), key=lambda x: x[1], reverse=True)
best_indexes = []
for i in range(len(index_and_score)):
if i >= n_best_size:
break
best_indexes.append(index_and_score[i][0])
return best_indexes
def _compute_softmax(scores):
"""Compute softmax probability over raw logits."""
if not scores:
return []
max_score = None
for score in scores:
if max_score is None or score > max_score:
max_score = score
exp_scores = []
total_sum = 0.0
for score in scores:
x = math.exp(score - max_score)
exp_scores.append(x)
total_sum += x
probs = []
for score in exp_scores:
probs.append(score / total_sum)
return probs
class FeatureWriter(object):
"""Writes InputFeature to TF example file."""
def __init__(self, filename, is_training):
self.filename = filename
self.is_training = is_training
self.num_features = 0
self._writer = tf.python_io.TFRecordWriter(filename)
def process_feature(self, feature):
"""Write a InputFeature to the TFRecordWriter as a tf.train.Example."""
self.num_features += 1
def create_int_feature(values):
feature = tf.train.Feature(
int64_list=tf.train.Int64List(value=list(values)))
return feature
features = collections.OrderedDict()
features["unique_ids"] = create_int_feature([feature.unique_id])
features["input_ids"] = create_int_feature(feature.input_ids)
features["input_mask"] = create_int_feature(feature.input_mask)
features["segment_ids"] = create_int_feature(feature.segment_ids)
if self.is_training:
features["start_positions"] = create_int_feature([feature.start_position])
features["end_positions"] = create_int_feature([feature.end_position])
impossible = 0
if feature.is_impossible:
impossible = 1
features["is_impossible"] = create_int_feature([impossible])
tf_example = tf.train.Example(features=tf.train.Features(feature=features))
self._writer.write(tf_example.SerializeToString())
def close(self):
self._writer.close()
def validate_flags_or_throw(bert_config):
"""Validate the input FLAGS or throw an exception."""
tokenization.validate_case_matches_checkpoint(FLAGS.do_lower_case,
FLAGS.init_checkpoint)
if not FLAGS.do_train and not FLAGS.do_predict:
raise ValueError("At least one of `do_train` or `do_predict` must be True.")
if FLAGS.do_train:
if not FLAGS.train_file:
raise ValueError(
"If `do_train` is True, then `train_file` must be specified.")
if FLAGS.do_predict:
if not FLAGS.predict_file:
raise ValueError(
"If `do_predict` is True, then `predict_file` must be specified.")
if FLAGS.max_seq_length > bert_config.max_position_embeddings:
raise ValueError(
"Cannot use sequence length %d because the BERT model "
"was only trained up to sequence length %d" %
(FLAGS.max_seq_length, bert_config.max_position_embeddings))
if FLAGS.max_seq_length <= FLAGS.max_query_length + 3:
raise ValueError(
"The max_seq_length (%d) must be greater than max_query_length "
"(%d) + 3" % (FLAGS.max_seq_length, FLAGS.max_query_length))
def main |
tf.logging.set_verbosity(tf.logging.INFO)
bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)
validate_flags_or_throw(bert_config)
tf.gfile.MakeDirs(FLAGS.output_dir)
tokenizer = tokenization.FullTokenizer(
vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)
tpu_cluster_resolver = None
if FLAGS.use_tpu and FLAGS.tpu_name:
tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(
FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)
is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2
run_config = tf.contrib.tpu.RunConfig(
cluster=tpu_cluster_resolver,
master=FLAGS.master,
model_dir=FLAGS.output_dir,
save_checkpoints_steps=FLAGS.save_checkpoints_steps,
tpu_config=tf.contrib.tpu.TPUConfig(
iterations_per_loop=FLAGS.iterations_per_loop,
num_shards=FLAGS.num_tpu_cores,
per_host_input_for_training=is_per_host))
train_examples = None
num_train_steps = None
num_warmup_steps = None
if FLAGS.do_train:
train_examples = read_squad_examples(
input_file=FLAGS.train_file, is_training=True)
num_train_steps = int(
len(train_examples) / FLAGS.train_batch_size * FLAGS.num_train_epochs)
num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion)
# Pre-shuffle the input to avoid having to make a very large shuffle
# buffer in in the `input_fn`.
rng = random.Random(12345)
rng.shuffle(train_examples)
model_fn = model_fn_builder(
bert_config=bert_config,
init_checkpoint=FLAGS.init_checkpoint,
learning_rate=FLAGS.learning_rate,
num_train_steps=num_train_steps,
num_warmup_steps=num_warmup_steps,
use_tpu=FLAGS.use_tpu,
use_one_hot_embeddings=FLAGS.use_tpu)
# If TPU is not available, this will fall back to normal Estimator on CPU
# or GPU.
estimator = tf.contrib.tpu.TPUEstimator(
use_tpu=FLAGS.use_tpu,
model_fn=model_fn,
config=run_config,
train_batch_size=FLAGS.train_batch_size,
predict_batch_size=FLAGS.predict_batch_size)
if FLAGS.do_train:
# We write to a temporary file to avoid storing very large constant tensors
# in memory.
train_writer = FeatureWriter(
filename=os.path.join(FLAGS.output_dir, "train.tf_record"),
is_training=True)
convert_examples_to_features(
examples=train_examples,
tokenizer=tokenizer,
max_seq_length=FLAGS.max_seq_length,
doc_stride=FLAGS.doc_stride,
max_query_length=FLAGS.max_query_length,
is_training=True,
output_fn=train_writer.process_feature)
train_writer.close()
tf.logging.info("***** Running training *****")
tf.logging.info(" Num orig examples = %d", len(train_examples))
tf.logging.info(" Num split examples = %d", train_writer.num_features)
tf.logging.info(" Batch size = %d", FLAGS.train_batch_size)
tf.logging.info(" Num steps = %d", num_train_steps)
del train_examples
train_input_fn = input_fn_builder(
input_file=train_writer.filename,
seq_length=FLAGS.max_seq_length,
is_training=True,
drop_remainder=True)
estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)
if FLAGS.do_predict:
eval_examples = read_squad_examples(
input_file=FLAGS.predict_file, is_training=False)
eval_writer = FeatureWriter(
filename=os.path.join(FLAGS.output_dir, "eval.tf_record"),
is_training=False)
eval_features = []
def append_feature(feature):
eval_features.append(feature)
eval_writer.process_feature(feature)
convert_examples_to_features(
examples=eval_examples,
tokenizer=tokenizer,
max_seq_length=FLAGS.max_seq_length,
doc_stride=FLAGS.doc_stride,
max_query_length=FLAGS.max_query_length,
is_training=False,
output_fn=append_feature)
eval_writer.close()
tf.logging.info("***** Running predictions *****")
tf.logging.info(" Num orig examples = %d", len(eval_examples))
tf.logging.info(" Num split examples = %d", len(eval_features))
tf.logging.info(" Batch size = %d", FLAGS.predict_batch_size)
all_results = []
predict_input_fn = input_fn_builder(
input_file=eval_writer.filename,
seq_length=FLAGS.max_seq_length,
is_training=False,
drop_remainder=False)
# If running eval on the TPU, you will need to specify the number of
# steps.
all_results = []
for result in estimator.predict(
predict_input_fn, yield_single_examples=True):
if len(all_results) % 1000 == 0:
tf.logging.info("Processing example: %d" % (len(all_results)))
unique_id = int(result["unique_ids"])
start_logits = [float(x) for x in result["start_logits"].flat]
end_logits = [float(x) for x in result["end_logits"].flat]
all_results.append(
RawResult(
unique_id=unique_id,
start_logits=start_logits,
end_logits=end_logits))
output_prediction_file = os.path.join(FLAGS.output_dir, "predictions.json")
output_nbest_file = os.path.join(FLAGS.output_dir, "nbest_predictions.json")
output_null_log_odds_file = os.path.join(FLAGS.output_dir, "null_odds.json")
write_predictions(eval_examples, eval_features, all_results,
FLAGS.n_best_size, FLAGS.max_answer_length,
FLAGS.do_lower_case, output_prediction_file,
output_nbest_file, output_null_log_odds_file)
if __name__ == "__main__":
flags.mark_flag_as_required("vocab_file")
flags.mark_flag_as_required("bert_config_file")
flags.mark_flag_as_required("output_dir")
tf.app.run()
| (_): |
framed.rs | extern crate tokio_codec;
extern crate tokio_io;
extern crate bytes;
extern crate futures;
use futures::{Stream, Future};
use std::io::{self, Read};
use tokio_codec::{Framed, FramedParts, Decoder, Encoder};
use tokio_io::AsyncRead;
use bytes::{BytesMut, Buf, BufMut, IntoBuf};
const INITIAL_CAPACITY: usize = 8 * 1024;
/// Encode and decode u32 values.
struct U32Codec;
impl Decoder for U32Codec {
type Item = u32;
type Error = io::Error;
fn decode(&mut self, buf: &mut BytesMut) -> io::Result<Option<u32>> {
if buf.len() < 4 {
return Ok(None);
}
let n = buf.split_to(4).into_buf().get_u32_be();
Ok(Some(n))
}
}
impl Encoder for U32Codec {
type Item = u32;
type Error = io::Error;
fn encode(&mut self, item: u32, dst: &mut BytesMut) -> io::Result<()> {
// Reserve space
dst.reserve(4);
dst.put_u32_be(item);
Ok(())
}
}
/// This value should never be used
struct DontReadIntoThis;
impl Read for DontReadIntoThis {
fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
Err(io::Error::new(io::ErrorKind::Other,
"Read into something you weren't supposed to."))
}
}
impl AsyncRead for DontReadIntoThis {}
#[test]
fn can_read_from_existing_buf() {
let mut parts = FramedParts::new(DontReadIntoThis, U32Codec);
parts.read_buf = vec![0, 0, 0, 42].into();
let framed = Framed::from_parts(parts);
let num = framed
.into_future()
.map(|(first_num, _)| { | .wait()
.map_err(|e| e.0)
.unwrap();
assert_eq!(num, 42);
}
#[test]
fn external_buf_grows_to_init() {
let mut parts = FramedParts::new(DontReadIntoThis, U32Codec);
parts.read_buf = vec![0, 0, 0, 42].into();
let framed = Framed::from_parts(parts);
let FramedParts { read_buf, .. } = framed.into_parts();
assert_eq!(read_buf.capacity(), INITIAL_CAPACITY);
}
#[test]
fn external_buf_does_not_shrink() {
let mut parts = FramedParts::new(DontReadIntoThis, U32Codec);
parts.read_buf = vec![0; INITIAL_CAPACITY * 2].into();
let framed = Framed::from_parts(parts);
let FramedParts { read_buf, .. } = framed.into_parts();
assert_eq!(read_buf.capacity(), INITIAL_CAPACITY * 2);
} | first_num.unwrap()
}) |
packet.py | import os
from django.conf import settings
import requests
def | ():
return os.path.join(settings.PROJECT_ROOT, 'static', settings.SPONSORSHIP_PACKET_FILE) if settings.SPONSORSHIP_PACKET_FILE else None
def fetch_packet():
if settings.SPONSORSHIP_PACKET_FILE and settings.SPONSORSHIP_PACKET_URL:
if not os.path.exists(get_packet_file_path()):
r = requests.get(settings.SPONSORSHIP_PACKET_URL, stream=True)
if r.status_code == 200:
with open(get_packet_file_path(), 'wb') as f:
for chunk in r.iter_content(1024):
f.write(chunk)
| get_packet_file_path |
distplot.py | """Matplotlib distplot."""
import warnings
import matplotlib.pyplot as plt
import numpy as np
from . import backend_show
from ...kdeplot import plot_kde
from ...plot_utils import matplotlib_kwarg_dealiaser
from ....numeric_utils import get_bins
def plot_dist(
values,
values2,
color,
kind,
cumulative,
label,
rotated,
rug,
bw,
quantiles,
contour,
fill_last,
textsize,
plot_kwargs,
fill_kwargs,
rug_kwargs,
contour_kwargs,
contourf_kwargs,
pcolormesh_kwargs,
hist_kwargs,
ax,
backend_kwargs,
show,
):
"""Matplotlib distplot."""
if backend_kwargs is not None:
warnings.warn(
(
"Argument backend_kwargs has not effect in matplotlib.plot_dist"
"Supplied value won't be used"
)
)
backend_kwargs = None
if ax is None:
|
if kind == "hist":
ax = _histplot_mpl_op(
values=values, values2=values2, rotated=rotated, ax=ax, hist_kwargs=hist_kwargs
)
elif kind == "kde":
plot_kwargs = matplotlib_kwarg_dealiaser(plot_kwargs, "plot")
plot_kwargs.setdefault("color", color)
legend = label is not None
ax = plot_kde(
values,
values2,
cumulative=cumulative,
rug=rug,
label=label,
bw=bw,
quantiles=quantiles,
rotated=rotated,
contour=contour,
legend=legend,
fill_last=fill_last,
textsize=textsize,
plot_kwargs=plot_kwargs,
fill_kwargs=fill_kwargs,
rug_kwargs=rug_kwargs,
contour_kwargs=contour_kwargs,
contourf_kwargs=contourf_kwargs,
pcolormesh_kwargs=pcolormesh_kwargs,
ax=ax,
backend="matplotlib",
backend_kwargs=backend_kwargs,
show=show,
)
if backend_show(show):
plt.show()
return ax
def _histplot_mpl_op(values, values2, rotated, ax, hist_kwargs):
"""Add a histogram for the data to the axes."""
if values2 is not None:
raise NotImplementedError("Insert hexbin plot here")
bins = hist_kwargs.pop("bins")
if bins is None:
bins = get_bins(values)
ax.hist(np.asarray(values).flatten(), bins=bins, **hist_kwargs)
if rotated:
ax.set_yticks(bins[:-1])
else:
ax.set_xticks(bins[:-1])
if hist_kwargs.get("label") is not None:
ax.legend()
return ax
| ax = plt.gca() |
csp_test.go | package csp
import (
"reflect"
"testing"
"github.com/vitaminmoo/orderedset"
)
func TestNewPolicy(t *testing.T) {
tests := []struct {
name string
want *Policy
}{
struct {
name string
want *Policy
}{
"blank",
&Policy{
Sources: make(map[string]*orderedset.OrderedSet),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := NewPolicy(); !reflect.DeepEqual(got, tt.want) {
t.Errorf("NewPolicy() = %v, want %v", got, tt.want)
}
})
}
}
func TestFromString(t *testing.T) {
type args struct {
header string
}
tests := []struct {
name string
args args
want *Policy
}{
struct {
name string
args args
want *Policy
}{
"simple",
args{header: "img-src 'none';"},
&Policy{
Directives: *orderedset.NewOrderedSet([]string{"img-src"}),
Sources: map[string]*orderedset.OrderedSet{
"img-src": orderedset.NewOrderedSet([]string{"'none'"}),
},
},
},
{
"medium",
args{header: "img-src https: 'self'; object-src 'none'; default-src 'none'"},
&Policy{
Directives: *orderedset.NewOrderedSet([]string{"img-src", "object-src", "default-src"}),
Sources: map[string]*orderedset.OrderedSet{
"img-src": orderedset.NewOrderedSet([]string{"https:", "'self'"}),
"object-src": orderedset.NewOrderedSet([]string{"'none'"}),
"default-src": orderedset.NewOrderedSet([]string{"'none'"}),
},
},
},
{
"dupe",
args{header: "img-src https: 'self'; img-src 'none'"},
&Policy{
Directives: *orderedset.NewOrderedSet([]string{"img-src"}),
Sources: map[string]*orderedset.OrderedSet{
"img-src": orderedset.NewOrderedSet([]string{"https:", "'self'"}),
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := FromString(tt.args.header); !reflect.DeepEqual(got, tt.want) {
t.Errorf("FromString() = %v, want %v", got, tt.want)
}
})
}
}
func TestRoundTripFromString(t *testing.T) |
func TestPolicy_Set(t *testing.T) {
type args struct {
directive string
sources []string
}
tests := []struct {
name string
p *Policy
args args
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.p.Set(tt.args.directive, tt.args.sources)
})
}
}
func TestPolicy_String(t *testing.T) {
tests := []struct {
name string
p *Policy
want string
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.p.String(); got != tt.want {
t.Errorf("Policy.String() = %v, want %v", got, tt.want)
}
})
}
}
func TestPolicy_SetModerateDefaults(t *testing.T) {
tests := []struct {
name string
p *Policy
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.p.SetModerateDefaults()
})
}
}
func TestPolicy_SetSecureDefaults(t *testing.T) {
tests := []struct {
name string
p *Policy
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.p.SetSecureDefaults()
})
}
}
func TestPolicy_AddAllowOldBrowsers(t *testing.T) {
tests := []struct {
name string
p *Policy
}{
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.p.AddAllowOldBrowsers()
})
}
}
| {
type args struct {
header string
}
tests := []struct {
name string
args args
want string
}{
struct {
name string
args args
want string
}{
"simple",
args{header: "img-src 'none';"},
"img-src 'none';",
},
{
"medium",
args{header: "img-src https: 'self'; object-src 'none'; default-src 'none';"},
"img-src https: 'self'; object-src 'none'; default-src 'none';",
},
{
"dupe",
args{header: "img-src https: 'self'; img-src 'none';"},
"img-src https: 'self';",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := FromString(tt.args.header).String(); !reflect.DeepEqual(got, tt.want) {
t.Errorf("FromString() = %v, want %v", got, tt.want)
}
})
}
} |
delete-delivery-channel.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_config::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Region.
#[structopt(short, long)]
region: Option<String>,
/// The channel to delete.
#[structopt(short, long)]
channel: String,
/// Whether to display additional information.
#[structopt(short, long)]
verbose: bool,
}
// Deletes a channel.
// snippet-start:[config.rust.delete-delivery-channel]
async fn delete_channel(
client: &Client,
channel: &str,
) -> Result<(), Error> {
client
.delete_delivery_channel()
.delivery_channel_name(channel)
.send()
.await?;
println!("Done");
Ok(())
}
// snippet-end:[config.rust.delete-delivery-channel]
/// Deletes an AWS Config delivery channel.
///
/// # Arguments
///
/// * `-c CHANNEL` - The name of the channel to delete.
/// * `[-r REGION]` - The Region in which the client is created.
/// If not supplied, uses the value of the **AWS_REGION** environment variable.
/// If the environment variable is not set, defaults to **us-west-2**.
/// * `[-v]` - Whether to display information.
#[tokio::main]
async fn | () -> Result<(), Error> {
tracing_subscriber::fmt::init();
let Opt {
channel,
region,
verbose,
} = Opt::from_args();
let region_provider = RegionProviderChain::first_try(region.map(Region::new))
.or_default_provider()
.or_else(Region::new("us-west-2"));
println!();
if verbose {
println!("Config client version: {}", PKG_VERSION);
println!(
"Region: {}",
region_provider.region().await.unwrap().as_ref()
);
println!("Delivery channel: {}", channel);
println!();
}
let shared_config = aws_config::from_env().region(region_provider).load().await;
let client = Client::new(&shared_config);
delete_channel(&client, &channel).await
}
| main |
app.py | from flask import Flask, jsonify
import data4app
app = Flask(__name__)
@app.route("/")
def | ():
return "Lets goooo!!!"
@app.route("/<var>")
def jsonified(var):
data = data4app.get_data(var)
return jsonify(data)
if __name__ == "__main__":
app.run(debug=True)
| home |
BACnetContextTagTime.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 (
"github.com/apache/plc4x/plc4go/internal/plc4go/spi/utils"
"github.com/pkg/errors"
)
// Code generated by code-generation. DO NOT EDIT.
// The data-structure of this message
type BACnetContextTagTime struct {
*BACnetContextTag
Payload *BACnetTagPayloadTime
// Arguments.
TagNumberArgument uint8
IsNotOpeningOrClosingTag bool
}
// The corresponding interface
type IBACnetContextTagTime interface {
IBACnetContextTag
// GetPayload returns Payload (property field)
GetPayload() *BACnetTagPayloadTime
// GetLengthInBytes returns the length in bytes
GetLengthInBytes() uint16
// GetLengthInBits returns the length in bits
GetLengthInBits() uint16
// Serialize serializes this type
Serialize(writeBuffer utils.WriteBuffer) error
}
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
/////////////////////// Accessors for discriminator values.
///////////////////////
func (m *BACnetContextTagTime) GetDataType() BACnetDataType {
return BACnetDataType_TIME
}
///////////////////////
///////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
func (m *BACnetContextTagTime) InitializeParent(parent *BACnetContextTag, header *BACnetTagHeader) {
m.BACnetContextTag.Header = header
}
func (m *BACnetContextTagTime) GetParent() *BACnetContextTag {
return m.BACnetContextTag
}
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
/////////////////////// Accessors for property fields.
///////////////////////
func (m *BACnetContextTagTime) GetPayload() *BACnetTagPayloadTime {
return m.Payload
}
///////////////////////
///////////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
// NewBACnetContextTagTime factory function for BACnetContextTagTime
func NewBACnetContextTagTime(payload *BACnetTagPayloadTime, header *BACnetTagHeader, tagNumberArgument uint8, isNotOpeningOrClosingTag bool) *BACnetContextTag {
child := &BACnetContextTagTime{
Payload: payload,
BACnetContextTag: NewBACnetContextTag(header, tagNumberArgument),
}
child.Child = child
return child.BACnetContextTag
}
func CastBACnetContextTagTime(structType interface{}) *BACnetContextTagTime |
func (m *BACnetContextTagTime) GetTypeName() string {
return "BACnetContextTagTime"
}
func (m *BACnetContextTagTime) GetLengthInBits() uint16 {
return m.GetLengthInBitsConditional(false)
}
func (m *BACnetContextTagTime) GetLengthInBitsConditional(lastItem bool) uint16 {
lengthInBits := uint16(m.GetParentLengthInBits())
// Simple field (payload)
lengthInBits += m.Payload.GetLengthInBits()
return lengthInBits
}
func (m *BACnetContextTagTime) GetLengthInBytes() uint16 {
return m.GetLengthInBits() / 8
}
func BACnetContextTagTimeParse(readBuffer utils.ReadBuffer, tagNumberArgument uint8, dataType BACnetDataType, isNotOpeningOrClosingTag bool) (*BACnetContextTagTime, error) {
if pullErr := readBuffer.PullContext("BACnetContextTagTime"); pullErr != nil {
return nil, pullErr
}
currentPos := readBuffer.GetPos()
_ = currentPos
// Validation
if !(isNotOpeningOrClosingTag) {
return nil, utils.ParseAssertError{"length 6 and 7 reserved for opening and closing tag"}
}
// Simple Field (payload)
if pullErr := readBuffer.PullContext("payload"); pullErr != nil {
return nil, pullErr
}
_payload, _payloadErr := BACnetTagPayloadTimeParse(readBuffer)
if _payloadErr != nil {
return nil, errors.Wrap(_payloadErr, "Error parsing 'payload' field")
}
payload := CastBACnetTagPayloadTime(_payload)
if closeErr := readBuffer.CloseContext("payload"); closeErr != nil {
return nil, closeErr
}
if closeErr := readBuffer.CloseContext("BACnetContextTagTime"); closeErr != nil {
return nil, closeErr
}
// Create a partially initialized instance
_child := &BACnetContextTagTime{
Payload: CastBACnetTagPayloadTime(payload),
BACnetContextTag: &BACnetContextTag{},
}
_child.BACnetContextTag.Child = _child
return _child, nil
}
func (m *BACnetContextTagTime) Serialize(writeBuffer utils.WriteBuffer) error {
ser := func() error {
if pushErr := writeBuffer.PushContext("BACnetContextTagTime"); pushErr != nil {
return pushErr
}
// Simple Field (payload)
if pushErr := writeBuffer.PushContext("payload"); pushErr != nil {
return pushErr
}
_payloadErr := m.Payload.Serialize(writeBuffer)
if popErr := writeBuffer.PopContext("payload"); popErr != nil {
return popErr
}
if _payloadErr != nil {
return errors.Wrap(_payloadErr, "Error serializing 'payload' field")
}
if popErr := writeBuffer.PopContext("BACnetContextTagTime"); popErr != nil {
return popErr
}
return nil
}
return m.SerializeParent(writeBuffer, m, ser)
}
func (m *BACnetContextTagTime) String() string {
if m == nil {
return "<nil>"
}
buffer := utils.NewBoxedWriteBufferWithOptions(true, true)
if err := m.Serialize(buffer); err != nil {
return err.Error()
}
return buffer.GetBox().String()
}
| {
if casted, ok := structType.(BACnetContextTagTime); ok {
return &casted
}
if casted, ok := structType.(*BACnetContextTagTime); ok {
return casted
}
if casted, ok := structType.(BACnetContextTag); ok {
return CastBACnetContextTagTime(casted.Child)
}
if casted, ok := structType.(*BACnetContextTag); ok {
return CastBACnetContextTagTime(casted.Child)
}
return nil
} |
array_list.rs | // 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.
use std::any::Any;
use std::fmt;
use std::mem;
use num::Num;
use super::{
array::print_long_array, make_array, raw_pointer::RawPtrBox, Array, ArrayData,
ArrayRef, BooleanBufferBuilder, GenericListArrayIter, PrimitiveArray,
};
use crate::{
buffer::MutableBuffer,
datatypes::{ArrowNativeType, ArrowPrimitiveType, DataType, Field},
error::ArrowError,
};
/// trait declaring an offset size, relevant for i32 vs i64 array types.
pub trait OffsetSizeTrait: ArrowNativeType + Num + Ord + std::ops::AddAssign {
fn is_large() -> bool;
}
impl OffsetSizeTrait for i32 {
#[inline]
fn is_large() -> bool {
false
}
}
impl OffsetSizeTrait for i64 {
#[inline]
fn is_large() -> bool {
true
}
}
/// Generic struct for a primitive Array
///
/// For non generic lists, you may wish to consider using [`ListArray`] or [`LargeListArray`]`
pub struct GenericListArray<OffsetSize> {
data: ArrayData,
values: ArrayRef,
value_offsets: RawPtrBox<OffsetSize>,
}
impl<OffsetSize: OffsetSizeTrait> GenericListArray<OffsetSize> {
/// Returns a reference to the values of this list.
pub fn values(&self) -> ArrayRef {
self.values.clone()
}
/// Returns a clone of the value type of this list.
pub fn value_type(&self) -> DataType {
self.values.data_ref().data_type().clone()
}
/// Returns ith value of this list array.
/// # Safety
/// Caller must ensure that the index is within the array bounds
pub unsafe fn value_unchecked(&self, i: usize) -> ArrayRef {
let end = *self.value_offsets().get_unchecked(i + 1);
let start = *self.value_offsets().get_unchecked(i);
self.values
.slice(start.to_usize().unwrap(), (end - start).to_usize().unwrap())
}
/// Returns ith value of this list array.
pub fn value(&self, i: usize) -> ArrayRef {
let end = self.value_offsets()[i + 1];
let start = self.value_offsets()[i];
self.values
.slice(start.to_usize().unwrap(), (end - start).to_usize().unwrap())
}
/// Returns the offset values in the offsets buffer
#[inline]
pub fn value_offsets(&self) -> &[OffsetSize] {
// Soundness
// pointer alignment & location is ensured by RawPtrBox
// buffer bounds/offset is ensured by the ArrayData instance.
unsafe {
std::slice::from_raw_parts(
self.value_offsets.as_ptr().add(self.data.offset()),
self.len() + 1,
)
}
}
/// Returns the length for value at index `i`.
#[inline]
pub fn value_length(&self, i: usize) -> OffsetSize {
let offsets = self.value_offsets();
offsets[i + 1] - offsets[i]
}
/// constructs a new iterator
pub fn iter<'a>(&'a self) -> GenericListArrayIter<'a, OffsetSize> {
GenericListArrayIter::<'a, OffsetSize>::new(&self)
}
#[inline]
fn get_type(data_type: &DataType) -> Option<&DataType> {
if OffsetSize::is_large() {
if let DataType::LargeList(child) = data_type {
Some(child.data_type())
} else {
None
}
} else if let DataType::List(child) = data_type {
Some(child.data_type())
} else {
None
}
}
/// Creates a [`GenericListArray`] from an iterator of primitive values
/// # Example
/// ```
/// # use arrow::array::ListArray;
/// # use arrow::datatypes::Int32Type;
/// let data = vec![
/// Some(vec![Some(0), Some(1), Some(2)]),
/// None,
/// Some(vec![Some(3), None, Some(5)]),
/// Some(vec![Some(6), Some(7)]),
/// ];
/// let list_array = ListArray::from_iter_primitive::<Int32Type, _, _>(data);
/// println!("{:?}", list_array);
/// ```
pub fn from_iter_primitive<T, P, I>(iter: I) -> Self
where
T: ArrowPrimitiveType,
P: AsRef<[Option<<T as ArrowPrimitiveType>::Native>]>
+ IntoIterator<Item = Option<<T as ArrowPrimitiveType>::Native>>,
I: IntoIterator<Item = Option<P>>,
{
let iterator = iter.into_iter();
let (lower, _) = iterator.size_hint();
let mut offsets =
MutableBuffer::new((lower + 1) * std::mem::size_of::<OffsetSize>());
let mut length_so_far = OffsetSize::zero();
offsets.push(length_so_far);
let mut null_buf = BooleanBufferBuilder::new(lower);
let values: PrimitiveArray<T> = iterator
.filter_map(|maybe_slice| {
// regardless of whether the item is Some, the offsets and null buffers must be updated.
match &maybe_slice {
Some(x) => {
length_so_far +=
OffsetSize::from_usize(x.as_ref().len()).unwrap();
null_buf.append(true);
}
None => null_buf.append(false),
};
offsets.push(length_so_far);
maybe_slice
})
.flatten()
.collect();
let field = Box::new(Field::new("item", T::DATA_TYPE, true));
let data_type = if OffsetSize::is_large() {
DataType::LargeList(field)
} else {
DataType::List(field)
};
let data = ArrayData::builder(data_type)
.len(null_buf.len())
.add_buffer(offsets.into())
.add_child_data(values.data().clone())
.null_bit_buffer(null_buf.into())
.build();
Self::from(data)
}
}
impl<OffsetSize: OffsetSizeTrait> From<ArrayData> for GenericListArray<OffsetSize> {
fn from(data: ArrayData) -> Self {
Self::try_new_from_array_data(data).expect(
"Expected infallable creation of GenericListArray from ArrayDataRef failed",
)
}
}
impl<OffsetSize: OffsetSizeTrait> GenericListArray<OffsetSize> {
fn try_new_from_array_data(data: ArrayData) -> Result<Self, ArrowError> {
if data.buffers().len() != 1 {
return Err(ArrowError::InvalidArgumentError(
format!("ListArray data should contain a single buffer only (value offsets), had {}",
data.len())));
}
if data.child_data().len() != 1 {
return Err(ArrowError::InvalidArgumentError(format!(
"ListArray should contain a single child array (values array), had {}",
data.child_data().len()
)));
}
let values = data.child_data()[0].clone();
if let Some(child_data_type) = Self::get_type(data.data_type()) {
if values.data_type() != child_data_type {
return Err(ArrowError::InvalidArgumentError(format!(
"[Large]ListArray's child datatype {:?} does not \
correspond to the List's datatype {:?}",
values.data_type(),
child_data_type
)));
}
} else {
return Err(ArrowError::InvalidArgumentError(format!(
"[Large]ListArray's datatype must be [Large]ListArray(). It is {:?}",
data.data_type()
)));
}
let values = make_array(values);
let value_offsets = data.buffers()[0].as_ptr();
let value_offsets = unsafe { RawPtrBox::<OffsetSize>::new(value_offsets) };
unsafe {
if !(*value_offsets.as_ptr().offset(0)).is_zero() {
return Err(ArrowError::InvalidArgumentError(String::from(
"offsets do not start at zero",
)));
}
}
Ok(Self {
data,
values,
value_offsets,
})
}
}
impl<OffsetSize: 'static + OffsetSizeTrait> Array for GenericListArray<OffsetSize> {
fn as_any(&self) -> &Any {
self
}
fn data(&self) -> &ArrayData {
&self.data
}
/// Returns the total number of bytes of memory occupied by the buffers owned by this [ListArray].
fn get_buffer_memory_size(&self) -> usize {
self.data.get_buffer_memory_size()
}
/// Returns the total number of bytes of memory occupied physically by this [ListArray].
fn get_array_memory_size(&self) -> usize {
self.data.get_array_memory_size() + mem::size_of_val(self)
}
}
impl<OffsetSize: OffsetSizeTrait> fmt::Debug for GenericListArray<OffsetSize> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let prefix = if OffsetSize::is_large() { "Large" } else { "" };
write!(f, "{}ListArray\n[\n", prefix)?;
print_long_array(self, f, |array, index, f| {
fmt::Debug::fmt(&array.value(index), f)
})?;
write!(f, "]")
}
}
/// A list array where each element is a variable-sized sequence of values with the same
/// type whose memory offsets between elements are represented by a i32.
///
/// # Example
///
/// ```
/// # use arrow::array::{Array, ListArray, Int32Array};
/// # use arrow::datatypes::{DataType, Int32Type};
/// let data = vec![
/// Some(vec![Some(0), Some(1), Some(2)]),
/// None,
/// Some(vec![Some(3), None, Some(5), Some(19)]),
/// Some(vec![Some(6), Some(7)]),
/// ];
/// let list_array = ListArray::from_iter_primitive::<Int32Type, _, _>(data);
/// assert_eq!(DataType::Int32, list_array.value_type());
/// assert_eq!(4, list_array.len());
/// assert_eq!(1, list_array.null_count());
/// assert_eq!(3, list_array.value_length(0));
/// assert_eq!(0, list_array.value_length(1));
/// assert_eq!(4, list_array.value_length(2));
/// assert_eq!(
/// 19,
/// list_array
/// .value(2)
/// .as_any()
/// .downcast_ref::<Int32Array>()
/// .unwrap()
/// .value(3)
/// )
/// ```
pub type ListArray = GenericListArray<i32>;
/// A list array where each element is a variable-sized sequence of values with the same
/// type whose memory offsets between elements are represented by a i64.
/// # Example
///
/// ```
/// # use arrow::array::{Array, LargeListArray, Int64Array};
/// # use arrow::datatypes::{DataType, Int64Type};
/// let data = vec![
/// Some(vec![Some(0), Some(1), Some(2)]),
/// None,
/// Some(vec![Some(3), None, Some(5), Some(19)]),
/// Some(vec![Some(6), Some(7)]),
/// ];
/// let list_array = LargeListArray::from_iter_primitive::<Int64Type, _, _>(data);
/// assert_eq!(DataType::Int64, list_array.value_type());
/// assert_eq!(4, list_array.len());
/// assert_eq!(1, list_array.null_count());
/// assert_eq!(3, list_array.value_length(0));
/// assert_eq!(0, list_array.value_length(1));
/// assert_eq!(4, list_array.value_length(2));
/// assert_eq!(
/// 19,
/// list_array
/// .value(2)
/// .as_any()
/// .downcast_ref::<Int64Array>()
/// .unwrap()
/// .value(3)
/// )
/// ```
pub type LargeListArray = GenericListArray<i64>;
/// A list array where each element is a fixed-size sequence of values with the same
/// type whose maximum length is represented by a i32.
pub struct FixedSizeListArray {
data: ArrayData,
values: ArrayRef,
length: i32,
}
impl FixedSizeListArray {
/// Returns a reference to the values of this list.
pub fn values(&self) -> ArrayRef {
self.values.clone()
}
/// Returns a clone of the value type of this list.
pub fn value_type(&self) -> DataType {
self.values.data_ref().data_type().clone()
}
/// Returns ith value of this list array.
pub fn value(&self, i: usize) -> ArrayRef {
self.values
.slice(self.value_offset(i) as usize, self.value_length() as usize)
}
/// Returns the offset for value at index `i`.
///
/// Note this doesn't do any bound checking, for performance reason.
#[inline]
pub fn value_offset(&self, i: usize) -> i32 {
self.value_offset_at(self.data.offset() + i)
}
/// Returns the length for value at index `i`.
///
/// Note this doesn't do any bound checking, for performance reason.
#[inline]
pub const fn value_length(&self) -> i32 {
self.length
}
#[inline]
const fn value_offset_at(&self, i: usize) -> i32 {
i as i32 * self.length
}
}
impl From<ArrayData> for FixedSizeListArray {
fn from(data: ArrayData) -> Self {
assert_eq!(
data.buffers().len(),
0,
"FixedSizeListArray data should not contain a buffer for value offsets"
);
assert_eq!(
data.child_data().len(),
1,
"FixedSizeListArray should contain a single child array (values array)"
);
let values = make_array(data.child_data()[0].clone());
let length = match data.data_type() {
DataType::FixedSizeList(_, len) => {
if *len > 0 {
// check that child data is multiple of length
assert_eq!(
values.len() % *len as usize,
0,
"FixedSizeListArray child array length should be a multiple of {}",
len
);
}
*len
}
_ => {
panic!("FixedSizeListArray data should contain a FixedSizeList data type")
}
};
Self {
data,
values,
length,
}
}
}
impl Array for FixedSizeListArray {
fn as_any(&self) -> &Any {
self
}
fn data(&self) -> &ArrayData {
&self.data
}
/// Returns the total number of bytes of memory occupied by the buffers owned by this [FixedSizeListArray].
fn get_buffer_memory_size(&self) -> usize {
self.data.get_buffer_memory_size() + self.values().get_buffer_memory_size()
}
/// Returns the total number of bytes of memory occupied physically by this [FixedSizeListArray].
fn get_array_memory_size(&self) -> usize {
self.data.get_array_memory_size()
+ self.values().get_array_memory_size()
+ mem::size_of_val(self)
}
}
impl fmt::Debug for FixedSizeListArray {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result |
}
#[cfg(test)]
mod tests {
use crate::{
alloc,
array::ArrayData,
array::Int32Array,
buffer::Buffer,
datatypes::Field,
datatypes::{Int32Type, ToByteSlice},
util::bit_util,
};
use super::*;
fn create_from_buffers() -> ListArray {
// Construct a value array
let value_data = ArrayData::builder(DataType::Int32)
.len(8)
.add_buffer(Buffer::from(&[0, 1, 2, 3, 4, 5, 6, 7].to_byte_slice()))
.build();
// Construct a buffer for value offsets, for the nested array:
// [[0, 1, 2], [3, 4, 5], [6, 7]]
let value_offsets = Buffer::from(&[0, 3, 6, 8].to_byte_slice());
// Construct a list array from the above two
let list_data_type =
DataType::List(Box::new(Field::new("item", DataType::Int32, true)));
let list_data = ArrayData::builder(list_data_type)
.len(3)
.add_buffer(value_offsets)
.add_child_data(value_data)
.build();
ListArray::from(list_data)
}
#[test]
fn test_from_iter_primitive() {
let data = vec![
Some(vec![Some(0), Some(1), Some(2)]),
Some(vec![Some(3), Some(4), Some(5)]),
Some(vec![Some(6), Some(7)]),
];
let list_array = ListArray::from_iter_primitive::<Int32Type, _, _>(data);
let another = create_from_buffers();
assert_eq!(list_array, another)
}
#[test]
fn test_list_array() {
// Construct a value array
let value_data = ArrayData::builder(DataType::Int32)
.len(8)
.add_buffer(Buffer::from_slice_ref(&[0, 1, 2, 3, 4, 5, 6, 7]))
.build();
// Construct a buffer for value offsets, for the nested array:
// [[0, 1, 2], [3, 4, 5], [6, 7]]
let value_offsets = Buffer::from_slice_ref(&[0, 3, 6, 8]);
// Construct a list array from the above two
let list_data_type =
DataType::List(Box::new(Field::new("item", DataType::Int32, false)));
let list_data = ArrayData::builder(list_data_type.clone())
.len(3)
.add_buffer(value_offsets.clone())
.add_child_data(value_data.clone())
.build();
let list_array = ListArray::from(list_data);
let values = list_array.values();
assert_eq!(&value_data, values.data());
assert_eq!(DataType::Int32, list_array.value_type());
assert_eq!(3, list_array.len());
assert_eq!(0, list_array.null_count());
assert_eq!(6, list_array.value_offsets()[2]);
assert_eq!(2, list_array.value_length(2));
assert_eq!(
0,
list_array
.value(0)
.as_any()
.downcast_ref::<Int32Array>()
.unwrap()
.value(0)
);
assert_eq!(
0,
unsafe { list_array.value_unchecked(0) }
.as_any()
.downcast_ref::<Int32Array>()
.unwrap()
.value(0)
);
for i in 0..3 {
assert!(list_array.is_valid(i));
assert!(!list_array.is_null(i));
}
// Now test with a non-zero offset
let list_data = ArrayData::builder(list_data_type)
.len(3)
.offset(1)
.add_buffer(value_offsets)
.add_child_data(value_data.clone())
.build();
let list_array = ListArray::from(list_data);
let values = list_array.values();
assert_eq!(&value_data, values.data());
assert_eq!(DataType::Int32, list_array.value_type());
assert_eq!(3, list_array.len());
assert_eq!(0, list_array.null_count());
assert_eq!(6, list_array.value_offsets()[1]);
assert_eq!(2, list_array.value_length(1));
assert_eq!(
3,
list_array
.value(0)
.as_any()
.downcast_ref::<Int32Array>()
.unwrap()
.value(0)
);
assert_eq!(
3,
unsafe { list_array.value_unchecked(0) }
.as_any()
.downcast_ref::<Int32Array>()
.unwrap()
.value(0)
);
}
#[test]
fn test_large_list_array() {
// Construct a value array
let value_data = ArrayData::builder(DataType::Int32)
.len(8)
.add_buffer(Buffer::from_slice_ref(&[0, 1, 2, 3, 4, 5, 6, 7]))
.build();
// Construct a buffer for value offsets, for the nested array:
// [[0, 1, 2], [3, 4, 5], [6, 7]]
let value_offsets = Buffer::from_slice_ref(&[0i64, 3, 6, 8]);
// Construct a list array from the above two
let list_data_type =
DataType::LargeList(Box::new(Field::new("item", DataType::Int32, false)));
let list_data = ArrayData::builder(list_data_type.clone())
.len(3)
.add_buffer(value_offsets.clone())
.add_child_data(value_data.clone())
.build();
let list_array = LargeListArray::from(list_data);
let values = list_array.values();
assert_eq!(&value_data, values.data());
assert_eq!(DataType::Int32, list_array.value_type());
assert_eq!(3, list_array.len());
assert_eq!(0, list_array.null_count());
assert_eq!(6, list_array.value_offsets()[2]);
assert_eq!(2, list_array.value_length(2));
assert_eq!(
0,
list_array
.value(0)
.as_any()
.downcast_ref::<Int32Array>()
.unwrap()
.value(0)
);
assert_eq!(
0,
unsafe { list_array.value_unchecked(0) }
.as_any()
.downcast_ref::<Int32Array>()
.unwrap()
.value(0)
);
for i in 0..3 {
assert!(list_array.is_valid(i));
assert!(!list_array.is_null(i));
}
// Now test with a non-zero offset
let list_data = ArrayData::builder(list_data_type)
.len(3)
.offset(1)
.add_buffer(value_offsets)
.add_child_data(value_data.clone())
.build();
let list_array = LargeListArray::from(list_data);
let values = list_array.values();
assert_eq!(&value_data, values.data());
assert_eq!(DataType::Int32, list_array.value_type());
assert_eq!(3, list_array.len());
assert_eq!(0, list_array.null_count());
assert_eq!(6, list_array.value_offsets()[1]);
assert_eq!(2, list_array.value_length(1));
assert_eq!(
3,
list_array
.value(0)
.as_any()
.downcast_ref::<Int32Array>()
.unwrap()
.value(0)
);
assert_eq!(
3,
unsafe { list_array.value_unchecked(0) }
.as_any()
.downcast_ref::<Int32Array>()
.unwrap()
.value(0)
);
}
#[test]
fn test_fixed_size_list_array() {
// Construct a value array
let value_data = ArrayData::builder(DataType::Int32)
.len(9)
.add_buffer(Buffer::from_slice_ref(&[0, 1, 2, 3, 4, 5, 6, 7, 8]))
.build();
// Construct a list array from the above two
let list_data_type = DataType::FixedSizeList(
Box::new(Field::new("item", DataType::Int32, false)),
3,
);
let list_data = ArrayData::builder(list_data_type.clone())
.len(3)
.add_child_data(value_data.clone())
.build();
let list_array = FixedSizeListArray::from(list_data);
let values = list_array.values();
assert_eq!(&value_data, values.data());
assert_eq!(DataType::Int32, list_array.value_type());
assert_eq!(3, list_array.len());
assert_eq!(0, list_array.null_count());
assert_eq!(6, list_array.value_offset(2));
assert_eq!(3, list_array.value_length());
assert_eq!(
0,
list_array
.value(0)
.as_any()
.downcast_ref::<Int32Array>()
.unwrap()
.value(0)
);
for i in 0..3 {
assert!(list_array.is_valid(i));
assert!(!list_array.is_null(i));
}
// Now test with a non-zero offset
let list_data = ArrayData::builder(list_data_type)
.len(3)
.offset(1)
.add_child_data(value_data.clone())
.build();
let list_array = FixedSizeListArray::from(list_data);
let values = list_array.values();
assert_eq!(&value_data, values.data());
assert_eq!(DataType::Int32, list_array.value_type());
assert_eq!(3, list_array.len());
assert_eq!(0, list_array.null_count());
assert_eq!(
3,
list_array
.value(0)
.as_any()
.downcast_ref::<Int32Array>()
.unwrap()
.value(0)
);
assert_eq!(6, list_array.value_offset(1));
assert_eq!(3, list_array.value_length());
}
#[test]
#[should_panic(
expected = "FixedSizeListArray child array length should be a multiple of 3"
)]
fn test_fixed_size_list_array_unequal_children() {
// Construct a value array
let value_data = ArrayData::builder(DataType::Int32)
.len(8)
.add_buffer(Buffer::from_slice_ref(&[0, 1, 2, 3, 4, 5, 6, 7]))
.build();
// Construct a list array from the above two
let list_data_type = DataType::FixedSizeList(
Box::new(Field::new("item", DataType::Int32, false)),
3,
);
let list_data = ArrayData::builder(list_data_type)
.len(3)
.add_child_data(value_data)
.build();
FixedSizeListArray::from(list_data);
}
#[test]
fn test_list_array_slice() {
// Construct a value array
let value_data = ArrayData::builder(DataType::Int32)
.len(10)
.add_buffer(Buffer::from_slice_ref(&[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
.build();
// Construct a buffer for value offsets, for the nested array:
// [[0, 1], null, null, [2, 3], [4, 5], null, [6, 7, 8], null, [9]]
let value_offsets = Buffer::from_slice_ref(&[0, 2, 2, 2, 4, 6, 6, 9, 9, 10]);
// 01011001 00000001
let mut null_bits: [u8; 2] = [0; 2];
bit_util::set_bit(&mut null_bits, 0);
bit_util::set_bit(&mut null_bits, 3);
bit_util::set_bit(&mut null_bits, 4);
bit_util::set_bit(&mut null_bits, 6);
bit_util::set_bit(&mut null_bits, 8);
// Construct a list array from the above two
let list_data_type =
DataType::List(Box::new(Field::new("item", DataType::Int32, false)));
let list_data = ArrayData::builder(list_data_type)
.len(9)
.add_buffer(value_offsets)
.add_child_data(value_data.clone())
.null_bit_buffer(Buffer::from(null_bits))
.build();
let list_array = ListArray::from(list_data);
let values = list_array.values();
assert_eq!(&value_data, values.data());
assert_eq!(DataType::Int32, list_array.value_type());
assert_eq!(9, list_array.len());
assert_eq!(4, list_array.null_count());
assert_eq!(2, list_array.value_offsets()[3]);
assert_eq!(2, list_array.value_length(3));
let sliced_array = list_array.slice(1, 6);
assert_eq!(6, sliced_array.len());
assert_eq!(1, sliced_array.offset());
assert_eq!(3, sliced_array.null_count());
for i in 0..sliced_array.len() {
if bit_util::get_bit(&null_bits, sliced_array.offset() + i) {
assert!(sliced_array.is_valid(i));
} else {
assert!(sliced_array.is_null(i));
}
}
// Check offset and length for each non-null value.
let sliced_list_array =
sliced_array.as_any().downcast_ref::<ListArray>().unwrap();
assert_eq!(2, sliced_list_array.value_offsets()[2]);
assert_eq!(2, sliced_list_array.value_length(2));
assert_eq!(4, sliced_list_array.value_offsets()[3]);
assert_eq!(2, sliced_list_array.value_length(3));
assert_eq!(6, sliced_list_array.value_offsets()[5]);
assert_eq!(3, sliced_list_array.value_length(5));
}
#[test]
fn test_large_list_array_slice() {
// Construct a value array
let value_data = ArrayData::builder(DataType::Int32)
.len(10)
.add_buffer(Buffer::from_slice_ref(&[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
.build();
// Construct a buffer for value offsets, for the nested array:
// [[0, 1], null, null, [2, 3], [4, 5], null, [6, 7, 8], null, [9]]
let value_offsets = Buffer::from_slice_ref(&[0i64, 2, 2, 2, 4, 6, 6, 9, 9, 10]);
// 01011001 00000001
let mut null_bits: [u8; 2] = [0; 2];
bit_util::set_bit(&mut null_bits, 0);
bit_util::set_bit(&mut null_bits, 3);
bit_util::set_bit(&mut null_bits, 4);
bit_util::set_bit(&mut null_bits, 6);
bit_util::set_bit(&mut null_bits, 8);
// Construct a list array from the above two
let list_data_type =
DataType::LargeList(Box::new(Field::new("item", DataType::Int32, false)));
let list_data = ArrayData::builder(list_data_type)
.len(9)
.add_buffer(value_offsets)
.add_child_data(value_data.clone())
.null_bit_buffer(Buffer::from(null_bits))
.build();
let list_array = LargeListArray::from(list_data);
let values = list_array.values();
assert_eq!(&value_data, values.data());
assert_eq!(DataType::Int32, list_array.value_type());
assert_eq!(9, list_array.len());
assert_eq!(4, list_array.null_count());
assert_eq!(2, list_array.value_offsets()[3]);
assert_eq!(2, list_array.value_length(3));
let sliced_array = list_array.slice(1, 6);
assert_eq!(6, sliced_array.len());
assert_eq!(1, sliced_array.offset());
assert_eq!(3, sliced_array.null_count());
for i in 0..sliced_array.len() {
if bit_util::get_bit(&null_bits, sliced_array.offset() + i) {
assert!(sliced_array.is_valid(i));
} else {
assert!(sliced_array.is_null(i));
}
}
// Check offset and length for each non-null value.
let sliced_list_array = sliced_array
.as_any()
.downcast_ref::<LargeListArray>()
.unwrap();
assert_eq!(2, sliced_list_array.value_offsets()[2]);
assert_eq!(2, sliced_list_array.value_length(2));
assert_eq!(4, sliced_list_array.value_offsets()[3]);
assert_eq!(2, sliced_list_array.value_length(3));
assert_eq!(6, sliced_list_array.value_offsets()[5]);
assert_eq!(3, sliced_list_array.value_length(5));
}
#[test]
#[should_panic(expected = "index out of bounds: the len is 10 but the index is 11")]
fn test_list_array_index_out_of_bound() {
// Construct a value array
let value_data = ArrayData::builder(DataType::Int32)
.len(10)
.add_buffer(Buffer::from_slice_ref(&[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
.build();
// Construct a buffer for value offsets, for the nested array:
// [[0, 1], null, null, [2, 3], [4, 5], null, [6, 7, 8], null, [9]]
let value_offsets = Buffer::from_slice_ref(&[0i64, 2, 2, 2, 4, 6, 6, 9, 9, 10]);
// 01011001 00000001
let mut null_bits: [u8; 2] = [0; 2];
bit_util::set_bit(&mut null_bits, 0);
bit_util::set_bit(&mut null_bits, 3);
bit_util::set_bit(&mut null_bits, 4);
bit_util::set_bit(&mut null_bits, 6);
bit_util::set_bit(&mut null_bits, 8);
// Construct a list array from the above two
let list_data_type =
DataType::LargeList(Box::new(Field::new("item", DataType::Int32, false)));
let list_data = ArrayData::builder(list_data_type)
.len(9)
.add_buffer(value_offsets)
.add_child_data(value_data)
.null_bit_buffer(Buffer::from(null_bits))
.build();
let list_array = LargeListArray::from(list_data);
assert_eq!(9, list_array.len());
list_array.value(10);
}
#[test]
fn test_fixed_size_list_array_slice() {
// Construct a value array
let value_data = ArrayData::builder(DataType::Int32)
.len(10)
.add_buffer(Buffer::from_slice_ref(&[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
.build();
// Set null buts for the nested array:
// [[0, 1], null, null, [6, 7], [8, 9]]
// 01011001 00000001
let mut null_bits: [u8; 1] = [0; 1];
bit_util::set_bit(&mut null_bits, 0);
bit_util::set_bit(&mut null_bits, 3);
bit_util::set_bit(&mut null_bits, 4);
// Construct a fixed size list array from the above two
let list_data_type = DataType::FixedSizeList(
Box::new(Field::new("item", DataType::Int32, false)),
2,
);
let list_data = ArrayData::builder(list_data_type)
.len(5)
.add_child_data(value_data.clone())
.null_bit_buffer(Buffer::from(null_bits))
.build();
let list_array = FixedSizeListArray::from(list_data);
let values = list_array.values();
assert_eq!(&value_data, values.data());
assert_eq!(DataType::Int32, list_array.value_type());
assert_eq!(5, list_array.len());
assert_eq!(2, list_array.null_count());
assert_eq!(6, list_array.value_offset(3));
assert_eq!(2, list_array.value_length());
let sliced_array = list_array.slice(1, 4);
assert_eq!(4, sliced_array.len());
assert_eq!(1, sliced_array.offset());
assert_eq!(2, sliced_array.null_count());
for i in 0..sliced_array.len() {
if bit_util::get_bit(&null_bits, sliced_array.offset() + i) {
assert!(sliced_array.is_valid(i));
} else {
assert!(sliced_array.is_null(i));
}
}
// Check offset and length for each non-null value.
let sliced_list_array = sliced_array
.as_any()
.downcast_ref::<FixedSizeListArray>()
.unwrap();
assert_eq!(2, sliced_list_array.value_length());
assert_eq!(6, sliced_list_array.value_offset(2));
assert_eq!(8, sliced_list_array.value_offset(3));
}
#[test]
#[should_panic(expected = "assertion failed: (offset + length) <= self.len()")]
fn test_fixed_size_list_array_index_out_of_bound() {
// Construct a value array
let value_data = ArrayData::builder(DataType::Int32)
.len(10)
.add_buffer(Buffer::from_slice_ref(&[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
.build();
// Set null buts for the nested array:
// [[0, 1], null, null, [6, 7], [8, 9]]
// 01011001 00000001
let mut null_bits: [u8; 1] = [0; 1];
bit_util::set_bit(&mut null_bits, 0);
bit_util::set_bit(&mut null_bits, 3);
bit_util::set_bit(&mut null_bits, 4);
// Construct a fixed size list array from the above two
let list_data_type = DataType::FixedSizeList(
Box::new(Field::new("item", DataType::Int32, false)),
2,
);
let list_data = ArrayData::builder(list_data_type)
.len(5)
.add_child_data(value_data)
.null_bit_buffer(Buffer::from(null_bits))
.build();
let list_array = FixedSizeListArray::from(list_data);
list_array.value(10);
}
#[test]
#[should_panic(
expected = "ListArray data should contain a single buffer only (value offsets)"
)]
fn test_list_array_invalid_buffer_len() {
let value_data = ArrayData::builder(DataType::Int32)
.len(8)
.add_buffer(Buffer::from_slice_ref(&[0, 1, 2, 3, 4, 5, 6, 7]))
.build();
let list_data_type =
DataType::List(Box::new(Field::new("item", DataType::Int32, false)));
let list_data = ArrayData::builder(list_data_type)
.len(3)
.add_child_data(value_data)
.build();
ListArray::from(list_data);
}
#[test]
#[should_panic(
expected = "ListArray should contain a single child array (values array)"
)]
fn test_list_array_invalid_child_array_len() {
let value_offsets = Buffer::from_slice_ref(&[0, 2, 5, 7]);
let list_data_type =
DataType::List(Box::new(Field::new("item", DataType::Int32, false)));
let list_data = ArrayData::builder(list_data_type)
.len(3)
.add_buffer(value_offsets)
.build();
ListArray::from(list_data);
}
#[test]
#[should_panic(expected = "offsets do not start at zero")]
fn test_list_array_invalid_value_offset_start() {
let value_data = ArrayData::builder(DataType::Int32)
.len(8)
.add_buffer(Buffer::from_slice_ref(&[0, 1, 2, 3, 4, 5, 6, 7]))
.build();
let value_offsets = Buffer::from_slice_ref(&[2, 2, 5, 7]);
let list_data_type =
DataType::List(Box::new(Field::new("item", DataType::Int32, false)));
let list_data = ArrayData::builder(list_data_type)
.len(3)
.add_buffer(value_offsets)
.add_child_data(value_data)
.build();
ListArray::from(list_data);
}
#[test]
#[should_panic(expected = "memory is not aligned")]
fn test_primitive_array_alignment() {
let ptr = alloc::allocate_aligned::<u8>(8);
let buf = unsafe { Buffer::from_raw_parts(ptr, 8, 8) };
let buf2 = buf.slice(1);
let array_data = ArrayData::builder(DataType::Int32).add_buffer(buf2).build();
Int32Array::from(array_data);
}
#[test]
#[should_panic(expected = "memory is not aligned")]
fn test_list_array_alignment() {
let ptr = alloc::allocate_aligned::<u8>(8);
let buf = unsafe { Buffer::from_raw_parts(ptr, 8, 8) };
let buf2 = buf.slice(1);
let values: [i32; 8] = [0; 8];
let value_data = ArrayData::builder(DataType::Int32)
.add_buffer(Buffer::from_slice_ref(&values))
.build();
let list_data_type =
DataType::List(Box::new(Field::new("item", DataType::Int32, false)));
let list_data = ArrayData::builder(list_data_type)
.add_buffer(buf2)
.add_child_data(value_data)
.build();
ListArray::from(list_data);
}
}
| {
write!(f, "FixedSizeListArray<{}>\n[\n", self.value_length())?;
print_long_array(self, f, |array, index, f| {
fmt::Debug::fmt(&array.value(index), f)
})?;
write!(f, "]")
} |
trove-pylint.py | #!/usr/bin/env python
# Copyright 2016 Tesora, Inc.
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import fnmatch
import json
from collections import OrderedDict
import io
import os
import re
import sys
from pylint import lint
from pylint.reporters import text
DEFAULT_CONFIG_FILE = "tools/trove-pylint.config"
DEFAULT_IGNORED_FILES = ['trove/tests']
DEFAULT_IGNORED_CODES = []
DEFAULT_IGNORED_MESSAGES = []
DEFAULT_ALWAYS_ERROR = [
"Undefined variable '_'",
"Undefined variable '_LE'",
"Undefined variable '_LI'",
"Undefined variable '_LW'",
"Undefined variable '_LC'"]
MODE_CHECK = "check"
MODE_REBUILD = "rebuild"
class Config(object):
def __init__(self, filename=DEFAULT_CONFIG_FILE):
self.default_config = {
"include": ["*.py"],
"folder": "trove",
"options": ["--rcfile=./pylintrc", "-E"],
"ignored_files": DEFAULT_IGNORED_FILES,
"ignored_codes": DEFAULT_IGNORED_CODES,
"ignored_messages": DEFAULT_IGNORED_MESSAGES,
"ignored_file_codes": [],
"ignored_file_messages": [],
"ignored_file_code_messages": [],
"always_error_messages": DEFAULT_ALWAYS_ERROR
}
self.config = self.default_config
def sort_config(self):
sorted_config = OrderedDict()
for key in sorted(self.config.keys()):
value = self.get(key)
if isinstance(value, list) and not isinstance(value,str):
sorted_config[key] = sorted(value)
else:
sorted_config[key] = value
return sorted_config
def save(self, filename=DEFAULT_CONFIG_FILE):
if os.path.isfile(filename):
os.rename(filename, "%s~" % filename)
with open(filename, 'w') as fp:
json.dump(self.sort_config(), fp, encoding="utf-8",
indent=2, separators=(',', ': '))
def load(self, filename=DEFAULT_CONFIG_FILE):
with open(filename) as fp:
self.config = json.load(fp, encoding="utf-8")
def get(self, attribute):
return self.config[attribute]
def is_file_ignored(self, f):
if any(f.startswith(i)
for i in self.config['ignored_files']):
return True
return False
def is_file_included(self, f):
if any(fnmatch.fnmatch(f, wc) for wc in self.config['include']):
return True
return False
def is_always_error(self, message):
if message in self.config['always_error_messages']:
return True
return False
def ignore(self, filename, code, codename, message):
# the high priority checks
if self.is_file_ignored(filename):
return True
# never ignore messages
if self.is_always_error(message):
return False
if code in self.config['ignored_codes']:
return True
if codename in self.config['ignored_codes']:
return True
if message and any(message.startswith(ignore_message)
for ignore_message
in self.config['ignored_messages']):
return True
if filename and message and (
[filename, message] in self.config['ignored_file_messages']):
return True
if filename and code and (
[filename, code] in self.config['ignored_file_codes']):
return True
if filename and codename and (
[filename, codename] in self.config['ignored_file_codes']):
return True
for fcm in self.config['ignored_file_code_messages']:
if filename != fcm[0]:
# This ignore rule is for a different file.
continue
if fcm[1] not in (code, codename):
# This ignore rule is for a different code or codename.
continue
if message.startswith(fcm[2]):
return True
return False
def ignore_code(self, c):
_c = set(self.config['ignored_codes'])
_c.add(c)
self.config['ignored_codes'] = list(_c)
def ignore_files(self, f):
|
def ignore_message(self, m):
_c = set(self.config['ignored_messages'])
_c.add(m)
self.config['ignored_messages'] = list(_c)
def ignore_file_code(self, f, c):
_c = set(self.config['ignored_file_codes'])
_c.add((f, c))
self.config['ignored_file_codes'] = list(_c)
def ignore_file_message(self, f, m):
_c = set(self.config['ignored_file_messages'])
_c.add((f, m))
self.config['ignored_file_messages'] = list(_c)
def ignore_file_code_message(self, f, c, m, fn):
_c = set(self.config['ignored_file_code_messages'])
_c.add((f, c, m, fn))
self.config['ignored_file_code_messages'] = list(_c)
def main():
if len(sys.argv) == 1 or sys.argv[1] == "check":
return check()
elif sys.argv[1] == "rebuild":
return rebuild()
elif sys.argv[1] == "initialize":
return initialize()
else:
return usage()
def usage():
print("Usage: %s [check|rebuild]" % sys.argv[0])
print("\tUse this tool to perform a lint check of the trove project.")
print("\t check: perform the lint check.")
print("\t rebuild: rebuild the list of exceptions to ignore.")
return 0
class ParseableTextReporter(text.TextReporter):
name = 'parseable'
line_format = '{path}:{line}: [{msg_id}({symbol}), {obj}] {msg}'
# that's it folks
class LintRunner(object):
def __init__(self):
self.config = Config()
self.idline = re.compile("^[*]* Module .*")
self.detail = re.compile(r"(\S+):(\d+): \[(\S+)\((\S+)\),"
r" (\S+)?] (.*)")
def dolint(self, filename):
exceptions = set()
buffer = io.StringIO()
reporter = ParseableTextReporter(output=buffer)
options = list(self.config.get('options'))
options.append(filename)
lint.Run(options, reporter=reporter, exit=False)
output = buffer.getvalue()
buffer.close()
for line in output.splitlines():
if self.idline.match(line):
continue
if self.detail.match(line):
mo = self.detail.search(line)
tokens = mo.groups()
fn = tokens[0]
ln = tokens[1]
code = tokens[2]
codename = tokens[3]
func = tokens[4]
message = tokens[5]
if not self.config.ignore(fn, code, codename, message):
exceptions.add((fn, ln, code, codename, func, message))
return exceptions
def process(self, mode=MODE_CHECK):
files_processed = 0
files_with_errors = 0
errors_recorded = 0
exceptions_recorded = 0
all_exceptions = []
for (root, dirs, files) in os.walk(self.config.get('folder')):
# if we shouldn't even bother about this part of the
# directory structure, we can punt quietly
if self.config.is_file_ignored(root):
continue
# since we are walking top down, let's clean up the dirs
# that we will walk by eliminating any dirs that will
# end up getting ignored
for d in dirs:
p = os.path.join(root, d)
if self.config.is_file_ignored(p):
dirs.remove(d)
# check if we can ignore the file and process if not
for f in files:
p = os.path.join(root, f)
if self.config.is_file_ignored(p):
continue
if not self.config.is_file_included(f):
continue
files_processed += 1
exceptions = self.dolint(p)
file_had_errors = 0
for e in exceptions:
# what we do with this exception depents on the
# kind of exception, and the mode
if self.config.is_always_error(e[5]):
all_exceptions.append(e)
errors_recorded += 1
file_had_errors += 1
elif mode == MODE_REBUILD:
# parameters to ignore_file_code_message are
# filename, code, message and function
self.config.ignore_file_code_message(e[0], e[2], e[-1], e[4])
self.config.ignore_file_code_message(e[0], e[3], e[-1], e[4])
exceptions_recorded += 1
elif mode == MODE_CHECK:
all_exceptions.append(e)
errors_recorded += 1
file_had_errors += 1
if file_had_errors:
files_with_errors += 1
for e in sorted(all_exceptions):
print("ERROR: %s %s: %s %s, %s: %s" %
(e[0], e[1], e[2], e[3], e[4], e[5]))
return (files_processed, files_with_errors, errors_recorded,
exceptions_recorded)
def rebuild(self):
self.initialize()
(files_processed,
files_with_errors,
errors_recorded,
exceptions_recorded) = self.process(mode=MODE_REBUILD)
if files_with_errors > 0:
print("Rebuild failed. %s files processed, %s had errors, "
"%s errors recorded." % (
files_processed, files_with_errors, errors_recorded))
return 1
self.config.save()
print("Rebuild completed. %s files processed, %s exceptions recorded." %
(files_processed, exceptions_recorded))
return 0
def check(self):
self.config.load()
(files_processed,
files_with_errors,
errors_recorded,
exceptions_recorded) = self.process(mode=MODE_CHECK)
if files_with_errors > 0:
print("Check failed. %s files processed, %s had errors, "
"%s errors recorded." % (
files_processed, files_with_errors, errors_recorded))
return 1
print("Check succeeded. %s files processed" % files_processed)
return 0
def initialize(self):
self.config.save()
return 0
def check():
exit(LintRunner().check())
def rebuild():
exit(LintRunner().rebuild())
def initialize():
exit(LintRunner().initialize())
if __name__ == "__main__":
main()
| _c = set(self.config['ignored_files'])
_c.add(f)
self.config['ignored_files'] = list(_c) |
parent_section_group_request_builder.go | package parentsectiongroup
import (
ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9 "github.com/microsoft/kiota/abstractions/go"
i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55 "github.com/microsoft/kiota/abstractions/go/serialization"
i4a838ef194e4c99e9f2c63ba10dab9cb120a89367c1d4ab0daa63bb424e20d87 "github.com/microsoftgraph/msgraph-sdk-go/models/microsoft/graph"
i42d70f33ea61d179633f274cf8d44baf74063b58f631405ca23dca51e0abc74d "github.com/microsoftgraph/msgraph-sdk-go/sites/item/onenote/notebooks/item/sections/item/parentsectiongroup/parentnotebook"
i7720156a69a994dae3332732c1320a603b52e6cc653600ce0899c631bf04dbab "github.com/microsoftgraph/msgraph-sdk-go/sites/item/onenote/notebooks/item/sections/item/parentsectiongroup/sectiongroups"
i90dd46654fccc9ad91c102855af50dce716e38f1d4fc74c9a1bef2a4ae203e4b "github.com/microsoftgraph/msgraph-sdk-go/sites/item/onenote/notebooks/item/sections/item/parentsectiongroup/sections"
i24156245e153b2d9be5bd83a721ed7c339f886781d7456fe58ea781f72b5e7db "github.com/microsoftgraph/msgraph-sdk-go/sites/item/onenote/notebooks/item/sections/item/parentsectiongroup/sectiongroups/item"
i79133609fe25ca4cbbb7da8a7bdf1bea65a45d895a281cf7e7a9e742953645ba "github.com/microsoftgraph/msgraph-sdk-go/sites/item/onenote/notebooks/item/sections/item/parentsectiongroup/sections/item"
)
// ParentSectionGroupRequestBuilder builds and executes requests for operations under \sites\{site-id}\onenote\notebooks\{notebook-id}\sections\{onenoteSection-id}\parentSectionGroup
type ParentSectionGroupRequestBuilder struct {
// Path parameters for the request
pathParameters map[string]string;
// The request adapter to use to execute the requests.
requestAdapter ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.RequestAdapter;
// Url template to use to build the URL for the current request builder
urlTemplate string;
}
// ParentSectionGroupRequestBuilderDeleteOptions options for Delete
type ParentSectionGroupRequestBuilderDeleteOptions struct {
// Request headers
H map[string]string;
// Request options
O []ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.RequestOption;
// Response handler to use in place of the default response handling provided by the core service
ResponseHandler ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.ResponseHandler;
}
// ParentSectionGroupRequestBuilderGetOptions options for Get
type ParentSectionGroupRequestBuilderGetOptions struct {
// Request headers
H map[string]string;
// Request options
O []ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.RequestOption;
// Request query parameters
Q *ParentSectionGroupRequestBuilderGetQueryParameters;
// Response handler to use in place of the default response handling provided by the core service
ResponseHandler ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.ResponseHandler;
}
// ParentSectionGroupRequestBuilderGetQueryParameters the section group that contains the section. Read-only.
type ParentSectionGroupRequestBuilderGetQueryParameters struct {
// Expand related entities
Expand []string;
// Select properties to be returned
Select_escaped []string;
}
// ParentSectionGroupRequestBuilderPatchOptions options for Patch
type ParentSectionGroupRequestBuilderPatchOptions struct {
//
Body *i4a838ef194e4c99e9f2c63ba10dab9cb120a89367c1d4ab0daa63bb424e20d87.SectionGroup;
// Request headers
H map[string]string;
// Request options
O []ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.RequestOption;
// Response handler to use in place of the default response handling provided by the core service
ResponseHandler ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.ResponseHandler;
}
// NewParentSectionGroupRequestBuilderInternal instantiates a new ParentSectionGroupRequestBuilder and sets the default values.
func NewParentSectionGroupRequestBuilderInternal(pathParameters map[string]string, requestAdapter ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.RequestAdapter)(*ParentSectionGroupRequestBuilder) {
m := &ParentSectionGroupRequestBuilder{
}
m.urlTemplate = "{+baseurl}/sites/{site_id}/onenote/notebooks/{notebook_id}/sections/{onenoteSection_id}/parentSectionGroup{?select,expand}";
urlTplParams := make(map[string]string)
for idx, item := range pathParameters {
urlTplParams[idx] = item
}
m.pathParameters = pathParameters;
m.requestAdapter = requestAdapter;
return m
}
// NewParentSectionGroupRequestBuilder instantiates a new ParentSectionGroupRequestBuilder and sets the default values.
func NewParentSectionGroupRequestBuilder(rawUrl string, requestAdapter ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.RequestAdapter)(*ParentSectionGroupRequestBuilder) {
urlParams := make(map[string]string)
urlParams["request-raw-url"] = rawUrl
return NewParentSectionGroupRequestBuilderInternal(urlParams, requestAdapter)
}
// CreateDeleteRequestInformation the section group that contains the section. Read-only.
func (m *ParentSectionGroupRequestBuilder) CreateDeleteRequestInformation(options *ParentSectionGroupRequestBuilderDeleteOptions)(*ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.RequestInformation, error) {
requestInfo := ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.NewRequestInformation()
requestInfo.UrlTemplate = m.urlTemplate
requestInfo.PathParameters = m.pathParameters
requestInfo.Method = ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.DELETE
if options != nil && options.H != nil {
requestInfo.Headers = options.H
}
if options != nil && len(options.O) != 0 {
err := requestInfo.AddRequestOptions(options.O...)
if err != nil {
return nil, err
}
}
return requestInfo, nil
}
// CreateGetRequestInformation the section group that contains the section. Read-only.
func (m *ParentSectionGroupRequestBuilder) CreateGetRequestInformation(options *ParentSectionGroupRequestBuilderGetOptions)(*ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.RequestInformation, error) {
requestInfo := ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.NewRequestInformation()
requestInfo.UrlTemplate = m.urlTemplate
requestInfo.PathParameters = m.pathParameters
requestInfo.Method = ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.GET
if options != nil && options.Q != nil {
requestInfo.AddQueryParameters(*(options.Q))
}
if options != nil && options.H != nil {
requestInfo.Headers = options.H
}
if options != nil && len(options.O) != 0 {
err := requestInfo.AddRequestOptions(options.O...)
if err != nil {
return nil, err | }
return requestInfo, nil
}
// CreatePatchRequestInformation the section group that contains the section. Read-only.
func (m *ParentSectionGroupRequestBuilder) CreatePatchRequestInformation(options *ParentSectionGroupRequestBuilderPatchOptions)(*ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.RequestInformation, error) {
requestInfo := ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.NewRequestInformation()
requestInfo.UrlTemplate = m.urlTemplate
requestInfo.PathParameters = m.pathParameters
requestInfo.Method = ida96af0f171bb75f894a4013a6b3146a4397c58f11adb81a2b7cbea9314783a9.PATCH
requestInfo.SetContentFromParsable(m.requestAdapter, "application/json", options.Body)
if options != nil && options.H != nil {
requestInfo.Headers = options.H
}
if options != nil && len(options.O) != 0 {
err := requestInfo.AddRequestOptions(options.O...)
if err != nil {
return nil, err
}
}
return requestInfo, nil
}
// Delete the section group that contains the section. Read-only.
func (m *ParentSectionGroupRequestBuilder) Delete(options *ParentSectionGroupRequestBuilderDeleteOptions)(error) {
requestInfo, err := m.CreateDeleteRequestInformation(options);
if err != nil {
return err
}
err = m.requestAdapter.SendNoContentAsync(*requestInfo, nil)
if err != nil {
return err
}
return nil
}
// Get the section group that contains the section. Read-only.
func (m *ParentSectionGroupRequestBuilder) Get(options *ParentSectionGroupRequestBuilderGetOptions)(*i4a838ef194e4c99e9f2c63ba10dab9cb120a89367c1d4ab0daa63bb424e20d87.SectionGroup, error) {
requestInfo, err := m.CreateGetRequestInformation(options);
if err != nil {
return nil, err
}
res, err := m.requestAdapter.SendAsync(*requestInfo, func () i04eb5309aeaafadd28374d79c8471df9b267510b4dc2e3144c378c50f6fd7b55.Parsable { return i4a838ef194e4c99e9f2c63ba10dab9cb120a89367c1d4ab0daa63bb424e20d87.NewSectionGroup() }, nil)
if err != nil {
return nil, err
}
return res.(*i4a838ef194e4c99e9f2c63ba10dab9cb120a89367c1d4ab0daa63bb424e20d87.SectionGroup), nil
}
func (m *ParentSectionGroupRequestBuilder) ParentNotebook()(*i42d70f33ea61d179633f274cf8d44baf74063b58f631405ca23dca51e0abc74d.ParentNotebookRequestBuilder) {
return i42d70f33ea61d179633f274cf8d44baf74063b58f631405ca23dca51e0abc74d.NewParentNotebookRequestBuilderInternal(m.pathParameters, m.requestAdapter);
}
func (m *ParentSectionGroupRequestBuilder) ParentSectionGroup()(*ParentSectionGroupRequestBuilder) {
return NewParentSectionGroupRequestBuilderInternal(m.pathParameters, m.requestAdapter);
}
// Patch the section group that contains the section. Read-only.
func (m *ParentSectionGroupRequestBuilder) Patch(options *ParentSectionGroupRequestBuilderPatchOptions)(error) {
requestInfo, err := m.CreatePatchRequestInformation(options);
if err != nil {
return err
}
err = m.requestAdapter.SendNoContentAsync(*requestInfo, nil)
if err != nil {
return err
}
return nil
}
func (m *ParentSectionGroupRequestBuilder) SectionGroups()(*i7720156a69a994dae3332732c1320a603b52e6cc653600ce0899c631bf04dbab.SectionGroupsRequestBuilder) {
return i7720156a69a994dae3332732c1320a603b52e6cc653600ce0899c631bf04dbab.NewSectionGroupsRequestBuilderInternal(m.pathParameters, m.requestAdapter);
}
// SectionGroupsById gets an item from the github.com/microsoftgraph/msgraph-sdk-go/.sites.item.onenote.notebooks.item.sections.item.parentSectionGroup.sectionGroups.item collection
func (m *ParentSectionGroupRequestBuilder) SectionGroupsById(id string)(*i24156245e153b2d9be5bd83a721ed7c339f886781d7456fe58ea781f72b5e7db.SectionGroupRequestBuilder) {
urlTplParams := make(map[string]string)
for idx, item := range m.pathParameters {
urlTplParams[idx] = item
}
if id != "" {
urlTplParams["sectionGroup_id"] = id
}
return i24156245e153b2d9be5bd83a721ed7c339f886781d7456fe58ea781f72b5e7db.NewSectionGroupRequestBuilderInternal(urlTplParams, m.requestAdapter);
}
func (m *ParentSectionGroupRequestBuilder) Sections()(*i90dd46654fccc9ad91c102855af50dce716e38f1d4fc74c9a1bef2a4ae203e4b.SectionsRequestBuilder) {
return i90dd46654fccc9ad91c102855af50dce716e38f1d4fc74c9a1bef2a4ae203e4b.NewSectionsRequestBuilderInternal(m.pathParameters, m.requestAdapter);
}
// SectionsById gets an item from the github.com/microsoftgraph/msgraph-sdk-go/.sites.item.onenote.notebooks.item.sections.item.parentSectionGroup.sections.item collection
func (m *ParentSectionGroupRequestBuilder) SectionsById(id string)(*i79133609fe25ca4cbbb7da8a7bdf1bea65a45d895a281cf7e7a9e742953645ba.OnenoteSectionRequestBuilder) {
urlTplParams := make(map[string]string)
for idx, item := range m.pathParameters {
urlTplParams[idx] = item
}
if id != "" {
urlTplParams["onenoteSection_id1"] = id
}
return i79133609fe25ca4cbbb7da8a7bdf1bea65a45d895a281cf7e7a9e742953645ba.NewOnenoteSectionRequestBuilderInternal(urlTplParams, m.requestAdapter);
} | } |
utils.py | from typing import Any
from werkzeug.http import HTTP_STATUS_CODES
_sentinel = object()
# TODO Remove these shortcuts when pin Flask>=2.0
def route_shortcuts(cls):
"""A decorator used to add route shortcuts for `Flask` and `Blueprint` objects.
Includes `get()`, `post()`, `put()`, `patch()`, `delete()`.
Examples:
```python
from flask import Flask
@route_shortcuts
class APIFlask(Flask):
pass
app = APIFlask(__name__)
@app.get('/')
def hello():
return 'Hello!'
```
*Version added: 0.2.0*
*Version changed: 0.3.0*
*Turn base class into class decorator.*
"""
cls_route = cls.route
def get(self, rule: str, **options: Any):
"""Shortcut for `app.route()`.
"""
return cls_route(self, rule, methods=['GET'], **options)
def post(self, rule: str, **options: Any):
"""Shortcut for `app.route(methods=['POST'])`.
"""
return cls_route(self, rule, methods=['POST'], **options)
| """
return cls_route(self, rule, methods=['PUT'], **options)
def patch(self, rule: str, **options: Any):
"""Shortcut for `app.route(methods=['PATCH'])`.
"""
return cls_route(self, rule, methods=['PATCH'], **options)
def delete(self, rule: str, **options: Any):
"""Shortcut for `app.route(methods=['DELETE'])`.
"""
return cls_route(self, rule, methods=['DELETE'], **options)
cls.get = get
cls.post = post
cls.put = put
cls.patch = patch
cls.delete = delete
return cls
def get_reason_phrase(status_code: int) -> str:
"""A helper function used to get the reason phrase of given status code.
Arguments:
status_code: A standard HTTP status code.
"""
return HTTP_STATUS_CODES.get(status_code, 'Unknown error') | def put(self, rule: str, **options: Any):
"""Shortcut for `app.route(methods=['PUT'])`. |
data_table.rs | use crate::prelude::*;
use skia_bindings as sb;
use skia_bindings::{SkDataTable, SkRefCntBase};
use std::convert::TryInto;
use std::ffi::{c_void, CStr};
use std::ops::Index;
use std::{mem, slice};
pub type DataTable = RCHandle<SkDataTable>;
unsafe impl Send for DataTable {}
impl NativeRefCountedBase for SkDataTable {
type Base = SkRefCntBase;
}
impl Index<usize> for DataTable {
type Output = [u8];
fn index(&self, index: usize) -> &Self::Output {
self.at(index)
}
}
impl RCHandle<SkDataTable> {
pub fn is_empty(&self) -> bool {
self.count() == 0
}
pub fn count(&self) -> usize {
unsafe { sb::C_SkDataTable_count(self.native()) }
.try_into()
.unwrap()
}
pub fn at_size(&self, index: usize) -> usize {
assert!(index < self.count());
unsafe { self.native().atSize(index.try_into().unwrap()) }
}
pub fn at(&self, index: usize) -> &[u8] {
unsafe { self.at_t(index) }
}
pub unsafe fn at_t<T: Copy>(&self, index: usize) -> &[T] {
assert!(index < self.count());
let mut size = usize::default();
let ptr = self.native().at(index.try_into().unwrap(), &mut size); | let element_size = mem::size_of::<T>();
assert_eq!(size % element_size, 0);
let elements = size / element_size;
slice::from_raw_parts(ptr as _, elements)
}
pub fn at_str(&self, index: usize) -> &CStr {
let bytes = self.at(index);
CStr::from_bytes_with_nul(bytes).unwrap()
}
pub fn new_empty() -> Self {
DataTable::from_ptr(unsafe { sb::C_SkDataTable_MakeEmpty() }).unwrap()
}
pub fn from_slices(slices: &[&[u8]]) -> Self {
let ptrs: Vec<*const c_void> = slices.iter().map(|s| s.as_ptr() as _).collect();
let sizes: Vec<usize> = slices.iter().map(|s| s.len()).collect();
unsafe {
DataTable::from_ptr(sb::C_SkDataTable_MakeCopyArrays(
ptrs.as_ptr(),
sizes.as_ptr(),
slices.len().try_into().unwrap(),
))
.unwrap()
}
}
pub fn from_slice<T: Copy>(slice: &[T]) -> Self {
unsafe {
DataTable::from_ptr(sb::C_SkDataTable_MakeCopyArray(
slice.as_ptr() as _,
mem::size_of::<T>(),
slice.len().try_into().unwrap(),
))
.unwrap()
}
}
// TODO: wrap MakeArrayProc()
}
impl RCHandle<SkDataTable> {
pub fn iter(&self) -> Iter {
Iter {
table: self,
count: self.count(),
current: 0,
}
}
}
pub struct Iter<'a> {
table: &'a DataTable,
count: usize,
current: usize,
}
impl<'a> Iterator for Iter<'a> {
type Item = &'a [u8];
fn next(&mut self) -> Option<Self::Item> {
if self.current < self.count {
let r = Some(self.table.at(self.current));
self.current += 1;
r
} else {
None
}
}
} | |
fake_automationdscconfiguration.go | /*
Copyright The Kubeform Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by client-gen. DO NOT EDIT.
package fake
import (
"context"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
labels "k8s.io/apimachinery/pkg/labels"
schema "k8s.io/apimachinery/pkg/runtime/schema"
types "k8s.io/apimachinery/pkg/types"
watch "k8s.io/apimachinery/pkg/watch"
testing "k8s.io/client-go/testing"
v1alpha1 "kubeform.dev/kubeform/apis/azurerm/v1alpha1"
)
// FakeAutomationDscConfigurations implements AutomationDscConfigurationInterface
type FakeAutomationDscConfigurations struct {
Fake *FakeAzurermV1alpha1
ns string
}
var automationdscconfigurationsResource = schema.GroupVersionResource{Group: "azurerm.kubeform.com", Version: "v1alpha1", Resource: "automationdscconfigurations"}
var automationdscconfigurationsKind = schema.GroupVersionKind{Group: "azurerm.kubeform.com", Version: "v1alpha1", Kind: "AutomationDscConfiguration"}
// Get takes name of the automationDscConfiguration, and returns the corresponding automationDscConfiguration object, and an error if there is any.
func (c *FakeAutomationDscConfigurations) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1alpha1.AutomationDscConfiguration, err error) {
obj, err := c.Fake.
Invokes(testing.NewGetAction(automationdscconfigurationsResource, c.ns, name), &v1alpha1.AutomationDscConfiguration{})
if obj == nil {
return nil, err
}
return obj.(*v1alpha1.AutomationDscConfiguration), err
}
// List takes label and field selectors, and returns the list of AutomationDscConfigurations that match those selectors.
func (c *FakeAutomationDscConfigurations) List(ctx context.Context, opts v1.ListOptions) (result *v1alpha1.AutomationDscConfigurationList, err error) {
obj, err := c.Fake.
Invokes(testing.NewListAction(automationdscconfigurationsResource, automationdscconfigurationsKind, c.ns, opts), &v1alpha1.AutomationDscConfigurationList{})
if obj == nil {
return nil, err
}
label, _, _ := testing.ExtractFromListOptions(opts)
if label == nil {
label = labels.Everything()
}
list := &v1alpha1.AutomationDscConfigurationList{ListMeta: obj.(*v1alpha1.AutomationDscConfigurationList).ListMeta}
for _, item := range obj.(*v1alpha1.AutomationDscConfigurationList).Items {
if label.Matches(labels.Set(item.Labels)) {
list.Items = append(list.Items, item)
}
}
return list, err
}
// Watch returns a watch.Interface that watches the requested automationDscConfigurations.
func (c *FakeAutomationDscConfigurations) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) {
return c.Fake.
InvokesWatch(testing.NewWatchAction(automationdscconfigurationsResource, c.ns, opts))
}
// Create takes the representation of a automationDscConfiguration and creates it. Returns the server's representation of the automationDscConfiguration, and an error, if there is any.
func (c *FakeAutomationDscConfigurations) Create(ctx context.Context, automationDscConfiguration *v1alpha1.AutomationDscConfiguration, opts v1.CreateOptions) (result *v1alpha1.AutomationDscConfiguration, err error) {
obj, err := c.Fake.
Invokes(testing.NewCreateAction(automationdscconfigurationsResource, c.ns, automationDscConfiguration), &v1alpha1.AutomationDscConfiguration{})
if obj == nil {
return nil, err
}
return obj.(*v1alpha1.AutomationDscConfiguration), err
}
// Update takes the representation of a automationDscConfiguration and updates it. Returns the server's representation of the automationDscConfiguration, and an error, if there is any.
func (c *FakeAutomationDscConfigurations) Update(ctx context.Context, automationDscConfiguration *v1alpha1.AutomationDscConfiguration, opts v1.UpdateOptions) (result *v1alpha1.AutomationDscConfiguration, err error) {
obj, err := c.Fake.
Invokes(testing.NewUpdateAction(automationdscconfigurationsResource, c.ns, automationDscConfiguration), &v1alpha1.AutomationDscConfiguration{})
if obj == nil {
return nil, err
}
return obj.(*v1alpha1.AutomationDscConfiguration), err
}
// UpdateStatus was generated because the type contains a Status member. | obj, err := c.Fake.
Invokes(testing.NewUpdateSubresourceAction(automationdscconfigurationsResource, "status", c.ns, automationDscConfiguration), &v1alpha1.AutomationDscConfiguration{})
if obj == nil {
return nil, err
}
return obj.(*v1alpha1.AutomationDscConfiguration), err
}
// Delete takes name of the automationDscConfiguration and deletes it. Returns an error if one occurs.
func (c *FakeAutomationDscConfigurations) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error {
_, err := c.Fake.
Invokes(testing.NewDeleteAction(automationdscconfigurationsResource, c.ns, name), &v1alpha1.AutomationDscConfiguration{})
return err
}
// DeleteCollection deletes a collection of objects.
func (c *FakeAutomationDscConfigurations) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error {
action := testing.NewDeleteCollectionAction(automationdscconfigurationsResource, c.ns, listOpts)
_, err := c.Fake.Invokes(action, &v1alpha1.AutomationDscConfigurationList{})
return err
}
// Patch applies the patch and returns the patched automationDscConfiguration.
func (c *FakeAutomationDscConfigurations) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1alpha1.AutomationDscConfiguration, err error) {
obj, err := c.Fake.
Invokes(testing.NewPatchSubresourceAction(automationdscconfigurationsResource, c.ns, name, pt, data, subresources...), &v1alpha1.AutomationDscConfiguration{})
if obj == nil {
return nil, err
}
return obj.(*v1alpha1.AutomationDscConfiguration), err
} | // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().
func (c *FakeAutomationDscConfigurations) UpdateStatus(ctx context.Context, automationDscConfiguration *v1alpha1.AutomationDscConfiguration, opts v1.UpdateOptions) (*v1alpha1.AutomationDscConfiguration, error) { |
operations.rs | #![doc = "generated by AutoRust 0.1.0"]
#![allow(unused_mut)]
#![allow(unused_variables)]
#![allow(unused_imports)]
use crate::models::*;
use snafu::{ResultExt, Snafu};
pub mod operations {
use crate::models::*;
use snafu::{ResultExt, Snafu};
pub async fn list(operation_config: &crate::OperationConfig) -> std::result::Result<OperationListResult, list::Error> {
let http_client = operation_config.http_client();
let url_str = &format!("{}/providers/Microsoft.Storage/operations", operation_config.base_path(),);
let mut url = url::Url::parse(url_str).context(list::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.context(list::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).context(list::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.context(list::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: OperationListResult =
serde_json::from_slice(rsp_body).context(list::DeserializeError { body: rsp_body.clone() })?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
list::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
}
.fail()
}
}
}
pub mod list {
use crate::{models, models::*};
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
ParseUrlError { source: url::ParseError },
BuildRequestError { source: http::Error },
ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
}
pub mod skus {
use crate::models::*;
use snafu::{ResultExt, Snafu};
pub async fn list(
operation_config: &crate::OperationConfig,
subscription_id: &str,
) -> std::result::Result<StorageSkuListResult, list::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.Storage/skus",
operation_config.base_path(),
subscription_id
);
let mut url = url::Url::parse(url_str).context(list::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.context(list::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).context(list::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.context(list::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: StorageSkuListResult =
serde_json::from_slice(rsp_body).context(list::DeserializeError { body: rsp_body.clone() })?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
list::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
}
.fail()
}
}
}
pub mod list {
use crate::{models, models::*};
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
ParseUrlError { source: url::ParseError },
BuildRequestError { source: http::Error },
ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
}
pub mod storage_accounts {
use crate::models::*;
use snafu::{ResultExt, Snafu};
pub async fn check_name_availability(
operation_config: &crate::OperationConfig,
account_name: &StorageAccountCheckNameAvailabilityParameters,
subscription_id: &str,
) -> std::result::Result<CheckNameAvailabilityResult, check_name_availability::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.Storage/checkNameAvailability",
operation_config.base_path(),
subscription_id
);
let mut url = url::Url::parse(url_str).context(check_name_availability::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.context(check_name_availability::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).context(check_name_availability::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.context(check_name_availability::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: CheckNameAvailabilityResult =
serde_json::from_slice(rsp_body).context(check_name_availability::DeserializeError { body: rsp_body.clone() })?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
check_name_availability::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
}
.fail()
}
}
}
pub mod check_name_availability {
use crate::{models, models::*};
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
ParseUrlError { source: url::ParseError },
BuildRequestError { source: http::Error },
ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn get_properties(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
account_name: &str,
subscription_id: &str,
expand: Option<&str>,
) -> std::result::Result<StorageAccount, get_properties::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Storage/storageAccounts/{}",
operation_config.base_path(),
subscription_id,
resource_group_name,
account_name
);
let mut url = url::Url::parse(url_str).context(get_properties::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.context(get_properties::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
if let Some(expand) = expand {
url.query_pairs_mut().append_pair("$expand", expand);
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).context(get_properties::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.context(get_properties::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: StorageAccount =
serde_json::from_slice(rsp_body).context(get_properties::DeserializeError { body: rsp_body.clone() })?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
get_properties::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
}
.fail()
}
}
}
pub mod get_properties {
use crate::{models, models::*};
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
ParseUrlError { source: url::ParseError },
BuildRequestError { source: http::Error },
ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn create(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
account_name: &str,
parameters: &StorageAccountCreateParameters,
subscription_id: &str,
) -> std::result::Result<create::Response, create::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Storage/storageAccounts/{}",
operation_config.base_path(),
subscription_id,
resource_group_name,
account_name
);
let mut url = url::Url::parse(url_str).context(create::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PUT);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.context(create::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).context(create::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.context(create::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: StorageAccount =
serde_json::from_slice(rsp_body).context(create::DeserializeError { body: rsp_body.clone() })?;
Ok(create::Response::Ok200(rsp_value))
}
http::StatusCode::ACCEPTED => Ok(create::Response::Accepted202),
status_code => {
let rsp_body = rsp.body();
create::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
}
.fail()
}
}
}
pub mod create {
use crate::{models, models::*};
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200(StorageAccount),
Accepted202,
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
ParseUrlError { source: url::ParseError },
BuildRequestError { source: http::Error },
ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn update(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
account_name: &str,
parameters: &StorageAccountUpdateParameters,
subscription_id: &str,
) -> std::result::Result<StorageAccount, update::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Storage/storageAccounts/{}",
operation_config.base_path(),
subscription_id,
resource_group_name,
account_name
);
let mut url = url::Url::parse(url_str).context(update::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PATCH);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.context(update::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).context(update::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.context(update::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: StorageAccount =
serde_json::from_slice(rsp_body).context(update::DeserializeError { body: rsp_body.clone() })?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
update::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
}
.fail()
}
}
}
pub mod update {
use crate::{models, models::*};
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
ParseUrlError { source: url::ParseError },
BuildRequestError { source: http::Error },
ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn delete(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
account_name: &str,
subscription_id: &str,
) -> std::result::Result<delete::Response, delete::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Storage/storageAccounts/{}",
operation_config.base_path(),
subscription_id,
resource_group_name,
account_name
);
let mut url = url::Url::parse(url_str).context(delete::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::DELETE);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.context(delete::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).context(delete::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.context(delete::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => Ok(delete::Response::Ok200),
http::StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204),
status_code => {
let rsp_body = rsp.body();
delete::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
}
.fail()
}
}
}
pub mod delete {
use crate::{models, models::*};
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200,
NoContent204,
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
ParseUrlError { source: url::ParseError },
BuildRequestError { source: http::Error },
ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn list(
operation_config: &crate::OperationConfig,
subscription_id: &str,
) -> std::result::Result<StorageAccountListResult, list::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.Storage/storageAccounts",
operation_config.base_path(),
subscription_id
);
let mut url = url::Url::parse(url_str).context(list::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.context(list::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).context(list::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.context(list::ExecuteRequestError)?;
match rsp.status() { | http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: StorageAccountListResult =
serde_json::from_slice(rsp_body).context(list::DeserializeError { body: rsp_body.clone() })?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
list::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
}
.fail()
}
}
}
pub mod list {
use crate::{models, models::*};
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
ParseUrlError { source: url::ParseError },
BuildRequestError { source: http::Error },
ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn list_by_resource_group(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
subscription_id: &str,
) -> std::result::Result<StorageAccountListResult, list_by_resource_group::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Storage/storageAccounts",
operation_config.base_path(),
subscription_id,
resource_group_name
);
let mut url = url::Url::parse(url_str).context(list_by_resource_group::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.context(list_by_resource_group::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).context(list_by_resource_group::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.context(list_by_resource_group::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: StorageAccountListResult =
serde_json::from_slice(rsp_body).context(list_by_resource_group::DeserializeError { body: rsp_body.clone() })?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
list_by_resource_group::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
}
.fail()
}
}
}
pub mod list_by_resource_group {
use crate::{models, models::*};
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
ParseUrlError { source: url::ParseError },
BuildRequestError { source: http::Error },
ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn list_keys(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
account_name: &str,
subscription_id: &str,
) -> std::result::Result<StorageAccountListKeysResult, list_keys::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Storage/storageAccounts/{}/listKeys",
operation_config.base_path(),
subscription_id,
resource_group_name,
account_name
);
let mut url = url::Url::parse(url_str).context(list_keys::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.context(list_keys::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).context(list_keys::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.context(list_keys::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: StorageAccountListKeysResult =
serde_json::from_slice(rsp_body).context(list_keys::DeserializeError { body: rsp_body.clone() })?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
list_keys::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
}
.fail()
}
}
}
pub mod list_keys {
use crate::{models, models::*};
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
ParseUrlError { source: url::ParseError },
BuildRequestError { source: http::Error },
ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn regenerate_key(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
account_name: &str,
regenerate_key: &StorageAccountRegenerateKeyParameters,
subscription_id: &str,
) -> std::result::Result<StorageAccountListKeysResult, regenerate_key::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Storage/storageAccounts/{}/regenerateKey",
operation_config.base_path(),
subscription_id,
resource_group_name,
account_name
);
let mut url = url::Url::parse(url_str).context(regenerate_key::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.context(regenerate_key::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).context(regenerate_key::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.context(regenerate_key::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: StorageAccountListKeysResult =
serde_json::from_slice(rsp_body).context(regenerate_key::DeserializeError { body: rsp_body.clone() })?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
regenerate_key::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
}
.fail()
}
}
}
pub mod regenerate_key {
use crate::{models, models::*};
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
ParseUrlError { source: url::ParseError },
BuildRequestError { source: http::Error },
ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn list_account_sas(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
account_name: &str,
parameters: &AccountSasParameters,
subscription_id: &str,
) -> std::result::Result<ListAccountSasResponse, list_account_sas::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Storage/storageAccounts/{}/ListAccountSas",
operation_config.base_path(),
subscription_id,
resource_group_name,
account_name
);
let mut url = url::Url::parse(url_str).context(list_account_sas::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.context(list_account_sas::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).context(list_account_sas::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.context(list_account_sas::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: ListAccountSasResponse =
serde_json::from_slice(rsp_body).context(list_account_sas::DeserializeError { body: rsp_body.clone() })?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
list_account_sas::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
}
.fail()
}
}
}
pub mod list_account_sas {
use crate::{models, models::*};
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
ParseUrlError { source: url::ParseError },
BuildRequestError { source: http::Error },
ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn list_service_sas(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
account_name: &str,
parameters: &ServiceSasParameters,
subscription_id: &str,
) -> std::result::Result<ListServiceSasResponse, list_service_sas::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Storage/storageAccounts/{}/ListServiceSas",
operation_config.base_path(),
subscription_id,
resource_group_name,
account_name
);
let mut url = url::Url::parse(url_str).context(list_service_sas::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.context(list_service_sas::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).context(list_service_sas::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.context(list_service_sas::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: ListServiceSasResponse =
serde_json::from_slice(rsp_body).context(list_service_sas::DeserializeError { body: rsp_body.clone() })?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
list_service_sas::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
}
.fail()
}
}
}
pub mod list_service_sas {
use crate::{models, models::*};
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
ParseUrlError { source: url::ParseError },
BuildRequestError { source: http::Error },
ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn failover(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
account_name: &str,
subscription_id: &str,
) -> std::result::Result<failover::Response, failover::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Storage/storageAccounts/{}/failover",
operation_config.base_path(),
subscription_id,
resource_group_name,
account_name
);
let mut url = url::Url::parse(url_str).context(failover::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.context(failover::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).context(failover::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.context(failover::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => Ok(failover::Response::Ok200),
http::StatusCode::ACCEPTED => Ok(failover::Response::Accepted202),
status_code => {
let rsp_body = rsp.body();
failover::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
}
.fail()
}
}
}
pub mod failover {
use crate::{models, models::*};
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200,
Accepted202,
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
ParseUrlError { source: url::ParseError },
BuildRequestError { source: http::Error },
ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
}
pub mod usages {
use crate::models::*;
use snafu::{ResultExt, Snafu};
pub async fn list_by_location(
operation_config: &crate::OperationConfig,
subscription_id: &str,
location: &str,
) -> std::result::Result<UsageListResult, list_by_location::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.Storage/locations/{}/usages",
operation_config.base_path(),
subscription_id,
location
);
let mut url = url::Url::parse(url_str).context(list_by_location::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.context(list_by_location::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).context(list_by_location::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.context(list_by_location::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: UsageListResult =
serde_json::from_slice(rsp_body).context(list_by_location::DeserializeError { body: rsp_body.clone() })?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
list_by_location::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
}
.fail()
}
}
}
pub mod list_by_location {
use crate::{models, models::*};
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
ParseUrlError { source: url::ParseError },
BuildRequestError { source: http::Error },
ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
}
pub mod blob_services {
use crate::models::*;
use snafu::{ResultExt, Snafu};
pub async fn get_service_properties(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
account_name: &str,
subscription_id: &str,
blob_services_name: &str,
) -> std::result::Result<BlobServiceProperties, get_service_properties::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Storage/storageAccounts/{}/blobServices/{}",
operation_config.base_path(),
subscription_id,
resource_group_name,
account_name,
blob_services_name
);
let mut url = url::Url::parse(url_str).context(get_service_properties::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.context(get_service_properties::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).context(get_service_properties::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.context(get_service_properties::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: BlobServiceProperties =
serde_json::from_slice(rsp_body).context(get_service_properties::DeserializeError { body: rsp_body.clone() })?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
get_service_properties::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
}
.fail()
}
}
}
pub mod get_service_properties {
use crate::{models, models::*};
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
ParseUrlError { source: url::ParseError },
BuildRequestError { source: http::Error },
ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn set_service_properties(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
account_name: &str,
subscription_id: &str,
blob_services_name: &str,
parameters: &BlobServiceProperties,
) -> std::result::Result<BlobServiceProperties, set_service_properties::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Storage/storageAccounts/{}/blobServices/{}",
operation_config.base_path(),
subscription_id,
resource_group_name,
account_name,
blob_services_name
);
let mut url = url::Url::parse(url_str).context(set_service_properties::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PUT);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.context(set_service_properties::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).context(set_service_properties::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.context(set_service_properties::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: BlobServiceProperties =
serde_json::from_slice(rsp_body).context(set_service_properties::DeserializeError { body: rsp_body.clone() })?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
set_service_properties::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
}
.fail()
}
}
}
pub mod set_service_properties {
use crate::{models, models::*};
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
ParseUrlError { source: url::ParseError },
BuildRequestError { source: http::Error },
ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
}
pub mod blob_containers {
use crate::models::*;
use snafu::{ResultExt, Snafu};
pub async fn list(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
account_name: &str,
subscription_id: &str,
) -> std::result::Result<ListContainerItems, list::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Storage/storageAccounts/{}/blobServices/default/containers",
operation_config.base_path(),
subscription_id,
resource_group_name,
account_name
);
let mut url = url::Url::parse(url_str).context(list::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.context(list::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).context(list::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.context(list::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: ListContainerItems =
serde_json::from_slice(rsp_body).context(list::DeserializeError { body: rsp_body.clone() })?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
list::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
}
.fail()
}
}
}
pub mod list {
use crate::{models, models::*};
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
ParseUrlError { source: url::ParseError },
BuildRequestError { source: http::Error },
ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn get(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
account_name: &str,
container_name: &str,
subscription_id: &str,
) -> std::result::Result<BlobContainer, get::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Storage/storageAccounts/{}/blobServices/default/containers/{}",
operation_config.base_path(),
subscription_id,
resource_group_name,
account_name,
container_name
);
let mut url = url::Url::parse(url_str).context(get::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.context(get::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).context(get::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.context(get::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: BlobContainer =
serde_json::from_slice(rsp_body).context(get::DeserializeError { body: rsp_body.clone() })?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
get::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
}
.fail()
}
}
}
pub mod get {
use crate::{models, models::*};
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
ParseUrlError { source: url::ParseError },
BuildRequestError { source: http::Error },
ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn create(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
account_name: &str,
container_name: &str,
blob_container: &BlobContainer,
subscription_id: &str,
) -> std::result::Result<BlobContainer, create::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Storage/storageAccounts/{}/blobServices/default/containers/{}",
operation_config.base_path(),
subscription_id,
resource_group_name,
account_name,
container_name
);
let mut url = url::Url::parse(url_str).context(create::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PUT);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.context(create::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).context(create::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.context(create::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::CREATED => {
let rsp_body = rsp.body();
let rsp_value: BlobContainer =
serde_json::from_slice(rsp_body).context(create::DeserializeError { body: rsp_body.clone() })?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
create::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
}
.fail()
}
}
}
pub mod create {
use crate::{models, models::*};
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
ParseUrlError { source: url::ParseError },
BuildRequestError { source: http::Error },
ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn update(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
account_name: &str,
container_name: &str,
blob_container: &BlobContainer,
subscription_id: &str,
) -> std::result::Result<BlobContainer, update::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Storage/storageAccounts/{}/blobServices/default/containers/{}",
operation_config.base_path(),
subscription_id,
resource_group_name,
account_name,
container_name
);
let mut url = url::Url::parse(url_str).context(update::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PATCH);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.context(update::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).context(update::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.context(update::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: BlobContainer =
serde_json::from_slice(rsp_body).context(update::DeserializeError { body: rsp_body.clone() })?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
update::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
}
.fail()
}
}
}
pub mod update {
use crate::{models, models::*};
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
ParseUrlError { source: url::ParseError },
BuildRequestError { source: http::Error },
ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn delete(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
account_name: &str,
container_name: &str,
subscription_id: &str,
) -> std::result::Result<delete::Response, delete::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Storage/storageAccounts/{}/blobServices/default/containers/{}",
operation_config.base_path(),
subscription_id,
resource_group_name,
account_name,
container_name
);
let mut url = url::Url::parse(url_str).context(delete::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::DELETE);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.context(delete::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).context(delete::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.context(delete::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => Ok(delete::Response::Ok200),
http::StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204),
status_code => {
let rsp_body = rsp.body();
delete::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
}
.fail()
}
}
}
pub mod delete {
use crate::{models, models::*};
use snafu::Snafu;
#[derive(Debug)]
pub enum Response {
Ok200,
NoContent204,
}
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
ParseUrlError { source: url::ParseError },
BuildRequestError { source: http::Error },
ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn set_legal_hold(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
account_name: &str,
container_name: &str,
subscription_id: &str,
legal_hold: &LegalHold,
) -> std::result::Result<LegalHold, set_legal_hold::Error> {
let http_client = operation_config.http_client();
let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Storage/storageAccounts/{}/blobServices/default/containers/{}/setLegalHold" , operation_config . base_path () , subscription_id , resource_group_name , account_name , container_name) ;
let mut url = url::Url::parse(url_str).context(set_legal_hold::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.context(set_legal_hold::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).context(set_legal_hold::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.context(set_legal_hold::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: LegalHold =
serde_json::from_slice(rsp_body).context(set_legal_hold::DeserializeError { body: rsp_body.clone() })?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
set_legal_hold::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
}
.fail()
}
}
}
pub mod set_legal_hold {
use crate::{models, models::*};
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
ParseUrlError { source: url::ParseError },
BuildRequestError { source: http::Error },
ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn clear_legal_hold(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
account_name: &str,
container_name: &str,
subscription_id: &str,
legal_hold: &LegalHold,
) -> std::result::Result<LegalHold, clear_legal_hold::Error> {
let http_client = operation_config.http_client();
let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Storage/storageAccounts/{}/blobServices/default/containers/{}/clearLegalHold" , operation_config . base_path () , subscription_id , resource_group_name , account_name , container_name) ;
let mut url = url::Url::parse(url_str).context(clear_legal_hold::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.context(clear_legal_hold::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).context(clear_legal_hold::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.context(clear_legal_hold::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: LegalHold =
serde_json::from_slice(rsp_body).context(clear_legal_hold::DeserializeError { body: rsp_body.clone() })?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
clear_legal_hold::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
}
.fail()
}
}
}
pub mod clear_legal_hold {
use crate::{models, models::*};
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
ParseUrlError { source: url::ParseError },
BuildRequestError { source: http::Error },
ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn get_immutability_policy(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
account_name: &str,
container_name: &str,
immutability_policy_name: &str,
subscription_id: &str,
if_match: Option<&str>,
) -> std::result::Result<ImmutabilityPolicy, get_immutability_policy::Error> {
let http_client = operation_config.http_client();
let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Storage/storageAccounts/{}/blobServices/default/containers/{}/immutabilityPolicies/{}" , operation_config . base_path () , subscription_id , resource_group_name , account_name , container_name , immutability_policy_name) ;
let mut url = url::Url::parse(url_str).context(get_immutability_policy::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.context(get_immutability_policy::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
if let Some(if_match) = if_match {
req_builder = req_builder.header("If-Match", if_match);
}
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).context(get_immutability_policy::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.context(get_immutability_policy::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: ImmutabilityPolicy =
serde_json::from_slice(rsp_body).context(get_immutability_policy::DeserializeError { body: rsp_body.clone() })?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
get_immutability_policy::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
}
.fail()
}
}
}
pub mod get_immutability_policy {
use crate::{models, models::*};
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
ParseUrlError { source: url::ParseError },
BuildRequestError { source: http::Error },
ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn create_or_update_immutability_policy(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
account_name: &str,
container_name: &str,
immutability_policy_name: &str,
subscription_id: &str,
parameters: Option<&ImmutabilityPolicy>,
if_match: Option<&str>,
) -> std::result::Result<ImmutabilityPolicy, create_or_update_immutability_policy::Error> {
let http_client = operation_config.http_client();
let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Storage/storageAccounts/{}/blobServices/default/containers/{}/immutabilityPolicies/{}" , operation_config . base_path () , subscription_id , resource_group_name , account_name , container_name , immutability_policy_name) ;
let mut url = url::Url::parse(url_str).context(create_or_update_immutability_policy::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PUT);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.context(create_or_update_immutability_policy::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
let req_body = if let Some(parameters) = parameters {
azure_core::to_json(parameters).context(create_or_update_immutability_policy::SerializeError)?
} else {
bytes::Bytes::from_static(azure_core::EMPTY_BODY)
};
if let Some(if_match) = if_match {
req_builder = req_builder.header("If-Match", if_match);
}
req_builder = req_builder.uri(url.as_str());
let req = req_builder
.body(req_body)
.context(create_or_update_immutability_policy::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.context(create_or_update_immutability_policy::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: ImmutabilityPolicy = serde_json::from_slice(rsp_body)
.context(create_or_update_immutability_policy::DeserializeError { body: rsp_body.clone() })?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
create_or_update_immutability_policy::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
}
.fail()
}
}
}
pub mod create_or_update_immutability_policy {
use crate::{models, models::*};
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
ParseUrlError { source: url::ParseError },
BuildRequestError { source: http::Error },
ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn delete_immutability_policy(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
account_name: &str,
container_name: &str,
immutability_policy_name: &str,
subscription_id: &str,
if_match: &str,
) -> std::result::Result<ImmutabilityPolicy, delete_immutability_policy::Error> {
let http_client = operation_config.http_client();
let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Storage/storageAccounts/{}/blobServices/default/containers/{}/immutabilityPolicies/{}" , operation_config . base_path () , subscription_id , resource_group_name , account_name , container_name , immutability_policy_name) ;
let mut url = url::Url::parse(url_str).context(delete_immutability_policy::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::DELETE);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.context(delete_immutability_policy::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
req_builder = req_builder.header("If-Match", if_match);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).context(delete_immutability_policy::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.context(delete_immutability_policy::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: ImmutabilityPolicy =
serde_json::from_slice(rsp_body).context(delete_immutability_policy::DeserializeError { body: rsp_body.clone() })?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
delete_immutability_policy::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
}
.fail()
}
}
}
pub mod delete_immutability_policy {
use crate::{models, models::*};
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
ParseUrlError { source: url::ParseError },
BuildRequestError { source: http::Error },
ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn lock_immutability_policy(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
account_name: &str,
container_name: &str,
subscription_id: &str,
if_match: &str,
) -> std::result::Result<ImmutabilityPolicy, lock_immutability_policy::Error> {
let http_client = operation_config.http_client();
let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Storage/storageAccounts/{}/blobServices/default/containers/{}/immutabilityPolicies/default/lock" , operation_config . base_path () , subscription_id , resource_group_name , account_name , container_name) ;
let mut url = url::Url::parse(url_str).context(lock_immutability_policy::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.context(lock_immutability_policy::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
req_builder = req_builder.header("If-Match", if_match);
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).context(lock_immutability_policy::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.context(lock_immutability_policy::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: ImmutabilityPolicy =
serde_json::from_slice(rsp_body).context(lock_immutability_policy::DeserializeError { body: rsp_body.clone() })?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
lock_immutability_policy::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
}
.fail()
}
}
}
pub mod lock_immutability_policy {
use crate::{models, models::*};
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
ParseUrlError { source: url::ParseError },
BuildRequestError { source: http::Error },
ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn extend_immutability_policy(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
account_name: &str,
container_name: &str,
subscription_id: &str,
parameters: Option<&ImmutabilityPolicy>,
if_match: &str,
) -> std::result::Result<ImmutabilityPolicy, extend_immutability_policy::Error> {
let http_client = operation_config.http_client();
let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Storage/storageAccounts/{}/blobServices/default/containers/{}/immutabilityPolicies/default/extend" , operation_config . base_path () , subscription_id , resource_group_name , account_name , container_name) ;
let mut url = url::Url::parse(url_str).context(extend_immutability_policy::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.context(extend_immutability_policy::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
let req_body = if let Some(parameters) = parameters {
azure_core::to_json(parameters).context(extend_immutability_policy::SerializeError)?
} else {
bytes::Bytes::from_static(azure_core::EMPTY_BODY)
};
req_builder = req_builder.header("If-Match", if_match);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).context(extend_immutability_policy::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.context(extend_immutability_policy::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: ImmutabilityPolicy =
serde_json::from_slice(rsp_body).context(extend_immutability_policy::DeserializeError { body: rsp_body.clone() })?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
extend_immutability_policy::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
}
.fail()
}
}
}
pub mod extend_immutability_policy {
use crate::{models, models::*};
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
ParseUrlError { source: url::ParseError },
BuildRequestError { source: http::Error },
ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
pub async fn lease(
operation_config: &crate::OperationConfig,
resource_group_name: &str,
account_name: &str,
container_name: &str,
subscription_id: &str,
parameters: Option<&LeaseContainerRequest>,
) -> std::result::Result<LeaseContainerResponse, lease::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.Storage/storageAccounts/{}/blobServices/default/containers/{}/lease",
operation_config.base_path(),
subscription_id,
resource_group_name,
account_name,
container_name
);
let mut url = url::Url::parse(url_str).context(lease::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.context(lease::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
let req_body = if let Some(parameters) = parameters {
azure_core::to_json(parameters).context(lease::SerializeError)?
} else {
bytes::Bytes::from_static(azure_core::EMPTY_BODY)
};
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).context(lease::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.context(lease::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: LeaseContainerResponse =
serde_json::from_slice(rsp_body).context(lease::DeserializeError { body: rsp_body.clone() })?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
lease::UnexpectedResponse {
status_code,
body: rsp_body.clone(),
}
.fail()
}
}
}
pub mod lease {
use crate::{models, models::*};
use snafu::Snafu;
#[derive(Debug, Snafu)]
#[snafu(visibility(pub(crate)))]
pub enum Error {
UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes },
ParseUrlError { source: url::ParseError },
BuildRequestError { source: http::Error },
ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send> },
SerializeError { source: Box<dyn std::error::Error + Sync + Send> },
DeserializeError { source: serde_json::Error, body: bytes::Bytes },
GetTokenError { source: azure_core::errors::AzureError },
}
}
} | |
isdelve_test.go | // Copyright © 2020 Hedzr Yeh.
package logex
import (
"github.com/hedzr/log"
"github.com/hedzr/log/dir"
"testing"
)
func TestEnable(t *testing.T) {
defer CaptureLog(t).Release()
Enable()
if GetLevel() != log.InfoLevel {
t.Fatal("wrong level")
}
EnableWith(log.DebugLevel)
if GetLevel() != log.DebugLevel {
t.Fatal("wrong level")
}
t.Logf("cwd: %v", dir.GetCurrentDir())
SetupLoggingFormat("json", 1)
SetupLoggingFormat("text", 1)
}
func TestSetupLoggingFormat(t *testing.T) {
c := CaptureLog(t)
defer c.Release()
EnableWith(log.OffLevel, func() {
_, _ = c.(interface {
Write(p []byte) (n int, err error)
}).Write([]byte("hello"))
})
if GetLevel() != log.OffLevel {
t.Fatal("wrong level")
}
log.SetLevel(log.OffLevel)
SetupLoggingFormat("any", 1) | SetTraceMode(true)
t.Logf("%v, %v, %v", GetDebugMode(), GetTraceMode(), InDebugging())
} |
t.Logf("%v, %v", GetDebugMode(), GetTraceMode())
SetDebugMode(true) |
promises.js | // Generated by CoffeeScript 1.10.0
(function() {
var Deferred, Promise, PromiseA, defer, fireHandlers, fs, fulfill, pad, readDir, reject, resolve, testFunc, thousand_sep,
bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
| return reject(promise, new TypeError("promise and resolution value can't be the same object"));
}
if ((x != null ? x.constructor.name : void 0) === 'Promise') {
if (x.isPending()) {
return x._dependants.push(promise);
}
if (x.isFulfilled()) {
return fulfill(promise, x.value);
}
if (x.isRejected()) {
return reject(promise, x.reason);
}
}
return fulfill(promise, x);
};
fulfill = function(promise, value) {
if (!promise.isPending()) {
return promise;
}
promise._state = Promise.states.fulfilled;
promise._value = value;
fireHandlers(promise, value);
promise._dependants.forEach(function(dependant) {
return resolve(dependant, value);
});
return promise;
};
reject = function(promise, reason) {
if (!promise.isPending()) {
return promise;
}
promise._state = Promise.states.rejected;
promise._reason = reason;
fireHandlers(promise, reason);
promise._dependants.forEach(function(dependant) {
return reject(dependant, reason);
});
return promise;
};
fireHandlers = function(promise, what) {
var handlers;
switch (promise._state) {
case Promise.states.rejected:
handlers = promise._rejectHandlers;
break;
case Promise.states.fulfilled:
handlers = promise._fulfillHandlers;
break;
default:
return;
}
handlers.forEach(function(handler, index) {
var cascade_promise, e, error, result;
if (promise._handlerCalls[index] !== 0) {
return;
}
promise._handlerCalls[index] += 1;
cascade_promise = promise._retPromises[index];
if ((handler != null ? handler.constructor.name : void 0) === "Function") {
try {
result = handler(what);
if (promise._state === Promise.states.fulfilled) {
return resolve(cascade_promise, result);
} else {
return reject(cascade_promise, result);
}
} catch (error) {
e = error;
return reject(cascade_promise, e);
}
} else {
if (promise._state === Promise.states.fulfilled) {
return resolve(cascade_promise, what);
} else {
return reject(cascade_promise, what);
}
}
});
return promise;
};
Promise = (function() {
"Returns a promise object which complies (really?) with promises A+ spec";
Promise.states = {
pending: 0,
rejected: -1,
fulfilled: 1
};
Object.defineProperties(Promise.prototype, {
value: {
get: function() {
return this._value;
}
},
reason: {
get: function() {
return this._reason;
}
},
state: {
get: function() {
return this._state;
}
}
});
function Promise(_options) {
this._options = _options != null ? _options : {};
this.isResolved = bind(this.isResolved, this);
this.isPending = bind(this.isPending, this);
this.isFulfilled = bind(this.isFulfilled, this);
this.isRejected = bind(this.isRejected, this);
this.fail = bind(this.fail, this);
this.done = bind(this.done, this);
this.then = bind(this.then, this);
Promise.init(this);
}
Promise.init = function(obj) {
obj._state = Promise.states.pending;
obj._fulfillHandlers = [];
obj._rejectHandlers = [];
obj._retPromises = [];
obj._handlerCalls = [];
obj._dependants = [];
return obj;
};
Promise.prototype.then = function(onFulfilled, onRejected) {
var retPromise;
this._fulfillHandlers.push(onFulfilled || null);
this._rejectHandlers.push(onRejected || null);
retPromise = new Promise({
level: this._options.level + 1
});
this._retPromises.push(retPromise);
if (this.isPending()) {
this._handlerCalls.push(0);
} else {
this._handlerCalls.push(1);
if (this.isRejected()) {
reject(retPromise, this._reason);
}
if (this.isFulfilled()) {
if ((onFulfilled != null ? onFulfilled.constructor.name : void 0) === "Function") {
resolve(retPromise, onFulfilled(this._value));
} else {
resolve(retPromise, this._value);
}
}
}
return retPromise;
};
Promise.prototype.done = function(onFulfilled) {
return this.then(onFulfilled, null);
};
Promise.prototype.fail = function(onRejected) {
return this.then(null, onRejected);
};
Promise.prototype.isRejected = function() {
if (this._state === Promise.states.rejected) {
return true;
} else {
return false;
}
};
Promise.prototype.isFulfilled = function() {
if (this._state === Promise.states.fulfilled) {
return true;
} else {
return false;
}
};
Promise.prototype.isPending = function() {
if (this._state === Promise.states.pending) {
return true;
} else {
return false;
}
};
Promise.prototype.isResolved = function() {
return !this.isPending();
};
return Promise;
})();
Deferred = (function() {
"Promise manager object";
function Deferred() {
this.reject = bind(this.reject, this);
this.resolve = bind(this.resolve, this);
this.promise = bind(this.promise, this);
this._promise = new Promise({
level: 0
});
}
Deferred.prototype.promise = function() {
return this._promise;
};
Deferred.prototype.resolve = function(value) {
return setImmediate((function(_this) {
return function() {
if (!_this._promise.isPending()) {
return;
}
return resolve(_this._promise, value);
};
})(this));
};
Deferred.prototype.reject = function(reason) {
return setImmediate((function(_this) {
return function() {
if (!_this._promise.isPending()) {
return;
}
return reject(_this._promise, reason);
};
})(this));
};
return Deferred;
})();
defer = function() {
return new Deferred;
};
if (typeof module !== "undefined" && module !== null) {
module.exports = PromiseA = {
Promise: Promise,
Deferred: Deferred,
defer: defer
};
}
if (!(typeof module !== "undefined" && module !== null ? module.parent : void 0)) {
thousand_sep = function(num, sep) {
var resp;
if (sep == null) {
sep = ",";
}
if (!(num.toString().length > 3)) {
return num.toString();
}
resp = num.toString().split('').reverse().join('').replace(/(\d{3})/g, "$1" + sep).split('').reverse().join('');
if (resp.charAt(0) === sep) {
return resp.slice(1);
} else {
return resp;
}
};
pad = function(stri, quantity, direction, padchar) {
var dif, len, n, padstri;
if (direction == null) {
direction = "r";
}
if (padchar == null) {
padchar = " ";
}
if (stri.constructor.name === "Number") {
stri = stri.toString();
}
len = stri.length;
dif = quantity - len;
if (dif <= 0) {
return stri;
}
padstri = ((function() {
var i, ref, results;
results = [];
for (n = i = 1, ref = dif; 1 <= ref ? i <= ref : i >= ref; n = 1 <= ref ? ++i : --i) {
results.push(padchar);
}
return results;
})()).join('');
if (direction === "r") {
return "" + stri + padstri;
} else {
return "" + padstri + stri;
}
};
testFunc = function() {
var d, p;
d = defer();
setTimeout((function() {
return d.resolve(10);
}), 100);
p = d.promise();
/*
setTimeout (->
console.log "\n"
console.log util.inspect p._fulfillHandlers
console.log util.inspect p._retPromises[0]?._fulfillHandlers
console.log util.inspect p._retPromises[0]?._retPromises[0]?._fulfillHandlers
console.log "\n"), 50
*/
console.log("Running test function");
console.log("---------------------\n");
return p;
};
/*
testFunc()
.then(
(number) ->
console.log "Promise level 0 received number #{number}"
number + 1
(err) =>
console.log "First promise triggered an error:", err.toString()
)
.then(
(number) ->
console.log "Promise level 1 received number #{number}"
number + 1
)
.then(
(number) ->
console.log "Promise level 2 received number #{number}"
number * 3
)
.then(
(resp) ->
console.log "Promise level 3 received number #{resp}"
resp
)
*/
fs = require('fs');
readDir = function() {
var d;
d = defer();
fs.readdir(process.cwd(), function(err, files) {
if (err) {
console.log("ERROR reading directory: ");
} else {
console.log("Current working directory: " + (process.cwd()) + "\n");
}
if (err) {
return d.reject(err);
} else {
return d.resolve(files);
}
});
console.log("Running file system test function");
console.log("---------------------------------\n");
return d.promise();
};
readDir().then(function(files) {
var d, len, p, stats;
len = files.length - 1;
stats = [];
d = defer();
p = d.promise();
files.forEach(function(file, index) {
return fs.stat(file, function(err, stat) {
if (err) {
return d.reject(err);
}
stats[index] = stat;
if (index === len) {
console.log("Retrieved", stats.length, "items.\n");
return d.resolve([files, stats]);
}
});
});
return p;
}, function(err) {
return console.log("ERROR reading current directory: " + err.message);
}).then(function(arrs) {
var file, fileInfo, fileSizes, files, i, index, j, len1, len2, ref, ref1, ref2, stats;
files = arrs[0], stats = arrs[1];
fileSizes = [];
for (index = i = 0, len1 = files.length; i < len1; index = ++i) {
file = files[index];
fileSizes.push({
name: '' + file + (((ref = stats[index]) != null ? ref.isDirectory() : void 0) ? ' [DIR]' : ''),
size: (ref1 = stats[index]) != null ? ref1.size : void 0,
isFile: (ref2 = stats[index]) != null ? ref2.isFile() : void 0
});
}
fileSizes.sort(function(info1, info2) {
return info1.isFile - info2.isFile;
});
for (j = 0, len2 = fileSizes.length; j < len2; j++) {
fileInfo = fileSizes[j];
console.log(pad(fileInfo.name, 40), " --- ", pad(thousand_sep(fileInfo.size), 40, "l"), "bytes.");
}
return fileSizes;
}, function(err) {
return console.log("Something horrible happened while processing file names and stats:", err.message);
}).then(function(fileSizes) {
var info;
info = "\nTotal Size of files in " + (process.cwd()) + ": ";
info += (thousand_sep(fileSizes.reduce((function(acum, fileInfo) {
return acum + (fileInfo.isFile ? fileInfo.size : 0);
}), 0))) + " bytes.\n";
return console.log(info);
}, function(err) {
return console.log("Something horrible happened while processing total files size:", err.message);
});
}
}).call(this); | resolve = function(promise, x) {
if (promise === x) { |
pyunit_get_model_gbm.py | import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
def get_model_gbm():
prostate = h2o.import_file(path=pyunit_utils.locate("smalldata/logreg/prostate.csv"))
prostate.describe()
prostate[1] = prostate[1].asfactor()
from h2o.estimators.gbm import H2OGradientBoostingEstimator
prostate_gbm = H2OGradientBoostingEstimator(distribution="bernoulli")
prostate_gbm.train(x=range(2,9),y=1, training_frame=prostate)
prostate_gbm.show()
prostate_gbm.predict(prostate)
model = h2o.get_model(prostate_gbm.model_id)
model.show()
| else:
get_model_gbm() | if __name__ == "__main__":
pyunit_utils.standalone_test(get_model_gbm) |
clip.py | ''' clip.py:
Implement's the clip ONNX node as a flexnode (for use with any accelerator)
'''
import uuid
import numpy as np
from operators.flexnode import FlexNode
from core.defines import Operator
from core.messaging import Message
class Clip(FlexNode):
def | (self, onnx_node, inputs, outputs):
FlexNode.__init__(self, onnx_node, inputs, outputs)
self._min = -3.402823466e+38
self._max = 3.402823466e+38
if len(inputs) != 1 and len(inputs) != 3:
raise ValueError("Clip can only have 1 or 3 inputs.")
self._input = inputs[0]
if len(inputs) == 3:
self._min = inputs[1]
self._max = inputs[2]
def map(self, memory_mapper):
pass
def unmap(self, memory_mapper):
pass
def _inputs2mem(self, memory_xfer_engine):
pass
def _mem2output(self, memory_xfer_engine):
pass
def compile(self, source, destinations):
tile_commands = list()
# Here, we are NOT generating tile_commands, (although, this is not difficult.)
np.copyto(self._outputs[0], np.clip(self._input, self._min, self._max))
return tile_commands
| __init__ |
post_lte_network_id_enodebs_responses.go | // Code generated by go-swagger; DO NOT EDIT.
package enode_bs
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"fmt"
"io"
"github.com/go-openapi/runtime"
strfmt "github.com/go-openapi/strfmt"
models "magma/orc8r/cloud/api/v1/go/models"
)
// PostLTENetworkIDEnodebsReader is a Reader for the PostLTENetworkIDEnodebs structure.
type PostLTENetworkIDEnodebsReader struct {
formats strfmt.Registry
}
// ReadResponse reads a server response into the received o.
func (o *PostLTENetworkIDEnodebsReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
switch response.Code() {
case 201:
result := NewPostLTENetworkIDEnodebsCreated()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return result, nil
default:
result := NewPostLTENetworkIDEnodebsDefault(response.Code())
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
if response.Code()/100 == 2 {
return result, nil
}
return nil, result
}
}
// NewPostLTENetworkIDEnodebsCreated creates a PostLTENetworkIDEnodebsCreated with default headers values
func NewPostLTENetworkIDEnodebsCreated() *PostLTENetworkIDEnodebsCreated {
return &PostLTENetworkIDEnodebsCreated{}
}
/*PostLTENetworkIDEnodebsCreated handles this case with default header values.
Success
*/
type PostLTENetworkIDEnodebsCreated struct {
}
func (o *PostLTENetworkIDEnodebsCreated) Error() string {
return fmt.Sprintf("[POST /lte/{network_id}/enodebs][%d] postLteNetworkIdEnodebsCreated ", 201) |
return nil
}
// NewPostLTENetworkIDEnodebsDefault creates a PostLTENetworkIDEnodebsDefault with default headers values
func NewPostLTENetworkIDEnodebsDefault(code int) *PostLTENetworkIDEnodebsDefault {
return &PostLTENetworkIDEnodebsDefault{
_statusCode: code,
}
}
/*PostLTENetworkIDEnodebsDefault handles this case with default header values.
Unexpected Error
*/
type PostLTENetworkIDEnodebsDefault struct {
_statusCode int
Payload *models.Error
}
// Code gets the status code for the post LTE network ID enodebs default response
func (o *PostLTENetworkIDEnodebsDefault) Code() int {
return o._statusCode
}
func (o *PostLTENetworkIDEnodebsDefault) Error() string {
return fmt.Sprintf("[POST /lte/{network_id}/enodebs][%d] PostLTENetworkIDEnodebs default %+v", o._statusCode, o.Payload)
}
func (o *PostLTENetworkIDEnodebsDefault) GetPayload() *models.Error {
return o.Payload
}
func (o *PostLTENetworkIDEnodebsDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
o.Payload = new(models.Error)
// response payload
if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
return err
}
return nil
} | }
func (o *PostLTENetworkIDEnodebsCreated) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { |
three.armarkermulti.js | THREE.ArMarkerMulti = function(options){
// call parent constructor
THREE.ArMarker.call( this );
// handle options
options = options || {}
this.options = {}
this.options.smoothingEnabled = options.smoothingEnabled !== undefined ? options.smoothingEnabled : true
this.options.smoothingFactor = options.smoothingFactor !== undefined ? options.smoothingFactor : 0.7
this.arMarkers = []
// create the marker Root
this.markerObject = new THREE.Object3D();
this.markerObject.name = 'Multi Marker Root'
this.markerObject.visible = true
| this.originObject = new THREE.Object3D();
this.originObject.name = 'Origin object'
this.markerObject.add(this.originObject)
}
THREE.ArMarkerMulti.prototype = Object.create( THREE.ArMarker.prototype );
THREE.ArMarkerMulti.prototype.constructor = THREE.ArMarkerMulti;
THREE.ArMarkerMulti.prototype.updatePose = function () {
// average the world position of each originObject
var isVisible = false
var visibleCount = 0
//////////////////////////////////////////////////////////////////////////////
// compute average position
//////////////////////////////////////////////////////////////////////////////
var averagedPosition = new THREE.Vector3
this.arMarkers.forEach(function(arMarker){
if( arMarker.markerObject.visible === false ) return
// honor markerObject.visible
isVisible = true
// count how many are visible
visibleCount++
// add the world position of arMarker origin object
var worldPosition = new THREE.Vector3
arMarker.originObject.localToWorld(worldPosition)
averagedPosition.add(worldPosition)
})
averagedPosition.multiplyScalar(1/visibleCount)
this.markerObject.position.copy(averagedPosition)
// set marker position
if( this.options.smoothingEnabled === true ){
var smoothingFactor = this.options.smoothingFactor
this.markerObject.position
.multiplyScalar(smoothingFactor)
.add(averagedPosition.clone().multiplyScalar(1-smoothingFactor))
}
// how to average the rotation
// http://wiki.unity3d.com/index.php/Averaging_Quaternions_and_Vectors
// honor markerObject.visible
this.markerObject.visible = isVisible
}; | |
ActionAnimation.js | /**
* 动作动画帧范围类
* @author 后天 2017.10.2
*
*/
var Entity;
(function (Entity) {
var ActionAnimation = /** @class */ (function () {
function ActionAnimation(nFra | Count, nActionTime) {
this._nFrameStart = 0; //帧起始
this._nFrameCount = 0; //帧数量
this._nActionTime = 0; //动作的周期时间,完成此动作所需要的时间
this._nFrameStart = nFrameStart;
this._nFrameCount = nFrameCount;
this._nActionTime = nActionTime;
}
return ActionAnimation;
}());
Entity.ActionAnimation = ActionAnimation;
})(Entity || (Entity = {}));
//# sourceMappingURL=ActionAnimation.js.map | meStart, nFrame |
storage_bucket.go | // ----------------------------------------------------------------------------
//
// This file is copied here by Magic Modules. The code for building up a
// storage bucket object is copied from the manually implemented
// provider file:
// third_party/terraform/resources/resource_storage_bucket.go
//
// ----------------------------------------------------------------------------
package google
import (
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"google.golang.org/api/storage/v1"
)
func GetStorageBucketCaiObject(d TerraformResourceData, config *Config) ([]Asset, error) {
name, err := assetName(d, config, "//storage.googleapis.com/{{name}}")
if err != nil {
return []Asset{}, err
}
if obj, err := GetStorageBucketApiObject(d, config); err == nil {
return []Asset{{
Name: name,
Type: "storage.googleapis.com/Bucket",
Resource: &AssetResource{
Version: "v1",
DiscoveryDocumentURI: "https://www.googleapis.com/discovery/v1/apis/storage/v1/rest",
DiscoveryName: "Bucket",
Data: obj,
},
}}, nil
} else {
return []Asset{}, err
}
}
func GetStorageBucketApiObject(d TerraformResourceData, config *Config) (map[string]interface{}, error) {
project, err := getProject(d, config)
if err != nil {
return nil, err
}
// Get the bucket and location
bucket := d.Get("name").(string)
location := d.Get("location").(string)
// Create a bucket, setting the labels, location and name.
sb := &storage.Bucket{
Name: bucket,
Labels: expandLabels(d),
Location: location,
IamConfiguration: expandIamConfiguration(d),
}
if v, ok := d.GetOk("storage_class"); ok {
sb.StorageClass = v.(string)
}
if err := resourceGCSBucketLifecycleCreateOrUpdate(d, sb); err != nil {
return nil, err
}
if v, ok := d.GetOk("versioning"); ok {
sb.Versioning = expandBucketVersioning(v)
}
if v, ok := d.GetOk("website"); ok {
sb.Website = expandBucketWebsite(v.([]interface{}))
}
if v, ok := d.GetOk("retention_policy"); ok {
sb.RetentionPolicy = expandBucketRetentionPolicy(v.([]interface{}))
}
if v, ok := d.GetOk("cors"); ok {
sb.Cors = expandCors(v.([]interface{}))
}
if v, ok := d.GetOk("default_event_based_hold"); ok {
sb.DefaultEventBasedHold = v.(bool)
}
if v, ok := d.GetOk("logging"); ok {
sb.Logging = expandBucketLogging(v.([]interface{}))
}
if v, ok := d.GetOk("encryption"); ok {
sb.Encryption = expandBucketEncryption(v.([]interface{}))
}
if v, ok := d.GetOk("requester_pays"); ok {
sb.Billing = &storage.BucketBilling{
RequesterPays: v.(bool),
}
}
m, err := jsonMap(sb)
if err != nil {
return nil, err
}
m["project"] = project
return m, nil
}
func expandCors(configured []interface{}) []*storage.BucketCors {
corsRules := make([]*storage.BucketCors, 0, len(configured))
for _, raw := range configured {
data := raw.(map[string]interface{})
corsRule := storage.BucketCors{
Origin: convertStringArr(data["origin"].([]interface{})),
Method: convertStringArr(data["method"].([]interface{})),
ResponseHeader: convertStringArr(data["response_header"].([]interface{})),
MaxAgeSeconds: int64(data["max_age_seconds"].(int)),
}
corsRules = append(corsRules, &corsRule)
}
return corsRules
}
func expandBucketEncryption(configured interface{}) *storage.BucketEncryption |
func expandBucketLogging(configured interface{}) *storage.BucketLogging {
loggings := configured.([]interface{})
if len(loggings) == 0 {
return nil
}
logging := loggings[0].(map[string]interface{})
bucketLogging := &storage.BucketLogging{
LogBucket: logging["log_bucket"].(string),
LogObjectPrefix: logging["log_object_prefix"].(string),
}
return bucketLogging
}
func expandBucketVersioning(configured interface{}) *storage.BucketVersioning {
versionings := configured.([]interface{})
if len(versionings) == 0 {
return nil
}
versioning := versionings[0].(map[string]interface{})
bucketVersioning := &storage.BucketVersioning{}
bucketVersioning.Enabled = versioning["enabled"].(bool)
bucketVersioning.ForceSendFields = append(bucketVersioning.ForceSendFields, "Enabled")
return bucketVersioning
}
func expandBucketWebsite(v interface{}) *storage.BucketWebsite {
if v == nil {
return nil
}
vs := v.([]interface{})
if len(vs) < 1 || vs[0] == nil {
return nil
}
website := vs[0].(map[string]interface{})
w := &storage.BucketWebsite{}
if v := website["not_found_page"]; v != "" {
w.NotFoundPage = v.(string)
}
if v := website["main_page_suffix"]; v != "" {
w.MainPageSuffix = v.(string)
}
return w
}
func expandBucketRetentionPolicy(configured interface{}) *storage.BucketRetentionPolicy {
retentionPolicies := configured.([]interface{})
if len(retentionPolicies) == 0 {
return nil
}
retentionPolicy := retentionPolicies[0].(map[string]interface{})
bucketRetentionPolicy := &storage.BucketRetentionPolicy{
RetentionPeriod: int64(retentionPolicy["retention_period"].(int)),
}
return bucketRetentionPolicy
}
func resourceGCSBucketLifecycleCreateOrUpdate(d TerraformResourceData, sb *storage.Bucket) error {
if v, ok := d.GetOk("lifecycle_rule"); ok {
lifecycle_rules := v.([]interface{})
sb.Lifecycle = &storage.BucketLifecycle{}
sb.Lifecycle.Rule = make([]*storage.BucketLifecycleRule, 0, len(lifecycle_rules))
for _, raw_lifecycle_rule := range lifecycle_rules {
lifecycle_rule := raw_lifecycle_rule.(map[string]interface{})
target_lifecycle_rule := &storage.BucketLifecycleRule{}
if v, ok := lifecycle_rule["action"]; ok {
if actions := v.(*schema.Set).List(); len(actions) == 1 {
action := actions[0].(map[string]interface{})
target_lifecycle_rule.Action = &storage.BucketLifecycleRuleAction{}
if v, ok := action["type"]; ok {
target_lifecycle_rule.Action.Type = v.(string)
}
if v, ok := action["storage_class"]; ok {
target_lifecycle_rule.Action.StorageClass = v.(string)
}
} else {
return fmt.Errorf("Exactly one action is required")
}
}
if v, ok := lifecycle_rule["condition"]; ok {
if conditions := v.(*schema.Set).List(); len(conditions) == 1 {
condition := conditions[0].(map[string]interface{})
target_lifecycle_rule.Condition = &storage.BucketLifecycleRuleCondition{}
if v, ok := condition["age"]; ok {
target_lifecycle_rule.Condition.Age = int64(v.(int))
}
if v, ok := condition["created_before"]; ok {
target_lifecycle_rule.Condition.CreatedBefore = v.(string)
}
if v, ok := condition["matches_storage_class"]; ok {
matches_storage_classes := v.([]interface{})
target_matches_storage_classes := make([]string, 0, len(matches_storage_classes))
for _, v := range matches_storage_classes {
target_matches_storage_classes = append(target_matches_storage_classes, v.(string))
}
target_lifecycle_rule.Condition.MatchesStorageClass = target_matches_storage_classes
}
if v, ok := condition["num_newer_versions"]; ok {
target_lifecycle_rule.Condition.NumNewerVersions = int64(v.(int))
}
} else {
return fmt.Errorf("Exactly one condition is required")
}
}
sb.Lifecycle.Rule = append(sb.Lifecycle.Rule, target_lifecycle_rule)
}
} else {
sb.Lifecycle = &storage.BucketLifecycle{
ForceSendFields: []string{"Rule"},
}
}
return nil
}
// remove this on next major release of the provider.
func expandIamConfiguration(d TerraformResourceData) *storage.BucketIamConfiguration {
// We are checking for a change because the last else block is only executed on Create.
enabled := false
if d.HasChange("bucket_policy_only") {
enabled = d.Get("bucket_policy_only").(bool)
} else if d.HasChange("uniform_bucket_level_access") {
enabled = d.Get("uniform_bucket_level_access").(bool)
} else {
enabled = d.Get("bucket_policy_only").(bool) || d.Get("uniform_bucket_level_access").(bool)
}
return &storage.BucketIamConfiguration{
ForceSendFields: []string{"UniformBucketLevelAccess"},
UniformBucketLevelAccess: &storage.BucketIamConfigurationUniformBucketLevelAccess{
Enabled: enabled,
ForceSendFields: []string{"Enabled"},
},
}
}
// Uncomment once the previous function is removed.
// func expandIamConfiguration(d TerraformResourceData) *storage.BucketIamConfiguration {
// return &storage.BucketIamConfiguration{
// ForceSendFields: []string{"UniformBucketLevelAccess"},
// UniformBucketLevelAccess: &storage.BucketIamConfigurationUniformBucketLevelAccess{
// Enabled: d.Get("uniform_bucket_level_access").(bool),
// ForceSendFields: []string{"Enabled"},
// },
// }
// }
| {
encs := configured.([]interface{})
if len(encs) == 0 || encs[0] == nil {
return nil
}
enc := encs[0].(map[string]interface{})
keyname := enc["default_kms_key_name"]
if keyname == nil || keyname.(string) == "" {
return nil
}
bucketenc := &storage.BucketEncryption{
DefaultKmsKeyName: keyname.(string),
}
return bucketenc
} |
sel_season_area.py | # Standard packages
from netCDF4 import Dataset, num2date
from datetime import datetime
import numpy as np
import pandas as pd
#____________Selecting a season (DJF,DJFM,NDJFM,JJA)
def sel_season(var,dates,season,timestep):
#----------------------------------------------------------------------------------------
#print('____________________________________________________________________________________________________________________')
#print('Selecting only {0} data'.format(season))
#----------------------------------------------------------------------------------------
dates_pdh = pd.to_datetime(dates)
print(dates_pdh)
mesi_short = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
if season=='DJF': #ONLY DEC-JAN-FEB
m=[12,1,2]
mask=(dates_pdh.month==12) | (dates_pdh.month==1) | (dates_pdh.month==2)
elif season=='DJFM': #ONLY DEC-JAN-FEB-MAR
m=[12,1,2,3]
mask=(dates_pdh.month==12) | (dates_pdh.month==1) | (dates_pdh.month==2) | (dates_pdh.month==3)
elif season=='NDJFM': #ONLY NOV-DEC-JAN-FEB-MAR
m=[11,12,1,2,3]
mask=(dates_pdh.month==11) | (dates_pdh.month==12) | (dates_pdh.month==1) | (dates_pdh.month==2) | (dates_pdh.month==3)
elif season=='JJA': #ONLY JUN-JUL-AUG
m=[6,7,8]
mask=(dates_pdh.month==6) | (dates_pdh.month==7) | (dates_pdh.month==8)
elif season=='MAM': #ONLY MAR-APR-MAY
m=[3,4,5]
mask=(dates_pdh.month==6) | (dates_pdh.month==7) | (dates_pdh.month==8)
elif season=='SON': #ONLY SEP-OCT-NOV
m=[9,10,11]
mask=(dates_pdh.month==6) | (dates_pdh.month==7) | (dates_pdh.month==8)
elif season in mesi_short:
print(mesi_short.index(season)+1)
mask = (dates_pdh.month == mesi_short.index(season)+1)
else:
print('season is not one of the following: DJF, DJFM, NDJFM, JJA, MAM, SON')
#print(np.sum(mask))
var_season = var[mask,:,:]
dates_season=dates[mask]
if var_season.ndim == 2:
var_season = var_season[np.newaxis, :]
cut = False
if timestep == 'month':
# count number of months
n_months = var_season.shape[0]
if n_months%len(season) != 0:
cut = True
elif timestep == 'day':
cut = True
if season in mesi_short:
cut = False
if cut:
if (12 in m) or (1 in m):
#REMOVING THE FIRST MONTHS (for the first year) because there is no previuos december
|
return var_season,dates_season
#____________Selecting only [latS-latN, lonW-lonE] box region
def sel_area(lat,lon,var,area):
'''
GOAL
Selecting the area of interest
USAGE
var_area, lat_area, lon_area =sel_area(lat,lon,var,area)
area can be 'EAT', 'PNA', 'NH'
'''
if area=='EAT':
printarea='Euro-Atlantic'
latN = 87.5
latS = 30.0
lonW =-80.0 #280
lonE = 40.0 #40
# lat and lon are extracted from the netcdf file, assumed to be 1D
#If 0<lon<360, convert to -180<lon<180
if lon.min() >= 0:
lon_new=lon-180
var_roll=np.roll(var,int(len(lon)/2),axis=-1)
else:
var_roll=var
lon_new=lon
elif area=='PNA':
printarea='Pacific North American'
latN = 87.5
latS = 30.0
lonW = 140.0
lonE = 280.0
# lat and lon are extracted from the netcdf file, assumed to be 1D
#If -180<lon<180, convert to 0<lon<360
if lon.min() < 0:
lon_new=lon+180
var_roll=np.roll(var,int(len(lon)/2),axis=-1)
else:
var_roll=var
lon_new=lon
elif area=='NH':
printarea='Northern Hemisphere'
latN = 90.0
latS = 0.0
lonW = lon.min()
lonE = lon.max()
var_roll=var
lon_new=lon
elif area=='Eu':
printarea='Europe'
latN = 72.0
latS = 27.0
lonW = -22.0
lonE = 45.0
# lat and lon are extracted from the netcdf file, assumed to be 1D
#If 0<lon<360, convert to -180<lon<180
if lon.min() >= 0:
lon_new=lon-180
var_roll=np.roll(var,int(len(lon)/2),axis=-1)
else:
var_roll=var
lon_new=lon
elif area=='Med':
printarea='Mediterranean'
latN = 50.0
latS = 25.0
lonW = -10.0
lonE = 40.0
# lat and lon are extracted from the netcdf file, assumed to be 1D
#If 0<lon<360, convert to -180<lon<180
if lon.min() >= 0:
lon_new=lon-180
print(var.shape)
var_roll=np.roll(var,int(len(lon)/2),axis=-1)
else:
var_roll=var
lon_new=lon
#----------------------------------------------------------------------------------------
#print('____________________________________________________________________________________________________________________')
#print('Selecting the area of interest: {0}'.format(printarea))
#----------------------------------------------------------------------------------------
#-------------------------Selecting only an area
latidx = (lat >= latS) & (lat <= latN)
lonidx = (lon_new >= lonW) & (lon_new <= lonE)
print(var_roll.shape, len(latidx), len(lonidx))
if var.ndim == 3:
var_area = var_roll[:, latidx][..., lonidx]
elif var.ndim == 2:
var_area = var_roll[latidx, ...][..., lonidx]
else:
raise ValueError('Variable has {} dimensions, should have 2 or 3.'.format(var.ndim))
#print('Grid dimension of the selected area ---> {0}'.format(var_area[0].shape))
return var_area,lat[latidx],lon_new[lonidx]
| print(np.where(dates_season==datetime(dates_pdh.year[0], m[0], dates_pdh.day[0], dates_pdh.hour[0], dates_pdh.minute[0]) ))
start=int(np.where(dates_season==datetime(dates_pdh.year[0], m[0], dates_pdh.day[0], dates_pdh.hour[0], dates_pdh.minute[0]) )[0])
#REMOVING THE LAST MONTHS (for the last year) because there is no following january
last_sea = dates_season==datetime(dates_pdh.year[-1], m[0], dates_pdh.day[0], dates_pdh.hour[0], dates_pdh.minute[0])
if np.sum(last_sea) > 0:
end = np.argmax(last_sea)
else:
end = -1
var_season=var_season[start:end,:,:]
dates_season=dates_season[start:end] |
exc.py | from .._py2 import *
class CacheError(Exception):
'''Base class for exceptions related to the cache'''
pass
class PageNotCachedError(CacheError):
'''Exception raised when a non-existent page is requested'''
def __init__(self):
super().__init__('This page has not been cached yet.')
class PageClearedError(CacheError):
'''Exception raised when a deleted page is requested'''
def __init__(self):
super().__init__('This page has been cleared.')
class CacheMemoryError(CacheError):
'''Exception raised when max data already stored in cache'''
def __init__(self):
super().__init__(
'Cannot save any more pages, call /cache/clear or' + | '/cache/clear/{page_name}')
class CacheOverwriteError(CacheError):
'''Exception raised when attempted overwriting of page'''
def __init__(self):
super().__init__(
'Cannot overwrite page, choose a different name') | |
expression.rs | #[cfg(feature = "validate")]
use super::{compose::validate_compose, FunctionInfo, ShaderStages, TypeFlags};
#[cfg(feature = "validate")]
use crate::arena::UniqueArena;
use crate::{
arena::{BadHandle, Handle},
proc::{IndexableLengthError, ResolveError},
};
#[derive(Clone, Debug, thiserror::Error)]
#[cfg_attr(test, derive(PartialEq))]
pub enum ExpressionError {
#[error("Doesn't exist")]
DoesntExist,
#[error("Used by a statement before it was introduced into the scope by any of the dominating blocks")]
NotInScope,
#[error("Depends on {0:?}, which has not been processed yet")]
ForwardDependency(Handle<crate::Expression>),
#[error(transparent)]
BadDependency(#[from] BadHandle),
#[error("Base type {0:?} is not compatible with this expression")]
InvalidBaseType(Handle<crate::Expression>),
#[error("Accessing with index {0:?} can't be done")]
InvalidIndexType(Handle<crate::Expression>),
#[error("Accessing index {1:?} is out of {0:?} bounds")]
IndexOutOfBounds(Handle<crate::Expression>, crate::ScalarValue),
#[error("The expression {0:?} may only be indexed by a constant")]
IndexMustBeConstant(Handle<crate::Expression>),
#[error("Function argument {0:?} doesn't exist")]
FunctionArgumentDoesntExist(u32),
#[error("Loading of {0:?} can't be done")]
InvalidPointerType(Handle<crate::Expression>),
#[error("Array length of {0:?} can't be done")]
InvalidArrayType(Handle<crate::Expression>),
#[error("Splatting {0:?} can't be done")]
InvalidSplatType(Handle<crate::Expression>),
#[error("Swizzling {0:?} can't be done")]
InvalidVectorType(Handle<crate::Expression>),
#[error("Swizzle component {0:?} is outside of vector size {1:?}")]
InvalidSwizzleComponent(crate::SwizzleComponent, crate::VectorSize),
#[error(transparent)]
Compose(#[from] super::ComposeError),
#[error(transparent)]
IndexableLength(#[from] IndexableLengthError),
#[error("Operation {0:?} can't work with {1:?}")]
InvalidUnaryOperandType(crate::UnaryOperator, Handle<crate::Expression>),
#[error("Operation {0:?} can't work with {1:?} and {2:?}")]
InvalidBinaryOperandTypes(
crate::BinaryOperator,
Handle<crate::Expression>,
Handle<crate::Expression>,
),
#[error("Selecting is not possible")]
InvalidSelectTypes,
#[error("Relational argument {0:?} is not a boolean vector")]
InvalidBooleanVector(Handle<crate::Expression>),
#[error("Relational argument {0:?} is not a float")]
InvalidFloatArgument(Handle<crate::Expression>),
#[error("Type resolution failed")]
Type(#[from] ResolveError),
#[error("Not a global variable")]
ExpectedGlobalVariable,
#[error("Not a global variable or a function argument")]
ExpectedGlobalOrArgument,
#[error("Calling an undeclared function {0:?}")]
CallToUndeclaredFunction(Handle<crate::Function>),
#[error("Needs to be an image instead of {0:?}")]
ExpectedImageType(Handle<crate::Type>),
#[error("Needs to be an image instead of {0:?}")]
ExpectedSamplerType(Handle<crate::Type>),
#[error("Unable to operate on image class {0:?}")]
InvalidImageClass(crate::ImageClass),
#[error("Derivatives can only be taken from scalar and vector floats")]
InvalidDerivative,
#[error("Image array index parameter is misplaced")]
InvalidImageArrayIndex,
#[error("Image other index parameter is misplaced")]
InvalidImageOtherIndex,
#[error("Image array index type of {0:?} is not an integer scalar")]
InvalidImageArrayIndexType(Handle<crate::Expression>),
#[error("Image other index type of {0:?} is not an integer scalar")]
InvalidImageOtherIndexType(Handle<crate::Expression>),
#[error("Image coordinate type of {1:?} does not match dimension {0:?}")]
InvalidImageCoordinateType(crate::ImageDimension, Handle<crate::Expression>),
#[error("Comparison sampling mismatch: image has class {image:?}, but the sampler is comparison={sampler}, and the reference was provided={has_ref}")]
ComparisonSamplingMismatch {
image: crate::ImageClass,
sampler: bool,
has_ref: bool,
},
#[error("Sample offset constant {1:?} doesn't match the image dimension {0:?}")]
InvalidSampleOffset(crate::ImageDimension, Handle<crate::Constant>),
#[error("Depth reference {0:?} is not a scalar float")]
InvalidDepthReference(Handle<crate::Expression>),
#[error("Depth sample level can only be Auto or Zero")]
InvalidDepthSampleLevel,
#[error("Gather level can only be Zero")]
InvalidGatherLevel,
#[error("Gather component {0:?} doesn't exist in the image")]
InvalidGatherComponent(crate::SwizzleComponent),
#[error("Gather can't be done for image dimension {0:?}")]
InvalidGatherDimension(crate::ImageDimension),
#[error("Sample level (exact) type {0:?} is not a scalar float")]
InvalidSampleLevelExactType(Handle<crate::Expression>),
#[error("Sample level (bias) type {0:?} is not a scalar float")]
InvalidSampleLevelBiasType(Handle<crate::Expression>),
#[error("Sample level (gradient) of {1:?} doesn't match the image dimension {0:?}")]
InvalidSampleLevelGradientType(crate::ImageDimension, Handle<crate::Expression>),
#[error("Unable to cast")]
InvalidCastArgument,
#[error("Invalid argument count for {0:?}")]
WrongArgumentCount(crate::MathFunction),
#[error("Argument [{1}] to {0:?} as expression {2:?} has an invalid type.")]
InvalidArgumentType(crate::MathFunction, u32, Handle<crate::Expression>),
#[error("Atomic result type can't be {0:?} of {1} bytes")]
InvalidAtomicResultType(crate::ScalarKind, crate::Bytes),
}
#[cfg(feature = "validate")]
struct ExpressionTypeResolver<'a> {
root: Handle<crate::Expression>,
types: &'a UniqueArena<crate::Type>,
info: &'a FunctionInfo,
}
#[cfg(feature = "validate")]
impl<'a> ExpressionTypeResolver<'a> {
fn resolve(
&self,
handle: Handle<crate::Expression>,
) -> Result<&'a crate::TypeInner, ExpressionError> {
if handle < self.root {
Ok(self.info[handle].ty.inner_with(self.types))
} else {
Err(ExpressionError::ForwardDependency(handle))
}
}
}
#[cfg(feature = "validate")]
impl super::Validator {
pub(super) fn validate_expression(
&self,
root: Handle<crate::Expression>,
expression: &crate::Expression,
function: &crate::Function,
module: &crate::Module,
info: &FunctionInfo,
other_infos: &[FunctionInfo],
) -> Result<ShaderStages, ExpressionError> {
use crate::{Expression as E, ScalarKind as Sk, TypeInner as Ti};
let resolver = ExpressionTypeResolver {
root,
types: &module.types,
info,
};
let stages = match *expression {
E::Access { base, index } => {
let base_type = resolver.resolve(base)?;
// See the documentation for `Expression::Access`.
let dynamic_indexing_restricted = match *base_type {
Ti::Vector { .. } => false,
Ti::Matrix { .. } | Ti::Array { .. } => true,
Ti::Pointer { .. } | Ti::ValuePointer { size: Some(_), .. } => false,
ref other => {
log::error!("Indexing of {:?}", other);
return Err(ExpressionError::InvalidBaseType(base));
}
};
match *resolver.resolve(index)? {
//TODO: only allow one of these
Ti::Scalar {
kind: Sk::Sint,
width: _,
}
| Ti::Scalar {
kind: Sk::Uint,
width: _,
} => {}
ref other => {
log::error!("Indexing by {:?}", other);
return Err(ExpressionError::InvalidIndexType(index));
}
}
if dynamic_indexing_restricted
&& function.expressions[index].is_dynamic_index(module)
{
return Err(ExpressionError::IndexMustBeConstant(base));
}
// If we know both the length and the index, we can do the
// bounds check now.
if let crate::proc::IndexableLength::Known(known_length) =
base_type.indexable_length(module)?
{
if let E::Constant(k) = function.expressions[index] {
if let crate::Constant {
// We must treat specializable constants as unknown.
specialization: None,
// Non-scalar indices should have been caught above.
inner: crate::ConstantInner::Scalar { value, .. },
..
} = module.constants[k]
{
match value {
crate::ScalarValue::Uint(u) if u >= known_length as u64 => {
return Err(ExpressionError::IndexOutOfBounds(base, value));
}
crate::ScalarValue::Sint(s)
if s < 0 || s >= known_length as i64 =>
{
return Err(ExpressionError::IndexOutOfBounds(base, value));
}
_ => (),
}
}
}
}
ShaderStages::all()
}
E::AccessIndex { base, index } => {
fn resolve_index_limit(
module: &crate::Module,
top: Handle<crate::Expression>,
ty: &crate::TypeInner,
top_level: bool,
) -> Result<u32, ExpressionError> {
let limit = match *ty {
Ti::Vector { size, .. }
| Ti::ValuePointer {
size: Some(size), ..
} => size as u32,
Ti::Matrix { columns, .. } => columns as u32,
Ti::Array {
size: crate::ArraySize::Constant(handle),
..
} => module.constants[handle].to_array_length().unwrap(),
Ti::Array { .. } => !0, // can't statically know, but need run-time checks
Ti::Pointer { base, .. } if top_level => {
resolve_index_limit(module, top, &module.types[base].inner, false)?
}
Ti::Struct { ref members, .. } => members.len() as u32,
ref other => {
log::error!("Indexing of {:?}", other);
return Err(ExpressionError::InvalidBaseType(top));
}
};
Ok(limit)
}
let limit = resolve_index_limit(module, base, resolver.resolve(base)?, true)?;
if index >= limit {
return Err(ExpressionError::IndexOutOfBounds(
base,
crate::ScalarValue::Uint(limit as _),
));
}
ShaderStages::all()
}
E::Constant(handle) => {
let _ = module.constants.try_get(handle)?;
ShaderStages::all()
}
E::Splat { size: _, value } => match *resolver.resolve(value)? {
Ti::Scalar { .. } => ShaderStages::all(),
ref other => {
log::error!("Splat scalar type {:?}", other);
return Err(ExpressionError::InvalidSplatType(value));
}
},
E::Swizzle {
size,
vector,
pattern,
} => {
let vec_size = match *resolver.resolve(vector)? {
Ti::Vector { size: vec_size, .. } => vec_size,
ref other => {
log::error!("Swizzle vector type {:?}", other);
return Err(ExpressionError::InvalidVectorType(vector));
}
};
for &sc in pattern[..size as usize].iter() {
if sc as u8 >= vec_size as u8 {
return Err(ExpressionError::InvalidSwizzleComponent(sc, vec_size));
}
}
ShaderStages::all()
}
E::Compose { ref components, ty } => {
for &handle in components {
if handle >= root {
return Err(ExpressionError::ForwardDependency(handle));
}
}
validate_compose(
ty,
&module.constants,
&module.types,
components.iter().map(|&handle| info[handle].ty.clone()),
)?;
ShaderStages::all()
}
E::FunctionArgument(index) => {
if index >= function.arguments.len() as u32 {
return Err(ExpressionError::FunctionArgumentDoesntExist(index));
}
ShaderStages::all()
}
E::GlobalVariable(handle) => {
let _ = module.global_variables.try_get(handle)?;
ShaderStages::all()
}
E::LocalVariable(handle) => {
let _ = function.local_variables.try_get(handle)?;
ShaderStages::all()
}
E::Load { pointer } => {
match *resolver.resolve(pointer)? {
Ti::Pointer { base, .. }
if self.types[base.index()]
.flags
.contains(TypeFlags::SIZED | TypeFlags::DATA) => {}
Ti::ValuePointer { .. } => {}
ref other => {
log::error!("Loading {:?}", other);
return Err(ExpressionError::InvalidPointerType(pointer));
}
}
ShaderStages::all()
}
E::ImageSample {
image,
sampler,
gather,
coordinate,
array_index,
offset,
level,
depth_ref,
} => {
// check the validity of expressions
let image_ty = match function.expressions[image] {
crate::Expression::GlobalVariable(var_handle) => {
module.global_variables[var_handle].ty
}
crate::Expression::FunctionArgument(i) => function.arguments[i as usize].ty,
_ => return Err(ExpressionError::ExpectedGlobalVariable),
};
let sampler_ty = match function.expressions[sampler] {
crate::Expression::GlobalVariable(var_handle) => {
module.global_variables[var_handle].ty
}
crate::Expression::FunctionArgument(i) => function.arguments[i as usize].ty,
_ => return Err(ExpressionError::ExpectedGlobalVariable),
};
let comparison = match module.types[sampler_ty].inner {
Ti::Sampler { comparison } => comparison,
_ => return Err(ExpressionError::ExpectedSamplerType(sampler_ty)),
};
let (class, dim) = match module.types[image_ty].inner {
Ti::Image {
class,
arrayed,
dim,
} => {
// check the array property
if arrayed != array_index.is_some() {
return Err(ExpressionError::InvalidImageArrayIndex);
}
if let Some(expr) = array_index {
match *resolver.resolve(expr)? {
Ti::Scalar {
kind: Sk::Sint,
width: _,
} => {}
_ => return Err(ExpressionError::InvalidImageArrayIndexType(expr)),
}
}
(class, dim)
}
_ => return Err(ExpressionError::ExpectedImageType(image_ty)),
};
// check sampling and comparison properties
let image_depth = match class {
crate::ImageClass::Sampled {
kind: crate::ScalarKind::Float,
multi: false,
} => false,
crate::ImageClass::Depth { multi: false } => true,
_ => return Err(ExpressionError::InvalidImageClass(class)),
};
if comparison != depth_ref.is_some() || (comparison && !image_depth) {
return Err(ExpressionError::ComparisonSamplingMismatch {
image: class,
sampler: comparison,
has_ref: depth_ref.is_some(),
});
}
// check texture coordinates type
let num_components = match dim {
crate::ImageDimension::D1 => 1,
crate::ImageDimension::D2 => 2,
crate::ImageDimension::D3 | crate::ImageDimension::Cube => 3,
};
match *resolver.resolve(coordinate)? {
Ti::Scalar {
kind: Sk::Float, ..
} if num_components == 1 => {}
Ti::Vector {
size,
kind: Sk::Float,
..
} if size as u32 == num_components => {}
_ => return Err(ExpressionError::InvalidImageCoordinateType(dim, coordinate)),
}
// check constant offset
if let Some(const_handle) = offset {
let good = match module.constants[const_handle].inner {
crate::ConstantInner::Scalar {
width: _,
value: crate::ScalarValue::Sint(_),
} => num_components == 1,
crate::ConstantInner::Scalar { .. } => false,
crate::ConstantInner::Composite { ty, .. } => {
match module.types[ty].inner {
Ti::Vector {
size,
kind: Sk::Sint,
..
} => size as u32 == num_components,
_ => false,
}
}
};
if !good {
return Err(ExpressionError::InvalidSampleOffset(dim, const_handle));
}
}
// check depth reference type
if let Some(expr) = depth_ref {
match *resolver.resolve(expr)? {
Ti::Scalar {
kind: Sk::Float, ..
} => {}
_ => return Err(ExpressionError::InvalidDepthReference(expr)),
}
match level {
crate::SampleLevel::Auto | crate::SampleLevel::Zero => {}
_ => return Err(ExpressionError::InvalidDepthSampleLevel),
}
}
if let Some(component) = gather {
match dim {
crate::ImageDimension::D2 | crate::ImageDimension::Cube => {}
crate::ImageDimension::D1 | crate::ImageDimension::D3 => {
return Err(ExpressionError::InvalidGatherDimension(dim))
}
};
let max_component = match class {
crate::ImageClass::Depth { .. } => crate::SwizzleComponent::X,
_ => crate::SwizzleComponent::W,
};
if component > max_component {
return Err(ExpressionError::InvalidGatherComponent(component));
}
match level {
crate::SampleLevel::Zero => {}
_ => return Err(ExpressionError::InvalidGatherLevel),
}
}
// check level properties
match level {
crate::SampleLevel::Auto => ShaderStages::FRAGMENT,
crate::SampleLevel::Zero => ShaderStages::all(),
crate::SampleLevel::Exact(expr) => {
match *resolver.resolve(expr)? {
Ti::Scalar {
kind: Sk::Float, ..
} => {}
_ => return Err(ExpressionError::InvalidSampleLevelExactType(expr)),
}
ShaderStages::all()
}
crate::SampleLevel::Bias(expr) => {
match *resolver.resolve(expr)? {
Ti::Scalar {
kind: Sk::Float, ..
} => {}
_ => return Err(ExpressionError::InvalidSampleLevelBiasType(expr)),
}
ShaderStages::all()
}
crate::SampleLevel::Gradient { x, y } => {
match *resolver.resolve(x)? {
Ti::Scalar {
kind: Sk::Float, ..
} if num_components == 1 => {}
Ti::Vector {
size,
kind: Sk::Float,
..
} if size as u32 == num_components => {}
_ => {
return Err(ExpressionError::InvalidSampleLevelGradientType(dim, x))
}
}
match *resolver.resolve(y)? {
Ti::Scalar {
kind: Sk::Float, ..
} if num_components == 1 => {}
Ti::Vector {
size,
kind: Sk::Float,
..
} if size as u32 == num_components => {}
_ => {
return Err(ExpressionError::InvalidSampleLevelGradientType(dim, y))
}
}
ShaderStages::all()
}
}
}
E::ImageLoad {
image,
coordinate,
array_index,
index,
} => {
let ty = match function.expressions[image] {
crate::Expression::GlobalVariable(var_handle) => {
module.global_variables[var_handle].ty
}
crate::Expression::FunctionArgument(i) => function.arguments[i as usize].ty,
_ => return Err(ExpressionError::ExpectedGlobalVariable),
};
match module.types[ty].inner {
Ti::Image {
class,
arrayed,
dim,
} => {
match resolver.resolve(coordinate)?.image_storage_coordinates() {
Some(coord_dim) if coord_dim == dim => {}
_ => {
return Err(ExpressionError::InvalidImageCoordinateType(
dim, coordinate,
))
}
};
let needs_index = match class {
crate::ImageClass::Storage { .. } => false,
_ => true,
};
if arrayed != array_index.is_some() {
return Err(ExpressionError::InvalidImageArrayIndex);
}
if needs_index != index.is_some() {
return Err(ExpressionError::InvalidImageOtherIndex);
}
if let Some(expr) = array_index {
match *resolver.resolve(expr)? {
Ti::Scalar {
kind: Sk::Sint,
width: _,
} => {}
_ => return Err(ExpressionError::InvalidImageArrayIndexType(expr)),
}
}
if let Some(expr) = index {
match *resolver.resolve(expr)? {
Ti::Scalar {
kind: Sk::Sint,
width: _,
} => {}
_ => return Err(ExpressionError::InvalidImageOtherIndexType(expr)),
}
}
}
_ => return Err(ExpressionError::ExpectedImageType(ty)),
}
ShaderStages::all()
}
E::ImageQuery { image, query } => {
let ty = match function.expressions[image] {
crate::Expression::GlobalVariable(var_handle) => {
module.global_variables[var_handle].ty
}
crate::Expression::FunctionArgument(i) => function.arguments[i as usize].ty,
_ => return Err(ExpressionError::ExpectedGlobalVariable),
};
match module.types[ty].inner {
Ti::Image { class, arrayed, .. } => {
let can_level = match class {
crate::ImageClass::Sampled { multi, .. } => !multi,
crate::ImageClass::Depth { multi } => !multi,
crate::ImageClass::Storage { .. } => false,
};
let good = match query {
crate::ImageQuery::NumLayers => arrayed,
crate::ImageQuery::Size { level: None } => true,
crate::ImageQuery::Size { level: Some(_) }
| crate::ImageQuery::NumLevels => can_level,
//TODO: forbid on storage images
crate::ImageQuery::NumSamples => !can_level,
};
if !good {
return Err(ExpressionError::InvalidImageClass(class));
}
}
_ => return Err(ExpressionError::ExpectedImageType(ty)),
}
ShaderStages::all()
}
E::Unary { op, expr } => {
use crate::UnaryOperator as Uo;
let inner = resolver.resolve(expr)?;
match (op, inner.scalar_kind()) {
(_, Some(Sk::Sint))
| (_, Some(Sk::Bool))
//TODO: restrict Negate for bools?
| (Uo::Negate, Some(Sk::Float))
| (Uo::Not, Some(Sk::Uint)) => {}
other => {
log::error!("Op {:?} kind {:?}", op, other);
return Err(ExpressionError::InvalidUnaryOperandType(op, expr));
}
}
ShaderStages::all()
}
E::Binary { op, left, right } => {
use crate::BinaryOperator as Bo;
let left_inner = resolver.resolve(left)?;
let right_inner = resolver.resolve(right)?;
let good = match op {
Bo::Add | Bo::Subtract => match *left_inner {
Ti::Scalar { kind, .. } | Ti::Vector { kind, .. } => match kind {
Sk::Uint | Sk::Sint | Sk::Float => left_inner == right_inner,
Sk::Bool => false,
},
Ti::Matrix { .. } => left_inner == right_inner,
_ => false,
},
Bo::Divide | Bo::Modulo => match *left_inner {
Ti::Scalar { kind, .. } | Ti::Vector { kind, .. } => match kind {
Sk::Uint | Sk::Sint | Sk::Float => left_inner == right_inner,
Sk::Bool => false,
},
_ => false,
},
Bo::Multiply => {
let kind_match = match left_inner.scalar_kind() {
Some(Sk::Uint) | Some(Sk::Sint) | Some(Sk::Float) => true,
Some(Sk::Bool) | None => false,
};
//TODO: should we be more restrictive here? I.e. expect scalar only to the left.
let types_match = match (left_inner, right_inner) {
(&Ti::Scalar { kind: kind1, .. }, &Ti::Scalar { kind: kind2, .. })
| (&Ti::Vector { kind: kind1, .. }, &Ti::Scalar { kind: kind2, .. })
| (&Ti::Scalar { kind: kind1, .. }, &Ti::Vector { kind: kind2, .. }) => {
kind1 == kind2
}
(
&Ti::Scalar {
kind: Sk::Float, ..
},
&Ti::Matrix { .. },
)
| (
&Ti::Matrix { .. },
&Ti::Scalar {
kind: Sk::Float, ..
},
) => true,
(
&Ti::Vector {
kind: kind1,
size: size1,
..
},
&Ti::Vector {
kind: kind2,
size: size2,
..
},
) => kind1 == kind2 && size1 == size2,
(
&Ti::Matrix { columns, .. },
&Ti::Vector {
kind: Sk::Float,
size,
..
},
) => columns == size,
(
&Ti::Vector {
kind: Sk::Float,
size,
..
},
&Ti::Matrix { rows, .. },
) => size == rows,
(&Ti::Matrix { columns, .. }, &Ti::Matrix { rows, .. }) => {
columns == rows
}
_ => false,
};
let left_width = match *left_inner {
Ti::Scalar { width, .. }
| Ti::Vector { width, .. }
| Ti::Matrix { width, .. } => width,
_ => 0,
};
let right_width = match *right_inner {
Ti::Scalar { width, .. }
| Ti::Vector { width, .. }
| Ti::Matrix { width, .. } => width,
_ => 0,
};
kind_match && types_match && left_width == right_width
}
Bo::Equal | Bo::NotEqual => left_inner.is_sized() && left_inner == right_inner,
Bo::Less | Bo::LessEqual | Bo::Greater | Bo::GreaterEqual => {
match *left_inner {
Ti::Scalar { kind, .. } | Ti::Vector { kind, .. } => match kind {
Sk::Uint | Sk::Sint | Sk::Float => left_inner == right_inner,
Sk::Bool => false,
},
ref other => {
log::error!("Op {:?} left type {:?}", op, other);
false
}
}
}
Bo::LogicalAnd | Bo::LogicalOr => match *left_inner {
Ti::Scalar { kind: Sk::Bool, .. } | Ti::Vector { kind: Sk::Bool, .. } => {
left_inner == right_inner
}
ref other => {
log::error!("Op {:?} left type {:?}", op, other);
false
}
},
Bo::And | Bo::InclusiveOr => match *left_inner {
Ti::Scalar { kind, .. } | Ti::Vector { kind, .. } => match kind {
Sk::Bool | Sk::Sint | Sk::Uint => left_inner == right_inner,
Sk::Float => false,
},
ref other => {
log::error!("Op {:?} left type {:?}", op, other);
false
}
},
Bo::ExclusiveOr => match *left_inner {
Ti::Scalar { kind, .. } | Ti::Vector { kind, .. } => match kind {
Sk::Sint | Sk::Uint => left_inner == right_inner,
Sk::Bool | Sk::Float => false,
},
ref other => {
log::error!("Op {:?} left type {:?}", op, other);
false
}
},
Bo::ShiftLeft | Bo::ShiftRight => {
let (base_size, base_kind) = match *left_inner {
Ti::Scalar { kind, .. } => (Ok(None), kind),
Ti::Vector { size, kind, .. } => (Ok(Some(size)), kind),
ref other => {
log::error!("Op {:?} base type {:?}", op, other);
(Err(()), Sk::Bool)
}
};
let shift_size = match *right_inner {
Ti::Scalar { kind: Sk::Uint, .. } => Ok(None),
Ti::Vector {
size,
kind: Sk::Uint,
..
} => Ok(Some(size)),
ref other => {
log::error!("Op {:?} shift type {:?}", op, other);
Err(())
}
};
match base_kind {
Sk::Sint | Sk::Uint => base_size.is_ok() && base_size == shift_size,
Sk::Float | Sk::Bool => false,
}
}
};
if !good {
log::error!(
"Left: {:?} of type {:?}",
function.expressions[left],
left_inner
);
log::error!(
"Right: {:?} of type {:?}",
function.expressions[right],
right_inner
);
return Err(ExpressionError::InvalidBinaryOperandTypes(op, left, right));
}
ShaderStages::all()
}
E::Select {
condition,
accept,
reject,
} => {
let accept_inner = resolver.resolve(accept)?;
let reject_inner = resolver.resolve(reject)?;
let condition_good = match *resolver.resolve(condition)? {
Ti::Scalar {
kind: Sk::Bool,
width: _,
} => {
// When `condition` is a single boolean, `accept` and
// `reject` can be vectors or scalars.
match *accept_inner {
Ti::Scalar { .. } | Ti::Vector { .. } => true,
_ => false,
}
}
Ti::Vector {
size,
kind: Sk::Bool,
width: _,
} => match *accept_inner {
Ti::Vector {
size: other_size, ..
} => size == other_size,
_ => false,
},
_ => false,
};
if !condition_good || accept_inner != reject_inner {
return Err(ExpressionError::InvalidSelectTypes);
}
ShaderStages::all()
}
E::Derivative { axis: _, expr } => {
match *resolver.resolve(expr)? {
Ti::Scalar {
kind: Sk::Float, ..
}
| Ti::Vector {
kind: Sk::Float, ..
} => {}
_ => return Err(ExpressionError::InvalidDerivative),
}
ShaderStages::FRAGMENT
}
E::Relational { fun, argument } => {
use crate::RelationalFunction as Rf;
let argument_inner = resolver.resolve(argument)?;
match fun {
Rf::All | Rf::Any => match *argument_inner {
Ti::Vector { kind: Sk::Bool, .. } => {}
ref other => {
log::error!("All/Any of type {:?}", other);
return Err(ExpressionError::InvalidBooleanVector(argument));
}
},
Rf::IsNan | Rf::IsInf | Rf::IsFinite | Rf::IsNormal => match *argument_inner {
Ti::Scalar {
kind: Sk::Float, ..
}
| Ti::Vector {
kind: Sk::Float, ..
} => {}
ref other => {
log::error!("Float test of type {:?}", other);
return Err(ExpressionError::InvalidFloatArgument(argument));
}
},
}
ShaderStages::all()
}
E::Math {
fun,
arg,
arg1,
arg2,
arg3,
} => {
use crate::MathFunction as Mf;
let arg_ty = resolver.resolve(arg)?;
let arg1_ty = arg1.map(|expr| resolver.resolve(expr)).transpose()?;
let arg2_ty = arg2.map(|expr| resolver.resolve(expr)).transpose()?;
let arg3_ty = arg3.map(|expr| resolver.resolve(expr)).transpose()?;
match fun {
Mf::Abs => {
if arg1_ty.is_some() | arg2_ty.is_some() | arg3_ty.is_some() {
return Err(ExpressionError::WrongArgumentCount(fun));
}
let good = match *arg_ty {
Ti::Scalar { kind, .. } | Ti::Vector { kind, .. } => kind != Sk::Bool,
_ => false,
};
if !good {
return Err(ExpressionError::InvalidArgumentType(fun, 0, arg));
}
}
Mf::Min | Mf::Max => {
let arg1_ty = match (arg1_ty, arg2_ty, arg3_ty) {
(Some(ty1), None, None) => ty1,
_ => return Err(ExpressionError::WrongArgumentCount(fun)),
};
let good = match *arg_ty {
Ti::Scalar { kind, .. } | Ti::Vector { kind, .. } => kind != Sk::Bool,
_ => false,
};
if !good {
return Err(ExpressionError::InvalidArgumentType(fun, 0, arg));
}
if arg1_ty != arg_ty {
return Err(ExpressionError::InvalidArgumentType(
fun,
1,
arg1.unwrap(),
));
}
}
Mf::Clamp => {
let (arg1_ty, arg2_ty) = match (arg1_ty, arg2_ty, arg3_ty) {
(Some(ty1), Some(ty2), None) => (ty1, ty2),
_ => return Err(ExpressionError::WrongArgumentCount(fun)),
};
let good = match *arg_ty {
Ti::Scalar { kind, .. } | Ti::Vector { kind, .. } => kind != Sk::Bool,
_ => false,
};
if !good {
return Err(ExpressionError::InvalidArgumentType(fun, 0, arg));
}
if arg1_ty != arg_ty {
return Err(ExpressionError::InvalidArgumentType(
fun,
1,
arg1.unwrap(),
));
}
if arg2_ty != arg_ty {
return Err(ExpressionError::InvalidArgumentType(
fun,
2,
arg2.unwrap(),
));
}
}
Mf::Cos
| Mf::Cosh
| Mf::Sin
| Mf::Sinh
| Mf::Tan
| Mf::Tanh
| Mf::Acos
| Mf::Asin
| Mf::Atan
| Mf::Asinh
| Mf::Acosh
| Mf::Atanh
| Mf::Radians
| Mf::Degrees
| Mf::Ceil
| Mf::Floor
| Mf::Round
| Mf::Fract
| Mf::Trunc
| Mf::Exp
| Mf::Exp2
| Mf::Log
| Mf::Log2
| Mf::Length
| Mf::Sign
| Mf::Sqrt
| Mf::InverseSqrt => {
if arg1_ty.is_some() | arg2_ty.is_some() | arg3_ty.is_some() {
return Err(ExpressionError::WrongArgumentCount(fun));
}
match *arg_ty {
Ti::Scalar {
kind: Sk::Float, ..
}
| Ti::Vector {
kind: Sk::Float, ..
} => {}
_ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)),
}
}
Mf::Atan2 | Mf::Pow | Mf::Distance | Mf::Step => {
let arg1_ty = match (arg1_ty, arg2_ty, arg3_ty) {
(Some(ty1), None, None) => ty1,
_ => return Err(ExpressionError::WrongArgumentCount(fun)),
};
match *arg_ty {
Ti::Scalar {
kind: Sk::Float, ..
}
| Ti::Vector {
kind: Sk::Float, ..
} => {}
_ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)),
}
if arg1_ty != arg_ty {
return Err(ExpressionError::InvalidArgumentType(
fun,
1,
arg1.unwrap(),
));
}
}
Mf::Modf | Mf::Frexp | Mf::Ldexp => {
let arg1_ty = match (arg1_ty, arg2_ty, arg3_ty) {
(Some(ty1), None, None) => ty1,
_ => return Err(ExpressionError::WrongArgumentCount(fun)),
};
let (size0, width0) = match *arg_ty {
Ti::Scalar {
kind: Sk::Float,
width,
} => (None, width),
Ti::Vector {
kind: Sk::Float,
size,
width,
} => (Some(size), width),
_ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)),
};
let good = match *arg1_ty {
Ti::Pointer { base, space: _ } => module.types[base].inner == *arg_ty,
Ti::ValuePointer {
size,
kind: Sk::Float,
width,
space: _,
} => size == size0 && width == width0,
_ => false,
};
if !good {
return Err(ExpressionError::InvalidArgumentType(
fun,
1,
arg1.unwrap(),
));
}
}
Mf::Dot | Mf::Outer | Mf::Cross | Mf::Reflect => {
let arg1_ty = match (arg1_ty, arg2_ty, arg3_ty) {
(Some(ty1), None, None) => ty1,
_ => return Err(ExpressionError::WrongArgumentCount(fun)),
};
match *arg_ty {
Ti::Vector {
kind: Sk::Float, ..
} => {}
_ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)),
}
if arg1_ty != arg_ty {
return Err(ExpressionError::InvalidArgumentType(
fun,
1,
arg1.unwrap(),
));
}
}
Mf::Refract => {
let (arg1_ty, arg2_ty) = match (arg1_ty, arg2_ty, arg3_ty) {
(Some(ty1), Some(ty2), None) => (ty1, ty2),
_ => return Err(ExpressionError::WrongArgumentCount(fun)),
};
match *arg_ty {
Ti::Vector {
kind: Sk::Float, ..
} => {}
_ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)),
}
if arg1_ty != arg_ty {
return Err(ExpressionError::InvalidArgumentType(
fun,
1,
arg1.unwrap(),
));
}
match (arg_ty, arg2_ty) {
(
&Ti::Vector {
width: vector_width,
..
},
&Ti::Scalar {
width: scalar_width,
kind: Sk::Float,
},
) if vector_width == scalar_width => {}
_ => {
return Err(ExpressionError::InvalidArgumentType(
fun,
2,
arg2.unwrap(),
))
}
}
}
Mf::Normalize => {
if arg1_ty.is_some() | arg2_ty.is_some() | arg3_ty.is_some() {
return Err(ExpressionError::WrongArgumentCount(fun));
}
match *arg_ty {
Ti::Vector {
kind: Sk::Float, ..
} => {}
_ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)),
}
}
Mf::FaceForward | Mf::Fma | Mf::SmoothStep => {
let (arg1_ty, arg2_ty) = match (arg1_ty, arg2_ty, arg3_ty) {
(Some(ty1), Some(ty2), None) => (ty1, ty2),
_ => return Err(ExpressionError::WrongArgumentCount(fun)),
};
match *arg_ty {
Ti::Scalar {
kind: Sk::Float, ..
}
| Ti::Vector {
kind: Sk::Float, ..
} => {}
_ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)),
}
if arg1_ty != arg_ty { | ));
}
if arg2_ty != arg_ty {
return Err(ExpressionError::InvalidArgumentType(
fun,
2,
arg2.unwrap(),
));
}
}
Mf::Mix => {
let (arg1_ty, arg2_ty) = match (arg1_ty, arg2_ty, arg3_ty) {
(Some(ty1), Some(ty2), None) => (ty1, ty2),
_ => return Err(ExpressionError::WrongArgumentCount(fun)),
};
let arg_width = match *arg_ty {
Ti::Scalar {
kind: Sk::Float,
width,
}
| Ti::Vector {
kind: Sk::Float,
width,
..
} => width,
_ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)),
};
if arg1_ty != arg_ty {
return Err(ExpressionError::InvalidArgumentType(
fun,
1,
arg1.unwrap(),
));
}
// the last argument can always be a scalar
match *arg2_ty {
Ti::Scalar {
kind: Sk::Float,
width,
} if width == arg_width => {}
_ if arg2_ty == arg_ty => {}
_ => {
return Err(ExpressionError::InvalidArgumentType(
fun,
2,
arg2.unwrap(),
));
}
}
}
Mf::Inverse | Mf::Determinant => {
if arg1_ty.is_some() | arg2_ty.is_some() | arg3_ty.is_some() {
return Err(ExpressionError::WrongArgumentCount(fun));
}
let good = match *arg_ty {
Ti::Matrix { columns, rows, .. } => columns == rows,
_ => false,
};
if !good {
return Err(ExpressionError::InvalidArgumentType(fun, 0, arg));
}
}
Mf::Transpose => {
if arg1_ty.is_some() | arg2_ty.is_some() | arg3_ty.is_some() {
return Err(ExpressionError::WrongArgumentCount(fun));
}
match *arg_ty {
Ti::Matrix { .. } => {}
_ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)),
}
}
Mf::CountOneBits | Mf::ReverseBits | Mf::FindLsb | Mf::FindMsb => {
if arg1_ty.is_some() | arg2_ty.is_some() | arg3_ty.is_some() {
return Err(ExpressionError::WrongArgumentCount(fun));
}
match *arg_ty {
Ti::Scalar { kind: Sk::Sint, .. }
| Ti::Scalar { kind: Sk::Uint, .. }
| Ti::Vector { kind: Sk::Sint, .. }
| Ti::Vector { kind: Sk::Uint, .. } => {}
_ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)),
}
}
Mf::InsertBits => {
let (arg1_ty, arg2_ty, arg3_ty) = match (arg1_ty, arg2_ty, arg3_ty) {
(Some(ty1), Some(ty2), Some(ty3)) => (ty1, ty2, ty3),
_ => return Err(ExpressionError::WrongArgumentCount(fun)),
};
match *arg_ty {
Ti::Scalar { kind: Sk::Sint, .. }
| Ti::Scalar { kind: Sk::Uint, .. }
| Ti::Vector { kind: Sk::Sint, .. }
| Ti::Vector { kind: Sk::Uint, .. } => {}
_ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)),
}
if arg1_ty != arg_ty {
return Err(ExpressionError::InvalidArgumentType(
fun,
1,
arg1.unwrap(),
));
}
match *arg2_ty {
Ti::Scalar { kind: Sk::Uint, .. } => {}
_ => {
return Err(ExpressionError::InvalidArgumentType(
fun,
2,
arg2.unwrap(),
))
}
}
match *arg3_ty {
Ti::Scalar { kind: Sk::Uint, .. } => {}
_ => {
return Err(ExpressionError::InvalidArgumentType(
fun,
2,
arg3.unwrap(),
))
}
}
}
Mf::ExtractBits => {
let (arg1_ty, arg2_ty) = match (arg1_ty, arg2_ty, arg3_ty) {
(Some(ty1), Some(ty2), None) => (ty1, ty2),
_ => return Err(ExpressionError::WrongArgumentCount(fun)),
};
match *arg_ty {
Ti::Scalar { kind: Sk::Sint, .. }
| Ti::Scalar { kind: Sk::Uint, .. }
| Ti::Vector { kind: Sk::Sint, .. }
| Ti::Vector { kind: Sk::Uint, .. } => {}
_ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)),
}
match *arg1_ty {
Ti::Scalar { kind: Sk::Uint, .. } => {}
_ => {
return Err(ExpressionError::InvalidArgumentType(
fun,
2,
arg1.unwrap(),
))
}
}
match *arg2_ty {
Ti::Scalar { kind: Sk::Uint, .. } => {}
_ => {
return Err(ExpressionError::InvalidArgumentType(
fun,
2,
arg2.unwrap(),
))
}
}
}
Mf::Pack2x16unorm | Mf::Pack2x16snorm | Mf::Pack2x16float => {
if arg1_ty.is_some() | arg2_ty.is_some() | arg3_ty.is_some() {
return Err(ExpressionError::WrongArgumentCount(fun));
}
match *arg_ty {
Ti::Vector {
size: crate::VectorSize::Bi,
kind: Sk::Float,
..
} => {}
_ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)),
}
}
Mf::Pack4x8snorm | Mf::Pack4x8unorm => {
if arg1_ty.is_some() | arg2_ty.is_some() | arg3_ty.is_some() {
return Err(ExpressionError::WrongArgumentCount(fun));
}
match *arg_ty {
Ti::Vector {
size: crate::VectorSize::Quad,
kind: Sk::Float,
..
} => {}
_ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)),
}
}
Mf::Unpack2x16float
| Mf::Unpack2x16snorm
| Mf::Unpack2x16unorm
| Mf::Unpack4x8snorm
| Mf::Unpack4x8unorm => {
if arg1_ty.is_some() | arg2_ty.is_some() | arg3_ty.is_some() {
return Err(ExpressionError::WrongArgumentCount(fun));
}
match *arg_ty {
Ti::Scalar { kind: Sk::Uint, .. } => {}
_ => return Err(ExpressionError::InvalidArgumentType(fun, 0, arg)),
}
}
}
ShaderStages::all()
}
E::As {
expr,
kind,
convert,
} => {
let base_width = match *resolver.resolve(expr)? {
crate::TypeInner::Scalar { width, .. }
| crate::TypeInner::Vector { width, .. }
| crate::TypeInner::Matrix { width, .. } => width,
_ => return Err(ExpressionError::InvalidCastArgument),
};
let width = convert.unwrap_or(base_width);
if !self.check_width(kind, width) {
return Err(ExpressionError::InvalidCastArgument);
}
ShaderStages::all()
}
E::CallResult(function) => other_infos[function.index()].available_stages,
E::AtomicResult {
kind,
width,
comparison: _,
} => {
let good = match kind {
crate::ScalarKind::Uint | crate::ScalarKind::Sint => {
self.check_width(kind, width)
}
_ => false,
};
if !good {
return Err(ExpressionError::InvalidAtomicResultType(kind, width));
}
ShaderStages::all()
}
E::ArrayLength(expr) => match *resolver.resolve(expr)? {
Ti::Pointer { base, .. } => {
let base_ty = resolver.types.get_handle(base)?;
if let Ti::Array {
size: crate::ArraySize::Dynamic,
..
} = base_ty.inner
{
ShaderStages::all()
} else {
return Err(ExpressionError::InvalidArrayType(expr));
}
}
ref other => {
log::error!("Array length of {:?}", other);
return Err(ExpressionError::InvalidArrayType(expr));
}
},
};
Ok(stages)
}
} | return Err(ExpressionError::InvalidArgumentType(
fun,
1,
arg1.unwrap(), |
nse_server.go | // Copyright (c) 2020-2022 Doc.ai and/or its affiliates.
//
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package memory
import (
"context"
"io"
"github.com/edwarnicke/serialize"
"github.com/golang/protobuf/ptypes/empty"
"github.com/google/uuid"
"github.com/networkservicemesh/api/pkg/api/registry"
"github.com/networkservicemesh/sdk/pkg/registry/core/next"
"github.com/networkservicemesh/sdk/pkg/tools/matchutils"
)
type memoryNSEServer struct {
networkServiceEndpoints NetworkServiceEndpointSyncMap
executor serialize.Executor
eventChannels map[string]chan *registry.NetworkServiceEndpointResponse
eventChannelSize int
}
// NewNetworkServiceEndpointRegistryServer creates new memory based NetworkServiceEndpointRegistryServer
func | (options ...Option) registry.NetworkServiceEndpointRegistryServer {
s := &memoryNSEServer{
eventChannelSize: defaultEventChannelSize,
eventChannels: make(map[string]chan *registry.NetworkServiceEndpointResponse),
}
for _, o := range options {
o.apply(s)
}
return s
}
func (s *memoryNSEServer) setEventChannelSize(l int) {
s.eventChannelSize = l
}
func (s *memoryNSEServer) Register(ctx context.Context, nse *registry.NetworkServiceEndpoint) (*registry.NetworkServiceEndpoint, error) {
r, err := next.NetworkServiceEndpointRegistryServer(ctx).Register(ctx, nse)
if err != nil {
return nil, err
}
s.networkServiceEndpoints.Store(r.Name, r.Clone())
s.sendEvent(®istry.NetworkServiceEndpointResponse{NetworkServiceEndpoint: r})
return r, err
}
func (s *memoryNSEServer) sendEvent(event *registry.NetworkServiceEndpointResponse) {
event = event.Clone()
s.executor.AsyncExec(func() {
for _, ch := range s.eventChannels {
ch <- event.Clone()
}
})
}
func (s *memoryNSEServer) Find(query *registry.NetworkServiceEndpointQuery, server registry.NetworkServiceEndpointRegistry_FindServer) error {
if !query.Watch {
for _, nse := range s.allMatches(query) {
nseResp := ®istry.NetworkServiceEndpointResponse{
NetworkServiceEndpoint: nse,
}
if err := server.Send(nseResp); err != nil {
return err
}
}
return next.NetworkServiceEndpointRegistryServer(server.Context()).Find(query, server)
}
if err := next.NetworkServiceEndpointRegistryServer(server.Context()).Find(query, server); err != nil {
return err
}
eventCh := make(chan *registry.NetworkServiceEndpointResponse, s.eventChannelSize)
id := uuid.New().String()
s.executor.AsyncExec(func() {
s.eventChannels[id] = eventCh
for _, entity := range s.allMatches(query) {
eventCh <- ®istry.NetworkServiceEndpointResponse{NetworkServiceEndpoint: entity}
}
})
defer s.closeEventChannel(id, eventCh)
var err error
for ; err == nil; err = s.receiveEvent(query, server, eventCh) {
}
if err != io.EOF {
return err
}
return nil
}
func (s *memoryNSEServer) allMatches(query *registry.NetworkServiceEndpointQuery) (matches []*registry.NetworkServiceEndpoint) {
s.networkServiceEndpoints.Range(func(_ string, nse *registry.NetworkServiceEndpoint) bool {
if matchutils.MatchNetworkServiceEndpoints(query.NetworkServiceEndpoint, nse) {
matches = append(matches, nse.Clone())
}
return true
})
return matches
}
func (s *memoryNSEServer) closeEventChannel(id string, eventCh <-chan *registry.NetworkServiceEndpointResponse) {
ctx, cancel := context.WithCancel(context.Background())
s.executor.AsyncExec(func() {
delete(s.eventChannels, id)
cancel()
})
for {
select {
case <-ctx.Done():
return
case <-eventCh:
}
}
}
func (s *memoryNSEServer) receiveEvent(
query *registry.NetworkServiceEndpointQuery,
server registry.NetworkServiceEndpointRegistry_FindServer,
eventCh <-chan *registry.NetworkServiceEndpointResponse,
) error {
select {
case <-server.Context().Done():
return io.EOF
case event := <-eventCh:
if matchutils.MatchNetworkServiceEndpoints(query.NetworkServiceEndpoint, event.NetworkServiceEndpoint) {
if err := server.Send(event); err != nil {
if server.Context().Err() != nil {
return io.EOF
}
return err
}
}
return nil
}
}
func (s *memoryNSEServer) Unregister(ctx context.Context, nse *registry.NetworkServiceEndpoint) (*empty.Empty, error) {
if unregisterNSE, ok := s.networkServiceEndpoints.LoadAndDelete(nse.GetName()); ok {
unregisterNSE = unregisterNSE.Clone()
s.sendEvent(®istry.NetworkServiceEndpointResponse{NetworkServiceEndpoint: unregisterNSE, Deleted: true})
}
return next.NetworkServiceEndpointRegistryServer(ctx).Unregister(ctx, nse)
}
| NewNetworkServiceEndpointRegistryServer |
converter.go | package object
import (
"time"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/caos/zitadel/internal/domain"
"github.com/caos/zitadel/pkg/grpc/object"
object_pb "github.com/caos/zitadel/pkg/grpc/object"
)
func DomainToChangeDetailsPb(objectDetail *domain.ObjectDetails) *object_pb.ObjectDetails {
return &object_pb.ObjectDetails{
Sequence: objectDetail.Sequence,
ChangeDate: timestamppb.New(objectDetail.EventDate),
ResourceOwner: objectDetail.ResourceOwner,
}
}
func DomainToAddDetailsPb(objectDetail *domain.ObjectDetails) *object_pb.ObjectDetails {
return &object_pb.ObjectDetails{
Sequence: objectDetail.Sequence,
CreationDate: timestamppb.New(objectDetail.EventDate),
ResourceOwner: objectDetail.ResourceOwner,
}
}
func ToViewDetailsPb(
sequence uint64,
creationDate,
changeDate time.Time,
resourceOwner string,
) *object_pb.ObjectDetails {
return &object_pb.ObjectDetails{
Sequence: sequence,
CreationDate: timestamppb.New(creationDate),
ChangeDate: timestamppb.New(changeDate),
ResourceOwner: resourceOwner,
}
}
func ChangeToDetailsPb(
sequence uint64,
changeDate time.Time,
resourceOwner string,
) *object_pb.ObjectDetails {
return &object_pb.ObjectDetails{
Sequence: sequence,
ChangeDate: timestamppb.New(changeDate),
ResourceOwner: resourceOwner,
}
}
func AddToDetailsPb(
sequence uint64,
creationDate time.Time,
resourceOwner string,
) *object_pb.ObjectDetails |
func ToListDetails(
totalResult,
processedSequence uint64,
viewTimestamp time.Time,
) *object.ListDetails {
return &object_pb.ListDetails{
TotalResult: totalResult,
ProcessedSequence: processedSequence,
ViewTimestamp: timestamppb.New(viewTimestamp),
}
}
func TextMethodToModel(method object_pb.TextQueryMethod) domain.SearchMethod {
switch method {
case object.TextQueryMethod_TEXT_QUERY_METHOD_EQUALS:
return domain.SearchMethodEquals
case object.TextQueryMethod_TEXT_QUERY_METHOD_EQUALS_IGNORE_CASE:
return domain.SearchMethodEqualsIgnoreCase
case object.TextQueryMethod_TEXT_QUERY_METHOD_STARTS_WITH:
return domain.SearchMethodStartsWith
case object.TextQueryMethod_TEXT_QUERY_METHOD_STARTS_WITH_IGNORE_CASE:
return domain.SearchMethodStartsWithIgnoreCase
case object.TextQueryMethod_TEXT_QUERY_METHOD_CONTAINS:
return domain.SearchMethodContains
case object.TextQueryMethod_TEXT_QUERY_METHOD_CONTAINS_IGNORE_CASE:
return domain.SearchMethodContainsIgnoreCase
case object.TextQueryMethod_TEXT_QUERY_METHOD_ENDS_WITH:
return domain.SearchMethodEndsWith
case object.TextQueryMethod_TEXT_QUERY_METHOD_ENDS_WITH_IGNORE_CASE:
return domain.SearchMethodEndsWithIgnoreCase
default:
return -1
}
}
func ListQueryToModel(query *object_pb.ListQuery) (offset, limit uint64, asc bool) {
if query == nil {
return
}
return query.Offset, uint64(query.Limit), query.Asc
}
| {
return &object_pb.ObjectDetails{
Sequence: sequence,
CreationDate: timestamppb.New(creationDate),
ResourceOwner: resourceOwner,
}
} |
utils.py | """Модуль со вспомогательными функциями."""
from argparse import ArgumentTypeError
from random import choice
from string import ascii_letters
from typing import Optional, Tuple, Union
from graphql_relay import from_global_id
def gid2int(gid: Union[str, int]) -> Optional[int]:
try:
return int(gid)
except ValueError:
try:
return int(from_global_id(gid)[1])
except TypeError:
return None
def from_gid_or_none(global_id: Optional[str]) -> Tuple[Optional[str], Optional[int]]:
"""Возвращает None в случае ошибк | ной строки из count."""
return ''.join(choice(ascii_letters) for _ in range(count))
def convert_str_to_bool(value: str) -> bool:
"""Преобразование строки в флаг."""
if isinstance(value, bool):
return value
if value.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif value.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise ArgumentTypeError('Ожидался флаг (true/false)')
def convert_str_to_int(value: Optional[Union[str, bytes]]) -> Optional[int]:
"""Преобразование строки в целое число."""
if value is None:
return None
if isinstance(value, bytes):
value = value.decode('utf-8')
try:
return int(value)
except ValueError:
return None
| и парсинга."""
if not global_id:
return None, None
try:
return from_global_id(global_id)
except TypeError:
return None, None
def random_string(count: int) -> str:
"""Генерация случай |
routingPolicyTermModel.js | /*
* Copyright (c) 2015 Juniper Networks, Inc. All rights reserved.
*/
define([
'underscore',
'knockout',
'contrail-model',
'config/networking/routingpolicy/ui/js/views/routingPolicyFormatter',
'config/networking/routingpolicy/ui/js/models/routingPolicyTermFromModel',
'config/networking/routingpolicy/ui/js/models/routingPolicyTermThenModel'
], function (_, Knockout, ContrailModel, RoutingPolicyFormatter, routingPolicyTermFromModel, routingPolicyTermThenModel) {
var routingPolicyFormatter = new RoutingPolicyFormatter();
var RoutingPolicyTermModel = ContrailModel.extend({
defaultConfig: {
"term_match_condition":{
"community_list":[],
"prefix":[]
},
"term_action_list":{
"update": {
"community":{},
"local_pref" : "",
},
"action": ""
},
"action":"Default",
"from_terms": "",
"then_terms": "",
"disabled_from_names": {}
},
constructor: function (parentModel, modelData) {
this.parentModel = parentModel;
ContrailModel.prototype.constructor.call(this, modelData);
return this;
},
formatModelConfig: function (config) {
var self = this,
modelConfig = $.extend({}, true, config),
routingPolicyTermFromModels = [], routingPolicyTermThenModels = [],
routingPolicyTermFromCollectionModel, routingPolicyTermThenCollectionModel;
var termMatchArray = routingPolicyFormatter.buildTermMatchObject (modelConfig.term_match_condition);
var termMatchArrayLen = termMatchArray.length;
for (var i = 0; i < termMatchArrayLen; i++) {
var termMatch = new routingPolicyTermFromModel(modelConfig, termMatchArray[i]);
routingPolicyTermFromModels.push(termMatch);
}
var termActionArray = routingPolicyFormatter.buildTermActionObject (modelConfig.term_action_list);
var termActionArrayLen = termActionArray.length;
for (var i = 0; i < termActionArrayLen; i++) {
var termAction = new routingPolicyTermThenModel(modelConfig, termActionArray[i]);
routingPolicyTermThenModels.push(termAction);
}
//This need to be fixed
if (termMatchArrayLen == 0) {
routingPolicyTermFromModels.push(new routingPolicyTermFromModel(modelConfig, {name: 'community', value: '', isDisable: true}));
routingPolicyTermFromModels.push(new routingPolicyTermFromModel(modelConfig, {name: 'protocol', value: '', isDisable: true}));
routingPolicyTermFromModels.push(new routingPolicyTermFromModel(modelConfig, {name: 'prefix', value: '', isDisable: true}));
}
if (termActionArrayLen == 0) {
routingPolicyTermThenModels.push(new routingPolicyTermThenModel(modelConfig, {name: 'add community'}));
}
routingPolicyTermFromCollectionModel = new Backbone.Collection(routingPolicyTermFromModels);
routingPolicyTermThenCollectionModel = new Backbone.Collection(routingPolicyTermThenModels);
modelConfig['from_terms'] = routingPolicyTermFromCollectionModel;
modelConfig['then_terms'] = routingPolicyTermThenCollectionModel;
return modelConfig;
},
validateAttr: function (attributePath, validation, data) {
var model = data.model().attributes.model(),
attr = cowu.getAttributeFromPath(attributePath),
errors = model.get(cowc.KEY_MODEL_ERRORS),
attrErrorObj = {}, isValid;
isValid = model.isValid(attributePath, validation);
attrErrorObj[attr + cowc.ERROR_SUFFIX_ID] = (isValid == true) ? false : isValid;
errors.set(attrErrorObj);
},
getOrClauseText: function (data) {
var fromTerms = data.from_terms()(),
thenTerms = data.then_terms()(),
fromTermArray = [], thenTermArray = [], termsText = '';
$.each(fromTerms, function (fromTermKey, fromTermValue) {
var name = fromTermValue.name(),
value = fromTermValue.value(),
additionalValue = fromTermValue.additionalValue(),
fromTermStr = '';
name = contrail.checkIfFunction(name) ? name() : name;
value = contrail.checkIfFunction(value) ? value() : value;
additionalValue = contrail.checkIfFunction(additionalValue) ? additionalValue() : additionalValue;
if (name == 'protocol') {
fromTermStr += name + ' ' + value;
fromTermArray.push(fromTermStr);
}
if (value != '' && name != 'protocol') {
fromTermStr = name + ' ' + value;
if (name == 'prefix') {
fromTermStr += ' ' + additionalValue;
}
fromTermArray.push(fromTermStr)
}
});
| actionCondition = thenTermValue.action_condition(),
thenTermStr = '';
name = contrail.checkIfFunction(name) ? name() : name;
value = contrail.checkIfFunction(value) ? value() : value;
actionCondition = contrail.checkIfFunction(actionCondition) ? actionCondition() : actionCondition;
if (value != '') {
thenTermStr = name + ' ' + value;
thenTermArray.push(thenTermStr);
} else if (name == 'action') {
thenTermStr = 'action ' + actionCondition;
thenTermArray.push(thenTermStr);
}
});
termsText += 'from: { ' + fromTermArray.join(', ') + ' } ';
termsText += 'then: { ' + thenTermArray.join(', ') + ' } ';
return (termsText !== '') ? termsText : '...';
},
addTermAtIndex: function (data, event) {
var self = this,
orClauses = this.model().collection,
orClause = this.model(),
orClauseIndex = _.indexOf(orClauses.models, orClause),
newOrClause = new RoutingPolicyTermModel(self.parentModel(), {});
orClauses.add(newOrClause, {at: orClauseIndex + 1});
$(event.target).parents('.collection').accordion('refresh');
$(event.target).parents('.collection').accordion("option", "active", orClauseIndex + 1);
event.stopImmediatePropagation();
},
deleteTerm: function () {
var orClauses = this.model().collection,
orClause = this.model();
if (orClauses.length > 1) {
orClauses.remove(orClause);
}
},
validations: {
termValidation: {
'then_terms': function (value, attr, finalObj) {
var thenModelObj = getValueByJsonPath(finalObj, "then_terms;models", []);
var thenModelObjLen = thenModelObj.length;
var elements = {'add community':0,'set community':0,
'remove community':0, 'local-preference':0, 'action':0};
for (var i = 0; i < thenModelObjLen; i++) {
var name = getValueByJsonPath(thenModelObj[i], "attributes;name")();
elements[name] += 1;
if (name == "local-preference") {
var value = getValueByJsonPath(thenModelObj[i], "attributes;value")();
if (!isNumber(String(value).trim())){
return "Local preference has to be a number.";
}
if (elements["local-preference"] > 1) {
return "cannot have more than one local preference";
}
}
if (name == "med") {
var value = getValueByJsonPath(thenModelObj[i], "attributes;value")();
if (!isNumber(String(value).trim())){
return "Med has to be a number.";
}
if (elements["med"] > 1) {
return "cannot have more than one Med";
}
}
if (elements["action"] > 1) {
return "cannot have more than one action";
}
}
}
}
}
});
return RoutingPolicyTermModel;
}); | $.each(thenTerms, function (thenTermKey, thenTermValue) {
var name = thenTermValue.name(),
value = thenTermValue.value(), |
main.rs | use std::io::{self, BufRead};
fn find_two_summing_to(numbers: &[i32], sum: i32) -> Option<(i32, i32)> {
let mut iter = numbers.iter();
let mut a = iter.next().unwrap();
let mut b = iter.next_back().unwrap();
loop {
match *a + *b {
n if n == sum => {
return Some((*a, *b));
}
n if n < sum => {
if let Some(val) = iter.next() {
a = val;
} else {
return None;
}
}
_ => {
if let Some(val) = iter.next_back() {
b = val;
} else {
return None;
}
}
}
}
}
fn find_three_summing_to(numbers: &[i32], sum: i32) -> Option<(i32, i32, i32)> {
let mut to_find_two = &numbers[..numbers.len() - 1];
let mut outer_iter = numbers.iter();
let mut c = outer_iter.next_back().unwrap();
loop {
if let Some((a, b)) = find_two_summing_to(to_find_two, sum - c) {
return Some((a, b, *c));
} else {
to_find_two = &to_find_two[..to_find_two.len() - 1];
if let Some(_c) = outer_iter.next_back() {
c = _c;
} else {
return None;
}
}
}
}
fn main() {
let numbers = io::stdin()
.lock()
.lines()
.map(|l| l.unwrap().parse::<i32>())
.collect::<Result<Vec<i32>, _>>()
.unwrap();
if let Some((a, b)) = solve_part1(numbers.clone()) |
if let Some((a, b, c)) = solve_part2(numbers) {
println!("PART2: {} * {} * {} = {}", a, b, c, a * b * c);
}
}
fn solve_part1(mut numbers: Vec<i32>) -> Option<(i32, i32)> {
numbers.sort();
find_two_summing_to(numbers.as_slice(), 2020)
}
fn solve_part2(mut numbers: Vec<i32>) -> Option<(i32, i32, i32)> {
numbers.sort();
find_three_summing_to(numbers.as_slice(), 2020)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part1() {
assert_eq!(
solve_part1(vec![1721, 979, 366, 299, 675, 1456]),
Some((299, 1721))
);
}
#[test]
fn test_part2() {
assert_eq!(
solve_part2(vec![1721, 979, 366, 299, 675, 1456]),
Some((366, 675, 979))
);
}
}
| {
println!("PART1: {} * {} = {}", a, b, a * b);
} |
_identity_sign_ins.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import TYPE_CHECKING
from azure.mgmt.core import ARMPipelineClient
from msrest import Deserializer, Serializer
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from typing import Any, Optional
from azure.core.credentials import TokenCredential
from ._configuration import IdentitySignInsConfiguration
from .operations import DataPolicyOperationsDataPolicyOperationOperations
from .operations import IdentityOperations
from .operations import IdentityConditionalAccessOperations
from .operations import IdentityProvidersIdentityProviderOperations
from .operations import InformationProtectionInformationProtectionOperations
from .operations import InformationProtectionOperations
from .operations import InformationProtectionThreatAssessmentRequestsOperations
from .operations import InvitationsInvitationOperations
from .operations import InvitationsOperations
from .operations import Oauth2PermissionGrantsOAuth2PermissionGrantOperations
from .operations import Oauth2PermissionGrantsOperations
from .operations import OrganizationOperations
from .operations import PoliciesPolicyRootOperations
from .operations import PoliciesOperations
from .operations import PoliciesPermissionGrantPoliciesOperations
from . import models
class IdentitySignIns(object):
"""IdentitySignIns.
:ivar data_policy_operations_data_policy_operation: DataPolicyOperationsDataPolicyOperationOperations operations
:vartype data_policy_operations_data_policy_operation: identity_sign_ins.operations.DataPolicyOperationsDataPolicyOperationOperations
:ivar identity: IdentityOperations operations
:vartype identity: identity_sign_ins.operations.IdentityOperations
:ivar identity_conditional_access: IdentityConditionalAccessOperations operations
:vartype identity_conditional_access: identity_sign_ins.operations.IdentityConditionalAccessOperations
:ivar identity_providers_identity_provider: IdentityProvidersIdentityProviderOperations operations
:vartype identity_providers_identity_provider: identity_sign_ins.operations.IdentityProvidersIdentityProviderOperations
:ivar information_protection_information_protection: InformationProtectionInformationProtectionOperations operations
:vartype information_protection_information_protection: identity_sign_ins.operations.InformationProtectionInformationProtectionOperations
:ivar information_protection: InformationProtectionOperations operations
:vartype information_protection: identity_sign_ins.operations.InformationProtectionOperations
:ivar information_protection_threat_assessment_requests: InformationProtectionThreatAssessmentRequestsOperations operations
:vartype information_protection_threat_assessment_requests: identity_sign_ins.operations.InformationProtectionThreatAssessmentRequestsOperations
:ivar invitations_invitation: InvitationsInvitationOperations operations
:vartype invitations_invitation: identity_sign_ins.operations.InvitationsInvitationOperations
:ivar invitations: InvitationsOperations operations
:vartype invitations: identity_sign_ins.operations.InvitationsOperations
:ivar oauth2_permission_grants_oauth2_permission_grant: Oauth2PermissionGrantsOAuth2PermissionGrantOperations operations
:vartype oauth2_permission_grants_oauth2_permission_grant: identity_sign_ins.operations.Oauth2PermissionGrantsOAuth2PermissionGrantOperations
:ivar oauth2_permission_grants: Oauth2PermissionGrantsOperations operations
:vartype oauth2_permission_grants: identity_sign_ins.operations.Oauth2PermissionGrantsOperations
:ivar organization: OrganizationOperations operations
:vartype organization: identity_sign_ins.operations.OrganizationOperations
:ivar policies_policy_root: PoliciesPolicyRootOperations operations
:vartype policies_policy_root: identity_sign_ins.operations.PoliciesPolicyRootOperations
:ivar policies: PoliciesOperations operations
:vartype policies: identity_sign_ins.operations.PoliciesOperations
:ivar policies_permission_grant_policies: PoliciesPermissionGrantPoliciesOperations operations
:vartype policies_permission_grant_policies: identity_sign_ins.operations.PoliciesPermissionGrantPoliciesOperations
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials.TokenCredential
:param top: Show only the first n items.
:type top: int
:param skip: Skip the first n items.
:type skip: int
:param search: Search items by search phrases.
:type search: str
:param filter: Filter items by property values.
:type filter: str
:param count: Include count of items.
:type count: bool
:param str base_url: Service URL
"""
def __init__(
self,
credential, # type: "TokenCredential"
top=None, # type: Optional[int]
skip=None, # type: Optional[int]
search=None, # type: Optional[str]
filter=None, # type: Optional[str]
count=None, # type: Optional[bool]
base_url=None, # type: Optional[str]
**kwargs # type: Any
):
# type: (...) -> None
if not base_url:
base_url = 'https://graph.microsoft.com/v1.0'
self._config = IdentitySignInsConfiguration(credential, top, skip, search, filter, count, **kwargs)
self._client = ARMPipelineClient(base_url=base_url, config=self._config, **kwargs)
client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)}
self._serialize = Serializer(client_models)
self._serialize.client_side_validation = False
self._deserialize = Deserializer(client_models)
| self.data_policy_operations_data_policy_operation = DataPolicyOperationsDataPolicyOperationOperations(
self._client, self._config, self._serialize, self._deserialize)
self.identity = IdentityOperations(
self._client, self._config, self._serialize, self._deserialize)
self.identity_conditional_access = IdentityConditionalAccessOperations(
self._client, self._config, self._serialize, self._deserialize)
self.identity_providers_identity_provider = IdentityProvidersIdentityProviderOperations(
self._client, self._config, self._serialize, self._deserialize)
self.information_protection_information_protection = InformationProtectionInformationProtectionOperations(
self._client, self._config, self._serialize, self._deserialize)
self.information_protection = InformationProtectionOperations(
self._client, self._config, self._serialize, self._deserialize)
self.information_protection_threat_assessment_requests = InformationProtectionThreatAssessmentRequestsOperations(
self._client, self._config, self._serialize, self._deserialize)
self.invitations_invitation = InvitationsInvitationOperations(
self._client, self._config, self._serialize, self._deserialize)
self.invitations = InvitationsOperations(
self._client, self._config, self._serialize, self._deserialize)
self.oauth2_permission_grants_oauth2_permission_grant = Oauth2PermissionGrantsOAuth2PermissionGrantOperations(
self._client, self._config, self._serialize, self._deserialize)
self.oauth2_permission_grants = Oauth2PermissionGrantsOperations(
self._client, self._config, self._serialize, self._deserialize)
self.organization = OrganizationOperations(
self._client, self._config, self._serialize, self._deserialize)
self.policies_policy_root = PoliciesPolicyRootOperations(
self._client, self._config, self._serialize, self._deserialize)
self.policies = PoliciesOperations(
self._client, self._config, self._serialize, self._deserialize)
self.policies_permission_grant_policies = PoliciesPermissionGrantPoliciesOperations(
self._client, self._config, self._serialize, self._deserialize)
def close(self):
# type: () -> None
self._client.close()
def __enter__(self):
# type: () -> IdentitySignIns
self._client.__enter__()
return self
def __exit__(self, *exc_details):
# type: (Any) -> None
self._client.__exit__(*exc_details) | |
config_test.go | package schema_test
import (
"bytes"
"flag"
"io/ioutil" |
"github.com/amazeeio/lagoon-cli/internal/schema"
)
var update = flag.Bool("update", false, "update .golden files")
func TestProjectsToConfig(t *testing.T) {
var testCases = map[string]struct {
input string
expect string
}{
"singleProject": {
input: "testdata/singleProject.json",
expect: "testdata/singleProject.golden.yaml",
},
"rocketChat": {
input: "testdata/rocketChat.json",
expect: "testdata/rocketChat.golden.yaml",
},
"ciBranchPicky": {
input: "testdata/ciBranchPicky.json",
expect: "testdata/ciBranchPicky.golden.yaml",
},
"noBillingGroups": {
input: "testdata/noBillingGroups.json",
expect: "testdata/noBillingGroups.golden.yaml",
},
"withBillingGroups": {
input: "testdata/withBillingGroups.json",
expect: "testdata/withBillingGroups.golden.yaml",
},
"noNewNotifications": {
input: "testdata/noNewNotifications.json",
expect: "testdata/noNewNotifications.golden.yaml",
},
"newNotifications": {
input: "testdata/newNotifications.json",
expect: "testdata/newNotifications.golden.yaml",
},
}
for name, tc := range testCases {
t.Run(name, func(tt *testing.T) {
// marshal testcase
testJSON, err := ioutil.ReadFile(tc.input)
if err != nil {
tt.Fatalf("couldn't read file: %v", err)
}
data := schema.ProjectByNameResponse{}
if err = schema.UnmarshalProjectByNameResponse(testJSON, &data); err != nil {
tt.Fatalf("couldn't unmarshal project config: %v", err)
}
result, err := schema.ProjectsToConfig(
[]schema.Project{*data.Response.Project},
map[string]bool{"project-private-keys": true})
if err != nil {
tt.Fatalf("couldn't translate ProjectConfigs: %v", err)
}
if *update {
tt.Logf("update golden file: %s", tc.expect)
if err = ioutil.WriteFile(tc.expect, result, 0644); err != nil {
tt.Fatalf("failed to update golden file: %v", err)
}
}
expected, err := ioutil.ReadFile(tc.expect)
if err != nil {
tt.Fatalf("failed reading golden file: %v", err)
}
if !bytes.Equal(result, expected) {
tt.Logf("result:\n%s\nexpected:\n%s", result, expected)
tt.Errorf("result does not match expected")
}
})
}
} | "testing" |
test.py | import wavio
import torch
import numpy as np
from specaugment import spec_augment_pytorch, melscale_pytorch
import matplotlib.pyplot as plt
PAD = 0
N_FFT = 512
SAMPLE_RATE = 16000
def trim(data, threshold_attack=0.01, threshold_release=0.05, attack_margin=5000, release_margin=5000):
data_size = len(data)
cut_head = 0
cut_tail = data_size
plt.subplot(5,1,1)
plt.plot(data)
# Square
w = np.power(np.divide(data, np.max(data)), 2)
plt.subplot(5,1,2)
plt.plot(w)
# Gaussian kernel
sig = 20000
time = np.linspace(-40000, 40000)
kernel = np.exp(-np.square(time)/2/sig/sig)
# Smooth and normalize | plt.subplot(5,1,3)
plt.plot(w)
# Detect crop sites
for sample in range(data_size):
sample_num = sample
sample_amp = w[sample_num]
if sample_amp > threshold_attack:
cut_head = np.max([sample_num - attack_margin, 0])
break
for sample in range(data_size):
sample_num = data_size-sample-1
sample_amp = w[sample_num]
if sample_amp > threshold_release:
cut_tail = np.min([sample_num + release_margin, data_size])
break
print(cut_head)
print(cut_tail)
plt.subplot(5,1,4)
plt.plot(data[cut_head:cut_tail])
data_copy = data[cut_head:cut_tail]
del w, time, kernel, data
plt.subplot(5,1,5)
plt.plot(data_copy)
#plt.show()
return data_copy
def get_spectrogram_feature(filepath, train_mode=False):
(rate, width, sig) = wavio.readwav(filepath)
wavio.writewav24("test.wav", rate=rate, data=sig)
sig = sig.ravel()
sig = trim(sig)
stft = torch.stft(torch.FloatTensor(sig),
N_FFT,
hop_length=int(0.01*SAMPLE_RATE),
win_length=int(0.030*SAMPLE_RATE),
window=torch.hamming_window(int(0.030*SAMPLE_RATE)),
center=False,
normalized=False,
onesided=True)
stft = (stft[:,:,0].pow(2) + stft[:,:,1].pow(2)).pow(0.5)
amag = stft.clone().detach()
amag = amag.view(-1, amag.shape[0], amag.shape[1]) # reshape spectrogram shape to [batch_size, time, frequency]
mel = melscale_pytorch.mel_scale(amag, sample_rate=SAMPLE_RATE, n_mels=N_FFT//2+1) # melspec with same shape
plt.subplot(1,2,1)
plt.imshow(mel.transpose(1,2).squeeze(), cmap='jet')
p = 1 # always augment
randp = np.random.uniform(0, 1)
do_aug = p > randp
if do_aug & train_mode: # apply augment
print("augment image")
mel = spec_augment_pytorch.spec_augment(mel, time_warping_para=80, frequency_masking_para=54,
time_masking_para=50, frequency_mask_num=1, time_mask_num=1)
feat = mel.view(mel.shape[1], mel.shape[2]) # squeeze back to [frequency, time]
feat = feat.transpose(0, 1).clone().detach()
plt.subplot(1,2,2)
plt.imshow(feat, cmap='jet')
plt.show() # display it
del stft, amag, mel
return feat
filepath = "./sample_dataset/train/train_data/wav_007.wav"
feat = get_spectrogram_feature(filepath, train_mode=True)
filepath = "./sample_dataset/train/train_data/wav_002.wav"
feat = get_spectrogram_feature(filepath, train_mode=True)
filepath = "./sample_dataset/train/train_data/wav_006.wav"
feat = get_spectrogram_feature(filepath, train_mode=True)
filepath = "./sample_dataset/train/train_data/wav_016.wav"
feat = get_spectrogram_feature(filepath, train_mode=True)
filepath = "./sample_dataset/train/train_data/wav_040.wav"
feat = get_spectrogram_feature(filepath, train_mode=True) | w = np.convolve(w, kernel, mode='same')
w = np.divide(w, np.max(w))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.